Revision: 201004 PDK_3.0.f
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Tue, 26 Jan 2010 15:20:08 +0200
changeset 0 164170e6151a
child 1 d5423fbb4f29
Revision: 201004
boottimeintegritycheck/BWINS/IntegrityCheckClientU.DEF
boottimeintegritycheck/EABI/IntegrityCheckClientU.DEF
boottimeintegritycheck/TrkDummy/group/TrkDummy.mmp
boottimeintegritycheck/TrkDummy/group/TrkDummy1.mmp
boottimeintegritycheck/TrkDummy/group/TrkDummy2.mmp
boottimeintegritycheck/TrkDummy/group/bld.inf
boottimeintegritycheck/TrkDummy/inc/TrkDummyApplication.h
boottimeintegritycheck/TrkDummy/src/TrkDummy.cpp
boottimeintegritycheck/TrkDummy/src/TrkDummyApplication.cpp
boottimeintegritycheck/group/IntegrityCheck.mmp
boottimeintegritycheck/group/IntegrityCheckClient.mmp
boottimeintegritycheck/group/IntegrityCheckServer.mmp
boottimeintegritycheck/group/bld.inf
boottimeintegritycheck/inc/InfoServerClient.h
boottimeintegritycheck/inc/IntegrityCheck.h
boottimeintegritycheck/inc/IntegrityCheckClient.h
boottimeintegritycheck/inc/IntegrityCheckDebug.h
boottimeintegritycheck/inc/IntegrityCheckDefs.h
boottimeintegritycheck/inc/IntegrityCheckServer.h
boottimeintegritycheck/rom/IntegrityCheck.iby
boottimeintegritycheck/src/InfoServerClient.cpp
boottimeintegritycheck/src/IntegrityCheck.cpp
boottimeintegritycheck/src/IntegrityCheckClient.cpp
boottimeintegritycheck/src/IntegrityCheckServer.cpp
cms/BMARM/CMSU.DEF
cms/BWINS/CMSU.DEF
cms/EABI/CMSU.DEF
cms/group/CMS.mmp
cms/group/Create-UT_CCMSAttribute-Sis.bat
cms/group/Create-UT_CCMSEncapsulatedContentInfo-Sis.bat
cms/group/Create-UT_CCMSIssuerAndSerialNumber-Sis.bat
cms/group/Create-UT_CCMSOriginatorPublicKey-Sis.bat
cms/group/Create-UT_CCMSSignerInfo-Sis.bat
cms/group/Create-UT_CCMSX509AlgorithmIdentifier-Sis.bat
cms/group/UT_CCMSAttribute.pkg
cms/group/UT_CCMSEncapsulatedContentInfo.pkg
cms/group/UT_CCMSIssuerAndSerialNumber.pkg
cms/group/UT_CCMSOriginatorPublicKey.pkg
cms/group/UT_CCMSSignerInfo.pkg
cms/group/UT_CCMSX509AlgorithmIdentifier.pkg
cms/group/bld.inf
cms/inc/TCMSTimeUtil.h
cms/rom/CMS.iby
cms/src/CCMSAttribute.cpp
cms/src/CCMSAuthenticatedData.cpp
cms/src/CCMSCertificateChoices.cpp
cms/src/CCMSContentInfo.cpp
cms/src/CCMSEncapsulatedContentInfo.cpp
cms/src/CCMSIssuerAndSerialNumber.cpp
cms/src/CCMSKEKRecipientInfo.cpp
cms/src/CCMSKeyAgreeRecipientInfo.cpp
cms/src/CCMSKeyIdentifier.cpp
cms/src/CCMSKeyTransRecipientInfo.cpp
cms/src/CCMSOriginatorIdentifierOrKey.cpp
cms/src/CCMSOriginatorInfo.cpp
cms/src/CCMSOriginatorPublicKey.cpp
cms/src/CCMSRecipientEncryptedKey.cpp
cms/src/CCMSRecipientInfo.cpp
cms/src/CCMSSequence.cpp
cms/src/CCMSSignedData.cpp
cms/src/CCMSSignerInfo.cpp
cms/src/CCMSX509AlgorithmIdentifier.cpp
cms/src/CCMSX509AttributeCertificate.cpp
cms/src/CCMSX509AttributeCertificateInfo.cpp
cms/src/CCMSX509Certificate.cpp
cms/src/CCMSX509CertificateList.cpp
cms/src/CCMSX509GeneralName.cpp
cms/src/CCMSX509GeneralNames.cpp
cms/src/CCMSX509IssuerSerial.cpp
cms/src/CCMSX509Signed.cpp
cms/src/CCMSX509SubjectPublicKeyInfo.cpp
cms/src/CCMSX509Validity.cpp
cms/src/CMS.cpp
cms/src/TCMSTimeUtil.cpp
devencdiskutils/DevEncCommonUtils/BWINS/devenccommonutilsu.def
devencdiskutils/DevEncCommonUtils/EABI/devenccommonutilsu.def
devencdiskutils/DevEncCommonUtils/conf/devencui.confml
devencdiskutils/DevEncCommonUtils/conf/devencui_200025A6.crml
devencdiskutils/DevEncCommonUtils/group/DevEncCommonUtils.mmp
devencdiskutils/DevEncCommonUtils/group/bld.inf
devencdiskutils/DevEncCommonUtils/inc/DevEncCommonUtils.hrh
devencdiskutils/DevEncCommonUtils/sis/DevEncCommonUtils.SIS
devencdiskutils/DevEncCommonUtils/sis/DevEncCommonUtils.pkg
devencdiskutils/DevEncCommonUtils/sis/DevEncCommonUtils.sisx
devencdiskutils/DevEncCommonUtils/src/DevEncDiskStatusObserver.cpp
devencdiskutils/DevEncCommonUtils/src/DevEncDiskUtils.cpp
devencdiskutils/DevEncCommonUtils/src/DevEncKeyUtils.cpp
devencdiskutils/DevEncCommonUtils/src/DevEncMmcObserver.cpp
devencdiskutils/DevEncCommonUtils/src/DevEncSession.cpp
devencdiskutils/DevEncRfsPlugin/data/200025B6.rss
devencdiskutils/DevEncRfsPlugin/group/DevEncRfsPlugin.mmp
devencdiskutils/DevEncRfsPlugin/group/bld.inf
devencdiskutils/DevEncRfsPlugin/inc/DevEncRfsPlugin.h
devencdiskutils/DevEncRfsPlugin/src/DevEncRfsPlugin.cpp
devencdiskutils/DevEncRfsPlugin/src/DevEncRfsPluginImp.cpp
devencdiskutils/DevEncStarter/data/DevEncStarter.rss
devencdiskutils/DevEncStarter/group/DevEncStarter.mmp
devencdiskutils/DevEncStarter/group/bld.inf
devencdiskutils/DevEncStarter/inc/DevEncStarterAppStarter.h
devencdiskutils/DevEncStarter/inc/DevEncStarterDebug.h
devencdiskutils/DevEncStarter/inc/DevEncStarterDef.h
devencdiskutils/DevEncStarter/inc/DevEncStarterEngine.h
devencdiskutils/DevEncStarter/inc/DevEncStarterMemoryEntity.h
devencdiskutils/DevEncStarter/inc/DevEncStarterMmcObserver.h
devencdiskutils/DevEncStarter/inc/DevEncStarterPropertyObserver.h
devencdiskutils/DevEncStarter/inc/DevEncStarterUids.h
devencdiskutils/DevEncStarter/inc/DevEncStarterUtils.h
devencdiskutils/DevEncStarter/inc/DevEncUiMemInfoObserver.h
devencdiskutils/DevEncStarter/rom/DevEncStarter.iby
devencdiskutils/DevEncStarter/src/DevEncStarter.cpp
devencdiskutils/DevEncStarter/src/DevEncStarterAppStarter.cpp
devencdiskutils/DevEncStarter/src/DevEncStarterEngine.cpp
devencdiskutils/DevEncStarter/src/DevEncStarterMemoryEntity.cpp
devencdiskutils/DevEncStarter/src/DevEncStarterMmcObserver.cpp
devencdiskutils/DevEncStarter/src/DevEncStarterPropertyObserver.cpp
devencdiskutils/DevEncStarter/src/DevEncStarterUtils.cpp
devencdiskutils/Pk5Recognizer/group/2000FD89.rss
devencdiskutils/Pk5Recognizer/group/Pk5Recognizer.mmp
devencdiskutils/Pk5Recognizer/group/bld.inf
devencdiskutils/Pk5Recognizer/inc/Pk5Recognizer.h
devencdiskutils/Pk5Recognizer/src/Pk5Recognizer.cpp
devencdiskutils/common/DevEncConfig.hrh
devencdiskutils/common/DevEncDef.h
devencdiskutils/common/DevEncLog.cpp
devencdiskutils/common/DevEncLog.h
devencdiskutils/common/DevEncUids.hrh
devencdiskutils/group/bld.inf
devencdiskutils/layers.sysdef.xml
devencdiskutils/rom/DevEncDiskUtils.iby
devencdiskutils/sis/DevEnc.pkg
devencdiskutils/sysdef_1_4_0.dtd
gba/common/GBALogger.cpp
gba/data/gba_license.txt
gba/gbaapi/BWINS/gba2u.def
gba/gbaapi/EABI/gba2u.def
gba/gbaapi/group/bld.inf
gba/gbaapi/group/gba.mmp
gba/gbaapi/inc/GbaClientrequesthandler.h
gba/gbaapi/inc/GbaServerSession.h
gba/gbaapi/src/GbaClientRequestHandler.cpp
gba/gbaapi/src/GbaServerSession.cpp
gba/gbaapi/src/GbaUtility.cpp
gba/gbafilter/Data/20029F09.rss
gba/gbafilter/group/bld.inf
gba/gbafilter/group/httpfiltergba.mmp
gba/gbafilter/inc/HTTPFilterGBA.h
gba/gbafilter/src/HTTPFilterGBA.cpp
gba/gbafilter/src/HTTPFilterGBAMain.cpp
gba/gbaserver/group/bld.inf
gba/gbaserver/group/gbaserver.mmp
gba/gbaserver/inc/GbaServer.h
gba/gbaserver/inc/GbaServerPolicy.h
gba/gbaserver/inc/GbaSession.h
gba/gbaserver/inc/M3GPPAuthenticationCallback.h
gba/gbaserver/inc/bootstrap.h
gba/gbaserver/inc/dataretriever.h
gba/gbaserver/src/GbaServer.cpp
gba/gbaserver/src/GbaSession.cpp
gba/gbaserver/src/bootstrap.cpp
gba/gbaserver/src/dataretriever.cpp
gba/group/bld.inf
gba/inc/GBALogger.h
gba/inc/GbaCommon.h
gba/inc/gbauicc.h
gba/rom/gba.iby
gba/sis/gba.pkg
gba/sis/gba.sis
gba/sis/gba.sisx
gba/sis/gba_stub.pkg
gba/sis/gba_stub.sis
gba/uicc/data/20029F0B.rss
gba/uicc/group/bld.inf
gba/uicc/group/gbauicc.mmp
gba/uicc/inc/GBAAkaIsa.h
gba/uicc/src/GbaAkaIsa.cpp
group/bld.inf
layers.sysdef.xml
package_definition.xml
pkiutilities/CTSecurityDialogs/BWINSCW/CTSecDilogImplU.DEF
pkiutilities/CTSecurityDialogs/BWINSCW/CTSecDlgsU.DEF
pkiutilities/CTSecurityDialogs/ClientInc/CDigSigningNote.h
pkiutilities/CTSecurityDialogs/ClientInc/CPKIDlg.h
pkiutilities/CTSecurityDialogs/ClientInc/CTSecurityDialogDefs.h
pkiutilities/CTSecurityDialogs/ClientInc/CTSecurityDialogRequestor.h
pkiutilities/CTSecurityDialogs/ClientInc/SecurityDialogBase.h
pkiutilities/CTSecurityDialogs/ClientSrc/CDigSigningNote.cpp
pkiutilities/CTSecurityDialogs/ClientSrc/CPKIDlg.cpp
pkiutilities/CTSecurityDialogs/ClientSrc/CTsecuritydialogrequestor.cpp
pkiutilities/CTSecurityDialogs/ClientSrc/DllMain.cpp
pkiutilities/CTSecurityDialogs/ClientSrc/SecurityDialogBase.cpp
pkiutilities/CTSecurityDialogs/Group/CTSecDialogImpl.mmp
pkiutilities/CTSecurityDialogs/Group/CTSecDlgNotifier.mmp
pkiutilities/CTSecurityDialogs/Group/CTSecDlgs.mmp
pkiutilities/CTSecurityDialogs/Group/bld.inf
pkiutilities/CTSecurityDialogs/NotifInc/CTCertificateQuery.h
pkiutilities/CTSecurityDialogs/NotifInc/CTInvalidCertNote.h
pkiutilities/CTSecurityDialogs/NotifInc/CTNoTrustQuery.h
pkiutilities/CTSecurityDialogs/NotifInc/CTPinPinQueryDialog.h
pkiutilities/CTSecurityDialogs/NotifInc/CTPinQueryDialog.h
pkiutilities/CTSecurityDialogs/NotifInc/CTQueryDialog.h
pkiutilities/CTSecurityDialogs/NotifInc/CTSecurityDialogNotifier.h
pkiutilities/CTSecurityDialogs/NotifInc/CTSecurityDialogsAO.h
pkiutilities/CTSecurityDialogs/NotifInc/CTSecurityDialogsLogger.h
pkiutilities/CTSecurityDialogs/NotifInc/CTSelectCertificateDialog.h
pkiutilities/CTSecurityDialogs/NotifInc/CTSignTextDialog.h
pkiutilities/CTSecurityDialogs/NotifSrc/CTCertificateQuery.cpp
pkiutilities/CTSecurityDialogs/NotifSrc/CTInvalidCertNote.cpp
pkiutilities/CTSecurityDialogs/NotifSrc/CTNoTrustQuery.cpp
pkiutilities/CTSecurityDialogs/NotifSrc/CTPinPinQueryDialog.cpp
pkiutilities/CTSecurityDialogs/NotifSrc/CTQueryDialog.cpp
pkiutilities/CTSecurityDialogs/NotifSrc/CTSecurityDialogsAO.cpp
pkiutilities/CTSecurityDialogs/NotifSrc/CTSecuritydialognotifier.cpp
pkiutilities/CTSecurityDialogs/NotifSrc/CTSelectcertificatedialog.cpp
pkiutilities/CTSecurityDialogs/NotifSrc/CTSigntextdialog.cpp
pkiutilities/CTSecurityDialogs/NotifSrc/CTpinquerydialog.cpp
pkiutilities/CTSecurityDialogs/NotifSrc/DllMain.cpp
pkiutilities/CTSecurityDialogs/data/CTsecdlgs.rss
pkiutilities/CTSecurityDialogs/data/qgn_stat_dsign.bmp
pkiutilities/CTSecurityDialogs/data/qgn_stat_dsign_mask.bmp
pkiutilities/CTSecurityDialogs/eabi/CTSecDilogImplU.DEF
pkiutilities/CTSecurityDialogs/eabi/CTSecDlgsU.DEF
pkiutilities/CTSecurityDialogs/ecomsrc/10008D4F.rss
pkiutilities/CTSecurityDialogs/ecomsrc/CTSecDlgWrapper.cpp
pkiutilities/CTSecurityDialogs/loc/wmlbrowser_wim.loc
pkiutilities/CertSaver/aif/CertSaveraif.rss
pkiutilities/CertSaver/data/CertSaver.rss
pkiutilities/CertSaver/data/CertSaver_caption.rss
pkiutilities/CertSaver/data/CertSaver_reg.rss
pkiutilities/CertSaver/group/CertSaver.mmp
pkiutilities/CertSaver/group/bld.inf
pkiutilities/CertSaver/inc/CertSaverApp.h
pkiutilities/CertSaver/inc/CertSaverAppUi.h
pkiutilities/CertSaver/inc/CertSaverContainer.h
pkiutilities/CertSaver/inc/CertSaverDocument.h
pkiutilities/CertSaver/inc/CertSaverModel.h
pkiutilities/CertSaver/inc/CertSaverSyncWrapper.h
pkiutilities/CertSaver/inc/certparser.h
pkiutilities/CertSaver/inc/certsaver.hrh
pkiutilities/CertSaver/loc/certsaver.loc
pkiutilities/CertSaver/src/CertSaverApp.cpp
pkiutilities/CertSaver/src/CertSaverAppUi.cpp
pkiutilities/CertSaver/src/CertSaverContainer.cpp
pkiutilities/CertSaver/src/CertSaverDocument.cpp
pkiutilities/CertSaver/src/CertSaverModel.cpp
pkiutilities/CertSaver/src/CertSaverSyncWrapper.cpp
pkiutilities/CertSaver/src/certparser.cpp
pkiutilities/Certificates/data/addclients.txt
pkiutilities/Certificates/data/certclients.dat
pkiutilities/Certificates/group/bld.inf
pkiutilities/CertmanUi/BMARM/CERTMANUIU.DEF
pkiutilities/CertmanUi/BWINS/CERTMANUIU.DEF
pkiutilities/CertmanUi/BWINSCW/CERTMANUIU.DEF
pkiutilities/CertmanUi/BWINSCW/CERTMANUI_EKA2U.DEF
pkiutilities/CertmanUi/EABI/CertManUiU.DEF
pkiutilities/CertmanUi/EABI/CertManUi_EKA2U.DEF
pkiutilities/CertmanUi/GROUP/CertmanuiPlugin.mmp
pkiutilities/CertmanUi/GROUP/bld.inf
pkiutilities/CertmanUi/INC/CertManUILogger.h
pkiutilities/CertmanUi/INC/Certmanui.h
pkiutilities/CertmanUi/INC/Certmanui.hrh
pkiutilities/CertmanUi/INC/CertmanuiCertificateHelper.h
pkiutilities/CertmanUi/INC/CertmanuiCommon.h
pkiutilities/CertmanUi/INC/CertmanuiKeeper.h
pkiutilities/CertmanUi/INC/CertmanuiPlugin.h
pkiutilities/CertmanUi/INC/CertmanuiPluginContainer.h
pkiutilities/CertmanUi/INC/CertmanuiSyncWrapper.h
pkiutilities/CertmanUi/INC/CertmanuicontainerAuthority.h
pkiutilities/CertmanUi/INC/CertmanuicontainerDevice.h
pkiutilities/CertmanUi/INC/CertmanuicontainerMain.h
pkiutilities/CertmanUi/INC/CertmanuicontainerPersonal.h
pkiutilities/CertmanUi/INC/CertmanuicontainerTrust.h
pkiutilities/CertmanUi/INC/CertmanuicontainerTrustedSite.h
pkiutilities/CertmanUi/INC/Certmanuidialogs.h
pkiutilities/CertmanUi/INC/Certmanuidll.h
pkiutilities/CertmanUi/INC/Certmanuitrustids.h
pkiutilities/CertmanUi/INC/CertmanuiviewAuthority.h
pkiutilities/CertmanUi/INC/CertmanuiviewDevice.h
pkiutilities/CertmanUi/INC/CertmanuiviewMain.h
pkiutilities/CertmanUi/INC/CertmanuiviewPersonal.h
pkiutilities/CertmanUi/INC/CertmanuiviewTrust.h
pkiutilities/CertmanUi/INC/CertmanuiviewTrustedSite.h
pkiutilities/CertmanUi/INC/Certmanuiviewid.h
pkiutilities/CertmanUi/SRC/CertmanuiCertificateHelper.cpp
pkiutilities/CertmanUi/SRC/CertmanuiKeeper.cpp
pkiutilities/CertmanUi/SRC/CertmanuiPlugin.cpp
pkiutilities/CertmanUi/SRC/CertmanuiPluginContainer.cpp
pkiutilities/CertmanUi/SRC/CertmanuiPluginImplementationTable.cpp
pkiutilities/CertmanUi/SRC/CertmanuiSyncWrapper.cpp
pkiutilities/CertmanUi/SRC/CertmanuicontainerAuthority.cpp
pkiutilities/CertmanUi/SRC/CertmanuicontainerDevice.cpp
pkiutilities/CertmanUi/SRC/CertmanuicontainerMain.cpp
pkiutilities/CertmanUi/SRC/CertmanuicontainerPersonal.cpp
pkiutilities/CertmanUi/SRC/CertmanuicontainerTrust.cpp
pkiutilities/CertmanUi/SRC/CertmanuicontainerTrustedSite.cpp
pkiutilities/CertmanUi/SRC/Certmanuidialogs.cpp
pkiutilities/CertmanUi/SRC/CertmanuiviewAuthority.cpp
pkiutilities/CertmanUi/SRC/CertmanuiviewDevice.cpp
pkiutilities/CertmanUi/SRC/CertmanuiviewMain.cpp
pkiutilities/CertmanUi/SRC/CertmanuiviewPersonal.cpp
pkiutilities/CertmanUi/SRC/CertmanuiviewTrust.cpp
pkiutilities/CertmanUi/SRC/CertmanuiviewTrustedSite.cpp
pkiutilities/CertmanUi/SRC/certmanui.cpp
pkiutilities/CertmanUi/data/10008D3D.rss
pkiutilities/CertmanUi/data/certmanui.rss
pkiutilities/CertmanUi/help/data/xhtml.zip
pkiutilities/CertmanUi/help/group/bld.inf
pkiutilities/CertmanUi/help/inc/cm.hlp.hrh
pkiutilities/CertmanUi/help/rom/certmanuihelps_variant.iby
pkiutilities/CertmanUi/loc/certmanui.loc
pkiutilities/DeviceToken/BWINS/DevTokenClientu.def
pkiutilities/DeviceToken/BWINS/DevTokenSharedu.def
pkiutilities/DeviceToken/Data/101FB667.rss
pkiutilities/DeviceToken/Data/101FB669.rss
pkiutilities/DeviceToken/Data/101FB66E.rss
pkiutilities/DeviceToken/EABI/DevTokenClientu.def
pkiutilities/DeviceToken/EABI/DevTokenSharedu.def
pkiutilities/DeviceToken/Group/DevTokenClient.mmp
pkiutilities/DeviceToken/Group/DevTokenDevCertStorePlugin.mmp
pkiutilities/DeviceToken/Group/DevTokenKeyStorePlugin.mmp
pkiutilities/DeviceToken/Group/DevTokenServer.mmp
pkiutilities/DeviceToken/Group/DevTokenShared.mmp
pkiutilities/DeviceToken/Group/DevTokenTruSrvCertStorePlugin.mmp
pkiutilities/DeviceToken/Group/bld.inf
pkiutilities/DeviceToken/Inc/DTClient.h
pkiutilities/DeviceToken/Inc/DevCertCreateKey.h
pkiutilities/DeviceToken/Inc/DevCertKeyDataManager.h
pkiutilities/DeviceToken/Inc/DevCertKeyEncryptor.h
pkiutilities/DeviceToken/Inc/DevCertKeyStore.h
pkiutilities/DeviceToken/Inc/DevCertKeyStoreConduit.h
pkiutilities/DeviceToken/Inc/DevCertKeyStoreServer.h
pkiutilities/DeviceToken/Inc/DevCertKeyStoreSession.h
pkiutilities/DeviceToken/Inc/DevCertKeyStreamUtils.h
pkiutilities/DeviceToken/Inc/DevCertOpenedKeys.h
pkiutilities/DeviceToken/Inc/DevCertOpenedKeysSrv.h
pkiutilities/DeviceToken/Inc/DevToken.h
pkiutilities/DeviceToken/Inc/DevTokenCliServ.h
pkiutilities/DeviceToken/Inc/DevTokenClientSession.h
pkiutilities/DeviceToken/Inc/DevTokenDataTypes.h
pkiutilities/DeviceToken/Inc/DevTokenDataTypes.inl
pkiutilities/DeviceToken/Inc/DevTokenDialog.h
pkiutilities/DeviceToken/Inc/DevTokenImplementationUID.hrh
pkiutilities/DeviceToken/Inc/DevTokenInterfaceFactory.h
pkiutilities/DeviceToken/Inc/DevTokenKeyInfoArray.h
pkiutilities/DeviceToken/Inc/DevTokenMarshaller.h
pkiutilities/DeviceToken/Inc/DevTokenNullStream.h
pkiutilities/DeviceToken/Inc/DevTokenPWManager.h
pkiutilities/DeviceToken/Inc/DevTokenServer.h
pkiutilities/DeviceToken/Inc/DevTokenServerDebug.h
pkiutilities/DeviceToken/Inc/DevTokenServerName.h
pkiutilities/DeviceToken/Inc/DevTokenType.h
pkiutilities/DeviceToken/Inc/DevTokenTypeSession.h
pkiutilities/DeviceToken/Inc/DevTokenTypesEnum.h
pkiutilities/DeviceToken/Inc/DevTokenUtil.h
pkiutilities/DeviceToken/Inc/DevTokenUtils.h
pkiutilities/DeviceToken/Inc/DevandTruSrvCertStore.h
pkiutilities/DeviceToken/Inc/DevandTruSrvCertStoreConduit.h
pkiutilities/DeviceToken/Inc/DevandTruSrvCertStoreEntry.h
pkiutilities/DeviceToken/Inc/DevandTruSrvCertStoreEntryList.h
pkiutilities/DeviceToken/Inc/DevandTruSrvCertStoreServer.h
pkiutilities/DeviceToken/Inc/DevandTruSrvCertStoreSession.h
pkiutilities/DeviceToken/Inc/DevtokenLog.h
pkiutilities/DeviceToken/Inc/SimpleDHKey.h
pkiutilities/DeviceToken/Inc/TrustedSitesConduit.h
pkiutilities/DeviceToken/Inc/TrustedSitesServer.h
pkiutilities/DeviceToken/Inc/TrustedSitesSession.h
pkiutilities/DeviceToken/Inc/TrustedSitesStore.h
pkiutilities/DeviceToken/Src/Certstore/DevECOMPlugin/DevTokenDevCertStorePlugin.cpp
pkiutilities/DeviceToken/Src/Certstore/TruSrvECOMPlugin/DevTokenTruSrvCertStorePlugin.cpp
pkiutilities/DeviceToken/Src/Certstore/client/DevandTruSrvCertStore.cpp
pkiutilities/DeviceToken/Src/Certstore/server/DevandTruSrvCertStoreConduit.cpp
pkiutilities/DeviceToken/Src/Certstore/server/DevandTruSrvCertStoreEntry.cpp
pkiutilities/DeviceToken/Src/Certstore/server/DevandTruSrvCertStoreEntryList.cpp
pkiutilities/DeviceToken/Src/Certstore/server/DevandTruSrvCertStoreServer.cpp
pkiutilities/DeviceToken/Src/Certstore/server/DevandTruSrvCertStoreSession.cpp
pkiutilities/DeviceToken/Src/Generic/Client/DTClient.cpp
pkiutilities/DeviceToken/Src/Generic/Client/DevToken.cpp
pkiutilities/DeviceToken/Src/Generic/Client/DevTokenClientSession.cpp
pkiutilities/DeviceToken/Src/Generic/Client/DevTokenInterfaceFactory.cpp
pkiutilities/DeviceToken/Src/Generic/Client/DevTokenType.cpp
pkiutilities/DeviceToken/Src/Generic/Client/DevTokenTypeSession.cpp
pkiutilities/DeviceToken/Src/Generic/Client/DevTokenUtils.cpp
pkiutilities/DeviceToken/Src/Generic/Common/DevTokenCliServ.cpp
pkiutilities/DeviceToken/Src/Generic/Server/DevTokenDialog.cpp
pkiutilities/DeviceToken/Src/Generic/Server/DevTokenServer.cpp
pkiutilities/DeviceToken/Src/Generic/Server/DevTokenServerDebug.cpp
pkiutilities/DeviceToken/Src/Generic/Server/DevTokenUtil.cpp
pkiutilities/DeviceToken/Src/KeyStore/Client/DevCertKeyStore.cpp
pkiutilities/DeviceToken/Src/KeyStore/Client/DevCertOpenedKeys.cpp
pkiutilities/DeviceToken/Src/KeyStore/EComPlugin/DevTokenKeyStorePlugin.cpp
pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertCreateKey.cpp
pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertKeyDataManager.cpp
pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertKeyEncryptor.cpp
pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertKeyStoreConduit.cpp
pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertKeyStoreServer.cpp
pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertKeyStoreSession.cpp
pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertKeyStreamUtils.cpp
pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertOpenedKeysSrv.cpp
pkiutilities/DeviceToken/Src/KeyStore/Server/DevTokenPWManager.cpp
pkiutilities/DeviceToken/Src/Shared/DevTokenCertInfo.cpp
pkiutilities/DeviceToken/Src/Shared/DevTokenDHParams.cpp
pkiutilities/DeviceToken/Src/Shared/DevTokenDataMarshaller.cpp
pkiutilities/DeviceToken/Src/Shared/DevTokenKeyInfo.cpp
pkiutilities/DeviceToken/Src/Shared/DevTokenNullStream.cpp
pkiutilities/DeviceToken/Src/TruSitesStore/Client/TrustedSitesStore.cpp
pkiutilities/DeviceToken/Src/TruSitesStore/Server/TrustedSitesConduit.cpp
pkiutilities/DeviceToken/Src/TruSitesStore/Server/TrustedSitesServer.cpp
pkiutilities/DeviceToken/Src/TruSitesStore/Server/TrustedSitesSession.cpp
pkiutilities/Include/securityuisvariant.hrh
pkiutilities/PKCS12/CrBer/BMARM/CRBERU.DEF
pkiutilities/PKCS12/CrBer/BWINS/CRBERU.DEF
pkiutilities/PKCS12/CrBer/Inc/crber.h
pkiutilities/PKCS12/CrBer/Inc/crdata.h
pkiutilities/PKCS12/CrBer/Src/Crberset.cpp
pkiutilities/PKCS12/CrBer/Src/crber.cpp
pkiutilities/PKCS12/CrBer/Src/crdata.cpp
pkiutilities/PKCS12/CrBer/bwinscw/crberU.DEF
pkiutilities/PKCS12/CrBer/eabi/crberU.DEF
pkiutilities/PKCS12/CrBer/group/crber.mmp
pkiutilities/PKCS12/CrPkcs12/Inc/CX509CertificateSet.h
pkiutilities/PKCS12/CrPkcs12/Inc/cralginfo.h
pkiutilities/PKCS12/CrPkcs12/Inc/crcrypto.h
pkiutilities/PKCS12/CrPkcs12/Inc/crpkcs12.h
pkiutilities/PKCS12/CrPkcs12/Inc/pkcs12.h
pkiutilities/PKCS12/CrPkcs12/Src/cralginfo.cpp
pkiutilities/PKCS12/CrPkcs12/Src/crcrypto.cpp
pkiutilities/PKCS12/CrPkcs12/Src/crpkcs12.cpp
pkiutilities/PKCS12/CrPkcs12/Src/cx509certificateset.cpp
pkiutilities/PKCS12/CrPkcs12/Src/pkcs12.cpp
pkiutilities/PKCS12/CrPkcs12/bwinscw/CRPKCS12U.DEF
pkiutilities/PKCS12/CrPkcs12/eabi/crpkcs12U.DEF
pkiutilities/PKCS12/CrPkcs12/group/crpkcs12.mmp
pkiutilities/PKCS12/Inc/crdefs.h
pkiutilities/PKCS12/PKCS12Recognizer/data/101F8714.rss
pkiutilities/PKCS12/PKCS12Recognizer/group/PKCS12Recognizer.mmp
pkiutilities/PKCS12/PKCS12Recognizer/inc/PKCS12Recognizer.h
pkiutilities/PKCS12/PKCS12Recognizer/src/PKCS12Recognizer.cpp
pkiutilities/PKCS12/group/bld.inf
pkiutilities/SecModUI/BWINSCW/SecModUI_EKA2U.DEF
pkiutilities/SecModUI/EABI/SecModUI_EKA2U.DEF
pkiutilities/SecModUI/data/101F8668.rss
pkiutilities/SecModUI/data/SecModUI.rss
pkiutilities/SecModUI/group/SecModUIPlugin.mmp
pkiutilities/SecModUI/group/bld.inf
pkiutilities/SecModUI/help/data/xhtml.zip
pkiutilities/SecModUI/help/group/bld.inf
pkiutilities/SecModUI/help/inc/wim.hlp.hrh
pkiutilities/SecModUI/help/rom/secmoduihelps_variant.iby
pkiutilities/SecModUI/inc/SecModUI.h
pkiutilities/SecModUI/inc/SecModUIContainerAccess.h
pkiutilities/SecModUI/inc/SecModUIContainerBase.h
pkiutilities/SecModUI/inc/SecModUIContainerCode.h
pkiutilities/SecModUI/inc/SecModUIContainerMain.h
pkiutilities/SecModUI/inc/SecModUIContainerSignature.h
pkiutilities/SecModUI/inc/SecModUILogger.h
pkiutilities/SecModUI/inc/SecModUIModel.h
pkiutilities/SecModUI/inc/SecModUIPlugin.h
pkiutilities/SecModUI/inc/SecModUIPluginContainer.h
pkiutilities/SecModUI/inc/SecModUISyncWrapper.h
pkiutilities/SecModUI/inc/SecModUIViewAccess.h
pkiutilities/SecModUI/inc/SecModUIViewBase.h
pkiutilities/SecModUI/inc/SecModUIViewCode.h
pkiutilities/SecModUI/inc/SecModUIViewMain.h
pkiutilities/SecModUI/inc/SecModUIViewSignature.h
pkiutilities/SecModUI/inc/secmodui.hrh
pkiutilities/SecModUI/inc/wim.hlp.hrh
pkiutilities/SecModUI/loc/secmodui.loc
pkiutilities/SecModUI/src/SecModUIContainerAccess.cpp
pkiutilities/SecModUI/src/SecModUIContainerBase.cpp
pkiutilities/SecModUI/src/SecModUIContainerCode.cpp
pkiutilities/SecModUI/src/SecModUIContainerMain.cpp
pkiutilities/SecModUI/src/SecModUIContainerSignature.cpp
pkiutilities/SecModUI/src/SecModUIModel.cpp
pkiutilities/SecModUI/src/SecModUIPlugin.cpp
pkiutilities/SecModUI/src/SecModUIPluginContainer.cpp
pkiutilities/SecModUI/src/SecModUIPluginImplementationTable.cpp
pkiutilities/SecModUI/src/SecModUISyncWrapper.cpp
pkiutilities/SecModUI/src/SecModUIViewAccess.cpp
pkiutilities/SecModUI/src/SecModUIViewBase.cpp
pkiutilities/SecModUI/src/SecModUIViewCode.cpp
pkiutilities/SecModUI/src/SecModUIViewMain.cpp
pkiutilities/SecModUI/src/SecModUIViewSignature.cpp
pkiutilities/StubSIS/CenRepStub.sis
pkiutilities/StubSIS/agnmodel.sis
pkiutilities/StubSIS/c32exe.sis
pkiutilities/StubSIS/cntmodel.sis
pkiutilities/StubSIS/esock.sis
pkiutilities/StubSIS/msgs.sis
pkiutilities/StubSIS/swicertstore.sis
pkiutilities/StubSIS/swipolicy.ini
pkiutilities/StubSIS/tlsproviderpolicy.ini
pkiutilities/group/bld.inf
pkiutilities/ocsp/bwins/ocsp_v2U.def
pkiutilities/ocsp/bwins/ocspcommonu.def
pkiutilities/ocsp/bwins/ocsptransport_v2U.def
pkiutilities/ocsp/doxygen_docs/Pkiutilities_OCSP_SoftwareInstall.png
pkiutilities/ocsp/doxygen_docs/Pkiutilities_OCSP_multiservers1.png
pkiutilities/ocsp/doxygen_docs/Pkiutilities_OCSP_multiservers2.png
pkiutilities/ocsp/doxygen_docs/Pkiutilities_OCSP_overview.dox
pkiutilities/ocsp/doxygen_docs/Pkiutilities_OCSP_singleserver.png
pkiutilities/ocsp/doxygen_docs/Thumbs.db
pkiutilities/ocsp/eabi/ocsp_v2U.def
pkiutilities/ocsp/eabi/ocspcommonu.def
pkiutilities/ocsp/eabi/ocsptransport_v2U.def
pkiutilities/ocsp/group/bld.inf
pkiutilities/ocsp/group/ocsp.mmp
pkiutilities/ocsp/group/ocspcommon.mmp
pkiutilities/ocsp/group/securitysrv_ocsp.mrp
pkiutilities/ocsp/inc/certid.h
pkiutilities/ocsp/inc/log.h
pkiutilities/ocsp/inc/ocsp.iby
pkiutilities/ocsp/inc/ocsp_v2.h
pkiutilities/ocsp/inc/ocsppolicy.h
pkiutilities/ocsp/inc/ocsprequestandresponse.h
pkiutilities/ocsp/inc/ocsptests.iby
pkiutilities/ocsp/inc/ocsptransport_v2.h
pkiutilities/ocsp/inc/oids.h
pkiutilities/ocsp/inc/panic.h
pkiutilities/ocsp/inc/requestencoder.h
pkiutilities/ocsp/inc/responsedecoder.h
pkiutilities/ocsp/inc/securitypolicy.h
pkiutilities/ocsp/inc/tcertutils.h
pkiutilities/ocsp/inc/transaction.h
pkiutilities/ocsp/inc/validator.h
pkiutilities/ocsp/src/cadirectauthorisation.cpp
pkiutilities/ocsp/src/certid.cpp
pkiutilities/ocsp/src/client.cpp
pkiutilities/ocsp/src/delegateauthorisation.cpp
pkiutilities/ocsp/src/directauthorisation.cpp
pkiutilities/ocsp/src/ocsppolicy.cpp
pkiutilities/ocsp/src/ocsputils.cpp
pkiutilities/ocsp/src/panic.cpp
pkiutilities/ocsp/src/parameters.cpp
pkiutilities/ocsp/src/request.cpp
pkiutilities/ocsp/src/requestencoder.cpp
pkiutilities/ocsp/src/response.cpp
pkiutilities/ocsp/src/responsecertinfo.cpp
pkiutilities/ocsp/src/responsedecoder.cpp
pkiutilities/ocsp/src/transaction.cpp
pkiutilities/ocsp/src/validator.cpp
pkiutilities/ocsp/test/TEFparser.cpp
pkiutilities/ocsp/test/TEFparser.h
pkiutilities/ocsp/test/command.cpp
pkiutilities/ocsp/test/command.h
pkiutilities/ocsp/test/comms.cpp
pkiutilities/ocsp/test/comms.h
pkiutilities/ocsp/test/engine.cpp
pkiutilities/ocsp/test/engine.h
pkiutilities/ocsp/test/logger.cpp
pkiutilities/ocsp/test/logger.h
pkiutilities/ocsp/test/main.cpp
pkiutilities/ocsp/test/main.h
pkiutilities/ocsp/test/ocspsupport.h
pkiutilities/ocsp/test/ocspsupporttransport.h
pkiutilities/ocsp/test/panic.cpp
pkiutilities/ocsp/test/panic.h
pkiutilities/ocsp/test/readme.txt
pkiutilities/ocsp/test/requestlogger.cpp
pkiutilities/ocsp/test/requestlogger.h
pkiutilities/ocsp/test/requests/openssl/request01.dat
pkiutilities/ocsp/test/requests/openssl/request02.dat
pkiutilities/ocsp/test/requests/openssl/request03.dat
pkiutilities/ocsp/test/requests/openssl/request04.dat
pkiutilities/ocsp/test/requests/openssl/request05.dat
pkiutilities/ocsp/test/requests/openssl/request06.dat
pkiutilities/ocsp/test/requests/openssl/request07.dat
pkiutilities/ocsp/test/requests/openssl/request08.dat
pkiutilities/ocsp/test/requests/openssl/request09.dat
pkiutilities/ocsp/test/requests/openssl/request10.dat
pkiutilities/ocsp/test/requests/openssl/request11.dat
pkiutilities/ocsp/test/requests/openssl/request12.dat
pkiutilities/ocsp/test/resign/README.TXT
pkiutilities/ocsp/test/resign/main.cpp
pkiutilities/ocsp/test/resign/resign.cpp
pkiutilities/ocsp/test/resign/resign.h
pkiutilities/ocsp/test/resign/resign.mmp
pkiutilities/ocsp/test/responses/Error_00_Single_R5.rsp
pkiutilities/ocsp/test/responses/Error_01_Double_R5.rsp
pkiutilities/ocsp/test/responses/README.TXT
pkiutilities/ocsp/test/responses/XCert_00_Good_RSA_XCert.rsp
pkiutilities/ocsp/test/responses/XCert_01_Revoked_RSA_XCert.rsp
pkiutilities/ocsp/test/responses/XCert_02_Suspended_RSA_XCert.rsp
pkiutilities/ocsp/test/responses/XCert_03_Unknown_RSA_XCert.rsp
pkiutilities/ocsp/test/responses/XCert_04_Good_DSA_XCert.rsp
pkiutilities/ocsp/test/responses/XCert_05_Revoked_DSA_XCert.rsp
pkiutilities/ocsp/test/responses/XCert_06_Suspended_DSA_XCert.rsp
pkiutilities/ocsp/test/responses/XCert_07_Unknown_DSA_XCert.rsp
pkiutilities/ocsp/test/responses/XCert_08_All_RSA_XCert.rsp
pkiutilities/ocsp/test/responses/XCert_09_All_DSA_XCert.rsp
pkiutilities/ocsp/test/responses/XCert_10_Expired_Subject_and_Issuer.rsp
pkiutilities/ocsp/test/responses/XCert_11_Expired_Signing.rsp
pkiutilities/ocsp/test/responses/XCert_12_Expired_Subject.rsp
pkiutilities/ocsp/test/responses/XCert_14_Expired_subject_valid_time.rsp
pkiutilities/ocsp/test/responses/XCert_15_Expired_unspecified.rsp
pkiutilities/ocsp/test/responses/XCert_16_ThisUpdateTooEarly.rsp
pkiutilities/ocsp/test/responses/XCert_20_Nonce_Off.rsp
pkiutilities/ocsp/test/responses/XCert_22_BadSig_DSA_XCert.rsp
pkiutilities/ocsp/test/responses/XCert_23_ResultCombination1.rsp
pkiutilities/ocsp/test/responses/XCert_24_ResultCombination2.rsp
pkiutilities/ocsp/test/responses/XCert_25_ResultCombination3.rsp
pkiutilities/ocsp/test/responses/XCert_26_ResultCombination4.rsp
pkiutilities/ocsp/test/responses/ca_1ext_usage_not_ocspsigning_resp.dat
pkiutilities/ocsp/test/responses/ca_2ext_usage_not_ocspsigning_resp.dat
pkiutilities/ocsp/test/responses/ca_2ext_usage_ocspsigning_bad_name_resp.dat
pkiutilities/ocsp/test/responses/ca_2ext_usage_ocspsigning_bad_sign_resp.dat
pkiutilities/ocsp/test/responses/ca_2ext_usage_ocspsigning_resp.dat
pkiutilities/ocsp/test/responses/ca_delg_wrong_key.dat
pkiutilities/ocsp/test/responses/ca_direct_good_wrong_key.dat
pkiutilities/ocsp/test/responses/ca_direct_multi_cert_inc_right.dat
pkiutilities/ocsp/test/responses/ca_direct_multi_cert_no_right.dat
pkiutilities/ocsp/test/responses/ca_direct_revoked.dat
pkiutilities/ocsp/test/responses/ca_direct_wrong_cert.dat
pkiutilities/ocsp/test/responses/ca_direct_wrong_resp_name.dat
pkiutilities/ocsp/test/responses/ca_no_ext_usage_resp.dat
pkiutilities/ocsp/test/responses/multi_cert_resp.dat
pkiutilities/ocsp/test/responses/multiple_response.dat
pkiutilities/ocsp/test/responses/no_cert_resp.dat
pkiutilities/ocsp/test/responses/no_certresp_signedby_delegate.dat
pkiutilities/ocsp/test/responses/openssl/no_aia_no_ocspext.dat
pkiutilities/ocsp/test/responses/openssl/response01.dat
pkiutilities/ocsp/test/responses/openssl/response02.dat
pkiutilities/ocsp/test/responses/openssl/response03.dat
pkiutilities/ocsp/test/responses/openssl/response04.dat
pkiutilities/ocsp/test/responses/openssl/response05.dat
pkiutilities/ocsp/test/responses/openssl/response06.dat
pkiutilities/ocsp/test/responses/openssl/response07.dat
pkiutilities/ocsp/test/responses/openssl/response08.dat
pkiutilities/ocsp/test/responses/openssl/response09.dat
pkiutilities/ocsp/test/responses/openssl/response10.dat
pkiutilities/ocsp/test/responses/openssl/response11.dat
pkiutilities/ocsp/test/responses/openssl/response12.dat
pkiutilities/ocsp/test/responses/response.000
pkiutilities/ocsp/test/responses/response.001
pkiutilities/ocsp/test/responses/response.002
pkiutilities/ocsp/test/responses/response.003
pkiutilities/ocsp/test/responses/response.004
pkiutilities/ocsp/test/responses/response.005
pkiutilities/ocsp/test/responses/response.006
pkiutilities/ocsp/test/responses/response.007
pkiutilities/ocsp/test/responses/response.008
pkiutilities/ocsp/test/responses/response.009
pkiutilities/ocsp/test/responses/response.010
pkiutilities/ocsp/test/responses/response.011
pkiutilities/ocsp/test/responses/response.012
pkiutilities/ocsp/test/responses/response.013
pkiutilities/ocsp/test/responses/response.014
pkiutilities/ocsp/test/responses/response.015
pkiutilities/ocsp/test/responses/response.016
pkiutilities/ocsp/test/responses/response.018
pkiutilities/ocsp/test/responses/response.019
pkiutilities/ocsp/test/responses/response.020
pkiutilities/ocsp/test/responses/response.021
pkiutilities/ocsp/test/responses/response.022
pkiutilities/ocsp/test/responses/response.023
pkiutilities/ocsp/test/responses/response.024
pkiutilities/ocsp/test/responses/response.025
pkiutilities/ocsp/test/responses/response.026
pkiutilities/ocsp/test/responses/response.027
pkiutilities/ocsp/test/responses/response.028
pkiutilities/ocsp/test/responses/response.029
pkiutilities/ocsp/test/responses/response.030
pkiutilities/ocsp/test/responses/response.031
pkiutilities/ocsp/test/responses/response.032
pkiutilities/ocsp/test/responses/response.033
pkiutilities/ocsp/test/responses/response.034
pkiutilities/ocsp/test/responses/response.035
pkiutilities/ocsp/test/responses/response.n1
pkiutilities/ocsp/test/responses/response.n2
pkiutilities/ocsp/test/responses/vs_explicit_version.dat
pkiutilities/ocsp/test/responses/wrong_ca_cert_resp.dat
pkiutilities/ocsp/test/result.cpp
pkiutilities/ocsp/test/result.h
pkiutilities/ocsp/test/script.cpp
pkiutilities/ocsp/test/script.h
pkiutilities/ocsp/test/scripts/2002b28b-new.txt
pkiutilities/ocsp/test/scripts/CertCo.txt
pkiutilities/ocsp/test/scripts/DefaultPolicy.ini
pkiutilities/ocsp/test/scripts/DefaultPolicy.script
pkiutilities/ocsp/test/scripts/Error.ini
pkiutilities/ocsp/test/scripts/Error.script
pkiutilities/ocsp/test/scripts/NewPolicy.script
pkiutilities/ocsp/test/scripts/NewPolicyTEF.ini
pkiutilities/ocsp/test/scripts/OpenSSL-local.ini
pkiutilities/ocsp/test/scripts/OpenSSL-local.script
pkiutilities/ocsp/test/scripts/OpenSSL-logging.txt
pkiutilities/ocsp/test/scripts/SmartTrust.txt
pkiutilities/ocsp/test/scripts/Valicert.txt
pkiutilities/ocsp/test/scripts/XCert-local.ini
pkiutilities/ocsp/test/scripts/XCert-local.script
pkiutilities/ocsp/test/scripts/XCert-logging.txt
pkiutilities/ocsp/test/scripts/XCert-oom.ini
pkiutilities/ocsp/test/scripts/XCert-oom.script
pkiutilities/ocsp/test/scripts/XCert.txt
pkiutilities/ocsp/test/scripts/error-logging.txt
pkiutilities/ocsp/test/scripts/httpinterface.ini
pkiutilities/ocsp/test/scripts/httpinterface.script
pkiutilities/ocsp/test/scripts/openssl-ocspsupport-oom.txt
pkiutilities/ocsp/test/scripts/openssl-ocspsupport.txt
pkiutilities/ocsp/test/scripts/openssl.ini
pkiutilities/ocsp/test/scripts/openssl.script
pkiutilities/ocsp/test/scripts/setupOcspPolicy.bat
pkiutilities/ocsp/test/scripts/setupOcspPolicy_urel.bat
pkiutilities/ocsp/test/server/OpenSSL/README
pkiutilities/ocsp/test/server/OpenSSL/generateCerts.sh
pkiutilities/ocsp/test/server/OpenSSL/openssl.config
pkiutilities/ocsp/test/server/OpenSSL/runOCSPResponder.sh
pkiutilities/ocsp/test/t_input.h
pkiutilities/ocsp/test/t_output.h
pkiutilities/ocsp/test/tcertutils.h
pkiutilities/ocsp/test/testfilterparameters.h
pkiutilities/ocsp/test/tocsp.mmp
pkiutilities/ocsp/test/tocsphttpfilter/A0004F14.rls
pkiutilities/ocsp/test/tocsphttpfilter/A0004F14.rss
pkiutilities/ocsp/test/tocsphttpfilter/ocsphttpfilter.cpp
pkiutilities/ocsp/test/tocsphttpfilter/ocsphttpfilter.h
pkiutilities/ocsp/test/tocsphttpfilter/ocsphttpfiltermain.cpp
pkiutilities/ocsp/test/tocsphttpfilter/tocsphttpfilter.mmp
pkiutilities/ocsp/test/transport.cpp
pkiutilities/ocsp/test/transport.h
pkiutilities/ocsp/transport/ocsptransport.mmp
pkiutilities/ocsp/transport/panic.cpp
pkiutilities/ocsp/transport/panic.h
pkiutilities/ocsp/transport/transportdefault.cpp
pkiutilities/ocsp/transport/transporthttp.cpp
pkiutilities/rom/CTSecurityDialogs.iby
pkiutilities/rom/CTSecurityDialogs_resources.iby
pkiutilities/rom/CertSaver.iby
pkiutilities/rom/CertSaver_resources.iby
pkiutilities/rom/DevToken.iby
pkiutilities/rom/SecModUI.iby
pkiutilities/rom/SecModUI_resources.iby
pkiutilities/rom/StubSIS.iby
pkiutilities/rom/certman.iby
pkiutilities/rom/certmanui.iby
pkiutilities/rom/certmanui_resources.iby
pkiutilities/rom/pkcs12.iby
pkiutilities/rom/x509certnameparser.iby
pkiutilities/x509certnameparser/BMARM/X509CERTNAMEPARSERU.DEF
pkiutilities/x509certnameparser/BWINS/X509CERTNAMEPARSERU.DEF
pkiutilities/x509certnameparser/BWINSCW/X509CERTNAMEPARSERU.DEF
pkiutilities/x509certnameparser/EABI/X509CertNameParserU.DEF
pkiutilities/x509certnameparser/group/X509CertNameParser.mmp
pkiutilities/x509certnameparser/group/bld.inf
pkiutilities/x509certnameparser/src/X509CertNameParser.cpp
remotelock/CenRep/RemoteLockPrivateCRKeys.h
remotelock/CenRep/keys_remotelock.xls
remotelock/Data/RemoteLock.rss
remotelock/Group/bld.inf
remotelock/Inc/RemoteLockTrace.h
remotelock/RemoteLockEngine/Group/RemoteLockEngine.mmp
remotelock/RemoteLockEngine/Inc/RLLockObserver.h
remotelock/RemoteLockEngine/Inc/RemoteLock.h
remotelock/RemoteLockEngine/Src/RLLockObserver.cpp
remotelock/RemoteLockEngine/Src/RemoteLock.cpp
remotelock/RemotelockSettings/BWINS/RLockSettingsU.DEF
remotelock/RemotelockSettings/EABI/RLockSettingsU.DEF
remotelock/RemotelockSettings/Group/RemoteLockSettings.mmp
remotelock/RemotelockSettings/Src/RemoteLockSettings.cpp
remotelock/Rom/RemoteLock.iby
remotelock/Rom/RemoteLockResources.iby
remotelock/conf/remotelock.confml
remotelock/conf/remotelock_101FB654.crml
remotelock/loc/remotelock.loc
secsrv_plat/cms_api/cms_api.metaxml
secsrv_plat/cms_api/group/bld.inf
secsrv_plat/cms_api/inc/CCMSAttribute.h
secsrv_plat/cms_api/inc/CCMSAuthenticatedData.h
secsrv_plat/cms_api/inc/CCMSCertificateChoices.h
secsrv_plat/cms_api/inc/CCMSContentInfo.h
secsrv_plat/cms_api/inc/CCMSEncapsulatedContentInfo.h
secsrv_plat/cms_api/inc/CCMSIssuerAndSerialNumber.h
secsrv_plat/cms_api/inc/CCMSKEKRecipientInfo.h
secsrv_plat/cms_api/inc/CCMSKeyAgreeRecipientInfo.h
secsrv_plat/cms_api/inc/CCMSKeyIdentifier.h
secsrv_plat/cms_api/inc/CCMSKeyTransRecipientInfo.h
secsrv_plat/cms_api/inc/CCMSOriginatorIdentifierOrKey.h
secsrv_plat/cms_api/inc/CCMSOriginatorInfo.h
secsrv_plat/cms_api/inc/CCMSOriginatorPublicKey.h
secsrv_plat/cms_api/inc/CCMSRecipientEncryptedKey.h
secsrv_plat/cms_api/inc/CCMSRecipientInfo.h
secsrv_plat/cms_api/inc/CCMSSequence.h
secsrv_plat/cms_api/inc/CCMSSignedData.h
secsrv_plat/cms_api/inc/CCMSSignerInfo.h
secsrv_plat/cms_api/inc/CCMSX509AlgorithmIdentifier.h
secsrv_plat/cms_api/inc/CCMSX509AttributeCertificate.h
secsrv_plat/cms_api/inc/CCMSX509AttributeCertificateInfo.h
secsrv_plat/cms_api/inc/CCMSX509Certificate.h
secsrv_plat/cms_api/inc/CCMSX509CertificateList.h
secsrv_plat/cms_api/inc/CCMSX509GeneralName.h
secsrv_plat/cms_api/inc/CCMSX509GeneralNames.h
secsrv_plat/cms_api/inc/CCMSX509IssuerSerial.h
secsrv_plat/cms_api/inc/CCMSX509Signed.h
secsrv_plat/cms_api/inc/CCMSX509SubjectPublicKeyInfo.h
secsrv_plat/cms_api/inc/CCMSX509Validity.h
secsrv_plat/cms_api/inc/MCMSModule.h
secsrv_plat/devencadaptation_api/group/bld.inf
secsrv_plat/devencadaptation_api/inc/DevEncEngineBase.h
secsrv_plat/devencadaptation_api/inc/DevEncEngineConstants.h
secsrv_plat/devenccommonutils_api/group/bld.inf
secsrv_plat/devenccommonutils_api/inc/DevEncConstants.h
secsrv_plat/devenccommonutils_api/inc/DevEncDiskStatusObserver.h
secsrv_plat/devenccommonutils_api/inc/DevEncDiskUtils.h
secsrv_plat/devenccommonutils_api/inc/DevEncExternalCRKeys.h
secsrv_plat/devenccommonutils_api/inc/DevEncKeyUtils.h
secsrv_plat/devenccommonutils_api/inc/DevEncMmcObserver.h
secsrv_plat/devenccommonutils_api/inc/DevEncProtectedPSKey.h
secsrv_plat/devenccommonutils_api/inc/DevEncSession.h
secsrv_plat/devenccommonutils_api/inc/DevEncSessionBase.h
secsrv_plat/devenccommonutils_api/inc/MmcInfo.h
secsrv_plat/device_key_store_encryption_plugin_api/device_key_store_encryption_plugin_api.metaxml
secsrv_plat/device_key_store_encryption_plugin_api/group/bld.inf
secsrv_plat/device_key_store_encryption_plugin_api/inc/KeyEncryptor.h
secsrv_plat/devicelock_access_api/group/ABLD.BAT
secsrv_plat/devicelock_access_api/group/bld.inf
secsrv_plat/devicelock_access_api/inc/devicelockaccessapi.h
secsrv_plat/gba_api/gba_api.metaxml
secsrv_plat/gba_api/group/bld.inf
secsrv_plat/gba_api/inc/GbaUtility.h
secsrv_plat/group/bld.inf
secsrv_plat/java_utils_api/group/bld.inf
secsrv_plat/java_utils_api/inc/JavaUtils.h
secsrv_plat/java_utils_api/java_utils_api.metaxml
secsrv_plat/keyguard_access_api/group/ABLD.BAT
secsrv_plat/keyguard_access_api/group/bld.inf
secsrv_plat/keyguard_access_api/inc/keyguardaccessapi.h
secsrv_plat/keyguard_configuration_api/group/bld.inf
secsrv_plat/keyguard_configuration_api/inc/LockDomainCRKeys.h
secsrv_plat/keyguard_configuration_api/keyguard_configuration_api.metaxml
secsrv_plat/keylock_policy_api/group/bld.inf
secsrv_plat/keylock_policy_api/inc/keylockpolicyapi.h
secsrv_plat/keylock_policy_api/keylock_policy_api.metaxml
secsrv_plat/lockapp_server_api/group/ABLD.BAT
secsrv_plat/lockapp_server_api/group/bld.inf
secsrv_plat/lockapp_server_api/inc/lockappclientserver.h
secsrv_plat/pkcs12_parser_api/group/bld.inf
secsrv_plat/pkcs12_parser_api/inc/mpkcs12.h
secsrv_plat/pkcs12_parser_api/pkcs12_parser_api.metaxml
secsrv_plat/pkidialog_api/group/bld.inf
secsrv_plat/pkidialog_api/inc/PKIDlg.h
secsrv_plat/pkidialog_api/pkidialog_api.metaxml
secsrv_plat/provisioning_api/group/bld.inf
secsrv_plat/provisioning_api/inc/ProvSC.h
secsrv_plat/provisioning_api/provisioning_api.metaxml
secsrv_plat/remote_lock_api/group/bld.inf
secsrv_plat/remote_lock_api/inc/RemoteLockSettings.h
secsrv_plat/remote_lock_api/remote_lock_api.metaxml
secsrv_plat/security_code_ui_api/group/bld.inf
secsrv_plat/security_code_ui_api/inc/SecUi.h
secsrv_plat/security_code_ui_api/inc/SecUi.hrh
secsrv_plat/security_code_ui_api/inc/SecUiCodeQueryDialog.h
secsrv_plat/security_code_ui_api/inc/SecUiManualSecuritySettings.h
secsrv_plat/security_code_ui_api/inc/SecUiSecurityHandler.h
secsrv_plat/security_code_ui_api/inc/SecUiSecuritySettings.h
secsrv_plat/security_code_ui_api/security_code_ui_api.metaxml
secsrv_plat/wim_cert_api/group/bld.inf
secsrv_plat/wim_cert_api/inc/WimCert.h
secsrv_plat/wim_cert_api/wim_cert_api.metaxml
secsrv_plat/x509certnameparser_api/group/bld.inf
secsrv_plat/x509certnameparser_api/inc/x509CertNameParser.h
secsrv_plat/x509certnameparser_api/x509certnameparser_api.metaxml
securitydialogs/Autolock/CenRep/AutolockPrivateCRKeys.h
securitydialogs/Autolock/CenRep/keys_autolock.xls
securitydialogs/Autolock/CenRep/keys_lock.xls
securitydialogs/Autolock/PubSub/SecurityUIsPrivatePSKeys.h
securitydialogs/Autolock/aif/Autolockaif.rss
securitydialogs/Autolock/conf/autolock.confml
securitydialogs/Autolock/conf/autolock_102824AE.crml
securitydialogs/Autolock/conf/lock.confml
securitydialogs/Autolock/conf/lock_10283322.crml
securitydialogs/Autolock/data/Autolock.rss
securitydialogs/Autolock/data/Autolock_reg.rss
securitydialogs/Autolock/group/Autolock.mmp
securitydialogs/Autolock/group/Autolock_Icons_dc.mk
securitydialogs/Autolock/group/bld.inf
securitydialogs/Autolock/inc/AutoKeyguardCenRepI.h
securitydialogs/Autolock/inc/AutoKeyguardObserver.h
securitydialogs/Autolock/inc/AutoLockCenRepI.h
securitydialogs/Autolock/inc/AutoLockLockObserverPS.h
securitydialogs/Autolock/inc/AutoLockModelPS.h
securitydialogs/Autolock/inc/AutoLockValueObserverPS.h
securitydialogs/Autolock/inc/AutolockApp.h
securitydialogs/Autolock/inc/AutolockAppUiPS.h
securitydialogs/Autolock/inc/AutolockContainer.h
securitydialogs/Autolock/inc/AutolockDocument.h
securitydialogs/Autolock/inc/AutolockFpsStatusObserver.h
securitydialogs/Autolock/inc/AutolockGripStatusObserver.h
securitydialogs/Autolock/inc/AutolockView.h
securitydialogs/Autolock/inc/AutolockWait.h
securitydialogs/Autolock/inc/autolock.hrh
securitydialogs/Autolock/loc/autolock.loc
securitydialogs/Autolock/rom/Autolock.iby
securitydialogs/Autolock/rom/AutolockResources.iby
securitydialogs/Autolock/src/AutoKeyGuardCenRepI.cpp
securitydialogs/Autolock/src/AutoKeyguardObserver.cpp
securitydialogs/Autolock/src/AutoLockCenRepI.cpp
securitydialogs/Autolock/src/AutoLockLockObserver.cpp
securitydialogs/Autolock/src/AutoLockModel.cpp
securitydialogs/Autolock/src/AutoLockValueObserver.cpp
securitydialogs/Autolock/src/AutoLockView.cpp
securitydialogs/Autolock/src/AutolockApp.cpp
securitydialogs/Autolock/src/AutolockAppUi.cpp
securitydialogs/Autolock/src/AutolockContainer.cpp
securitydialogs/Autolock/src/AutolockDocument.cpp
securitydialogs/Autolock/src/AutolockFpsStatusObserver.cpp
securitydialogs/Autolock/src/AutolockGripStatusObserver.cpp
securitydialogs/Autolock/src/AutolockWait.cpp
securitydialogs/SecUi/BWinsCw/SECUI_EKA2U.def
securitydialogs/SecUi/Bmarm/Secuiu.def
securitydialogs/SecUi/Bwins/Secuiu.def
securitydialogs/SecUi/Data/SecUi.rss
securitydialogs/SecUi/EABI/Secuiu.def
securitydialogs/SecUi/GSSimSecPlugin/Data/10207438.rss
securitydialogs/SecUi/GSSimSecPlugin/Data/GSSimSecPluginRsc.rss
securitydialogs/SecUi/GSSimSecPlugin/GSSimSecPlugin.mmp
securitydialogs/SecUi/GSSimSecPlugin/Inc/GSPubSubsListener.h
securitydialogs/SecUi/GSSimSecPlugin/Inc/GSSimSecPlugin.h
securitydialogs/SecUi/GSSimSecPlugin/Inc/GSSimSecPlugin.hrh
securitydialogs/SecUi/GSSimSecPlugin/Inc/GSSimSecPlugin.rh
securitydialogs/SecUi/GSSimSecPlugin/Inc/GSSimSecPluginContainer.h
securitydialogs/SecUi/GSSimSecPlugin/Inc/GSSimSecPluginModel.h
securitydialogs/SecUi/GSSimSecPlugin/Inc/MGSSettingPSObserver.h
securitydialogs/SecUi/GSSimSecPlugin/Src/GSPubSubsListener.cpp
securitydialogs/SecUi/GSSimSecPlugin/Src/GSSimSecPlugin.cpp
securitydialogs/SecUi/GSSimSecPlugin/Src/GSSimSecPluginContainer.cpp
securitydialogs/SecUi/GSSimSecPlugin/Src/GSSimSecPluginImplementationTable.cpp
securitydialogs/SecUi/GSSimSecPlugin/Src/GSSimSecPluginModel.cpp
securitydialogs/SecUi/GSSimSecPlugin/loc/gssecurity.loc
securitydialogs/SecUi/Inc/SecUiAutoLockSettingPage.h
securitydialogs/SecUi/Inc/SecUiCodeQueryControl.h
securitydialogs/SecUi/Inc/SecUiLockObserver.h
securitydialogs/SecUi/Inc/SecUiObsStartter.h
securitydialogs/SecUi/Inc/SecUiRemoteLockSettingPage.h
securitydialogs/SecUi/Inc/SecUiSystemLock.h
securitydialogs/SecUi/Inc/SecUiWait.h
securitydialogs/SecUi/Src/SecUi.cpp
securitydialogs/SecUi/Src/SecUiAutoLockSettingPage.cpp
securitydialogs/SecUi/Src/SecUiCodeQueryControl.cpp
securitydialogs/SecUi/Src/SecUiCodeQueryDialog.cpp
securitydialogs/SecUi/Src/SecUiLockObserver.cpp
securitydialogs/SecUi/Src/SecUiManualSecuritySettings.cpp
securitydialogs/SecUi/Src/SecUiObsStartter.cpp
securitydialogs/SecUi/Src/SecUiRemoteLockSettingPage.cpp
securitydialogs/SecUi/Src/SecUiSecurityHandler.cpp
securitydialogs/SecUi/Src/SecUiSecuritySettings.cpp
securitydialogs/SecUi/Src/SecUiSystemLock.cpp
securitydialogs/SecUi/Src/SecUiWait.cpp
securitydialogs/SecUi/group/SecUi.mmp
securitydialogs/SecUi/group/bld.inf
securitydialogs/SecUi/loc/SecUi.loc
securitydialogs/SecUi/rom/GSSimSecPlugin.iby
securitydialogs/SecUi/rom/GSSimSecPluginResources.iby
securitydialogs/SecUi/rom/SecUi.iby
securitydialogs/SecUi/rom/SecUiResources.iby
securitydialogs/Securitynotifier/BWinsCw/SecurityNotifierU.def
securitydialogs/Securitynotifier/BWinsCw/SecurityNotifierUU.def
securitydialogs/Securitynotifier/Bmarm/SECURITYNOTIFIERU.DEF
securitydialogs/Securitynotifier/Bwins/SECURITYNOTIFIERU.DEF
securitydialogs/Securitynotifier/EABI/SecurityNotifierU.DEF
securitydialogs/Securitynotifier/Group/102071FA.rss
securitydialogs/Securitynotifier/Group/Securitynotifier.mmp
securitydialogs/Securitynotifier/Group/Securitynotifierappserver_reg.rss
securitydialogs/Securitynotifier/Group/Securitynotifierwrapper.mmp
securitydialogs/Securitynotifier/Group/bld.inf
securitydialogs/Securitynotifier/Inc/SecurityNotifier.h
securitydialogs/Securitynotifier/Src/SecurityNotifier.cpp
securitydialogs/Securitynotifier/Src/Securitynotifierwrapper.cpp
securitydialogs/Securityobserver/Bmarm/SECURITYOBSERVERU.DEF
securitydialogs/Securityobserver/Bwins/SECURITYOBSERVERU.DEF
securitydialogs/Securityobserver/EABI/SecurityObserverU.DEF
securitydialogs/Securityobserver/Group/SecurityObserver.mmp
securitydialogs/Securityobserver/Group/bld.inf
securitydialogs/Securityobserver/Inc/SecObsNotify.h
securitydialogs/Securityobserver/Inc/SecPhoneObserver.h
securitydialogs/Securityobserver/Inc/SecSimLockObserver.h
securitydialogs/Securityobserver/Inc/SecurityObserver.h
securitydialogs/Securityobserver/Inc/SecurityObserver.hrh
securitydialogs/Securityobserver/Src/SecObsNotify.cpp
securitydialogs/Securityobserver/Src/SecPhoneObserver.cpp
securitydialogs/Securityobserver/Src/SecSimLockObserver.cpp
securitydialogs/Securityobserver/Src/SecurityObserver.cpp
securitydialogs/group/bld.inf
securitydialogs/keylockpolicyapi/bwins/keylockpolicyapiu.def
securitydialogs/keylockpolicyapi/eabi/keylockpolicyapiu.def
securitydialogs/keylockpolicyapi/group/bld.inf
securitydialogs/keylockpolicyapi/group/keylockpolicyapi.mmp
securitydialogs/keylockpolicyapi/inc/gendebug.h
securitydialogs/keylockpolicyapi/inc/keylockpolicyapiimpl.h
securitydialogs/keylockpolicyapi/rom/keylockpolicyapi.iby
securitydialogs/keylockpolicyapi/src/keylockpolicyapi.cpp
securitydialogs/keylockpolicyapi/src/keylockpolicyapiimpl.cpp
securitydialogs/lockapp/cenrep/AutolockPrivateCRKeys.h
securitydialogs/lockapp/data/lockapp.rss
securitydialogs/lockapp/data/lockapp_reg.rss
securitydialogs/lockapp/group/ABLD.BAT
securitydialogs/lockapp/group/bld.inf
securitydialogs/lockapp/group/lockapp.mmp
securitydialogs/lockapp/group/lockapp_icons_dc.mk
securitydialogs/lockapp/inc/lockapp.hrh
securitydialogs/lockapp/inc/lockappapplication.h
securitydialogs/lockapp/inc/lockappappui.h
securitydialogs/lockapp/inc/lockappbasecontrol.h
securitydialogs/lockapp/inc/lockappcenrepobserver.h
securitydialogs/lockapp/inc/lockappdevicelockcontainer.h
securitydialogs/lockapp/inc/lockappdevicelockcontrol.h
securitydialogs/lockapp/inc/lockappdocument.h
securitydialogs/lockapp/inc/lockappecsdetector.h
securitydialogs/lockapp/inc/lockappecsnote.h
securitydialogs/lockapp/inc/lockappidlecontrol.h
securitydialogs/lockapp/inc/lockappkeycapturecontroller.h
securitydialogs/lockapp/inc/lockappkeyguardcontrol.h
securitydialogs/lockapp/inc/lockappkeypattern.h
securitydialogs/lockapp/inc/lockapplockednote.h
securitydialogs/lockapp/inc/lockappobserverinterface.h
securitydialogs/lockapp/inc/lockappobserverlist.h
securitydialogs/lockapp/inc/lockapppubsubobserver.h
securitydialogs/lockapp/inc/lockappserver.h
securitydialogs/lockapp/inc/lockappsession.h
securitydialogs/lockapp/inc/lockappsleepingnote.h
securitydialogs/lockapp/inc/lockappstatecontrol.h
securitydialogs/lockapp/inc/lockappstatecontrolinterface.h
securitydialogs/lockapp/inc/lockappstateobserver.h
securitydialogs/lockapp/inc/lockappstatepublisher.h
securitydialogs/lockapp/inc/lockapptrace.h
securitydialogs/lockapp/inc/lockapptraceconfiguration.hrh
securitydialogs/lockapp/inc/lockapputils.h
securitydialogs/lockapp/inc/lockappwait.h
securitydialogs/lockapp/loc/lockapp.loc
securitydialogs/lockapp/pubsub/SecurityUIsPrivatePSKeys.h
securitydialogs/lockapp/rom/lockapp.iby
securitydialogs/lockapp/rom/lockappresources.iby
securitydialogs/lockapp/sis/lockapp.pkg
securitydialogs/lockapp/sis/lockapp_stub.sis
securitydialogs/lockapp/sis/make_stubsis.bat
securitydialogs/lockapp/sis/rd-key.pem
securitydialogs/lockapp/sis/rd.cer
securitydialogs/lockapp/src/lockappapplication.cpp
securitydialogs/lockapp/src/lockappappui.cpp
securitydialogs/lockapp/src/lockappbasecontrol.cpp
securitydialogs/lockapp/src/lockappcenrepobserver.cpp
securitydialogs/lockapp/src/lockappdevicelockcontainer.cpp
securitydialogs/lockapp/src/lockappdevicelockcontrol.cpp
securitydialogs/lockapp/src/lockappdocument.cpp
securitydialogs/lockapp/src/lockappecsdetector.cpp
securitydialogs/lockapp/src/lockappecsnote.cpp
securitydialogs/lockapp/src/lockappidlecontrol.cpp
securitydialogs/lockapp/src/lockappkeycapturecontroller.cpp
securitydialogs/lockapp/src/lockappkeyguardcontrol.cpp
securitydialogs/lockapp/src/lockappkeypattern.cpp
securitydialogs/lockapp/src/lockapplockednote.cpp
securitydialogs/lockapp/src/lockappobserverlist.cpp
securitydialogs/lockapp/src/lockapppubsubobserver.cpp
securitydialogs/lockapp/src/lockappserver.cpp
securitydialogs/lockapp/src/lockappsession.cpp
securitydialogs/lockapp/src/lockappsleepingnote.cpp
securitydialogs/lockapp/src/lockappstatecontrol.cpp
securitydialogs/lockapp/src/lockappstatepublisher.cpp
securitydialogs/lockapp/src/lockapputils.cpp
securitydialogs/lockapp/src/lockappwait.cpp
securitydialogs/lockclient/bwins/lockclientu.def
securitydialogs/lockclient/eabi/lockclientu.def
securitydialogs/lockclient/group/ABLD.BAT
securitydialogs/lockclient/group/bld.inf
securitydialogs/lockclient/group/lockclient.mmp
securitydialogs/lockclient/inc/lockaccessextension.h
securitydialogs/lockclient/rom/lockclient.iby
securitydialogs/lockclient/src/devicelockaccessapi.cpp
securitydialogs/lockclient/src/keyguardaccessapi.cpp
securitydialogs/lockclient/src/lockaccessextension.cpp
securitydialogs/lockclient/tsrc/public/basic/bwins/MT_RDevicelockAccessApiu.def
securitydialogs/lockclient/tsrc/public/basic/bwins/MT_RKeyguardAccessApiu.def
securitysrv_info/securitysrv_metadata/securitysrv_metadata.mrp
sysdef_1_4_0.dtd
tsrc/group/bld.inf
wim/Group/bld.inf
wim/Scard/EABI/ScardU.DEF
wim/Scard/bwins/SCARDU.DEF
wim/Scard/group/Scard.mmp
wim/Scard/inc/ScardAccessControl.h
wim/Scard/inc/ScardAccessControl.inl
wim/Scard/inc/ScardAccessControlRegistry.h
wim/Scard/inc/ScardChannelManager.h
wim/Scard/inc/ScardClsv.h
wim/Scard/inc/ScardCommandTimer.h
wim/Scard/inc/ScardConnectionRegistry.h
wim/Scard/inc/ScardConnectionTimer.h
wim/Scard/inc/ScardConnector.h
wim/Scard/inc/ScardEventStack.h
wim/Scard/inc/ScardLogs.h
wim/Scard/inc/ScardMessageStack.h
wim/Scard/inc/ScardMessageStack.inl
wim/Scard/inc/ScardNotifier.h
wim/Scard/inc/ScardNotifyRegistry.h
wim/Scard/inc/ScardReaderRegistry.h
wim/Scard/inc/ScardResourceRegistry.h
wim/Scard/inc/ScardServer.h
wim/Scard/inc/ScardServer.inl
wim/Scard/inc/ScardServerBase.h
wim/Scard/inc/ScardSession.h
wim/Scard/src/Scard.cpp
wim/Scard/src/ScardAccessControl.cpp
wim/Scard/src/ScardAccessControlRegistry.cpp
wim/Scard/src/ScardChannelManager.cpp
wim/Scard/src/ScardComm.cpp
wim/Scard/src/ScardCommandTimer.cpp
wim/Scard/src/ScardConnectionRegistry.cpp
wim/Scard/src/ScardConnectionRequirement.cpp
wim/Scard/src/ScardConnectionTimer.cpp
wim/Scard/src/ScardConnector.cpp
wim/Scard/src/ScardEventStack.cpp
wim/Scard/src/ScardListener.cpp
wim/Scard/src/ScardMessageStack.cpp
wim/Scard/src/ScardNotifier.cpp
wim/Scard/src/ScardNotifyRegistry.cpp
wim/Scard/src/ScardReaderQuery.cpp
wim/Scard/src/ScardReaderRegistry.cpp
wim/Scard/src/ScardResourceRegistry.cpp
wim/Scard/src/ScardServer.cpp
wim/Scard/src/ScardSession.cpp
wim/SwimReader/EABI/SwimReaderU.DEF
wim/SwimReader/bwins/SWIMREADERU.DEF
wim/SwimReader/group/SwimReader.mmp
wim/SwimReader/inc/SwimApduReqHeader.h
wim/SwimReader/inc/SwimApduRespHeader.h
wim/SwimReader/inc/SwimEtelApdu.h
wim/SwimReader/inc/SwimLauncher.h
wim/SwimReader/inc/SwimReader.h
wim/SwimReader/inc/SwimReaderConsts.h
wim/SwimReader/inc/SwimReaderIF.h
wim/SwimReader/inc/SwimSysAgentObserver.h
wim/SwimReader/src/SwimApduReqHeader.cpp
wim/SwimReader/src/SwimApduRespHeader.cpp
wim/SwimReader/src/SwimEtelApdu.cpp
wim/SwimReader/src/SwimLauncher.cpp
wim/SwimReader/src/SwimReader.cpp
wim/SwimReader/src/SwimReaderIF.cpp
wim/SwimReader/src/SwimSysAgentObserver.cpp
wim/WimClient/EABI/WIMCLIENTU.DEF
wim/WimClient/bwins/WIMCLIENTU.DEF
wim/WimClient/group/WimClient.mmp
wim/WimClient/inc/WimCertMgmt.h
wim/WimClient/inc/WimCertTClassWrappers.h
wim/WimClient/inc/WimCertTClassWrappers.inl
wim/WimClient/inc/WimClient.h
wim/WimClient/inc/WimMgmt.h
wim/WimClient/inc/WimSecModule.h
wim/WimClient/inc/WimSecModuleMgr.h
wim/WimClient/inc/WimTrustSettingsMgmt.h
wim/WimClient/src/JavaUtils.cpp
wim/WimClient/src/ProvSC.cpp
wim/WimClient/src/WimCert.cpp
wim/WimClient/src/WimCertConverter.cpp
wim/WimClient/src/WimCertMgmt.cpp
wim/WimClient/src/WimClient.cpp
wim/WimClient/src/WimKeyDetails.cpp
wim/WimClient/src/WimMgmt.cpp
wim/WimClient/src/WimPin.cpp
wim/WimClient/src/WimSecModule.cpp
wim/WimClient/src/WimSecModuleMgr.cpp
wim/WimClient/src/WimTrustSettingsAPI.cpp
wim/WimClient/src/WimTrustSettingsMgmt.cpp
wim/WimPlugin/data/101FB674.rss
wim/WimPlugin/group/WimPlugin.mmp
wim/WimPlugin/inc/WimAuthenticationObject.h
wim/WimPlugin/inc/WimAuthenticationObjectList.h
wim/WimPlugin/inc/WimCertStore.h
wim/WimPlugin/inc/WimCertStoreMapping.h
wim/WimPlugin/inc/WimCertStoreMappings.h
wim/WimPlugin/inc/WimImplementationUID.hrh
wim/WimPlugin/inc/WimKeyStore.h
wim/WimPlugin/inc/WimRSASigner.h
wim/WimPlugin/inc/WimToken.h
wim/WimPlugin/inc/WimTokenListener.h
wim/WimPlugin/inc/WimTokenType.h
wim/WimPlugin/src/WimAuthenticationObject.cpp
wim/WimPlugin/src/WimAuthenticationObjectList.cpp
wim/WimPlugin/src/WimCertStore.cpp
wim/WimPlugin/src/WimCertStoreMapping.cpp
wim/WimPlugin/src/WimCertStoreMappings.cpp
wim/WimPlugin/src/WimKeyStore.cpp
wim/WimPlugin/src/WimRSASigner.cpp
wim/WimPlugin/src/WimToken.cpp
wim/WimPlugin/src/WimTokenListener.cpp
wim/WimPlugin/src/WimTokenType.cpp
wim/WimServer/group/WimServer.mmp
wim/WimServer/inc/WimApduImpl.h
wim/WimServer/inc/WimAuthObjHandler.h
wim/WimServer/inc/WimBTSapObserver.h
wim/WimServer/inc/WimCallbackImpl.h
wim/WimServer/inc/WimCertHandler.h
wim/WimServer/inc/WimCertUtil.h
wim/WimServer/inc/WimCleanup.h
wim/WimServer/inc/WimJavaProvisioning.h
wim/WimServer/inc/WimKeyMgmtHandler.h
wim/WimServer/inc/WimMemMgmt.h
wim/WimServer/inc/WimOmaProvisioning.h
wim/WimServer/inc/WimResponse.h
wim/WimServer/inc/WimSatRefreshObserver.h
wim/WimServer/inc/WimScardListener.h
wim/WimServer/inc/WimSecurityDlgHandler.h
wim/WimServer/inc/WimServer.h
wim/WimServer/inc/WimSession.h
wim/WimServer/inc/WimSessionRegistry.h
wim/WimServer/inc/WimSignTextHandler.h
wim/WimServer/inc/WimSimFileHandler.h
wim/WimServer/inc/WimTimer.h
wim/WimServer/inc/WimTokenHandler.h
wim/WimServer/inc/WimTrustSettingsHandler.h
wim/WimServer/inc/WimTrustSettingsStore.h
wim/WimServer/inc/WimUtilityFuncs.h
wim/WimServer/src/WimApduImpl.cpp
wim/WimServer/src/WimAuthObjHandler.cpp
wim/WimServer/src/WimBTSapObserver.cpp
wim/WimServer/src/WimCallbackImpl.cpp
wim/WimServer/src/WimCertHandler.cpp
wim/WimServer/src/WimCertUtil.cpp
wim/WimServer/src/WimCleanup.cpp
wim/WimServer/src/WimJavaProvisioning.cpp
wim/WimServer/src/WimKeyMgmtHandler.cpp
wim/WimServer/src/WimMemMgmt.cpp
wim/WimServer/src/WimOmaProvisioning.cpp
wim/WimServer/src/WimResponse.cpp
wim/WimServer/src/WimSatRefreshObserver.cpp
wim/WimServer/src/WimScardListener.cpp
wim/WimServer/src/WimSecurityDlgHandler.cpp
wim/WimServer/src/WimServer.cpp
wim/WimServer/src/WimSession.cpp
wim/WimServer/src/WimSessionRegistry.cpp
wim/WimServer/src/WimSignTextHandler.cpp
wim/WimServer/src/WimSimFileHandler.cpp
wim/WimServer/src/WimTimer.cpp
wim/WimServer/src/WimTokenHandler.cpp
wim/WimServer/src/WimTrustSettingsHandler.cpp
wim/WimServer/src/WimTrustSettingsStore.cpp
wim/WimServer/src/WimUtilityFuncs.cpp
wim/WimSoft/armv5/udeb/wimi.lib
wim/WimSoft/armv5/urel/wimi.lib
wim/WimSoft/winscw/udeb/WIMI.LIB
wim/WimSoft/winscw/urel/WIMI.LIB
wim/WimUtil/Bwins/WIMUTILU.DEF
wim/WimUtil/EABI/WimUtilU.DEF
wim/WimUtil/group/WimUtil.mmp
wim/WimUtil/inc/WimDummyToken.h
wim/WimUtil/src/WimCertInfo.cpp
wim/WimUtil/src/WimDummyToken.cpp
wim/WimUtil/src/WimUtilEntry.cpp
wim/inc/DigSigningNote.h
wim/inc/Scard.h
wim/inc/ScardBase.h
wim/inc/ScardComm.h
wim/inc/ScardConnectionRequirement.h
wim/inc/ScardDefs.h
wim/inc/ScardListener.h
wim/inc/ScardNotifyObserver.h
wim/inc/ScardReader.h
wim/inc/ScardReaderLauncher.h
wim/inc/ScardReaderQuery.h
wim/inc/WimBerConsts.h
wim/inc/WimBerSet.h
wim/inc/WimCertConverter.h
wim/inc/WimCertInfo.h
wim/inc/WimClsv.h
wim/inc/WimConsts.h
wim/inc/WimDefs.h
wim/inc/WimKeyDetails.h
wim/inc/WimOpcode.h
wim/inc/WimPin.h
wim/inc/WimSig.h
wim/inc/WimSig.inl
wim/inc/WimTrace.h
wim/inc/WimTrustSettingsAPI.h
wim/inc/Wimi.h
wim/rom/wim.iby
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/BWINS/IntegrityCheckClientU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	?Close@RIntegrityCheckClient@@QAEXXZ @ 1 NONAME ; void RIntegrityCheckClient::Close(void)
+	?Connect@RIntegrityCheckClient@@QAEHXZ @ 2 NONAME ; int RIntegrityCheckClient::Connect(void)
+	?GetSWBootReason@RIntegrityCheckClient@@QAEHAAH@Z @ 3 NONAME ; int RIntegrityCheckClient::GetSWBootReason(int &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/EABI/IntegrityCheckClientU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	_ZN21RIntegrityCheckClient15GetSWBootReasonERi @ 1 NONAME
+	_ZN21RIntegrityCheckClient5CloseEv @ 2 NONAME
+	_ZN21RIntegrityCheckClient7ConnectEv @ 3 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/TrkDummy/group/TrkDummy.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,61 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Dummy exe to prevent installing too liberal TrkApp
+*  Version     : %version: tr1sido#9 %
+*
+*/
+
+
+// This MMP file builds dummy exe that can be included in ROM image
+// to prevent installing old TrkApp.exe, which allows hacking platform
+// security. Dummy exe has the same UID3 as old TrkApp.exe, and hence
+// installing old TrkApp.exe will fail (error: 'Unable to install').
+// If the same file name (TrkApp.exe, see TrkDummy.iby) is used too,
+// then installing old TrkApp.exe fails with error: 'Cannot install!
+// This component is built-in'.
+
+
+#if(!defined __SERIES60_30__ && !defined __SERIES60_31__)
+  #include <platform_paths.hrh>
+#endif
+
+CAPABILITY      None
+
+TARGETPATH      /sys/bin
+TARGET          TrkDummy.exe
+TARGETTYPE      exe
+
+// Note: UID3 matches to the TrkApp UID to block it's installation.
+UID             0x100039CE 0x101F7159
+
+LANG            SC
+
+SOURCEPATH      ../src
+SOURCE          TrkDummy.cpp
+SOURCE          TrkDummyApplication.cpp
+
+USERINCLUDE     ../inc 
+#if defined (__SERIES60_30__) || defined(__SERIES60_31__)
+	SYSTEMINCLUDE	/epoc32/include  
+#else
+    MW_LAYER_SYSTEMINCLUDE    
+#endif
+
+
+LIBRARY         euser.lib
+LIBRARY         apparc.lib
+LIBRARY         eikcore.lib
+LIBRARY         avkon.lib
+
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/TrkDummy/group/TrkDummy1.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Dummy exe to prevent installing too liberal TrkApp
+*  Version     : %version: 7 %
+*
+*/
+
+
+// This MMP file builds dummy exe that can be included in ROM image
+// to prevent installing old TrkApp.exe, which allows hacking platform
+// security. Dummy exe has the same UID3 as old TrkApp.exe, and hence
+// installing old TrkApp.exe will fail (error: 'Unable to install').
+// If the same file name (TrkApp.exe, see TrkDummy.iby) is used too,
+// then installing old TrkApp.exe fails with error: 'Cannot install!
+// This component is built-in'.
+
+
+#if(!defined __SERIES60_30__ && !defined __SERIES60_31__)
+  #include <platform_paths.hrh>
+#endif
+
+CAPABILITY      None
+
+TARGETPATH      /sys/bin
+TARGET          TrkDummy1.exe
+TARGETTYPE      exe
+
+// Note: UID3 matches to the TrkApplication UID to block it's installation.
+UID             0x100039CE 0x200159D8
+
+LANG            SC
+
+SOURCEPATH      ../src
+SOURCE          TrkDummy.cpp
+SOURCE          TrkDummyApplication.cpp
+
+USERINCLUDE     ../inc 
+#if defined (__SERIES60_30__) || defined(__SERIES60_31__)
+	SYSTEMINCLUDE	/epoc32/include  
+#else
+    MW_LAYER_SYSTEMINCLUDE    
+#endif
+
+LIBRARY         euser.lib
+LIBRARY         apparc.lib
+LIBRARY         eikcore.lib
+LIBRARY         avkon.lib
+
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/TrkDummy/group/TrkDummy2.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Dummy exe to prevent installing too liberal TrkApp
+*  Version     : %version: 7 %
+*
+*/
+
+
+// This MMP file builds dummy exe that can be included in ROM image
+// to prevent installing old TrkApp.exe, which allows hacking platform
+// security. Dummy exe has the same UID3 as old TrkApp.exe, and hence
+// installing old TrkApp.exe will fail (error: 'Unable to install').
+// If the same file name (TrkApp.exe, see TrkDummy.iby) is used too,
+// then installing old TrkApp.exe fails with error: 'Cannot install!
+// This component is built-in'.
+
+
+#if(!defined __SERIES60_30__ && !defined __SERIES60_31__)
+  #include <platform_paths.hrh>
+#endif
+
+
+CAPABILITY      None
+
+TARGETPATH      /sys/bin
+TARGET          TrkDummy2.exe
+TARGETTYPE      exe
+
+// Note: UID3 matches to the trkguiapp UID to block it's installation.
+UID             0x100039CE 0x200170BC
+
+LANG            SC
+
+SOURCEPATH      ../src
+SOURCE          TrkDummy.cpp
+SOURCE          TrkDummyApplication.cpp
+
+USERINCLUDE     ../inc 
+#if defined (__SERIES60_30__) || defined(__SERIES60_31__)
+	SYSTEMINCLUDE	/epoc32/include  
+#else
+    MW_LAYER_SYSTEMINCLUDE    
+#endif
+
+
+LIBRARY         euser.lib
+LIBRARY         apparc.lib
+LIBRARY         eikcore.lib
+LIBRARY         avkon.lib
+
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/TrkDummy/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Dummy exe to prevent installing too liberal TrkApp
+*
+*/
+
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_MMPFILES
+TrkDummy.mmp
+TrkDummy1.mmp
+TrkDummy2.mmp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/TrkDummy/inc/TrkDummyApplication.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Dummy exe to prevent installing too liberal TrkApp
+*
+*/
+
+
+#ifndef __TRKDUMMY_APPLICATION_H__
+#define __TRKDUMMY_APPLICATION_H__
+
+#include <aknapp.h>
+
+class CTrkDummyApplication : public CAknApplication
+    {
+    public:     // from CAknApplication
+        TUid AppDllUid() const;
+
+    protected:  // from CAknApplication
+        CApaDocument* CreateDocumentL();
+    };
+
+#endif // __TRKDUMMY_APPLICATION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/TrkDummy/src/TrkDummy.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Dummy exe to prevent installing too liberal TrkApp
+*
+*/
+
+
+#include <eikstart.h>
+#include "TrkDummyApplication.h"
+
+CApaApplication* NewApplication()
+	{
+	return new CTrkDummyApplication;
+	}
+
+TInt E32Main()
+	{
+	return EikStart::RunApplication( NewApplication );
+	}
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/TrkDummy/src/TrkDummyApplication.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Dummy exe to prevent installing too liberal TrkApp
+*
+*/
+
+
+#include "TrkDummyApplication.h"
+
+static const TUid KUidTrkDummyApp = { 0x101F7159 };   // See also MMP file
+
+CApaDocument* CTrkDummyApplication::CreateDocumentL()
+    {
+    User::Leave( KErrPermissionDenied );
+    return NULL;
+    }
+
+TUid CTrkDummyApplication::AppDllUid() const
+    {
+    return KUidTrkDummyApp;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/group/IntegrityCheck.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2005-2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Boot time integrity check of binaries.
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET                  IntegrityCheck.exe
+TARGETTYPE              exe
+UID                     0x0 0x101FB65F
+
+CAPABILITY              TCB ReadUserData AllFiles ReadDeviceData
+SECUREID                0x101FB65F
+VENDORID                VID_DEFAULT
+
+SOURCEPATH              ../src
+SOURCE                  IntegrityCheck.cpp
+SOURCE                  InfoServerClient.cpp
+
+USERINCLUDE             ../inc
+
+APP_LAYER_SYSTEMINCLUDE
+
+LIBRARY	                euser.lib
+LIBRARY                 efsrv.lib 
+LIBRARY                 bafl.lib                // for path search
+LIBRARY                 estor.lib               // for TStreamId 
+LIBRARY                 x500.lib                // for ExactMatchL etc.
+LIBRARY                 x509.lib                // for x509 certs
+LIBRARY                 crypto.lib              // for VerifySignaturL etc.
+LIBRARY                 sisregistryclient.lib   // Sis registery operations
+LIBRARY                 hash.lib                // for SHA1 hash
+LIBRARY                 CTFramework.lib         // for TCertLabel, CCTCertInfo, 
+                                                // TCapabilitySet
+LIBRARY                 IntegrityCheckClient.lib // BTIC Server client                                                
+                                              
+SMPSAFE
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/group/IntegrityCheckClient.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2007-2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Client mmp file
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          IntegrityCheckClient.dll
+TARGETTYPE      dll
+UID             0x1000008d 0x101FB660
+
+CAPABILITY      ALL
+VENDORID        VID_DEFAULT
+
+SOURCEPATH      .
+SOURCE          ../src/IntegrityCheckClient.cpp
+
+USERINCLUDE     . 
+USERINCLUDE     ../inc 
+
+APP_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/group/IntegrityCheckServer.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2007-2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  server mmp file
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          IntegrityCheckServer.exe
+TARGETTYPE      EXE
+UID             0x0 0x101FB661
+
+
+CAPABILITY      ReadDeviceData ProtServ
+SECUREID        0x101FB661
+VENDORID        VID_DEFAULT
+
+SOURCEPATH      .
+SOURCE          ../src/IntegrityCheckServer.cpp
+
+USERINCLUDE     .
+USERINCLUDE     ../inc
+
+APP_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib                                      
+LIBRARY         centralrepository.lib 
+
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2005-2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Boot time integrity check of binaries.
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+../rom/IntegrityCheck.iby    CORE_APP_LAYER_IBY_EXPORT_PATH( integritycheck.iby ) 
+
+PRJ_MMPFILES
+IntegrityCheckClient.mmp
+IntegrityCheckServer.mmp
+IntegrityCheck.mmp
+
+../TrkDummy/group/TrkDummy.mmp
+../TrkDummy/group/TrkDummy1.mmp
+../TrkDummy/group/TrkDummy2.mmp
+
+PRJ_TESTMMPFILES
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/inc/InfoServerClient.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,76 @@
+/*
+* Copyright (c) 2005-2006 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Header file for direct use of cert provisioner info server.
+*
+*/
+
+
+#ifndef INFOSERVERCLIENT_H
+#define INFOSERVERCLIENT_H
+
+// INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <e32cons.h>
+#include <etelmm.h>
+#include <f32file.h>
+
+
+// CONSTANTS
+_LIT( KBTICCertProvInfoServer, "CertProvisionerInfoServer" );
+_LIT( KBTICCPEmulatorSn,  "123456789123456789" );
+
+const TUid KBTICCertProvInfoServerUid3 = { 0x1027508A };
+
+enum TPSMessages
+  {
+  EPSSerialNumber
+  };
+
+// CLASS DECLARATION
+
+/**
+*  RInfoServerClient class
+*  Class for using directly Certificate Provisioner Info Server.
+*
+*  @lib
+*  @since
+*/
+class RInfoServerClient : public RSessionBase
+  {
+    public:
+        /**
+        * Connects Certificate Provisioner Server
+        * @param
+        * @return
+        **/
+        TInt Connect();
+
+        /**
+        * Closes session to Certificate Provisioner Server
+        * @param
+        * @return
+        **/
+        void Close();
+
+        /**
+        * Gets Serial Number from Certificate Provisioner Info Server
+        * @param
+        * @return
+        **/
+        TInt GetSerialNumber( TDes& aSerialNumber );
+
+    };
+
+#endif  // INFOSERVERCLIENT_H
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/inc/IntegrityCheck.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,211 @@
+/*
+* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Header file for integrity check program.
+*
+*/
+
+
+#ifndef INTEGRITYCHECK_H
+#define INTEGRITYCHECK_H
+
+// INCLUDES 
+#include    <e32base.h>
+#include    <s32std.h>          // TStreamId
+#include    <cctcertinfo.h>     // TCertLabel
+#include    <securitydefs.h>    // TKeyIdentifier
+
+// CONSTANTS 
+
+// MACROS 
+
+// Enable C:\sys\bin binaries check.
+//#define __BTIC_BINARIES_CHECK_ENABLED
+
+// Enable sis controller verify.
+#define __BTIC_VERIFY_CONTROLLER 
+
+// DATA TYPES 
+
+// FUNCTION PROTOTYPES 
+
+// FORWARD DECLARATIONS
+
+class CCTCertInfo; // TCapabilitySet
+
+// LOCAL FUNCTION PROTOTYPES 
+
+// CLASS DECLARATION 
+
+/**
+* Class CRootCertificateEntry
+*
+* Class for reading root certificates from certificate store file. 
+*/
+NONSHARABLE_CLASS( CRootCertificateEntry ) : public CBase
+    {
+    public:
+        
+        /**
+         * Symbian constructor
+         *
+         * @since 
+         * @param aStream Certificate stream           
+         */
+        static CRootCertificateEntry* NewLC( RReadStream& aStream );
+        
+        /**
+         * Destructor
+         *
+         * @since                   
+         */        
+        virtual ~CRootCertificateEntry();
+
+        /**
+         * Returns certificates data stream. This is actual 
+         * x509 certificate.
+         *
+         * @since        
+         * @return TStreamId         
+         */                
+        TStreamId DataStreamId() const;
+        
+        /**
+         * Returns certificates capability set.
+         *
+         * @since 
+         * @return TCapabilitySet        
+         */        
+        const TCapabilitySet& Capabilities() const;               
+
+        /**
+         * Returns certificate's size. This is actual size of
+         * x509 certificate.
+         *
+         * @since 
+         * @return TInt Size of certificate in bytes.        
+         */        
+        TInt Size() const;
+
+        /**
+         * Returns certificate's store ID number.
+         *
+         * @since 
+         * @return TInt Store ID number.         
+         */        
+        TInt CertID() const;
+        
+    private:
+
+        /**
+         * C++ default constructor. 
+         *
+         * @since         
+         */            
+        CRootCertificateEntry();
+ 
+         /**
+         * Reads data from stream.
+         *
+         * @since 
+         * @param aStream Certificate stream         
+         */               
+        void InternalizeL( RReadStream& aStream );
+
+    private:
+    
+        TUint8          iX509CertificateType; // Defines type eg. X509
+        TInt            iSize;         // Size of certificate data  
+        TCertLabel      iLabel; 
+        TInt            iCertId;       // Certificate's store id
+        TUint8          iCACertificateType;
+        TKeyIdentifier  iSubjectKeyId;
+        TKeyIdentifier  iIssuerKeyId;
+        RArray<TUid>    iApplications;
+        TBool           iTrusted;      // Certs are always trusted
+        TStreamId       iDataStreamId; // Certificate data stream
+        TCapabilitySet  iCapabilities; // Certificates capability set
+        TBool           iMandatory;         
+    };
+
+
+/**
+* Class 
+*
+* Class for . 
+*/
+NONSHARABLE_CLASS( CActiveFileObserver ) : public CActive
+    {
+    public:
+
+        /**
+        * Destructor.
+        */
+        virtual ~CActiveFileObserver();
+
+        /**
+        * Two-phased constructor.       
+        */    
+        static CActiveFileObserver* NewL(    
+            RFs&  aFs,
+            const TDesC& aPath,
+            TInt& aResult );
+
+        /**
+        * Function íssues request to 
+        */        
+        void IssueRequest();
+
+    protected:
+
+        /**
+        * Function                
+        */
+        void RunL();
+
+        /**
+        * Cancel request.
+        */
+        void DoCancel();  
+        
+        /**
+        * Handles a leave occurring in the request completion 
+        * event handler RunL.
+        */             
+        TInt RunError( TInt aError );         
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CActiveFileObserver( RFs&  aFs, TInt& aResult );
+
+        /**
+        * 2nd phase constructor.         
+        */        
+        void ConstructL( const TDesC& aPath );
+
+    private:
+                       
+        RFs&    iFs;
+        TInt&   iResult; 
+        TInt    iRunCount;   
+        RTimer  iRTimer;    
+        HBufC*  iPath;                                                                                  
+    };
+
+
+#endif //INTEGRITYCHECK_H
+
+//EOF 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/inc/IntegrityCheckClient.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,79 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Client header file
+*
+*/
+
+
+#ifndef INTEGRITYCHECKCLIENT_H
+#define INTEGRITYCHECKCLIENT_H
+
+// INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <f32file.h>
+
+// CONSTANTS 
+
+const TUid KBTICServerUid3 = { 0x101FB661 };
+_LIT( KBTICServer,"IntegrityCheckServer" );
+_LIT( KBTICServerName,"!IntegrityCheckServer" );
+
+// MACROS
+
+// DATA TYPES 
+
+// FUNCTION PROTOTYPES 
+
+// FORWARD DECLARATIONS
+
+// LOCAL FUNCTION PROTOTYPES 
+
+// CLASS DECLARATION 
+
+/**
+*  RIntegrityCheckClient class
+*  Client for Integrity Check server.
+*
+*  @lib
+*  @since 3.1
+*/
+class RIntegrityCheckClient : public RSessionBase
+    {
+    public:
+    
+        /**
+        * Connects Integrity Check Server      
+        * @return
+        **/
+        IMPORT_C TInt Connect();
+
+        /**
+        * Closes session to server       
+        **/
+        IMPORT_C void Close();
+
+        /**
+        * Get sw boot reason from system. 
+        * @param aBootReason
+        * @return System wide error code.
+        **/
+        //IMPORT_C TInt GetSWBootReason( TDes& aBootReason );
+        IMPORT_C TInt GetSWBootReason( TInt& aBootReason );
+
+    };
+
+#endif  // INTEGRITYCHECKCLIENT_H
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/inc/IntegrityCheckDebug.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Header file for debug settings.
+*
+*/
+
+
+#ifndef INTEGRITYCHECKDEBUG_H
+#define INTEGRITYCHECKDEBUG_H
+
+// INCLUDES 
+#include    <e32base.h>
+
+// CONSTANTS 
+    
+// MACROS 
+
+#ifdef _DEBUG
+// Enable trace printing
+#define INTEGRITYCHECK_TRACE
+#endif
+
+#ifdef INTEGRITYCHECK_TRACE
+#include <e32svr.h>
+#define BTIC_TRACE_PRINT( aText ) { RDebug::Print( _L(aText) ); }
+#define BTIC_TRACE_PRINT_NUM( aText, aNum ) \
+    { RDebug::Print( _L(aText), aNum ); }
+#define BTIC_TRACE_PRINT_RAW( aPtr ) \
+    { RDebug::RawPrint( aPtr ); RDebug::Print( _L("\n") ); }  
+#define BTIC_TRACE_PRINT_ALLOC_CELLS( aText ) \
+    { RDebug::Print( _L(aText), User::CountAllocCells() ); }
+#else 
+#define BTIC_TRACE_PRINT( aText )
+#define BTIC_TRACE_PRINT_NUM( aText, aNum )
+#define BTIC_TRACE_PRINT_RAW( aPtr )
+#define BTIC_TRACE_PRINT_ALLOC_CELLS( aText )  
+#endif
+
+// DATA TYPES 
+
+// FUNCTION PROTOTYPES 
+
+// FORWARD DECLARATIONS
+
+// LOCAL FUNCTION PROTOTYPES 
+
+// CLASS DECLARATION 
+
+#endif //INTEGRITYCHECKDEBUG_H
+
+//EOF 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/inc/IntegrityCheckDefs.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Header file for program's defines.
+*
+*/
+
+
+#ifndef INTEGRITYCHECKDEFS_H
+#define INTEGRITYCHECKDEFS_H
+
+// INCLUDES 
+#include    <e32base.h>
+
+// CONSTANTS 
+
+const TInt KBTICCertProvUID = 0x101FB665;          //UID for CertProvisioner       
+const TInt KBTICSymbianSWIUpdaterUID = 0x101FB666; //UID for Symbian SWI updater
+
+// For client server
+
+enum TBTICServerCommand
+    {    
+    EBTICBootReasonSW,    
+    };
+
+enum TBTICBootReason
+    { 
+    EBTICNoSWReason = 200,   
+    EBTICNormalBoot = 201,     
+    EBTICRestoreFactorySetDeep = 202,            
+    };
+    
+// DATA TYPES 
+
+// FUNCTION PROTOTYPES 
+
+// FORWARD DECLARATIONS
+
+// LOCAL FUNCTION PROTOTYPES 
+
+// CLASS DECLARATION 
+
+#endif
+
+//EOF 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/inc/IntegrityCheckServer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,196 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Server header file
+*
+*/
+
+
+#ifndef INTEGRITYCHECKSERVER_H
+#define INTEGRITYCHECKSERVER_H
+
+// INCLUDES
+
+#include <e32std.h>
+#include <e32base.h>
+#include <e32cons.h>
+#include <e32svr.h>
+#include <f32file.h>
+
+// CONSTANTS
+
+_LIT( KIntecrityCheckServer,"IntegrityCheckServer" );
+_LIT( KIntecrityCheckServerName,"!IntegrityCheckServer" );
+_LIT( KIntecrityCheckServerText,"Boot Time Integrity Check Server" );
+
+const TInt KParam0 = 0;
+// BTIC Server auto close time.
+const TInt KServerCloseTime = 8000000; // 8 sec.
+
+// ---------------------------------------------------------------------------
+// Server's policy 
+// ---------------------------------------------------------------------------
+
+//Total number of ranges
+const TUint CPRangeCount = 2;
+
+//Definition of the ranges of IPC numbers
+const TInt CPRanges[CPRangeCount] =
+        {
+        0,
+        1
+        };
+
+//Policy to implement for each of the above ranges
+const TUint8 CPElementsIndex[CPRangeCount] =
+        {
+        0,
+        CPolicyServer::ENotSupported
+        };
+
+//Specific capability checks
+const CPolicyServer::TPolicyElement CPElements[] =
+        {
+        {_INIT_SECURITY_POLICY_C1(ECapabilityReadDeviceData), 
+        CPolicyServer::EPanicClient},
+        };
+
+//Package all the above together into a policy
+const CPolicyServer::TPolicy CPPolicy =
+        {
+        CPolicyServer::EAlwaysPass, // All connect attempts pass
+        CPRangeCount,               // Number of ranges
+        CPRanges,                   // Ranges array
+        CPElementsIndex,            // Elements<->ranges index
+        CPElements,                 // Array of elements
+        };
+
+// CLASS DECLARATION
+
+// MACROS
+
+// DATA TYPES 
+
+// FUNCTION PROTOTYPES 
+
+// FORWARD DECLARATIONS
+
+// LOCAL FUNCTION PROTOTYPES 
+
+// CLASS DECLARATION 
+
+/**
+*  CShutdown class
+*
+*  @lib
+*/
+class CShutdown : public CTimer
+    {
+    public:
+        CShutdown();           
+        void ConstructL();               
+        void Start();
+        
+    private:
+        void RunL();        
+    };
+
+/**
+*  CIntegrityCheckServer class
+*
+*  @lib
+*  @since 3.1
+*/
+class CIntegrityCheckServer : public CPolicyServer
+    {
+    public:
+    
+        static CServer2* NewLC();
+        
+        void AddSession();
+        
+        void RemoveSession();        
+
+    private:
+    
+        /**
+        * Default constructor        
+        */
+        CIntegrityCheckServer();
+
+        void ConstructL();
+        
+        /**
+        * From CServer2
+        */       
+        virtual CSession2* NewSessionL( 
+            const TVersion& aVersion, 
+            const RMessage2& aMessage ) const;       
+        
+    private:
+        TInt iSessionCount;
+        CShutdown iShutDown;       
+    };
+
+/**
+*  CIntegrityCheckSession class
+*  Class for Integrity Check server session
+*
+*  @lib
+*  @since 3.1
+*/
+class CIntegrityCheckSession : public CSession2
+    {
+    public:
+    
+        /**
+        * Constructor        
+        */
+        CIntegrityCheckSession();
+        
+        /**
+        * Called by the CServer2 framework after constructor.
+        */       
+        void CreateL();
+ 
+        /**
+         * Called by the CServer2 framework after client close.
+         */     
+        void Disconnect( const RMessage2 &aMessage );
+
+    private:
+    
+        /**
+        * Destructor.
+        *
+        */
+        ~CIntegrityCheckSession();
+                
+        void ServiceL( const RMessage2& aMessage );        
+
+        void ServiceError( const RMessage2& aMessage, TInt aError );
+
+        /**
+        * Get device sw boot reason
+        * @param aMessage user parameters        
+        */
+        void GetSWBootReasonL( const RMessage2& aMessage );
+
+    private: // Data
+                
+
+    };
+
+#endif  // INTEGRITYCHECKSERVER_H
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/rom/IntegrityCheck.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2005-2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Boot time integrity check of binaries in C.
+*
+*/
+
+
+#ifndef INTEGRITYCHECK_IBY
+#define INTEGRITYCHECK_IBY
+
+file=ABI_DIR\BUILD_DIR\IntegrityCheck.exe         sys\bin\IntegrityCheck.exe
+file=ABI_DIR\BUILD_DIR\IntegrityCheckServer.exe	  sys\bin\IntegrityCheckServer.exe
+file=ABI_DIR\BUILD_DIR\IntegrityCheckClient.dll   sys\bin\IntegrityCheckClient.dll
+
+#ifndef _IMAGE_TYPE_RND
+// Dummy exe with TrkApp UID to prevent installing old, too liberal TrkApp
+file=ABI_DIR\BUILD_DIR\TrkDummy.exe               sys\bin\TrkApp.exe
+file=ABI_DIR\BUILD_DIR\TrkDummy1.exe              sys\bin\trkapplication.exe
+file=ABI_DIR\BUILD_DIR\TrkDummy2.exe              sys\bin\trkguiapp.exe
+#endif
+
+#endif // INTEGRITYCHECK_IBY
+
+//  End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/src/InfoServerClient.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,145 @@
+/*
+* Copyright (c) 2005-2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Header file for direct use of cert provisioner info server.
+*
+*/
+
+
+// INCLUDE FILES
+#include <mmtsy_names.h>
+
+#include "InfoServerClient.h"
+#include "IntegrityCheckDefs.h"
+#include "IntegrityCheckDebug.h"
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ---------------------------------------------------------------------------
+// StartServer()
+//
+// Start CertProvisionInfoServer
+// ---------------------------------------------------------------------------
+//
+static TInt StartServer()
+    {
+    BTIC_TRACE_PRINT("[CInfoServerClient] StartServer --->");
+    
+    const TUidType serverUid( 
+        KNullUid, 
+        KNullUid, 
+        KBTICCertProvInfoServerUid3 );
+
+    RProcess server;
+
+    TInt r = server.Create( KBTICCertProvInfoServer, KNullDesC );
+    
+    if ( r != KErrNone )
+        {
+        BTIC_TRACE_PRINT_NUM( "[Info server client] server start failed %d", r );
+        return r;
+        }
+
+    TRequestStatus stat;
+    server.Rendezvous( stat );
+
+    if ( stat != KRequestPending )
+       {
+       server.Kill( 0 );
+       }
+    else
+       {
+       server.Resume();
+       }
+
+    User::WaitForRequest( stat );
+
+    r = ( server.ExitType() == EExitPanic ) ? KErrGeneral : stat.Int();
+
+    server.Close();
+
+    BTIC_TRACE_PRINT("[CInfoServerClient] StartServer <---");
+
+    return r;
+    }
+
+
+// ---------------------------------------------------------------------------
+// Connect()
+//
+// Connect to CertProvisionInfoServer
+// ---------------------------------------------------------------------------
+//
+TInt RInfoServerClient::Connect()
+    {
+    BTIC_TRACE_PRINT("[CInfoServerClient] Connect --->");
+    
+    TInt retry( 2 );
+
+    for (;;)
+        {
+        TInt status = 
+            CreateSession( KBTICCertProvInfoServer, TVersion( 0, 0, 0 ), 1 );
+
+        if ( ( status != KErrNotFound ) && ( status != KErrServerTerminated ) )
+            {
+            return status;
+            }
+       
+        if ( --retry == 0 )
+            {
+            return status;
+            }
+
+        status = StartServer();
+
+        if ( ( status != KErrNone ) && ( status != KErrAlreadyExists ) )
+            {
+            return status;
+            }
+        }               
+    }
+
+
+// ---------------------------------------------------------------------------
+// Close()
+// ---------------------------------------------------------------------------
+//
+void RInfoServerClient::Close()
+    {
+    BTIC_TRACE_PRINT("[CInfoServerClient] Close");
+    RSessionBase::Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// GetSerialNumber()
+//
+// Get device's serial number (IMEI) from info server.
+// ---------------------------------------------------------------------------
+//
+TInt RInfoServerClient::GetSerialNumber( TDes& aSerialNumber )
+    {
+    BTIC_TRACE_PRINT("[CInfoServerClient] GetSerialNumber");
+    
+    return SendReceive( EPSSerialNumber, TIpcArgs( &aSerialNumber ) );        
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/src/IntegrityCheck.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,2858 @@
+/*
+* Copyright (c) 2005-2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of boot time integrity check program.
+*
+*/
+
+
+// INCLUDE FILES
+
+#include <e32cons.h>
+#include <f32file.h>
+#include <cctcertinfo.h>        // TCapabilitySet
+#include <s32file.h> 
+#include <signed.h>             // VerifySignatureL
+#include <x500dn.h>             // ExactMatchL
+#include <x509cert.h>           // x509
+#include <swi/hashcontainer.h>
+#include <swi/sisregistrysession.h>
+#include <swi/sisregistryentry.h>
+#include <swi/sisregistrypackage.h>
+#include <hash.h>
+#include <etelmm.h>             // For serial number size
+
+#include "IntegrityCheck.h"
+#include "InfoServerClient.h"
+#include "IntegrityCheckDefs.h"
+#include "IntegrityCheckClient.h"
+#include "IntegrityCheckDebug.h"
+
+
+// CONSTANTS
+
+_LIT(KBTICThreadName,"BootIntegrityCheck"); 
+_LIT(KBTICCertStoreZ,"z:\\resource\\swicertstore.dat");
+_LIT(KBTICCertStoreCName,"updatedswicertstore.dat");
+_LIT(KBTICCertStoreCPath,"c:\\resource\\swicertstore\\dat\\");
+_LIT(KBTICDriveC,"c:\\");
+_LIT(KBTICDriveCWildcard,"c:\\*");
+_LIT(KBTICExtensionExe,"*.exe");
+_LIT(KBTICSerialNumberFile,"*imei.txt");
+_LIT(KBTICStarWildcard,"*\\");
+/*
+#ifdef __BTIC_BINARIES_CHECK_ENABLED
+_LIT(KBTICSysPathC,"c:\\sys\\bin\\");
+_LIT(KBTICCertStoreC,
+    "c:\\resource\\swicertstore\\dat\\updatedswicertstore.dat"); 
+_LIT(KBTICSysPathCWildcard,"c:\\sys\\bin\\*");
+_LIT(KBTICExtensionDll,"*.dll");
+_LIT(KBTICExtensionDat,"*.dat");
+#endif //__BTIC_BINARIES_CHECK_ENABLED 
+*/    
+const TInt KBTICCapaCount = 2;  //Number of capabilities.
+const TUint64 KBTIC_DRM = 64;   //0000 0000 0000 0000 0000 0000 0100 0000
+const TUint64 KBTIC_TCB = 1;    //0000 0000 0000 0000 0000 0000 0000 0001
+const TInt KBTICCabaWordOffset = 17; //File heder offset for capa. word @ 64bit.  
+const TInt KBTICHashSize = 20; 
+const TInt KBTICTryToOpen = 240;  //Try to open file. (240 x 0.5sec = 120sec)   
+const TInt KBTICTryToCreate = 5; // Try to create process.
+const TUint KBTICObserverTime = 1000000; // 1sec.
+const TUint KBTICRunCount = 10; 
+        
+// MACROS
+
+using namespace Swi;
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+LOCAL_C TInt ThreadStartL();
+
+LOCAL_C TInt ReadCertificatesL( 
+    RFs& aFs, 
+    const TDesC& aPath,     
+    RPointerArray<CX509Certificate>& aX509CertArray,
+    RPointerArray<TCapabilitySet>& aCapabilityArray  );
+ 
+LOCAL_C TBool ValidateCertStoreL(
+    RFs& aFs,     
+    RPointerArray<CX509Certificate>& aX509CertArray,
+    RPointerArray<TCapabilitySet>& aCapaArray,
+    const TDesC& aCertStoreFileName,
+    const TDesC& aCertStoreFilePath ); 
+    
+LOCAL_C TBool ValidateProvisonerCertStoreL(
+    RFs& aFs,                                           
+    RPointerArray<CX509Certificate>& aX509CertArray,
+    RPointerArray<TCapabilitySet>& aCapaArray,     
+    const TDesC& aCertStoreFileName,
+    const TDesC& aCertStoreFilePath,
+    RSisRegistryEntry& aEntry );
+    
+LOCAL_C TBool ValidateSymbianCertStoreL(
+    RFs& aFs,                                           
+    RPointerArray<CX509Certificate>& aX509CertArray,
+    RPointerArray<TCapabilitySet>& aCapaArray,              
+    RSisRegistryEntry& aEntry,
+    RPointerArray<HBufC>& aUpdaterExePaths ); 
+    
+LOCAL_C TBool RunUpdaterL( RFs& aFs, RPointerArray<HBufC>& aUpdaterExePaths );    
+    
+LOCAL_C TBool DeleteAllFilesL( RFs& aFs, const TDesC& aFolderPath );                
+
+LOCAL_C TBool SearchFilesFromArrayL( 
+    RPointerArray<HBufC>& aSourceArray,
+    const TDesC& aDriveAndPath,
+    RPointerArray<HBufC>& aStringArray, 
+    RPointerArray<HBufC>& aFilesArray );
+                  
+LOCAL_C TBool SearchValidCertificateL( 
+    RSisRegistryEntry& aEntry, 
+    RPointerArray<CX509Certificate>& aX509CertArray,
+    RPointerArray<TCapabilitySet>& aCertCapaArray,
+    TUint64 aCapability );
+
+LOCAL_C TCapability GetCapability( TUint64 aCapability );
+    
+LOCAL_C TBool VerifyHashL(    
+    RSisRegistryEntry& aEntry, 
+    RPointerArray<HBufC>& aPathArray,
+    RPointerArray<HBufC8>& aHashArray );
+
+LOCAL_C TBool CompareToRegisteryHashL( 
+    RSisRegistryEntry& aEntry, 
+    TDesC& aEntryFile, 
+    TDesC8& aHashBuffer ); 
+      
+LOCAL_C TBool CheckSerialNumberL( RFs& aFs, const TDesC& aFileName ); 
+
+LOCAL_C void CorruptFileL( RFs& aFs, const TDesC& aFileName );                              
+
+LOCAL_C TBool CheckCapabilityWordAndCalcHashL( 
+    RFs& aFs, 
+    TBool aCheckCapa,
+    TUint64* aCapaVector,    
+    RPointerArray<HBufC>& aSourceArray,
+    RPointerArray<HBufC>& aFilesArray,
+    RPointerArray<HBufC8>& aHashArray,
+    RArray<TUint64>& aCapaArray );
+/*
+#ifdef __BTIC_BINARIES_CHECK_ENABLED
+
+LOCAL_C void RenameFileL( RFs& aFs, const TDesC& aFileName );
+
+LOCAL_C void UniteCertArraysL(     
+    RPointerArray<CX509Certificate>& aTargetCertArray,
+    RPointerArray<CX509Certificate>& aSourceCertArray );
+
+LOCAL_C void UniteCapaArraysL( 
+    RPointerArray<TCapabilitySet>& aTargetCapaArray,
+    RPointerArray<TCapabilitySet>& aSourceCapaArray );     
+        
+LOCAL_C void CheckBinariesL( 
+    RFs& aFs, 
+    RPointerArray<CX509Certificate>& aX509CertArray,
+    RPointerArray<TCapabilitySet>& aCertCapaArray );  
+ 
+LOCAL_C void FindFilesL( 
+    RFs& aFs, 
+    const TDesC& aPath,
+    const TDesC& aSearchString,    
+    RPointerArray<HBufC>& aFoundFilesArray );
+                 
+LOCAL_C TBool FindMatchFromSisPackageL( 
+    RFs& aFs,    
+    RPointerArray<HBufC>& aFilesArray, 
+    RPointerArray<HBufC8>& aHashArray, 
+    RArray<TUint64>& aCapaArray,
+    RPointerArray<CX509Certificate>& aX509CertArray,
+    RPointerArray<TCapabilitySet>& aCertCapaArray ); 
+
+#endif //__BTIC_BINARIES_CHECK_ENABLED
+*/     
+
+// FORWARD DECLARATIONS
+
+// LOCAL FUNCTION PROTOTYPES
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// E32Main()
+// Main for ARM environment.
+// Returns: KErrNone if successful  
+//          Othervice some system error code.
+// -----------------------------------------------------------------------------
+//
+GLDEF_C TInt E32Main()
+    {
+    BTIC_TRACE_PRINT_ALLOC_CELLS("[BOOT INTECRITY CHECK] Main cell count = %d");  
+    TInt err = KErrNone;
+
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+
+    if ( !cleanup )
+        {
+        return KErrNoMemory;
+        }
+
+    TRAP( err, ThreadStartL() );
+
+    BTIC_TRACE_PRINT_NUM("[BOOT INTECRITY CHECK] Main TRAP error = %d", err);
+    
+    delete cleanup;
+
+    BTIC_TRACE_PRINT_ALLOC_CELLS("[BOOT INTECRITY CHECK] Main cell count = %d"); 
+    return err;
+    }
+
+
+// -----------------------------------------------------------------------------
+// ThreadStart()
+// 
+// This is programs main.
+// -----------------------------------------------------------------------------
+//
+LOCAL_C TInt ThreadStartL()
+    {                                                       
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] START PROGRAM");    
+    __UHEAP_MARK;
+    BTIC_TRACE_PRINT_ALLOC_CELLS("Start Cell count = %d");  
+   
+    BTIC_TRACE_PRINT("Rename thread to BootIntegrityCheck");
+    // Rename thread as SecEnvInit.
+    User::RenameThread( KBTICThreadName );  
+      
+    // This should be read with feature manager etc. but since we 
+    // only support certificate database checking this is ok.
+    TBool binariesCheckEnbled = EFalse;   
+    
+    TBool certFileFound = EFalse; 
+    TInt err = KErrNone; 
+    TInt pushToStack = 0; 
+        
+    // GET BOOT REASON   
+    
+    BTIC_TRACE_PRINT("Get boot reason");     
+    TBool bootReasonFormat = EFalse;   
+    RIntegrityCheckClient bticServer;
+        
+    err = bticServer.Connect();    
+    BTIC_TRACE_PRINT_NUM("BTIC Server connect error = %d", err );
+    
+    if ( err == KErrNone )
+        {            
+        CleanupClosePushL( bticServer );                                
+        TInt bootReason = KErrNone;     
+                                               
+        // Get boot reason from btic server.
+        err = bticServer.GetSWBootReason( bootReason );                          
+        BTIC_TRACE_PRINT_NUM("GetSWBootReason error = %d", err );
+                            
+        if ( err == KErrNone )
+            {                                  
+            BTIC_TRACE_PRINT_NUM("Boot Reason number = %d", bootReason );
+            
+            if ( bootReason == EBTICRestoreFactorySetDeep )
+                {                                                                
+                BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] Boot reason: FORMAT");  
+                bootReasonFormat = ETrue;
+                }                                   
+            }             
+        CleanupStack::PopAndDestroy(); //bticServer                                  
+        }
+               
+    // OPEN FILE SERVER    
+    BTIC_TRACE_PRINT("Open FS session");
+
+    RFs fs;
+    // Connect to file server.
+    User::LeaveIfError( fs.Connect() );
+    CleanupClosePushL( fs );
+    pushToStack++;
+
+    // Find SWICertStore.dat in C drive.
+    TFindFile find( fs ); 
+    TBool certStoreOk = EFalse;  
+    CDir* entryList = NULL;   
+    HBufC* certStoreFilePath = NULL; 
+    HBufC* certStoreFileName = NULL; 
+           
+    BTIC_TRACE_PRINT("Find C SWI certificate store");    
+    
+    // Get all files from folder. 
+    if ( KErrNone == fs.GetDir ( 
+        KBTICCertStoreCPath, 
+        KEntryAttNormal,
+        ESortByName|EDirsFirst, 
+        entryList ) )
+        {     
+        if ( entryList )
+            {
+            CleanupStack::PushL( entryList );
+
+            TInt count = entryList->Count(); 
+
+            // If file is found.            
+            if ( count )
+                {                                              
+                BTIC_TRACE_PRINT("Store file found");
+                
+                // Get the highest version certstore file
+                const TEntry& entry = (*entryList)[count - 1];                                
+                
+                // Make temp buffer for file path. 
+                TBuf<KMaxFileName> path( KBTICCertStoreCPath );
+                path.Append( entry.iName );
+                
+                certStoreFilePath = path.AllocLC(); 
+                pushToStack++;                              
+                                                   
+                certStoreFileName = entry.iName.AllocLC(); 
+                pushToStack++;                                                              
+                                                
+                certFileFound = ETrue; 
+                
+                CleanupStack::Pop(); //certStoreFilePath
+                CleanupStack::Pop(); //certStoreFileName
+                CleanupStack::PopAndDestroy( 1, entryList ); 
+                CleanupStack::PushL( certStoreFilePath );                         
+                CleanupStack::PushL( certStoreFileName );                           
+                }
+            else
+                {
+                BTIC_TRACE_PRINT("No store file present");
+                CleanupStack::PopAndDestroy( 1, entryList ); 
+                }                                                
+            }
+        }
+    
+    BTIC_TRACE_PRINT("Check boot reason");  
+    // Check boot reason. If certificate store file is found start active file
+    // observer which checks that file is deleted. If not continue checking.        
+    if ( bootReasonFormat )
+        {
+        BTIC_TRACE_PRINT("Boot reason format");    
+        if( certFileFound )
+            {
+            BTIC_TRACE_PRINT("Start active file observer"); 
+            TInt status = KErrUnknown;
+                        
+            // Create active scheduler.
+            CActiveScheduler* threadScheduler = new CActiveScheduler;
+            CleanupStack::PushL( threadScheduler );
+            pushToStack++;
+
+            CActiveScheduler::Install( threadScheduler );
+
+            // Create file observer object.
+            CActiveFileObserver* observer =
+                CActiveFileObserver::NewL( fs, *certStoreFilePath, status );
+            CleanupStack::PushL( observer );
+            pushToStack++;
+             
+            BTIC_TRACE_PRINT("Start active scheduler");            
+            CActiveScheduler::Start();            
+            
+            BTIC_TRACE_PRINT_NUM("File observer status = %d", status );
+            
+            if ( status == KErrNone )
+                {
+                // Boot reason is fromat and certificate file is deleted.
+                // Stop checking and exit.                    
+                BTIC_TRACE_PRINT("Stop checking and exit");
+                certFileFound = EFalse;   
+                binariesCheckEnbled = EFalse;                 
+                }
+            }
+        else
+            {  
+            // Boot reason is fromat and no certificate file is found.
+            // Stop checking and exit.      
+            BTIC_TRACE_PRINT("Stop checking and exit");
+            certFileFound = EFalse;   
+            binariesCheckEnbled = EFalse;        
+            }    
+        }
+               
+ 
+    BTIC_TRACE_PRINT_NUM("Updated store read enabled(1) = %d",certFileFound);
+    BTIC_TRACE_PRINT_NUM("Binaries check enabled(0) = %d",binariesCheckEnbled);           
+   
+    // Create pointer array for root certificates.  
+    RPointerArray<CX509Certificate> x509CertArray;     
+    RPointerArray<TCapabilitySet> certCapaArray;
+    TInt fileError = 0;
+     
+    // Read root certificates if needed.      
+    if ( certFileFound || binariesCheckEnbled )
+        {                                    
+        // Get root certificates to x509 format.  
+        fileError = 
+          ReadCertificatesL( 
+              fs, 
+              KBTICCertStoreZ, 
+              x509CertArray, 
+              certCapaArray );
+
+        // Can't read root certificates or array is empty. 
+        // Let's return and try this in next boot.    
+        if ( fileError || x509CertArray.Count() == 0 )
+            {
+            BTIC_TRACE_PRINT("ERROR Can't read root certificates ! ! !");
+            CleanupStack::PopAndDestroy( pushToStack );
+            x509CertArray.ResetAndDestroy();                   
+            certCapaArray.ResetAndDestroy();
+            User::Leave( fileError );
+            }               
+        }
+              
+    // Create temporary pointer array for C-drive updated certificates. 
+    RPointerArray<CX509Certificate> tempCertArray;  
+    RPointerArray<TCapabilitySet> tempCapaArray;    
+             
+    // If candidate for certstore file is found read it and validate file.
+    if ( certFileFound )
+        {        
+        BTIC_TRACE_PRINT("Read certificates from C");       
+                                        
+        // Read certificates from C drive and set them to x509 format         
+        TRAP( err ,
+            fileError = ReadCertificatesL( 
+                fs, 
+                *certStoreFilePath, 
+                tempCertArray,                                          
+                tempCapaArray ) );
+                
+        BTIC_TRACE_PRINT_NUM("C read file error (0) = %d", fileError );
+        BTIC_TRACE_PRINT_NUM("C read Trap err (0) = %d", err );                
+               
+        // If ReadCertificatesL function leaves, we assume that something is
+        // tampered and the file is corrupted. However if function returns
+        // an error code, file is not corrupted.           
+        if ( err )
+            {
+            fileError = err;
+            TRAP_IGNORE( CorruptFileL( fs, *certStoreFilePath ) );
+            }                     
+                
+        // If there is no error when constructing a permanent file store object
+        // let's continue.                      
+        if ( fileError == KErrNone )
+            {
+            BTIC_TRACE_PRINT("Validate cert store");
+             
+            // Validate the certstore in C if certs are found. 
+            TRAP( err, 
+                  certStoreOk = ValidateCertStoreL( 
+                        fs, 
+                        x509CertArray, 
+                        certCapaArray, 
+                        *certStoreFileName,
+                        *certStoreFilePath ) );
+          
+            BTIC_TRACE_PRINT_NUM("Trap err (0) = %d", err );
+            BTIC_TRACE_PRINT_NUM("Cert storage valid (1) = %d", certStoreOk ); 
+         
+            // If validation fails or function leaves we will assume
+            // that database is tempered and it will be corrupted. 
+            // In practice this mean that all binaries signed with 
+            // certificates in C database will be corrupted.                                                                            
+            if ( ! certStoreOk || err != KErrNone )
+                {                                                    
+                TRAP_IGNORE( CorruptFileL( fs, *certStoreFilePath ) );
+                } 
+                
+            BTIC_TRACE_PRINT("\nStore validation complete"); 
+            }                                                
+        }  
+/*                               
+#ifdef __BTIC_BINARIES_CHECK_ENABLED
+          
+    // If found cert store is valid unite arrays.
+    if ( certStoreOk )
+        {
+        UniteCertArraysL( x509CertArray, tempCertArray ); 
+        // Reset tempCertArray because x509CertArray owns entrys now.
+        tempCertArray.Reset();
+         
+        UniteCapaArraysL( certCapaArray, tempCapaArray );
+        // Reset tempCapaArray because certCapaArray owns entrys now.               
+        tempCapaArray.Reset();
+        }
+
+    // Check that certificates are found before checking binaries.
+    if ( x509CertArray.Count() )
+        {
+        // Check that cert array and capa array has same amount of entrys.
+        // If amount is diffrent do not check binaries. Something is wrong.
+        if ( x509CertArray.Count() == certCapaArray.Count() )
+            {
+            // Check that binaries found in C: are istalled from a valid SIS 
+            // pagaces and binary's hash is valid.        
+            CheckBinariesL( fs, x509CertArray, certCapaArray );              
+            
+            BTIC_TRACE_PRINT("\nBinaries check complete\n");
+            }                     
+        }
+                                  
+#endif //__BTIC_BINARIES_CHECK_ENABLED
+*/      
+                            
+    BTIC_TRACE_PRINT("\nProgram complete\n");
+    // DELETE ALL ARRAYS AND ARRAY CONTENT    
+    x509CertArray.ResetAndDestroy();                
+    tempCertArray.ResetAndDestroy();
+    certCapaArray.ResetAndDestroy();
+    tempCapaArray.ResetAndDestroy();  
+  
+    CleanupStack::PopAndDestroy( pushToStack ); //fs, buffers
+      
+    BTIC_TRACE_PRINT("UHEAP MARK END");
+    __UHEAP_MARKEND;
+    BTIC_TRACE_PRINT_ALLOC_CELLS("End Cell count = %d");
+     
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] PROGRAM END");   
+    return KErrNone;
+    }
+
+
+// -----------------------------------------------------------------------------
+// ReadCertificatesL
+// 
+// This function reads certificates from certificate storage and adds them in to 
+// given cert array if certificate can grant TCB or/and DRM. Also certificates 
+// capability set is added to given capability array. 
+// Given path must be valid one, othervice function returns error code.
+//
+// Returns: KErrNone if successful 
+//          Othervice some system-wide error code.
+// -----------------------------------------------------------------------------
+//
+LOCAL_C TInt ReadCertificatesL( 
+    RFs& aFs,                                        // File server handle 
+    const TDesC& aPath,                              // Path to storage file. 
+    RPointerArray<CX509Certificate>& aX509CertArray, // Cert array.
+    RPointerArray<TCapabilitySet>& aCapabilityArray )// Capability array.
+    {            
+    TInt err = KErrNone;      
+    RFile file;
+    
+    err = file.Open( aFs, aPath, EFileRead );
+    
+    if ( err == KErrNone )
+        {                             
+        CleanupClosePushL( file );
+      
+        CPermanentFileStore* certStore = NULL;
+      
+        // Trap FromL if file is not in correct form it may leave.
+        TRAP( err, certStore = CPermanentFileStore::FromL( file ) );    
+          
+        if ( certStore && err == KErrNone )
+            {
+            CleanupStack::Pop( &file ); // Now owned by store.
+            CleanupStack::PushL( certStore );
+
+            // Read id of cert list stream
+            TStreamId streamId;
+            RStoreReadStream stream;  
+            stream.OpenLC( *certStore, certStore->Root() );     
+            stream >> streamId; 
+            CleanupStack::PopAndDestroy( &stream ); 
+
+            // Read the certificate list
+            RStoreReadStream certEntryStream;
+            certEntryStream.OpenLC( *certStore, streamId );
+
+            // Count entrys from stream.
+            TInt count = certEntryStream.ReadInt32L();    
+            BTIC_TRACE_PRINT_NUM("CertEntryStream count = %d", count );
+                       
+            HBufC8* certDataBuf = NULL;
+                               
+            for ( TInt index = 0 ; index < count ; index++ )
+                {
+                // Read data from stream.
+                CRootCertificateEntry* entry = 
+                    CRootCertificateEntry::NewLC( certEntryStream );
+                        
+                // Get certificate's capabilties from entry.
+                TCapabilitySet* capaSet = 
+                new( ELeave ) TCapabilitySet( entry->Capabilities() );        
+                CleanupStack::PushL( capaSet );
+              
+                // Check that certificate can grant TCB or DRM capabiltiy.                                 
+                if ( capaSet->HasCapability( GetCapability( KBTIC_TCB ) ) || 
+                    capaSet->HasCapability( GetCapability( KBTIC_DRM ) ) )
+                    {         
+                    // Append certificates capability set to array.         
+                    User::LeaveIfError( aCapabilityArray.Append( capaSet ) );
+
+                    CleanupStack::Pop( capaSet );                 
+                        
+                    // Open certificate data stream. This is actual x509 certificate.    
+                    RStoreReadStream stream;                  
+                    stream.OpenLC( *certStore, entry->DataStreamId() );
+                                                      
+                    // Get x509 size.
+                    TInt size = entry->Size();                                  
+
+                    // Since we do not have so meny certs in device let's make alloc
+                    // inside of the loop.                 
+                    certDataBuf = HBufC8::NewMaxLC( size );
+
+                    TPtr8 dataBufPtr = certDataBuf->Des();                       
+                                
+                    // Read x509 binary data to buffer.
+                    stream.ReadL( dataBufPtr, size );                   
+
+                    // Create x509 certificate object from binary data.   
+                    CX509Certificate* x509Cert = 
+                        CX509Certificate::NewLC( *certDataBuf ); 
+
+                    // Append x509 certificate object to pointer array. 
+                    User::LeaveIfError( aX509CertArray.Append( x509Cert ) );
+                                                  
+                    CleanupStack::Pop( x509Cert );
+                    x509Cert = NULL;
+                    CleanupStack::PopAndDestroy( certDataBuf );
+                    certDataBuf = NULL; 
+                    CleanupStack::PopAndDestroy( &stream );                     
+                    }
+                else
+                    {
+                    // Delete capaSet if certificate has not TCB or DRM.
+                    CleanupStack::PopAndDestroy( capaSet );
+                    capaSet = NULL;
+                    }    
+                        
+                CleanupStack::PopAndDestroy( entry );
+                entry = NULL;       
+                }   
+              
+            CleanupStack::PopAndDestroy( 2 );//certStore, certEntryStream               
+            }
+        else
+            {
+            // Clean up file is FromL leaves.
+            CleanupStack::PopAndDestroy( &file );
+            BTIC_TRACE_PRINT("ERROR CPermanentFileStore - Can not read certs.");
+            }           
+        }
+      
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] ReadCertificatesL <---"); 
+  
+    return err;      
+    }                
+
+
+// -----------------------------------------------------------------------------
+// ValidateCertStoreL()
+//
+// This function checks that updated SWI certstore in C drive has been installed 
+// from valid SIS pacage. 
+// SIS pacage must have valid certificate and exe with a TCB capabilities. 
+//
+// NOTE this function assumes that Certprovisioner tool has imei.txt file. 
+//
+// Returns: ETure if successful  
+//          EFalse othervice
+// -----------------------------------------------------------------------------
+//
+LOCAL_C TBool ValidateCertStoreL( 
+    RFs& aFs,                                       // File server handle
+    RPointerArray<CX509Certificate>& aX509CertArray,// Certificate array
+    RPointerArray<TCapabilitySet>& aCapaArray,      // Capability array
+    const TDesC& aCertStoreFileName,
+    const TDesC& aCertStoreFilePath  )     
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] ValidateCertStoreL v2->");
+    __UHEAP_MARK;
+                          
+    TBool storeOK = EFalse;                  
+    
+    RPointerArray<HBufC> updaterExePaths;
+         
+    Swi::RSisRegistrySession sisRegSession;  
+
+    // Leave if we can not connect to sis register. Othervice we have a risk 
+    // that valid files will be renamed if updated certstore is left out.             
+    User::LeaveIfError( sisRegSession.Connect() );
+        
+    CleanupClosePushL( sisRegSession );
+    
+    RPointerArray<CSisRegistryPackage> sisPackages;
+                
+    // Find installed packages.
+    sisRegSession.InstalledPackagesL( sisPackages );            
+            
+    Swi::RSisRegistryEntry entry;        
+        
+    TInt packageUID;   
+        
+    BTIC_TRACE_PRINT("Find matching UID");
+    
+    // If CertProvisioner tool has install updatedswicertstore file.
+    if ( aCertStoreFileName.Compare( KBTICCertStoreCName ) == KErrNone )
+        {
+        BTIC_TRACE_PRINT("UID -> KBTICCertProvUID");
+        packageUID = KBTICCertProvUID;
+        }
+    else
+        {
+        BTIC_TRACE_PRINT("UID -> KBTICSymbianSWIUpdaterUID");
+        packageUID = KBTICSymbianSWIUpdaterUID;
+        }
+                
+    TBool entryOpen = EFalse;       
+    
+    // Search correct sis pagace and open entry to it.
+    for( TInt index = 0; index < sisPackages.Count(); index++)
+        {  
+        BTIC_TRACE_PRINT_NUM("Search entry from sis reg. index = %d", index );
+             
+        if ( sisPackages[index]->Uid() == TUid::Uid( packageUID ) )
+            { 
+            BTIC_TRACE_PRINT("Open entry");
+                                                                    
+            User::LeaveIfError( entry.Open( 
+                sisRegSession, TUid::Uid( packageUID ) ) );
+ 
+            CleanupClosePushL( entry );
+
+            entryOpen = ETrue;                                                          
+            break;                                       
+            }             
+        } 
+                        
+    // Validate cert storage.     
+    if ( entryOpen )
+        {        
+        TBool controllerOk = EFalse;   
+
+#ifdef __BTIC_VERIFY_CONTROLLER        
+        // Check that sis controller is valid.       
+        controllerOk = entry.VerifyControllerSignatureL( aX509CertArray );
+                                     
+        BTIC_TRACE_PRINT("Controller verify ENABLED"); 
+        BTIC_TRACE_PRINT_NUM("Controller verify result (1) = %d", controllerOk );                                             
+#else   
+        // If controller verify is disabled set boolen to true.     
+        controllerOk = ETrue;          
+        BTIC_TRACE_PRINT("Controller verify DISABLED" );      
+#endif
+    
+        if ( controllerOk )
+            {            
+            if ( packageUID == KBTICCertProvUID )
+                {                   
+                storeOK = ValidateProvisonerCertStoreL(
+                    aFs,                                       
+                    aX509CertArray,
+                    aCapaArray,      
+                    aCertStoreFileName,
+                    aCertStoreFilePath,
+                    entry );
+                }
+            else
+                {
+                storeOK = ValidateSymbianCertStoreL(
+                    aFs,                                       
+                    aX509CertArray,
+                    aCapaArray,                                      
+                    entry,
+                    updaterExePaths );
+                }                
+            }                                                        
+        }                       
+                                                   
+    // Cleanup array.           
+    sisPackages.ResetAndDestroy();                                           
+
+    if ( entryOpen )
+        {        
+        CleanupStack::PopAndDestroy(); //RSisRegistryEntry               
+        }
+                       
+    CleanupStack::PopAndDestroy(); //RSisRegistrySession    
+    
+    // Ok Symbian store is valid, let's run Symbian updater exe.
+    // NOTE SisRegistry server etc. has file handle open, so we should
+    // close SisRegistryEntry before running updater. 
+    if ( storeOK && packageUID == KBTICSymbianSWIUpdaterUID )
+        {              
+        storeOK = RunUpdaterL( aFs, updaterExePaths );                        
+        }
+        
+    updaterExePaths.ResetAndDestroy();    
+                  
+    BTIC_TRACE_PRINT("UHEAP MARK END");     
+    __UHEAP_MARKEND;   
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] ValidateCertStoreL v2 <-");        
+    
+    return storeOK;        
+    }
+    
+    
+// -----------------------------------------------------------------------------
+// ValidateProvisonerCertStoreL()
+//
+// 
+//
+//
+// Returns: ETure if successful  
+//          EFalse othervice
+// -----------------------------------------------------------------------------
+//
+LOCAL_C TBool ValidateProvisonerCertStoreL(
+    RFs& aFs,                                       // File server handle
+    RPointerArray<CX509Certificate>& aX509CertArray,// Certificate array
+    RPointerArray<TCapabilitySet>& aCapaArray,      // Capability array
+    const TDesC& aCertStoreFileName,
+    const TDesC& aCertStoreFilePath,
+    RSisRegistryEntry& aEntry )
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] ValidateProvisonerStoreL --->");
+    __UHEAP_MARK;
+        
+    TBool retOK = EFalse;                      
+    // installedFiles array owns entry's files.
+    RPointerArray<HBufC> installedFilesArray;
+    RPointerArray<HBufC> foundFilesArray;  
+    RPointerArray<HBufC> fileArray;  // Files that need to be cheked.
+    RPointerArray<HBufC8> hashArray; // Hash for each fileArray's file.
+    RArray<TUint64> capaArray;              
+    RPointerArray<HBufC> stringArray;
+    HBufC* string = NULL;
+    
+    TUint64* capaVector = new( ELeave ) TUint64[KBTICCapaCount];
+    CleanupArrayDeletePushL( capaVector );
+    capaVector[0] = KBTIC_TCB;
+                                                                                    
+    // Get all installed files from this sis register entry 
+    // to installedFilesArray.                                                            
+    aEntry.FilesL( installedFilesArray );  
+                                                                  
+    // Search all exes from array.   
+    if ( installedFilesArray.Count() > 0 )
+        { 
+        string = KBTICExtensionExe().AllocLC();
+        User::LeaveIfError( stringArray.Append( string ) );
+        CleanupStack::Pop();
+        
+        retOK = SearchFilesFromArrayL( 
+            installedFilesArray,
+            KBTICDriveCWildcard, 
+            stringArray, 
+            foundFilesArray );                                  
+        } 
+                                                                                                               
+    // Find a exe that has TCB capapility and calculate hash over the file. 
+    if ( retOK )                       
+        {                                     
+        retOK = CheckCapabilityWordAndCalcHashL( 
+            aFs, 
+            ETrue, 
+            capaVector, 
+            foundFilesArray,
+            fileArray,
+            hashArray,
+            capaArray );                        
+        }                           
+                                                  
+    // Validate certificate from this entry and check that 
+    // certificate can grant the capability which is neede for the exe (TCB).     
+    if ( retOK )
+        {                                   
+        retOK = SearchValidCertificateL( 
+            aEntry, 
+            aX509CertArray, 
+            aCapaArray, 
+            KBTIC_TCB );     
+        }         
+                 
+    // Calculate hash over each exe file found in this entry.     
+    // Let's be confident that server is not tempered.    
+    if ( retOK )
+        {
+        retOK = EFalse;
+        
+        // Ok so now we should have one TCB file in fileArray and 2 other 
+        // files in foundFilesArray. We do not need to calculate hash over 
+        // TCB files again, so let's remove TCB files from array.              
+        TInt countExe = foundFilesArray.Count();        
+        TInt countTCB =  fileArray.Count();        
+        TBool removeFile = EFalse;                
+        
+        for ( TInt i = countExe-1; i >= 0 ; i-- )
+            {
+            removeFile = EFalse;            
+            
+            for ( TInt k = countTCB-1; k >= 0; k-- )
+                {  
+                // If fileArray has this path remove it.                               
+                if ( (fileArray[k]->Compare( *foundFilesArray[i] )) 
+                    == KErrNone )
+                    {
+                    removeFile = ETrue;                 
+                    }
+                }
+            
+            if ( removeFile )
+                {                
+                foundFilesArray.Remove( i );                      
+                }                          
+            }
+            
+        // Compress array so we don not have null pointers on it.        
+        foundFilesArray.Compress(); 
+        
+        // If all files are removed something is wrong. Return False.
+        if ( foundFilesArray.Count() )
+            {
+            // Ok let's calculate hashes for the other exes.
+            retOK = CheckCapabilityWordAndCalcHashL( 
+                aFs, 
+                EFalse, 
+                0, 
+                foundFilesArray,
+                fileArray,
+                hashArray,
+                capaArray );                             
+            }                   
+        }          
+           
+    // Remove previous strings from array.
+    stringArray.ResetAndDestroy();
+    // Remove pointers from array. Let's not calc. hash again.
+    foundFilesArray.Reset();                                    
+     
+    // Search imei.txt file from array and check that device's serial number
+    // is found in the file. NOTE file name must be imei.txt. 
+    if ( retOK )
+        {          
+        retOK = EFalse;
+                                 
+        string = KBTICSerialNumberFile().AllocLC();
+        User::LeaveIfError( stringArray.Append( string ) );
+        CleanupStack::Pop();
+               
+        TBool foundFile = SearchFilesFromArrayL( 
+            installedFilesArray,
+            KBTICDriveCWildcard, 
+            stringArray, 
+            foundFilesArray );               
+                                   
+        if ( foundFile && foundFilesArray.Count() )
+            {
+            retOK = CheckSerialNumberL( aFs, *foundFilesArray[0] ); 
+            }                            
+        }        
+    
+    // Calculate hash over each file (*.dat and imei.txt) and check that 
+    // sisregistery has same hash (*.exe,*.dat,imei.txt).             
+    if ( retOK )
+        {        
+        retOK = EFalse;
+                        
+        // Note that certstore path from sis reg. points to private 
+        // directory not file's current logation. So we have to switch 
+        // file paths to get correct hash.
+
+        // Remove previous strings from array.
+        stringArray.ResetAndDestroy();
+                        
+        string = HBufC::NewLC( 
+            aCertStoreFileName.Length() + 
+            sizeof( KBTICStarWildcard ) );            
+        TPtr stringPtr = string->Des();  
+        
+        // Append certstorage name and wildcard (*\\) to string for search. 
+        // String should be = "*\\filename.dat"  Let's add "\\" to string
+        // so search do not accept eg. Öfilename.dat etc.
+        stringPtr.Copy( KBTICStarWildcard );     
+        stringPtr.Append( aCertStoreFileName );
+         
+        User::LeaveIfError( stringArray.Append( string ) );
+        CleanupStack::Pop(); //String                
+                                        
+        // Search correct certstorage file from installedFilesArray.(sis reg.)                           
+        TBool foundFile = SearchFilesFromArrayL( 
+            installedFilesArray,
+            KBTICDriveCWildcard, 
+            stringArray, 
+            foundFilesArray );                   
+                
+        if ( foundFile )
+            { 
+            BTIC_TRACE_PRINT("Correct CertStore file found");
+                                   
+            // Get original certstorage path from array. 
+            HBufC* sisRegPath = foundFilesArray[foundFilesArray.Count() - 1];
+                
+            // Remove original path from array.     
+            foundFilesArray.Remove( foundFilesArray.Count() - 1 );
+            CleanupStack::PushL( sisRegPath ); //sisRegPath
+            
+            // Get current certstorage path.
+            HBufC* currentPath = aCertStoreFilePath.AllocLC();
+
+            // Set current path to array. So now we get correct hash. 
+            foundFilesArray.Append( currentPath );
+            CleanupStack::Pop(); //currentPath
+
+            BTIC_TRACE_PRINT("Calculate HASH for files");
+
+            // Calculate hash over files in foundFilesArray and add result to
+            // filesArray and hashArray                                 
+            CheckCapabilityWordAndCalcHashL( 
+                aFs, 
+                EFalse, 
+                0, 
+                foundFilesArray,
+                fileArray,
+                hashArray,
+                capaArray );   
+                
+             // Ok now we have correct hash but certstore path is not 
+             // correct for sis register. So we have to copy original 
+             // certstorage file path from sis reg. to filesArray.
+             
+             // Remove currentPath entry from array.             
+             fileArray.Remove( fileArray.Count() - 1 );
+             
+             // Delete currentPath buffer. We need to delete buffer because 
+             // we call only reset for foundFilesArray. Reset do not delete 
+             // buffer.  
+             delete currentPath;
+             
+             // Append orginal path from sis reg. for hash checking. 
+             fileArray.Append( sisRegPath ); 
+             CleanupStack::Pop(); //sisRegPath                                                                
+                                         
+            // Check that sis registery entry has same hash as we have.                                                                                                                                              
+            retOK = VerifyHashL( aEntry, fileArray, hashArray );   
+                         
+            }                                                                       
+        }
+    
+    CleanupStack::PopAndDestroy(); //capaVector   
+                                              
+    // Reset only. InstalledFiles array owns buffers.
+    foundFilesArray.Reset();
+    fileArray.Reset(); 
+    hashArray.ResetAndDestroy();                                    
+    installedFilesArray.ResetAndDestroy();         
+    stringArray.ResetAndDestroy(); 
+    capaArray.Close();                 
+    
+    BTIC_TRACE_PRINT("UHEAP MARK END");     
+    __UHEAP_MARKEND;
+    
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] ValidateProvisonerStoreL <---");
+    
+    return retOK;    
+    }
+  
+            
+// -----------------------------------------------------------------------------
+// ValidateSymbianCertStoreL()
+//
+// 
+//
+//
+// Returns: ETure if successful  
+//          EFalse othervice
+// -----------------------------------------------------------------------------
+//
+LOCAL_C TBool ValidateSymbianCertStoreL(
+    RFs& aFs,                                       // File server handle
+    RPointerArray<CX509Certificate>& aX509CertArray,// Certificate array
+    RPointerArray<TCapabilitySet>& aCapaArray,      // Capability array        
+    RSisRegistryEntry& aEntry,
+    RPointerArray<HBufC>& aUpdaterExePaths )
+    {  
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] ValidateSymbianStoreL v2 --->");   
+      
+    TBool retOK  = EFalse;                       
+    // installedFiles array owns entry's files.
+    RPointerArray<HBufC> installedFilesArray;
+    RPointerArray<HBufC> foundFilesArray;  
+    RPointerArray<HBufC> fileArray;  // Files that need to be cheked.
+    RPointerArray<HBufC8> hashArray; // Hash for each fileArray's file.
+    RArray<TUint64> capaArray;              
+    RPointerArray<HBufC> stringArray;
+    HBufC* string = NULL;
+    
+    TUint64* capaVector = new( ELeave ) TUint64[KBTICCapaCount];
+    CleanupArrayDeletePushL( capaVector );
+    capaVector[0] = KBTIC_TCB;
+                                                                                   
+    // Get all installed files from this sis register entry 
+    // to installedFilesArray.                                                            
+    aEntry.FilesL( installedFilesArray );                                          
+                     
+    // Search all exes from array.   
+    if ( installedFilesArray.Count() > 0 )
+        { 
+        string = KBTICExtensionExe().AllocLC();
+        User::LeaveIfError( stringArray.Append( string ) );
+        CleanupStack::Pop();
+        
+        retOK = SearchFilesFromArrayL( 
+            installedFilesArray,
+            KBTICDriveCWildcard, 
+            stringArray, 
+            foundFilesArray );                                  
+        } 
+                                                                                             
+    // Find a exe that has TCB capapility and calculate hash over the file. 
+    if ( retOK )                       
+        {                                     
+        retOK = CheckCapabilityWordAndCalcHashL( 
+            aFs, 
+            ETrue, 
+            capaVector, 
+            foundFilesArray,
+            fileArray,
+            hashArray,
+            capaArray );                        
+        }    
+                                                          
+    // Validate certificate from this entry and check that 
+    // certificate can grant the capability which is neede for the exe (TCB).     
+    if ( retOK )
+        {                                   
+        retOK = SearchValidCertificateL( 
+            aEntry, 
+            aX509CertArray, 
+            aCapaArray, 
+            KBTIC_TCB );     
+        } 
+    
+    // Check that sis registery has same hash as we have.              
+    if ( retOK )
+        {                                                  
+        retOK = VerifyHashL( aEntry, fileArray, hashArray );             
+        } 
+    
+    // Return exe's path to caller. NOTE Updater exe can not be executed
+    // before SisRegistryEntry is closed.    
+    if ( retOK )
+        {
+        // We will assume that updater has only one exe with TCB.
+        HBufC* path = fileArray[0]->AllocLC();          
+        // Append path to pointer array. 
+        User::LeaveIfError( aUpdaterExePaths.Append( path ) );         
+        CleanupStack::Pop(); //path          
+        }
+   
+    CleanupStack::PopAndDestroy(); //capaVector   
+                                              
+    // Reset only. InstalledFiles array owns buffers.
+    foundFilesArray.Reset();
+    fileArray.Reset(); 
+    hashArray.ResetAndDestroy();                                    
+    installedFilesArray.ResetAndDestroy();         
+    stringArray.ResetAndDestroy();  
+    capaArray.Close();              
+        
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] ValidateSymbianStoreL v2 <---"); 
+                                     
+    return retOK;
+    }
+
+
+// -----------------------------------------------------------------------------
+// RunUpdaterL()
+//
+// Returns: ETure if successful  
+//          EFalse othervice
+// -----------------------------------------------------------------------------
+// 
+LOCAL_C TBool RunUpdaterL( RFs& aFs, RPointerArray<HBufC>& aUpdaterExePaths )
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] RunUpdaterL ->");
+    // SIS register do not have hash values for storage file if it is provided 
+    // by Symbian SWI updater exe. We have to remove current storage file 
+    // and run exe again to get a verified swicertstorage in folder.
+            
+    TBool retOK = EFalse; 
+    
+    BTIC_TRACE_PRINT("Delete old store file(s)");          
+    // Delete all files from dat folder. If delete fails storage file is 
+    // corrupted.
+    // NOTE that SisRegistry Server has some closing time so we must try this 
+    // in loop.                
+    for ( TInt loop = 0; loop < KBTICTryToOpen; loop++ )
+        {                
+        if ( DeleteAllFilesL( aFs, KBTICCertStoreCPath ) )
+            {            
+            // We will assume that updater has only on exe with TCB.
+            HBufC* updaterExePath = aUpdaterExePaths[0];
+                                                           
+            RProcess process;
+            
+            BTIC_TRACE_PRINT("Run updater exe to get new store file"); 
+            
+            for ( TInt i = 0; i < KBTICTryToCreate; i++ )
+                {  
+                BTIC_TRACE_PRINT("Try to create Updater process");
+                              
+                if ( process.Create( *updaterExePath, KNullDesC ) == KErrNone )
+                    {
+                    // Run updater exe again.
+                    process.Resume(); 
+                    // Get rid of our handle. 
+                    process.Close();
+                                        
+                    retOK = ETrue;  
+
+                    BTIC_TRACE_PRINT("Updater process started OK"); 
+                    break;                                                 
+                    }                
+                }
+                                        
+            // Break the loop if delete is succesful.    
+            break;    			                                      
+            }
+        else
+            {
+            BTIC_TRACE_PRINT_NUM("Wait 0.5 sec. Attempt nr.%d", loop );
+            User::After( 500000 );
+            }                                                                   
+        }
+        
+    return retOK;                                                     
+    }
+
+// -----------------------------------------------------------------------------
+// DeleteAllFiles()
+//
+// Delete all files from given folder.
+//
+// Returns: ETure if successful  
+//          EFalse othervice
+// -----------------------------------------------------------------------------
+// 
+LOCAL_C TBool DeleteAllFilesL( RFs& aFs, const TDesC& aFolderPath )
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] DeleteAllFilesL ");
+    
+    TBool folderEmpty = EFalse;                      
+    CDir* entryList = NULL; 
+    TBuf<KMaxFileName> path;        
+    
+    // Get all files from folder.    
+    if ( KErrNone == 
+            aFs.GetDir ( 
+                aFolderPath, 
+                KEntryAttNormal, 
+                ESortByName|EDirsFirst, 
+                entryList ) )
+        {
+        if ( entryList )
+            {
+            CleanupStack::PushL( entryList );
+            
+            TInt delCount = KErrNone;
+            TInt count = entryList->Count();            
+            
+            for ( TInt index = 0; index < count; index++ )
+                {
+                // Get file name.
+                const TEntry& entry = (*entryList)[index];
+                
+                // Set path to file. 
+                path.Copy( aFolderPath );
+                path.Append( entry.iName ); 
+                
+                // Remove Read Only attribute.
+                TInt err = aFs.SetAtt( path, 0, KEntryAttReadOnly );
+                BTIC_TRACE_PRINT_NUM("Remove Read Only attrib. = %d", err );                                 
+                       
+                if ( KErrNone == aFs.Delete( path ) )
+                    {                    
+                    delCount++;
+                    BTIC_TRACE_PRINT_NUM("Delete file with index = %d", index);
+                    }
+                }
+            
+            // If all files are removed.           
+            if ( delCount == count )
+                {
+                folderEmpty = ETrue; 
+                BTIC_TRACE_PRINT("All files removed");
+                }
+
+            CleanupStack::PopAndDestroy( 1, entryList );                             
+            }                                     
+        }
+                                    
+    return folderEmpty;
+    }
+
+
+// -----------------------------------------------------------------------------
+// SearchFilesFromArrayL
+// 
+// This function search file names containing given string from aSourceArray and 
+// add found file (path) to an aFilesArray. Search is limited to specified drive 
+// and path.
+// Note this function only adds source arrays pointers to files array. It dos not
+// create new heap descriptor.    
+// 
+//
+// Returns: ETure if successful  
+//          EFalse othervice
+// -----------------------------------------------------------------------------
+// 
+LOCAL_C TBool SearchFilesFromArrayL( 
+    RPointerArray<HBufC>& aSourceArray, // Array for searching.
+    const TDesC& aDriveAndPath,         // Accepted drive or/and path. 
+    RPointerArray<HBufC>& aStringArray, // String to be searched from path.
+    RPointerArray<HBufC>& aFilesArray ) // Result array.
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] SearchFilesFromArrayL --->");
+
+    TBool retVal = EFalse; 
+                
+    TInt count = aSourceArray.Count();
+    TInt stringCount = aStringArray.Count();
+    
+    // This loop gos through all paths from aSourceArray.                                 
+    for ( TInt index = 0; index < count; index++ )
+        {                
+        HBufC* filePath = aSourceArray[index];
+        
+        // Convert descriptor to lower case so we don't get problems with 
+        // Match or Compare functions. 
+        TPtr filePathPtr = filePath->Des();
+        filePathPtr.LowerCase(); 
+        
+        // Check that file is in correct directory.
+        TInt offsetA = filePath->Match( aDriveAndPath );
+        
+        if ( offsetA >= 0 )
+            {                                                       
+            // This loop gos through all strings what we are looking for.
+            for ( TInt indexB = 0; indexB < stringCount; indexB++ )
+                {                                
+                // Search string from file path.            
+                TInt offset = filePath->Match( *aStringArray[indexB] );
+                                                    
+                if ( offset >= 0 )
+                    {            
+                    User::LeaveIfError( aFilesArray.Append( filePath ) );  
+                                        
+                    retVal = ETrue;                                    
+                    }
+                }  
+            }
+        }                              
+     
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] SearchFilesFromArrayL <---");         
+        
+    return retVal;                    
+    }
+
+
+// -----------------------------------------------------------------------------
+// SearchValidCertificateL
+// 
+// This function validates entry's certificate against to certificate found in 
+// given array. It check also that certificate has rigth to grant given 
+// capability. 
+//
+// Note This function only validates first chain.    
+// 
+// Returns: ETure if successful  
+//          EFalse othervice
+// -----------------------------------------------------------------------------
+//              
+LOCAL_C TBool SearchValidCertificateL( 
+    RSisRegistryEntry& aEntry,                      // SIS Registery entry
+    RPointerArray<CX509Certificate>& aX509CertArray,// Array for certificates
+    RPointerArray<TCapabilitySet>& aCertCapaArray,  // Array for certs capability
+    TUint64 aCapability )                           // Needed capabiltiy
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] SearchValidCertificate v2.1 --->");      
+
+    RPointerArray<HBufC8> binaryCertChainArray;
+    // Get certificates in binary format.
+    aEntry.CertificateChainsL( binaryCertChainArray );
+                            
+    TInt chainCount = binaryCertChainArray.Count();
+    BTIC_TRACE_PRINT_NUM("Entry chain count (1) = %d", chainCount );
+        
+    TBool retVal = EFalse;                                                                  
+
+    RPointerArray<CX509Certificate> chainCertArray;
+
+    // Check all entry's chains    
+    for ( TInt chain = 0; chain < chainCount; chain++ )
+        {  
+        BTIC_TRACE_PRINT_NUM("Check chain nr = %d", chain);
+                                   
+        TPtr8 chainData = binaryCertChainArray[chain]->Des();
+
+        TInt pos = 0;
+        TInt end = chainData.Length();                                                    
+
+        // Get all certificates from chain.
+        while ( pos < end )
+            {                                   
+            CX509Certificate* decoded = 
+                CX509Certificate::NewLC( chainData, pos ); 
+                                    
+            // Add x509 certificate to pointter array. 
+            User::LeaveIfError( chainCertArray.Append( decoded ) );  
+                                                                     
+            CleanupStack::Pop( decoded );
+            }
+                       
+        TInt chainCertCount = chainCertArray.Count();    
+        BTIC_TRACE_PRINT_NUM("Chain's certificate count = %d", chainCertCount);
+
+        // Search certificate issued to root and verify signature against the root.
+        if ( chainCertCount > 0 )
+            {        
+            BTIC_TRACE_PRINT("Validate last cert against root");                  
+            // Last cert in chain should be issued to root.
+            const CX509Certificate* x509LastChainCert = chainCertArray[chainCertCount-1];    
+                
+            TInt rootCertCount = aX509CertArray.Count();                   
+            BTIC_TRACE_PRINT_NUM("Root cert array count = %d", rootCertCount);
+            TBool rootFound = EFalse;
+            TInt rootIndex = 0;         
+                
+            // Find matching root certificate and validate certificates.
+            for ( rootIndex = 0; rootIndex < rootCertCount; rootIndex++ )
+                {
+                BTIC_TRACE_PRINT_NUM("Root cert index = %d", rootIndex );
+                            
+                const CX509Certificate* x509RootCert = aX509CertArray[rootIndex];
+
+                // Compare entry cert's issuer to root cert's subject. 
+                if ( x509LastChainCert->IssuerName().ExactMatchL(
+                     x509RootCert->SubjectName() ) )
+                    {
+                    BTIC_TRACE_PRINT("Root found for this chain"); 
+                    BTIC_TRACE_PRINT("Verify signature");                                
+                    
+                    // Verify signature 
+                    if ( x509LastChainCert->VerifySignatureL( 
+                        x509RootCert->PublicKey().KeyData() ) )
+                        {                                                    
+                        BTIC_TRACE_PRINT("Signature OK");                    
+                        rootFound = ETrue;
+                        break; // Break loop.
+                        }
+                    }
+                }            
+              
+              // If root is found we have correct chain.
+              if ( rootFound )
+                  {              
+                  // If Chain has more then one certificate, verify chain.
+                  if ( chainCertCount > 1 )
+                    {
+                    BTIC_TRACE_PRINT("Verify certificate chain"); 
+                    TBool chainOK = ETrue;
+                    TInt certindex;
+                    
+                    for ( certindex = 0; certindex < chainCertCount-1; certindex++ )
+                        {    
+                        BTIC_TRACE_PRINT_NUM("Cert index = %d", certindex);
+                        BTIC_TRACE_PRINT_NUM("Signature Cert index = %d", certindex+1);                    
+                                        
+                        const CX509Certificate* cert = chainCertArray[certindex];
+                        const CX509Certificate* signatureCert = 
+                            chainCertArray[certindex+1];                    
+                                            
+                        // Compare issuer name to subject name.
+                        if ( cert->IssuerName().ExactMatchL(
+                             signatureCert->SubjectName() ) )
+                            {  
+                            BTIC_TRACE_PRINT("Issuer match found."); 
+                            BTIC_TRACE_PRINT("Verify signature against next cert");                                               
+                            // Validate certificate 
+                            if ( ! cert->VerifySignatureL( 
+                                signatureCert->PublicKey().KeyData() ) )
+                                {                                                    
+                                // Chain is broken. Validation failed. 
+                                BTIC_TRACE_PRINT("ERROR Chain broken, validation failed"); 
+                                chainOK = EFalse;
+                                break;                       
+                                } 
+                            }
+                         else
+                            {
+                            // Issuer do not match. Validation failed.
+                            BTIC_TRACE_PRINT("ERROR Chain broken, issuer error"); 
+                            chainOK = EFalse;
+                            break;
+                            }   
+                        }
+                    
+                    if ( chainOK )
+                        {
+                        BTIC_TRACE_PRINT("Entry's chain valid"); 
+                        retVal = ETrue;
+                        }
+                                   
+                    }
+                  // Chain has only one certificate, root.  
+                  else
+                    {
+                    BTIC_TRACE_PRINT("Entry's chain has only one certificate"); 
+                    retVal = ETrue;
+                    }  
+                    
+                  }
+              else
+                {
+                BTIC_TRACE_PRINT("No root found for this chain");
+                retVal = EFalse; 
+                }
+
+            // Check that matching root certificate has same capablitiy 
+            // as aCapability parameter.
+            if ( aCapability && retVal )
+                {            
+                TCapabilitySet* rootCapaSet = aCertCapaArray[rootIndex];  
+                
+                retVal = rootCapaSet->HasCapability( GetCapability( aCapability ) );
+                }
+            
+            // Reset array for next chain.                                                             
+            chainCertArray.ResetAndDestroy();  
+            }
+        
+        // If this is a valid certificate chain, break to loop.   
+        if ( retVal )
+            {                
+            break;
+            }
+            
+        } // FOR LOOP
+                    
+    binaryCertChainArray.ResetAndDestroy();
+    
+                                        
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] SearchValidCertificate v2.1 <---");         
+    
+    return retVal;
+    }
+
+
+// -----------------------------------------------------------------------------
+// GetCapability
+// 
+// This function converts 64 bit capability integer to Symbian capability 
+// enumeration. 
+//
+// Returns: ECapabilityTCB if capabilty is TCB 
+//          ECapabilityDRM if capabilty is DRM
+//          ECapability_Denied if capability not found 
+// -----------------------------------------------------------------------------
+//  
+LOCAL_C TCapability GetCapability( TUint64 aCapability )
+    {            
+    if ( aCapability == KBTIC_TCB )
+        {        
+        return ECapabilityTCB;
+        }
+        
+    else if ( aCapability == KBTIC_DRM )    
+        {        
+        return ECapabilityDRM;
+        }
+        
+    else
+        {
+        BTIC_TRACE_PRINT("! ! ERROR GetCapability -> ECapability_Denied ! !");
+        return ECapability_Denied;
+        }            
+    }
+
+
+// -----------------------------------------------------------------------------
+// VerifyHashL
+// 
+// This function compare file's hash to hash found in SIS Register. 
+//
+// Returns: ETure if all compare operations was successful.  
+//          EFalse other vice
+// -----------------------------------------------------------------------------
+//  
+LOCAL_C TBool VerifyHashL(    
+    RSisRegistryEntry& aEntry, 
+    RPointerArray<HBufC>& aPathArray,
+    RPointerArray<HBufC8>& aHashArray )
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] VerifyHashL --->");
+    __UHEAP_MARK;
+           
+    TBool retVal = EFalse; 
+    TInt hashOk = 0;                        
+    TInt count = aPathArray.Count();                    
+    
+    for ( TInt index = 0; index < count; index++ )
+        {        
+        // Take first file        
+        HBufC* path = aPathArray[index];
+        HBufC8* hash = aHashArray[index];
+                                            
+        if ( CompareToRegisteryHashL( 
+            aEntry, 
+            *path, 
+            *hash ) )
+            {
+            hashOk++;                    
+            }                                                               
+        }
+        
+    // If all hashes are ok return ETrue.
+    if ( hashOk == count )
+        {
+        BTIC_TRACE_PRINT("\nAll hashes are ok\n");
+        retVal = ETrue;
+        }
+         
+     __UHEAP_MARKEND;     
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] VerifyHashL <---");
+    
+    return retVal;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CompareToRegisteryHashL
+// 
+// Note this function returns EFalse is HashL function leaves.   
+//
+// Returns: ETure if hash is valid.
+//          EFalse if hash was not valid.
+// -----------------------------------------------------------------------------
+// 
+LOCAL_C TBool CompareToRegisteryHashL( 
+    RSisRegistryEntry& aEntry, 
+    TDesC& aEntryFile, 
+    TDesC8& aHashBuffer )
+    {    
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] CompareToRegisteryHashL --->");    
+       
+    TInt err = 0; 
+    TBool hashOk = EFalse;    
+    CHashContainer* hashContainer = NULL; 
+
+    BTIC_TRACE_PRINT("Get hash for file: ");        
+    BTIC_TRACE_PRINT_RAW( aEntryFile );     
+    
+    BTIC_TRACE_PRINT("RSisRegistryEntry.HashL()");                       
+    // Get hashConteiner for given file. 
+    TRAP( err, hashContainer = aEntry.HashL( aEntryFile ) ); 
+                
+    if ( err == KErrNone && hashContainer )    
+        {                            
+        CleanupStack::PushL( hashContainer );
+        
+        // Get hash data from hashConteiner.                                                                                                                                       
+        TBufC8<KBTICHashSize> hashFromReg( hashContainer->Data() );
+                                                
+        if ( hashFromReg.Compare( aHashBuffer ) == 0 )
+            {
+            hashOk = ETrue;
+            
+            BTIC_TRACE_PRINT("Hash ok"); 
+            }
+                                               
+        CleanupStack::PopAndDestroy(); //hashContainer       
+        }
+    else
+        {
+        // If HashL function leaves, return false.          
+        hashOk = EFalse;
+        BTIC_TRACE_PRINT_NUM("ERROR RSisRegistryEntry HashL = %d", err ); 
+        }    
+              
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] CompareToRegisteryHashL <---");         
+           
+    return hashOk;
+    }
+    
+    
+// -----------------------------------------------------------------------------
+// CheckSerialNumberL
+//
+// This function opens IMEI file and checks that device's serial number is found 
+// in the file.
+//
+// Returns: ETure if serial number is found or some error with server. 
+//          EFalse if serial number not found
+// -----------------------------------------------------------------------------
+//     
+LOCAL_C TBool CheckSerialNumberL( RFs& aFs, const TDesC& aFileName )
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] CheckSerialNumberL --->");
+    __UHEAP_MARK;      
+    
+    TBool matchFound = EFalse;        
+           
+    RInfoServerClient server;
+              
+    // Connect to server.    
+    TInt err = server.Connect();
+    
+    BTIC_TRACE_PRINT_NUM("Server connect error = %d", err );
+    
+    if ( err == KErrNone )
+        {            
+        CleanupClosePushL( server );
+        
+        TBuf<RMobilePhone::KPhoneSerialNumberSize> deviceSerialNumber;
+                            
+        // Get device serial number from server.
+        err = server.GetSerialNumber( deviceSerialNumber );          
+        
+        RFile file;  
+            
+        if ( err == KErrNone )
+            {                        
+            // Open text file.
+            User::LeaveIfError( file.Open( aFs, aFileName, EFileRead ) );         
+            CleanupClosePushL( file );
+          
+            TInt size; 
+            file.Size( size );
+          
+            HBufC8* content = HBufC8::NewLC( size );      
+            TPtr8 ptr(content->Des());
+
+            // Read content
+            User::LeaveIfError( file.Read( ptr, size ) );                                
+            
+            TLex8 input( ptr );
+            TBool lineEnd( EFalse );
+            TChar ch;
+
+            TBuf<RMobilePhone::KPhoneSerialNumberSize> serialNumber;                
+            
+            while ( ! input.Eos() )
+                {                         
+                ch = input.Get();
+                                                          
+                if ( ( ch != '\n' ) && ( ch != '\r' ) )
+                    {
+                    // Check that we have space for next number. 
+                    if ( serialNumber.Size() < serialNumber.MaxSize() )
+                        {
+                        serialNumber.Append( ch ); 
+                        } 
+                    else
+                        {
+                        // Buffer size is 50 and it should be enoug, if not 
+                        // then something is wrong. Let's break to loop and
+                        // return false.      
+                        break;
+                        }                                        
+                   }                                  
+                else
+                   {
+                   lineEnd = ETrue;
+                   }
+
+                if ( ( lineEnd ) || ( input.Eos() ) )
+                   {                   
+                   if ( deviceSerialNumber == serialNumber )
+                        {
+                        BTIC_TRACE_PRINT("Correct serial number found");
+                        matchFound = ETrue;
+                        break;
+                        }                              
+                   
+                   serialNumber.FillZ(0);
+                   serialNumber.SetLength(0);
+                   lineEnd = EFalse;
+                   }               
+                }                
+            CleanupStack::PopAndDestroy( 2 ); //file, content                   
+            }                       
+        CleanupStack::PopAndDestroy(); //client                                                           
+        }  
+                
+    __UHEAP_MARKEND;                                  
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] CheckSerialNumberL <---");
+                         
+    return matchFound;     
+    }
+ 
+           
+// -----------------------------------------------------------------------------
+// CorruptFileL
+//
+// This function corrupts certificate file so that certs can not be read.
+// -----------------------------------------------------------------------------
+//
+LOCAL_C void CorruptFileL( RFs& aFs, const TDesC& aFileName )
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] ! ! CORRUPT STORE FILE ! !");           
+              
+    TFindFile find( aFs );
+    
+    TUint8 byteVector[8] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF };    
+    
+    // Find given file in C drive.
+    if ( find.FindByDir( aFileName, KBTICDriveC ) == KErrNone )
+        {             
+        RFile file;
+        TInt err;
+                     
+        for ( TInt loop = 0; loop < KBTICTryToOpen; loop++ )
+            {
+            err = file.Open( aFs, aFileName, EFileRead | EFileWrite );
+            BTIC_TRACE_PRINT_NUM("File Open error = %d", err );            
+            
+            // If file is open or it has ReadOnly attribute wait and try again. 
+            if ( err )
+                {
+                BTIC_TRACE_PRINT_NUM("Wait 0.5 sec. Attempt nr.%d", loop );
+                User::After( 500000 );
+                
+                TInt seterr = aFs.SetAtt( aFileName, 0, KEntryAttReadOnly );
+                BTIC_TRACE_PRINT_NUM("Remove Read Only attrib. = %d", seterr );                    
+                }
+            else
+                {
+                break;
+                }    
+            }
+            
+        // Leave if error.
+        User::LeaveIfError( err );          
+        
+        CleanupClosePushL( file );
+           
+        TInt size = 0;
+        file.Size( size );
+
+        HBufC8* fileData = HBufC8::NewLC( size );
+        TPtr8 dataPtr = fileData->Des();                        
+
+        HBufC8* newFileData = HBufC8::NewLC( size + sizeof( byteVector ) );
+        TPtr8 newDataPtr = newFileData->Des();
+
+        file.Read( dataPtr ); 
+        // Copy corrupted bytes to buffer.
+        newDataPtr.Copy( &byteVector[0], sizeof( byteVector ) ); 
+        // Copy original file data to buffer.
+        newDataPtr.Append( dataPtr );            
+        // Write data at start of file.  
+        file.Write( 0, *newFileData ); 
+
+        file.Flush();  
+
+        CleanupStack::PopAndDestroy( 3 ); 
+        
+        BTIC_TRACE_PRINT("File corrupted" );        
+        }                        
+    }
+
+
+// -----------------------------------------------------------------------------
+// CheckCapabilityWordAndCalcHashL
+//
+// This function reads capability word from file heder and compares that to given
+// capability (aCapaVector). If there is more then one whanted capability the 
+// first match is selected. If match is found file path is added to aFilesArray
+// and hash is calculated over the binary and found capa is added to array. 
+// If aCheckCapa is set as EFalse, capability word is not checked and all files 
+// from aSourceArray is added to aFilesArray.
+// Note aCapaArray conteins only matched capability. Not all file's capabilities.
+//
+// Returns: ETure if successful  
+//          EFalse othervice
+// -----------------------------------------------------------------------------
+//        
+LOCAL_C TBool CheckCapabilityWordAndCalcHashL( 
+    RFs& aFs,                           // File server handle
+    TBool aCheckCapa,                   // Enables capability check.
+    TUint64* aCapaVector,               // Vector con. capa. that are checked.
+    RPointerArray<HBufC>& aSourceArray, // Files to be checked.
+    RPointerArray<HBufC>& aFilesArray,  // Passed files
+    RPointerArray<HBufC8>& aHashArray,  // File's hash
+    RArray<TUint64>& aCapaArray )       // File's capability.
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] CheckCapaWordAndCalcHashL v3.1 ->");
+       
+    TFindFile find( aFs );    
+    
+    TInt pathCount = aSourceArray.Count();    
+    
+    TBool retVal = EFalse;     
+    TInt index;
+    TInt err;    
+    
+    CSHA1* sha = CSHA1::NewL();
+    CleanupStack::PushL( sha );
+    
+    RFile file; 
+    
+    for ( index = 0; index < pathCount; index++ )
+        {
+        BTIC_TRACE_PRINT_NUM("File array index = %d", index );
+        
+        HBufC* path = aSourceArray[index]; 
+        
+        BTIC_TRACE_PRINT("File path: ");
+        BTIC_TRACE_PRINT_RAW( *path );        
+                                                            
+        err = file.Open( aFs, *path, EFileShareReadersOnly );              
+      
+        if ( err == KErrNone )
+            {                               
+            CleanupClosePushL( file );                
+
+            TInt size = 0; 
+            file.Size( size );                                                               
+
+            // Alloc buffer for file.
+            HBufC8* buffer = HBufC8::NewLC( size );
+
+            if ( buffer )
+                {
+                TPtr8 bufferPtr = buffer->Des();                            
+
+                // Read file binary to buffer.          
+                err = file.Read( bufferPtr );               
+                                 
+                if ( err == KErrNone || buffer->Length() != 0 )
+                    { 
+                    TUint64 capa = 0;
+                    TBool capabilityOk = EFalse;   
+                     
+                    // Check capability if needed.                    
+                    if ( aCheckCapa )
+                        {
+                        // Get pointer to heap buffer.
+                        const TUint8* ptr = buffer->Ptr();   
+                                                     
+                        // Capapility word (64bit) is found in 0x88 bytes after 
+                        // file heder offset. 0x88 = 136 bytes/8=17 words@64.                                                     
+                        TUint64 word = ((TUint64*)ptr)[KBTICCabaWordOffset]; 
+                                                                            
+                        for ( TInt iCapa = 0; iCapa < KBTICCapaCount; iCapa++ ) 
+                            {
+                            BTIC_TRACE_PRINT_NUM("Capa index = %d", iCapa );
+                            
+                            capa = aCapaVector[iCapa];
+                            
+                            if ( (word & capa) == capa )
+                                {  
+                                BTIC_TRACE_PRINT("Capability match found");                      
+                                capabilityOk = ETrue;
+                                break;
+                                }                                     
+                            }                                                              
+                        }
+                        
+                    // If capa check is not needed calculate hash over the file. 
+                    // Capability is set as zero.   
+                    else
+                        {
+                        BTIC_TRACE_PRINT("Capability NOT REGUIRED");
+                        capabilityOk = ETrue;    
+                        }
+                                           
+                    if ( capabilityOk )
+                        {              
+                        BTIC_TRACE_PRINT("Append file information to array"); 
+                        
+                        // Add found capability to array
+                        User::LeaveIfError( aCapaArray.Append( capa ) );                    
+                                                                         
+                        // Append pointer to files path.
+                        User::LeaveIfError( aFilesArray.Append( path ) ); 
+                                               
+                        HBufC8* hash = HBufC8::NewLC( KBTICHashSize );                        
+                        TPtr8 hashPtr = hash->Des();
+                                                                                
+                        sha->Reset();                        
+                                                
+                        // Calucalte hash over file's binary.
+                        hashPtr.Copy( sha->Hash( bufferPtr ) );
+                        
+                        // Check that digest has correct length.
+                        if ( hash->Length() != KBTICHashSize )
+                            {
+                            BTIC_TRACE_PRINT("\nERROR HASH SIZE"); 
+                            User::Leave( KErrGeneral );
+                            }                                                        
+                        
+                        // Add file's hash to array
+                        User::LeaveIfError( aHashArray.Append( hash ) );                                                  
+                        
+                        CleanupStack::Pop(); // hash; 
+                        
+                        retVal = ETrue;                          
+                        }
+                    }
+                else
+                    {
+                    BTIC_TRACE_PRINT_NUM("\nERROR File read = %d", err );            
+                    User::Leave( KErrGeneral );  
+                    }                                                   
+                }
+            else
+                {
+                BTIC_TRACE_PRINT("\nERROR HBufC8 buffer alloc failed");              
+                User::Leave( KErrGeneral );  
+                }      
+                                                                                
+            CleanupStack::PopAndDestroy( 2 ); // file,  fileBuffer         
+            }
+        else
+            {
+            BTIC_TRACE_PRINT_NUM("\nERROR File open = %d", err );              
+            User::Leave( KErrGeneral );  
+            }                                    
+        } 
+            
+    CleanupStack::PopAndDestroy(); // sha                 
+                    
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] CheckCapaWordAndCalcHashL v3 <---");     
+    
+    return retVal;            
+    }    
+
+/*
+#ifdef __BTIC_BINARIES_CHECK_ENABLED
+
+
+// -----------------------------------------------------------------------------
+// RenameFileL
+//
+// This function renames given file by replacing existing file extension to .bak
+// -----------------------------------------------------------------------------
+//    
+LOCAL_C void RenameFileL( RFs& aFs, const TDesC& aFileName )
+    { 
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] ! ! ! RenameFileL --->");
+       
+    _LIT( KBTICFileExtensionBak,".bak" );
+              
+    TFindFile find( aFs );
+      
+    // Find given file in C drive.
+    if ( find.FindByDir( aFileName, KBTICSysPathC ) == KErrNone )
+        {          
+        TInt length = aFileName.Length();
+        HBufC* newName = HBufC::NewLC( length + sizeof( KBTICFileExtensionBak ) );
+        TPtr newNamePtr = newName->Des();                        
+        
+        newNamePtr.Copy( aFileName ); 
+        // Add ".bak" extension to file name.
+        newNamePtr.Append( KBTICFileExtensionBak );                              
+        
+        // Rename file.
+        TInt err = aFs.Rename( aFileName, *newName );
+        
+        // If error try ones more. 
+        if ( err != KErrNone )
+            {
+            aFs.Rename( aFileName, *newName );
+            }
+        }
+
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] ! ! ! RenameFileL <---");        
+    }
+    
+
+// -----------------------------------------------------------------------------
+// UniteCertArraysL
+//
+// Function append source array's pointers to target array. 
+// -----------------------------------------------------------------------------
+//
+LOCAL_C void UniteCertArraysL(     
+    RPointerArray<CX509Certificate>& aTargetCertArray,
+    RPointerArray<CX509Certificate>& aSourceCertArray )
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] UniteCertArraysL --->");    
+        
+    TInt count = aSourceCertArray.Count();
+        
+    if ( count > 0 )
+        {
+        for ( TInt index = 0; index < count; index++ )
+            {
+            CX509Certificate* x509Cert = aSourceCertArray[index];
+            // Note if append fails -> some binaries will be corrupted.          
+            aTargetCertArray.Append( x509Cert );                        
+            }                
+        }
+            
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] UniteCertArraysL <---");            
+    }
+
+
+// -----------------------------------------------------------------------------
+// UniteCapaArraysL
+//
+// Function append source array's pointers to target array. 
+// -----------------------------------------------------------------------------
+//
+LOCAL_C void UniteCapaArraysL( 
+    RPointerArray<TCapabilitySet>& aTargetCapaArray,
+    RPointerArray<TCapabilitySet>& aSourceCapaArray )
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] UniteCapaArraysL --->");    
+   
+    TInt count = aSourceCapaArray.Count();            
+        
+    if ( count > 0 )
+        {
+        for ( TInt index = 0; index < count; index++ )
+            {
+            TCapabilitySet* capaSet = aSourceCapaArray[index];
+            // Note if append fails -> some binaries will be corrupted.           
+            aTargetCapaArray.Append( capaSet );                        
+            }                
+        }       
+        
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] UniteCapaArraysL <---");    
+    }
+
+
+// -----------------------------------------------------------------------------
+// CheckBinariesL
+//
+// This function checks all exe or dll binarys conteining TCB and DRM capability 
+// in C:\sys\bin directory. It calculates hash over the binary and compares that 
+// to one found in SIS Registery. It check also that SIS pacage's certificate 
+// has rigth to grant TCB or DRM capabiltity.
+// If some file in C:\sys\bin directory is not found in SIS Registery it is 
+// renamed.
+// 
+// -----------------------------------------------------------------------------
+//
+LOCAL_C void CheckBinariesL( 
+    RFs& aFs, 
+    RPointerArray<CX509Certificate>& aX509CertArray,
+    RPointerArray<TCapabilitySet>& aCertCapaArray )    
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] CheckBinariesL --->");
+    __UHEAP_MARK;          
+    
+    TInt pushToStack = 0;
+    TInt err = 0;            
+    
+    RPointerArray<HBufC> allFilesArray;
+    
+    // Find all exe files from c:\sys\bin.
+    FindFilesL( aFs, KBTICSysPathC, KBTICExtensionExe, allFilesArray );    
+    // Find all dll files from c:\sys\bin.
+    FindFilesL( aFs, KBTICSysPathC, KBTICExtensionDll, allFilesArray );
+     
+    TInt count = allFilesArray.Count();
+    
+    if ( count > 0 )
+        {            
+        RPointerArray<HBufC> filesArray;
+        RPointerArray<HBufC8> hashArray; 
+        RArray<TUint64> capaArray;  
+                
+        TBool foundFiles = EFalse;
+
+        // Copy whanted capabilities to array.                   
+        TUint64* capaVector = new( ELeave ) TUint64[KBTICCapaCount];
+        CleanupArrayDeletePushL( capaVector );
+        capaVector[0] = KBTIC_TCB;
+        capaVector[1] = KBTIC_DRM;
+        
+        // Find files conteining whanted capability and calculate hash over file.  
+        
+        // NOTE NOTE currently this function addends only one capability to 
+        // capaArray. This must be changed if all capabilities should be 
+        // checked from certificate.        
+                         
+        foundFiles = CheckCapabilityWordAndCalcHashL( 
+            aFs,
+            ETrue, 
+            capaVector,                        
+            allFilesArray, 
+            filesArray, 
+            hashArray,
+            capaArray );                             
+                                                 
+        CleanupStack::PopAndDestroy();  //capaVector 
+                    
+        if ( foundFiles && err == KErrNone )
+            {
+            // Find match for fileArray's files from SIS registery
+            // Check that file's (binary) hash matches to SIS registery's hash 
+            // Check that SIS registery cert. is valid and has file's capability.              
+            FindMatchFromSisPackageL( 
+                aFs,                 
+                filesArray, 
+                hashArray,
+                capaArray, 
+                aX509CertArray,
+                aCertCapaArray );                           
+                            
+            count = filesArray.Count();
+            
+            BTIC_TRACE_PRINT_NUM("Files array count = %d (should be 0 )", count );
+            
+            // Rename all files which was not found in sis registery.
+            if ( count )  
+                {                               
+                for ( TInt index = 0; index < count; index++ )
+                    {
+                    HBufC* filePath = filesArray[index];
+                                        
+                    RenameFileL( aFs, *filePath );                                                                 
+                    }
+                }                
+            }    
+                                           
+        filesArray.Reset(); // Reset only. allFilesArray owns heap memory.                               
+        hashArray.ResetAndDestroy();                                       
+        }
+    
+    allFilesArray.ResetAndDestroy(); 
+               
+    CleanupStack::PopAndDestroy( pushToStack );  //searchPath    
+       
+    BTIC_TRACE_PRINT("UHEAP MARK END");  
+    __UHEAP_MARKEND;    
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] CheckBinariesL <---");  
+    }
+
+
+// -----------------------------------------------------------------------------
+// FindFilesL
+//
+// This function searches one or more files that conteins given string in file 
+// name. File names are added to array with complete path.  
+// -----------------------------------------------------------------------------
+//       
+LOCAL_C void FindFilesL( 
+    RFs& aFs,                               // File server handle.
+    const TDesC& aPath,                     // Search directory and drive.
+    const TDesC& aSearchString,             // String to be found in file name.
+    RPointerArray<HBufC>& aFoundFilesArray )// Result files.
+    {  
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] FindFilesL --->"); 
+     
+    TInt err = 0;
+    TFindFile find( aFs ); 
+    CDir* dirList = NULL;
+    HBufC* path;
+          
+    TFileName searchExtension;
+    searchExtension.Copy( aSearchString );
+    
+    // Find files from searchPath directory. Note that dirlist
+    // contains only file name not path to it.                  
+    err = find.FindWildByPath( searchExtension, &aPath, dirList );
+                    
+    TInt pathLength = aPath.Length(); 
+    
+    if ( err == KErrNone && dirList )
+        {
+        CleanupStack::PushL( dirList );
+        
+        // Get the count of find files.
+        TInt count = dirList->Count();
+        
+        BTIC_TRACE_PRINT_NUM("Dir list count = %d", count ); 
+                                   
+        for ( TInt index = 0; index < count; index++ )
+            {                                    
+            path = HBufC::NewLC( pathLength + (*dirList)[index].iName.Length() );              
+            TPtr ptrPath = path->Des();
+            
+            // Copy system path to buffer.
+            ptrPath.Copy( KBTICSysPathC );
+            // Append files name to path buffer.
+            ptrPath.Append( (*dirList)[index].iName ); 
+            
+            ptrPath.LowerCase();                                   
+            
+            aFoundFilesArray.Append( path );
+            
+            CleanupStack::Pop(); //path
+            }
+            
+        CleanupStack::Pop(); //dirList 
+        delete dirList;  
+        }
+                       
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] FindFilesL <---");                 
+    }
+
+
+
+// -----------------------------------------------------------------------------  
+// FindMatchFromSisPackageL
+//
+// This function search given files from SIS Registery. Function removes file 
+// from aFilesArray alway when it is found in Registery. If aFilesArray contains 
+// files after function return those files are not found in SIS Registery.
+// 
+// Returns: ETure if successful  
+//          EFalse othervice
+// -----------------------------------------------------------------------------
+//  
+LOCAL_C TBool FindMatchFromSisPackageL( 
+    RFs& aFs,                           // File server handle
+    RPointerArray<HBufC>& aFilesArray,  // Files to be checked
+    RPointerArray<HBufC8>& aHashArray,  // File's hash
+    RArray<TUint64>& aCapaArray,        // File's capability
+    RPointerArray<CX509Certificate>& aX509CertArray, // Cert array
+    RPointerArray<TCapabilitySet>& aCertCapaArray )  // Cert's capability
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] FindMatchFromSisPackageL --->");
+    __UHEAP_MARK; 
+    
+    TInt err = KErrNone;        
+    TBool allOK = EFalse; 
+               
+    Swi::RSisRegistrySession sisRegSession;  
+            
+    err = sisRegSession.Connect();
+    
+    if ( err == KErrNone )
+        {
+        CleanupClosePushL( sisRegSession );
+        
+        RPointerArray<CSisRegistryPackage> sisPackages;
+                       
+        // Find installed packages.
+        sisRegSession.InstalledPackagesL( sisPackages );                
+                      
+        TBool entryOpen = EFalse;    
+        TInt entryFilesCount = 0;
+        TInt fileCount = 0;        
+        Swi::RSisRegistryEntry entry; 
+        // Array for entrys files. This owns heap memory.                       
+        RPointerArray<HBufC> installedFiles; 
+        // Array for dll and exe files found in sis registery.
+        RPointerArray<HBufC> entryFiles;
+        // Array for wild card string to be search from file list.
+        RPointerArray<HBufC> stringArray;
+        HBufC* string;
+        
+        // Add wild card strings to array.                    
+        string = KBTICExtensionExe().AllocLC();
+        User::LeaveIfError( stringArray.Append( string ) );
+        CleanupStack::Pop();
+        
+        string = KBTICExtensionDll().AllocLC();
+        User::LeaveIfError( stringArray.Append( string ) );
+        CleanupStack::Pop();                     
+                
+        // Open sis registery entry and search paths to installed exes and dlls.
+        for( TInt index = 0; index < sisPackages.Count(); index++)
+            {  
+            BTIC_TRACE_PRINT_NUM("entry loop Index = %d", index );
+
+            // If error happens make leave. If some pacage is left out we can 
+            // not continue, because all files found in C must be found also 
+            // in sis registery.                                           
+            User::LeaveIfError( 
+                entry.OpenL( sisRegSession, *sisPackages[index] ) );                         
+                                                 
+            CleanupClosePushL( entry );
+            entryOpen = ETrue; 
+            
+            // Get this entrys installed files.                                                                          
+            entry.FilesL( installedFiles );                                          
+                        
+            if ( installedFiles.Count() > 0 )
+                {                     
+                // Search match for string array conten from entrys files.
+                // Note that heap memory is owned by installeFiles array.
+                SearchFilesFromArrayL( 
+                    installedFiles, 
+                    KBTICSysPathCWildcard,
+                    stringArray, 
+                    entryFiles );                                                                                             
+                }                                                                                                                                                                              
+                                                                            
+            entryFilesCount = entryFiles.Count();
+            
+            BTIC_TRACE_PRINT_NUM("Entry files count = %d", entryFilesCount );
+                    
+            if ( entryFilesCount > 0 )
+                {
+                TBool pagaceCertValid = EFalse;                                
+                
+                // Go torug all file paths from entryFiles aray.
+                for ( TInt indexB = 0; indexB < entryFilesCount; indexB++ )
+                    {
+                    BTIC_TRACE_PRINT_NUM("file path loop IndexB = %d", indexB );
+                    
+                    // Get file's path from sis pagace entry.
+                    HBufC* entryFile = entryFiles[indexB];                                         
+                    
+                    fileCount = aFilesArray.Count();
+                                                                     
+                    // Compare registery file path to files found in C:\sys\bin.            
+                    for ( TInt indexC = fileCount - 1; indexC >= 0; indexC-- )
+                        {                                                
+                        // Get file's path from array conteining dlls and exes.
+                        HBufC* file = aFilesArray[indexC];                                                                                                
+                        
+                        TInt result = entryFile->CompareC( *file );
+                                               
+                        BTIC_TRACE_PRINT_NUM("\nCompare result = %d", result );                        
+                        
+                        // If result is zero match is found.
+                        if ( result == 0 )                        
+                            {
+                            BTIC_TRACE_PRINT("File path Match found" ); 
+                            
+                            // Get file's hash
+                            HBufC8* hash = aHashArray[indexC];                                                                                                                                                                       
+                                                    
+                            BTIC_TRACE_PRINT("CompareToRegisteryHashL -->" );                            
+                           
+                            TBool hashOk = CompareToRegisteryHashL( 
+                                entry, 
+                                *entryFile, 
+                                *hash );
+                                
+                            BTIC_TRACE_PRINT("CompareToRegisteryHashL <--" );     
+                            
+                                                      
+                            if ( hashOk )
+                                {
+                                BTIC_TRACE_PRINT("HASH OK");
+                                
+                                // Check if entry cert is already valid.
+                                if ( ! pagaceCertValid )
+                                    {                                          
+                                    BTIC_TRACE_PRINT("Validate pagace cert");
+                                     
+                                    // Validate entry's certificate and 
+                                    // check that certificate has correct 
+                                    // capablities.                                                                                                                  
+                                    TBool certOk = SearchValidCertificateL( 
+                                        entry, 
+                                        aX509CertArray,                                             
+                                        aCertCapaArray,
+                                        aCapaArray[indexC] );
+                                    
+                                    if ( certOk )
+                                        {
+                                        BTIC_TRACE_PRINT("Pagace CERT VALID - OK");
+                                        
+                                        // Validate pagace cert. only once.
+                                        pagaceCertValid = ETrue;
+                                        }
+                                    else
+                                        {
+                                        // Rename file if cert is not ok.
+                                        
+                                        RenameFileL( aFs, *entryFile );                                            
+                                        // Should we rename all files in this
+                                        // entry or only this one.
+                                        }                                            
+                                    }                                                                   
+                                } 
+                            else
+                                {
+                                BTIC_TRACE_PRINT("HASH Error -> Rename file");
+                                // If hash is false rename file.
+                                RenameFileL( aFs, *entryFile );
+                                }      
+                                                                                                                                                                                                                     
+                            // Set arrays entry to zero so we will not 
+                            // compear it twice. We do not have to delete 
+                            // entry because aFilesArray do not own heap 
+                            // memory.                                
+                            aFilesArray.Remove( indexC );
+                            
+                            //Remove also hash and capa entry from array.
+                            HBufC8* hashBuffer = aHashArray[indexC];
+                            delete hashBuffer;
+                            aHashArray.Remove( indexC);
+                            
+                            aCapaArray.Remove( indexC );                                                        
+                                                                                                                                                         
+                            break;                  
+                            }                                                                                                         
+                        }
+                    }
+                } 
+                
+            if ( entryOpen )
+                {    
+                BTIC_TRACE_PRINT("Clear ENTRY and installedFiles array");
+                    
+                CleanupStack::PopAndDestroy(); //entry                   
+                entryFiles.Reset(); //Reset only.
+                installedFiles.ResetAndDestroy();               
+                }
+                
+           // Break entry loop if all files are removed.     
+           if ( aFilesArray.Count() == 0 )
+                {
+                BTIC_TRACE_PRINT("NO MORE EXE/DLL FILES -> BREAK LOOP");
+                break;
+                }                                                                                                                   
+            }                       
+        
+        stringArray.ResetAndDestroy();
+        CleanupStack::PopAndDestroy(); // sisRegSession 
+        
+        allOK = ETrue;    
+        }
+     
+     
+    BTIC_TRACE_PRINT("UHEAP MARK END");  
+    __UHEAP_MARKEND;          
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] FindMatchFromSisPackageL <---"); 
+    
+    return allOK;
+    }
+
+
+#endif //__BTIC_BINARIES_CHECK_ENABLED
+*/
+      
+// =========================== CRootCertificateEntry ===========================
+
+// -----------------------------------------------------------------------------
+// NewLC()
+// 
+// -----------------------------------------------------------------------------
+//
+CRootCertificateEntry* CRootCertificateEntry::NewLC( RReadStream& aStream )
+    {
+    CRootCertificateEntry* self = new(ELeave) CRootCertificateEntry();
+    CleanupStack::PushL(self);
+
+    self->InternalizeL( aStream );
+
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CRootCertificateEntry()
+// 
+// -----------------------------------------------------------------------------
+//
+CRootCertificateEntry::CRootCertificateEntry()
+    { 
+    }
+
+
+// -----------------------------------------------------------------------------
+// ~CRootCertificateEntry()
+// 
+// -----------------------------------------------------------------------------
+//
+CRootCertificateEntry::~CRootCertificateEntry()
+    {
+    iApplications.Close();    
+    }
+
+
+// -----------------------------------------------------------------------------
+// InternalizeL()
+// 
+// -----------------------------------------------------------------------------
+//
+void CRootCertificateEntry::InternalizeL( RReadStream& aStream )
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] InternalizeL");
+
+    iX509CertificateType = aStream.ReadUint8L();
+
+    iSize = aStream.ReadInt32L();
+
+    aStream >> iLabel;
+
+    iCertId = aStream.ReadInt32L();
+
+    iCACertificateType = aStream.ReadUint8L();
+
+    aStream >> iSubjectKeyId;
+
+    aStream >> iIssuerKeyId; 
+
+    TInt count = aStream.ReadInt32L();
+
+    for ( TInt i = 0 ; i < count ; ++i )
+        {
+        TUid id;
+        aStream >> id;
+        User::LeaveIfError( iApplications.Append( id ) );
+        }
+
+    iTrusted = !!aStream.ReadUint8L();  // converts TUint8 to TBool
+
+    aStream >> iDataStreamId;
+
+    TPckg<TCapabilitySet> capsPckg( iCapabilities );  
+    aStream >> capsPckg;  
+
+    iMandatory = !!aStream.ReadUint8L();    
+    }
+
+     
+// -----------------------------------------------------------------------------
+// DataStreamId()
+// 
+// -----------------------------------------------------------------------------
+//
+TStreamId CRootCertificateEntry::DataStreamId() const
+    {
+    return iDataStreamId;
+    }
+
+
+// -----------------------------------------------------------------------------
+// Capabilities()
+// 
+// -----------------------------------------------------------------------------
+//
+const TCapabilitySet& CRootCertificateEntry::Capabilities() const
+    {
+    return iCapabilities;
+    }
+
+// -----------------------------------------------------------------------------
+// Size()
+// 
+// -----------------------------------------------------------------------------
+//
+TInt CRootCertificateEntry::Size() const
+    {
+    return iSize;
+    }
+
+  
+// -----------------------------------------------------------------------------
+// CertID()
+// 
+// -----------------------------------------------------------------------------
+//
+TInt CRootCertificateEntry::CertID() const
+    {
+    return iCertId;
+    }
+
+
+
+// =========================== CActiveFileObserver ============================
+
+// -----------------------------------------------------------------------------
+// CActiveFileObserver::CActiveFileObserver()
+// -----------------------------------------------------------------------------
+//
+CActiveFileObserver::CActiveFileObserver( RFs&  aFs, TInt& aResult) 
+    : CActive( EPriorityNormal ),
+    iFs( aFs ), 
+    iResult( aResult )    
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CActiveFileObserver::~CActiveFileObserver()
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CActiveFileObserver::~CActiveFileObserver()
+    {  
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] ~CActiveFileObserver");   
+    // Cancel the outstanding request. This calls DoCancel().
+    Cancel();  
+    // Close timer.    
+    iRTimer.Close();
+    
+    if ( iPath )
+        {
+        delete iPath;
+        iPath = NULL;
+        }        
+    }
+
+
+// -----------------------------------------------------------------------------
+// CActiveFileObserver* CActiveFileObserver::NewL()
+// Factory method.
+// -----------------------------------------------------------------------------
+//
+CActiveFileObserver* CActiveFileObserver::NewL( 
+    RFs&  aFs,
+    const TDesC& aPath,      
+    TInt& aResult )
+    {
+    CActiveFileObserver* observer = 
+        new(ELeave) CActiveFileObserver( aFs, aResult );
+        
+    CleanupStack::PushL( observer );
+
+    observer->ConstructL( aPath );
+
+    CleanupStack::Pop();
+
+    return observer;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CActiveFileObserver::ConstructL()
+// Second-phase constructor.
+// -----------------------------------------------------------------------------
+//
+void CActiveFileObserver::ConstructL( const TDesC& aPath )
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] CActiveFileObserver::ConstructL"); 
+    
+    iRunCount = 0;
+       
+    iPath = HBufC::NewL( aPath.Length() );
+    TPtr iPathPtr = iPath->Des();
+    iPathPtr.Copy( aPath );
+    
+    iRTimer.CreateLocal();
+    
+    // Add to scheduler.    
+    CActiveScheduler::Add( this );
+    
+    // Issue first timer request.
+    IssueRequest();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CActiveFileObserver::DoCancel()
+// Cancel function for active object.
+// -----------------------------------------------------------------------------
+//
+void CActiveFileObserver::DoCancel()
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] CActiveFileObserver::DoCancel"); 
+    // Cancel outstanding request.    
+    iRTimer.Cancel();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CActiveFileObserver::RunError()
+// Handles a leave occurring in the request completion event handler RunL.
+// -----------------------------------------------------------------------------
+//
+TInt CActiveFileObserver::RunError( TInt aError )
+    { 
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] CActiveFileObserver::RunError"); 
+    iResult = aError;             
+    BTIC_TRACE_PRINT_NUM("[BOOT INTE.] RunError: err = %d", aError );
+    return aError;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CActiveFileObserver::IssueRequest()
+// This function issues new 
+// -----------------------------------------------------------------------------
+void CActiveFileObserver::IssueRequest()
+    {     
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] CActiveFileObserver::IssueRequest");            
+    //iFs.NotifyChange( ENotifyEntry, iStatus, *iPath );
+    iRunCount++;
+
+    iRTimer.After( iStatus, KBTICObserverTime );
+       
+    // Wait request to complete.
+    SetActive();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CActiveFileObserver::RunL()
+// This function handles active object’s request completion event
+// -----------------------------------------------------------------------------
+//
+void CActiveFileObserver::RunL()
+    {
+    BTIC_TRACE_PRINT("[BOOT INTECRITY CHECK] CActiveFileObserver::RunL"); 
+                                      
+    TInt err = KErrNone; 
+    RFile file;
+    // Try to open the file.
+    err = file.Open( iFs, *iPath, EFileShareReadersOrWriters | EFileRead );               
+    
+    BTIC_TRACE_PRINT_NUM("[BOOT INTE.] RunL: file open err = %d", err );
+    
+    if ( err == KErrNone )
+        {
+        // Close the file.
+        file.Close();
+        
+        if ( iRunCount < KBTICRunCount )        
+            {
+            // Make new request.
+            IssueRequest();      
+            }
+        else
+            {
+            BTIC_TRACE_PRINT("[BOOT INTE.] RunL: File not deleted -> CANCEL"); 
+            // File is not deleted. Stop active observer 
+            // and continue data base checking.
+            iResult = KErrCancel;
+            Deque();
+            CActiveScheduler::Stop();             
+            }    
+        }        
+    else if ( err == KErrNotFound || err == KErrPathNotFound )
+        {
+        // Ok file is deleted. Stop active observer and return.
+        BTIC_TRACE_PRINT("[BOOT INTE.] RunL: File deleted -> OK");         
+        iResult = KErrNone;   
+        Deque();
+        CActiveScheduler::Stop();       
+        } 
+    else
+        {
+        // Some other file open error etc. KErrInUse. Let's continue.
+                         
+        if ( iRunCount < KBTICRunCount )        
+            {
+            // Make new request.
+            IssueRequest();      
+            }
+        else
+            {
+            BTIC_TRACE_PRINT("[BOOT INTE.] RunL: File not deleted -> CANCEL"); 
+            // File is not deleted. Stop active observer 
+            // and continue data base checking.
+            iResult = KErrCancel;
+            Deque();
+            CActiveScheduler::Stop();             
+            }            
+        }                                               
+    }
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/src/IntegrityCheckClient.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,144 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Client source file
+*
+*/
+
+
+// INCLUDE FILES
+#include "IntegrityCheckClient.h"
+#include "IntegrityCheckDefs.h"
+#include "IntegrityCheckDebug.h"
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ---------------------------------------------------------------------------
+// StartServer()
+//
+// ---------------------------------------------------------------------------
+//
+static TInt StartServer()
+    {
+    BTIC_TRACE_PRINT("[BTIC Client] StartServer"); 
+    
+    const TUidType serverUid( 
+        KNullUid, 
+        KNullUid, 
+        KBTICServerUid3 );
+
+    RProcess server;
+
+    TInt err = server.Create( KBTICServer, KNullDesC );
+    BTIC_TRACE_PRINT_NUM("StartServer: Create error = %d", err );
+    
+    if ( err != KErrNone )
+        {      
+        return err;
+        }
+
+    TRequestStatus status;
+    
+    server.Rendezvous( status );
+
+    if ( status != KRequestPending )
+        {
+        server.Kill( 0 );
+        }
+    else
+        {
+        server.Resume();
+        }
+    
+    // Wait to server to start.
+    User::WaitForRequest( status );
+
+    err = ( server.ExitType() == EExitPanic ) ? KErrGeneral : status.Int();
+
+    server.Close();
+
+    return err;
+    }
+
+
+// ---------------------------------------------------------------------------
+// RIntegrityCheckClient::Connect()
+//
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TInt RIntegrityCheckClient::Connect()
+    {
+    BTIC_TRACE_PRINT("[BTIC Client] Connect"); 
+    TInt retry( 2 );
+
+    for (;;)
+        {
+   
+        TInt status = 
+            CreateSession( KBTICServer, TVersion( 0, 0, 0 ), 1 );
+        BTIC_TRACE_PRINT_NUM("Connect: CreateSession status = %d", status );
+
+        if ( ( status != KErrNotFound ) && ( status != KErrServerTerminated ) )
+            {
+            return status;
+            }
+
+        if ( --retry == 0 )
+            {
+            return status;
+            }
+        
+        BTIC_TRACE_PRINT("Connect: StartServer"); 
+        status = StartServer();
+        BTIC_TRACE_PRINT_NUM("Connect: StartServer status = %d", status );
+        
+        if ( ( status != KErrNone ) && ( status != KErrAlreadyExists ) )
+            {
+            return status;
+            }       
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// RIntegrityCheckClient::Close()
+//
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void RIntegrityCheckClient::Close()
+    {
+    BTIC_TRACE_PRINT("[BTIC Client] Close"); 
+    RSessionBase::Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// RIntegrityCheckClient::GetSWBootReason()
+//
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TInt RIntegrityCheckClient::GetSWBootReason( TInt& aBootReason  )
+    {
+    BTIC_TRACE_PRINT("[BTIC Client] GetSWBootReason"); 
+    TPckg<TInt> pckgBootReason( aBootReason );
+    return SendReceive( EBTICBootReasonSW, TIpcArgs( &pckgBootReason ) );
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/boottimeintegritycheck/src/IntegrityCheckServer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,403 @@
+/*
+* Copyright (c) 2007-2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Server source file
+*
+*/
+
+
+// INCLUDE FILES
+
+#include <centralrepository.h>
+#include <startupreason.h>
+#include <starterdomaincrkeys.h>
+
+#include "IntegrityCheckServer.h"
+#include "IntegrityCheckDefs.h"
+#include "IntegrityCheckDebug.h"
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+
+// ---------------------------------------------------------------------------
+// RunServerL
+//
+// ---------------------------------------------------------------------------
+
+static void RunServerL()
+    {
+    BTIC_TRACE_PRINT("[BTIC Server] RunServerL");
+        
+    User::LeaveIfError( RThread::RenameMe(KIntecrityCheckServerName) );
+    
+    // Create and install the active scheduler
+    CActiveScheduler* scheduler = new ( ELeave ) CActiveScheduler;   
+    CleanupStack::PushL( scheduler );
+    
+    CActiveScheduler::Install( scheduler );
+
+    // Create server
+    CIntegrityCheckServer::NewLC();
+
+    // Initialisation complete
+    RProcess::Rendezvous( KErrNone );
+
+    BTIC_TRACE_PRINT("[BTIC Server] RunServerL: CActiveScheduler::Start");
+    // Start active scheduler
+    CActiveScheduler::Start();
+    
+    CleanupStack::PopAndDestroy( 2 ); // scheduler, CIntegrityCheckServer
+    }
+
+
+// ---------------------------------------------------------------------------
+// E32Main()
+//
+// ---------------------------------------------------------------------------
+//
+GLDEF_C TInt E32Main()
+    {
+    __UHEAP_MARK;
+    BTIC_TRACE_PRINT("[BTIC Server] E32Main");
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+    
+    if ( cleanup == NULL )
+        {
+        return KErrNoMemory;
+        }
+    
+    TRAPD( err, RunServerL() );
+    
+    __ASSERT_ALWAYS( !err, User::Panic( KIntecrityCheckServerText, err ) );
+    
+    delete cleanup;
+
+    __UHEAP_MARKEND;
+
+    return KErrNone;
+    }
+
+
+//======================== CIntegrityCheckServer =============================
+
+// ---------------------------------------------------------------------------
+// CIntegrityCheckServer::CIntegrityCheckServer
+//
+// ---------------------------------------------------------------------------
+//
+CIntegrityCheckServer::CIntegrityCheckServer()
+    :CPolicyServer( 0, CPPolicy, ESharableSessions )
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CIntegrityCheckServer::NewLC
+//
+// ---------------------------------------------------------------------------
+//
+CServer2* CIntegrityCheckServer::NewLC()
+    {
+    CIntegrityCheckServer* self = new ( ELeave ) CIntegrityCheckServer;
+    CleanupStack::PushL( self );
+    
+    self->ConstructL();
+    
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CIntegrityCheckServer::ConstructL
+//
+// ---------------------------------------------------------------------------
+//
+void CIntegrityCheckServer::ConstructL()
+    {
+    BTIC_TRACE_PRINT("[BTIC Server] ConstructL");
+    iSessionCount = 0;
+    StartL( KIntecrityCheckServer );    
+    iShutDown.ConstructL();
+    BTIC_TRACE_PRINT("[BTIC Server] ConstructL: Start shutdown timer");
+    iShutDown.Start();    
+    }
+
+
+// ---------------------------------------------------------------------------
+// CIntegrityCheckServer::NewSessionL
+//
+// ---------------------------------------------------------------------------
+//
+CSession2* CIntegrityCheckServer::NewSessionL(
+    const TVersion&,
+    const RMessage2&) const
+    {
+    BTIC_TRACE_PRINT("[BTIC Server] NewSessionL");
+    return new (ELeave) CIntegrityCheckSession();
+    }
+
+// -----------------------------------------------------------------------------
+// CIntegrityCheckServer::AddSession()
+// Cancel the shutdown timer now, the new session is connected
+//
+// -----------------------------------------------------------------------------
+//
+void CIntegrityCheckServer::AddSession()
+    {
+    BTIC_TRACE_PRINT("[BTIC Server] AddSession");
+    iSessionCount++;
+    BTIC_TRACE_PRINT("[BTIC Server] Cancel shutdown timer");
+    iShutDown.Cancel();  // Cancel any outstanding shutdown timer    
+    }
+ 
+// -----------------------------------------------------------------------------
+// CIntegrityCheckServer::RemoveSession
+// Decrement the session counter and start the shutdown timer if the last client
+// has disconnected
+// -----------------------------------------------------------------------------
+//
+void CIntegrityCheckServer::RemoveSession()
+    {
+    BTIC_TRACE_PRINT("[BTIC Server] RemoveSession");
+    BTIC_TRACE_PRINT_NUM("[BTIC Server] Session count = %d", iSessionCount );
+    if ( --iSessionCount == 0 )
+        {      
+        BTIC_TRACE_PRINT("[BTIC Server] Remove session and shutdown ");
+        iShutDown.Start();
+        }
+    }
+
+
+//======================== CIntegrityCheckSession ============================
+
+// ---------------------------------------------------------------------------
+// CIntegrityCheckSession::CIntegrityCheckSession
+//
+// ---------------------------------------------------------------------------
+//
+CIntegrityCheckSession::CIntegrityCheckSession()
+    {    
+    }
+
+
+// ---------------------------------------------------------------------------
+// CIntegrityCheckSession::CreateL
+// Called by the CServer2
+// ---------------------------------------------------------------------------
+//
+void CIntegrityCheckSession::CreateL()
+    {
+    BTIC_TRACE_PRINT("[BTIC Srv session] CIntegrityCheckSession");
+    
+    CIntegrityCheckServer* server( static_cast<CIntegrityCheckServer*>
+            ( const_cast<CServer2*>( CSession2::Server() ) ) );    
+    // Ok we have client so let's cancel shutdown timer.
+    server->AddSession();    
+    }
+
+
+// ---------------------------------------------------------------------------
+// CIntegrityCheckSession::~CIntegrityCheckSession
+//
+// ---------------------------------------------------------------------------
+//
+CIntegrityCheckSession::~CIntegrityCheckSession()
+    {
+    BTIC_TRACE_PRINT("[BTIC Srv session] ~CIntegrityCheckSession");
+    
+    CIntegrityCheckServer* server( static_cast<CIntegrityCheckServer*>
+            ( const_cast<CServer2*>( CSession2::Server() ) ) );
+    
+    server->RemoveSession();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CIntegrityCheckSession::Disconnect
+//
+// ---------------------------------------------------------------------------
+//
+void CIntegrityCheckSession::Disconnect( const RMessage2 &aMessage )
+    {
+    BTIC_TRACE_PRINT("[BTIC Srv session] Disconnect");    
+    CSession2::Disconnect( aMessage );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CIntegrityCheckSession::ServiceL
+//
+// ---------------------------------------------------------------------------
+//
+void CIntegrityCheckSession::ServiceL(const RMessage2& aMessage)
+    {
+    BTIC_TRACE_PRINT("[BTIC Srv session] ServiceL");
+    
+    switch ( aMessage.Function() )
+        {
+        case EBTICBootReasonSW:
+            {            
+            TRAPD( err, GetSWBootReasonL( aMessage ) );
+            
+            aMessage.Complete( err );
+            break;
+            }
+        default:      
+            aMessage.Complete( KErrGeneral );
+            break;
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CIntegrityCheckSession::ServiceError
+//
+// ---------------------------------------------------------------------------
+//
+void CIntegrityCheckSession::ServiceError( 
+    const RMessage2& aMessage,
+    TInt aError )
+    {
+    BTIC_TRACE_PRINT("[BTIC Srv session] ServiceError");
+    CSession2::ServiceError( aMessage, aError );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CIntegrityCheckSession::GetSWBootReasonL
+//
+// ---------------------------------------------------------------------------
+//
+void CIntegrityCheckSession::GetSWBootReasonL( const RMessage2& aMessage )
+    {  
+    BTIC_TRACE_PRINT("[BTIC Srv session] GetSWBootReasonL");  
+    // Get sw boot reason from system.   
+    TInt bootReason = KErrNone;     
+    TInt startupReason = KErrNone;
+    CRepository* repository( NULL );
+    BTIC_TRACE_PRINT("[BTIC Srv session] Get startup reason from CRepository");
+        
+    TInt err = KErrNone;
+            
+    TRAP( err, repository = CRepository::NewL( KCRUidStartup ) );
+    
+    BTIC_TRACE_PRINT_NUM("[BTIC Srv session] CRepository TRAPD Err = %d", err );
+	
+    if ( err == KErrNone )
+        {
+        CleanupStack::PushL( repository );
+                               
+        err = repository->Get( KStartupReason, startupReason );        
+        
+        BTIC_TRACE_PRINT_NUM("[BTIC Srv session] CRepository Get Err = %d", err );
+        
+	    if ( err == KErrNone )
+		   {
+		   BTIC_TRACE_PRINT_NUM("Returned startup reason: %d ",startupReason );
+		    
+            if ( startupReason == EDeepRFSReset )
+			    {
+			     // C drive will be formatted, so let's stop checking.
+			     bootReason = EBTICRestoreFactorySetDeep;
+			     BTIC_TRACE_PRINT("[BTIC Srv session] Startup reason is FORMAT");
+			     }
+            else
+                {
+                // All other reasons are "normal" boot for BTIC.
+                bootReason = EBTICNormalBoot;
+                BTIC_TRACE_PRINT("[BTIC Srv session] Startup reason is NORMAL");
+                }    			    
+            }
+        else if ( err == KErrNotFound )
+            {
+            // Reason not found. Propably first boot etc.
+            bootReason = EBTICNoSWReason;
+            BTIC_TRACE_PRINT("[BTIC Srv session] No SW Startup reason found");            
+            }
+        else
+            {
+            // Some other error.
+            bootReason = err;
+            }                
+                
+	    CleanupStack::PopAndDestroy(); //repository    
+	    }
+        
+    TPckg<TInt> bootReasonValue( bootReason );
+    
+    BTIC_TRACE_PRINT("[BTIC Srv session] Write result to client side.");
+    // Write boot reason to client side.
+    aMessage.WriteL( KParam0, bootReasonValue );      
+    }
+ 
+
+//============================== CShutdown =====================================
+
+// -----------------------------------------------------------------------------
+// CShutdown::CShutdown
+// 
+//
+// -----------------------------------------------------------------------------
+//
+CShutdown::CShutdown():CTimer(-1)
+    {
+    BTIC_TRACE_PRINT("[BTIC Shutdown] CShutdown: Add scheduler");
+    CActiveScheduler::Add(this);
+    }
+
+// -----------------------------------------------------------------------------
+// CShutdown::ConstructL
+// 
+//
+// -----------------------------------------------------------------------------
+//
+void CShutdown::ConstructL()
+    {
+    BTIC_TRACE_PRINT("[BTIC Shutdown] ConstructL");
+    CTimer::ConstructL();
+    }
+
+// -----------------------------------------------------------------------------
+// CShutdown::Start
+// Set shutdown timer for server.
+//
+// -----------------------------------------------------------------------------
+//
+void CShutdown::Start()
+    {
+    BTIC_TRACE_PRINT("[BTIC Shutdown] Start timer");
+    After( KServerCloseTime );
+    }
+
+// -----------------------------------------------------------------------------
+// CShutdown::RunServerL
+// Initiates server exit when the timer expires
+//
+// -----------------------------------------------------------------------------
+//
+void CShutdown::RunL()
+    {
+    BTIC_TRACE_PRINT("[BTIC Shutdown] RunL: Stop BTIC server");
+    CActiveScheduler::Stop();
+    }
+
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/BMARM/CMSU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,340 @@
+EXPORTS
+	__33CCMSX509CertificateListParameters @ 1 NONAME R3UNUSED ; CCMSX509CertificateListParameters::CCMSX509CertificateListParameters(void)
+	AlgorithmIdentifier__C27CCMSX509AlgorithmIdentifier @ 2 NONAME R3UNUSED ; CCMSX509AlgorithmIdentifier::AlgorithmIdentifier(void) const
+	Algorithm__C23CCMSOriginatorPublicKey @ 3 NONAME R3UNUSED ; CCMSOriginatorPublicKey::Algorithm(void) const
+	Algorithm__C28CCMSX509SubjectPublicKeyInfo @ 4 NONAME R3UNUSED ; CCMSX509SubjectPublicKeyInfo::Algorithm(void) const
+	AttrCert__C22CCMSCertificateChoices @ 5 NONAME R3UNUSED ; CCMSCertificateChoices::AttrCert(void) const
+	AttributeType__C13CCMSAttribute @ 6 NONAME R3UNUSED ; CCMSAttribute::AttributeType(void) const
+	AttributeValues__C13CCMSAttribute @ 7 NONAME R3UNUSED ; CCMSAttribute::AttributeValues(void) const
+	Attributes__C32CCMSX509AttributeCertificateInfo @ 8 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::Attributes(void) const
+	AuthenticatedAttributes__C21CCMSAuthenticatedData @ 9 NONAME R3UNUSED ; CCMSAuthenticatedData::AuthenticatedAttributes(void) const
+	BaseCertificateID__C32CCMSX509AttributeCertificateInfo @ 10 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::BaseCertificateID(void) const
+	CMSVersion__C14CCMSSignerInfo @ 11 NONAME R3UNUSED ; CCMSSignerInfo::CMSVersion(void) const
+	Certificate__C22CCMSCertificateChoices @ 12 NONAME R3UNUSED ; CCMSCertificateChoices::Certificate(void) const
+	Certificates__C14CCMSSignedData @ 13 NONAME R3UNUSED ; CCMSSignedData::Certificates(void) const
+	Certs__C18CCMSOriginatorInfo @ 14 NONAME R3UNUSED ; CCMSOriginatorInfo::Certs(void) const
+	ConstructL__13CCMSAttribute @ 15 NONAME R3UNUSED ; CCMSAttribute::ConstructL(void)
+	ConstructL__13CCMSAttributeRC7TDesC16RC11CDesC8Array @ 16 NONAME R3UNUSED ; CCMSAttribute::ConstructL(TDesC16 const &, CDesC8Array const &)
+	ConstructL__13CCMSAttributeRC7TDesC16RC6TDesC8 @ 17 NONAME R3UNUSED ; CCMSAttribute::ConstructL(TDesC16 const &, TDesC8 const &)
+	ConstructL__14CCMSSignedData @ 18 NONAME R3UNUSED ; CCMSSignedData::ConstructL(void)
+	ConstructL__14CCMSSignedDataRCt9CArrayPtr1Z27CCMSX509AlgorithmIdentifierRC27CCMSEncapsulatedContentInfoRCt9CArrayPtr1Z14CCMSSignerInfoPCt9CArrayPtr1Z22CCMSCertificateChoicesPCt9CArrayPtr1Z23CCMSX509CertificateList @ 19 NONAME ; CCMSSignedData::ConstructL(CArrayPtr<CCMSX509AlgorithmIdentifier> const &, CCMSEncapsulatedContentInfo const &, CArrayPtr<CCMSSignerInfo> const &, CArrayPtr<CCMSCertificateChoices> const *, CArrayPtr<CCMSX509CertificateList> const *)
+	ConstructL__14CCMSSignerInfoRC19CCMSX509CertificateRC6TDesC8 @ 20 NONAME R3UNUSED ; CCMSSignerInfo::ConstructL(CCMSX509Certificate const &, TDesC8 const &)
+	ConstructL__14CCMSSignerInfoRC6TDesC8N21 @ 21 NONAME ; CCMSSignerInfo::ConstructL(TDesC8 const &, TDesC8 const &, TDesC8 const &)
+	ConstructL__15CCMSContentInfo @ 22 NONAME R3UNUSED ; CCMSContentInfo::ConstructL(void)
+	ConstructL__15CCMSContentInfoRC7TDesC16 @ 23 NONAME R3UNUSED ; CCMSContentInfo::ConstructL(TDesC16 const &)
+	ConstructL__17CCMSKeyIdentifierRC6TDesC8 @ 24 NONAME R3UNUSED ; CCMSKeyIdentifier::ConstructL(TDesC8 const &)
+	ConstructL__17CCMSKeyIdentifierRC6TDesC8RC5TTime @ 25 NONAME R3UNUSED ; CCMSKeyIdentifier::ConstructL(TDesC8 const &, TTime const &)
+	ConstructL__19CCMSX509Certificate @ 26 NONAME R3UNUSED ; CCMSX509Certificate::ConstructL(void)
+	ConstructL__19CCMSX509CertificateRC16CX509Certificate @ 27 NONAME R3UNUSED ; CCMSX509Certificate::ConstructL(CX509Certificate const &)
+	ConstructL__19CCMSX509CertificateRC6TDesC8RC27CCMSX509AlgorithmIdentifierRC22CX500DistinguishedNameRC16CCMSX509ValidityT3RC28CCMSX509SubjectPublicKeyInfoT2T1 @ 28 NONAME ; CCMSX509Certificate::ConstructL(TDesC8 const &, CCMSX509AlgorithmIdentifier const &, CX500DistinguishedName const &, CCMSX509Validity const &, CX500DistinguishedName const &, CCMSX509SubjectPublicKeyInfo const &, CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	ConstructL__19CCMSX509GeneralNameUiRC6TDesC8 @ 29 NONAME R3UNUSED ; CCMSX509GeneralName::ConstructL(unsigned int, TDesC8 const &)
+	ConstructL__20CCMSKEKRecipientInfoRC17CCMSKeyIdentifierRC27CCMSX509AlgorithmIdentifierRC6TDesC8 @ 30 NONAME ; CCMSKEKRecipientInfo::ConstructL(CCMSKeyIdentifier const &, CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	ConstructL__20CCMSX509GeneralNamesRCt9CArrayPtr1Z19CCMSX509GeneralName @ 31 NONAME R3UNUSED ; CCMSX509GeneralNames::ConstructL(CArrayPtr<CCMSX509GeneralName> const &)
+	ConstructL__20CCMSX509IssuerSerialRC20CCMSX509GeneralNames @ 32 NONAME R3UNUSED ; CCMSX509IssuerSerial::ConstructL(CCMSX509GeneralNames const &)
+	ConstructL__20CCMSX509IssuerSerialRC20CCMSX509GeneralNamesRC6TDesC8 @ 33 NONAME R3UNUSED ; CCMSX509IssuerSerial::ConstructL(CCMSX509GeneralNames const &, TDesC8 const &)
+	ConstructL__21CCMSAuthenticatedData @ 34 NONAME R3UNUSED ; CCMSAuthenticatedData::ConstructL(void)
+	ConstructL__21CCMSAuthenticatedDataPt9CArrayPtr1Z17CCMSRecipientInfoP27CCMSX509AlgorithmIdentifierP27CCMSEncapsulatedContentInfoRC6TDesC8 @ 35 NONAME ; CCMSAuthenticatedData::ConstructL(CArrayPtr<CCMSRecipientInfo> *, CCMSX509AlgorithmIdentifier *, CCMSEncapsulatedContentInfo *, TDesC8 const &)
+	ConstructL__22CCMSCertificateChoicesRC19CCMSX509Certificate @ 36 NONAME R3UNUSED ; CCMSCertificateChoices::ConstructL(CCMSX509Certificate const &)
+	ConstructL__22CCMSCertificateChoicesRC28CCMSX509AttributeCertificate @ 37 NONAME R3UNUSED ; CCMSCertificateChoices::ConstructL(CCMSX509AttributeCertificate const &)
+	ConstructL__23CCMSOriginatorPublicKeyRC27CCMSX509AlgorithmIdentifierRC6TDesC8 @ 38 NONAME R3UNUSED ; CCMSOriginatorPublicKey::ConstructL(CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	ConstructL__23CCMSX509CertificateList @ 39 NONAME R3UNUSED ; CCMSX509CertificateList::ConstructL(void)
+	ConstructL__23CCMSX509CertificateListRC16CX509CertificateRCt13CArrayPtrFlat1Z16CX509Certificate @ 40 NONAME R3UNUSED ; CCMSX509CertificateList::ConstructL(CX509Certificate const &, CArrayPtrFlat<CX509Certificate> const &)
+	ConstructL__25CCMSIssuerAndSerialNumberRC22CX500DistinguishedNameRC6TDesC8 @ 41 NONAME R3UNUSED ; CCMSIssuerAndSerialNumber::ConstructL(CX500DistinguishedName const &, TDesC8 const &)
+	ConstructL__25CCMSKeyAgreeRecipientInfo @ 42 NONAME R3UNUSED ; CCMSKeyAgreeRecipientInfo::ConstructL(void)
+	ConstructL__25CCMSKeyAgreeRecipientInfoRC29CCMSOriginatorIdentifierOrKeyRC27CCMSX509AlgorithmIdentifierRCt9CArrayPtr1Z25CCMSRecipientEncryptedKey @ 43 NONAME ; CCMSKeyAgreeRecipientInfo::ConstructL(CCMSOriginatorIdentifierOrKey const &, CCMSX509AlgorithmIdentifier const &, CArrayPtr<CCMSRecipientEncryptedKey> const &)
+	ConstructL__25CCMSKeyAgreeRecipientInfoRC29CCMSOriginatorIdentifierOrKeyRC6TDesC8RC27CCMSX509AlgorithmIdentifierRCt9CArrayPtr1Z25CCMSRecipientEncryptedKey @ 44 NONAME ; CCMSKeyAgreeRecipientInfo::ConstructL(CCMSOriginatorIdentifierOrKey const &, TDesC8 const &, CCMSX509AlgorithmIdentifier const &, CArrayPtr<CCMSRecipientEncryptedKey> const &)
+	ConstructL__25CCMSKeyTransRecipientInfoRC25CCMSIssuerAndSerialNumberRC27CCMSX509AlgorithmIdentifierRC6TDesC8 @ 45 NONAME ; CCMSKeyTransRecipientInfo::ConstructL(CCMSIssuerAndSerialNumber const &, CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	ConstructL__25CCMSKeyTransRecipientInfoRC6TDesC8RC27CCMSX509AlgorithmIdentifierT1 @ 46 NONAME ; CCMSKeyTransRecipientInfo::ConstructL(TDesC8 const &, CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	ConstructL__25CCMSRecipientEncryptedKeyRC17CCMSKeyIdentifierRC6TDesC8 @ 47 NONAME R3UNUSED ; CCMSRecipientEncryptedKey::ConstructL(CCMSKeyIdentifier const &, TDesC8 const &)
+	ConstructL__25CCMSRecipientEncryptedKeyRC25CCMSIssuerAndSerialNumberRC6TDesC8 @ 48 NONAME R3UNUSED ; CCMSRecipientEncryptedKey::ConstructL(CCMSIssuerAndSerialNumber const &, TDesC8 const &)
+	ConstructL__27CCMSEncapsulatedContentInfo @ 49 NONAME R3UNUSED ; CCMSEncapsulatedContentInfo::ConstructL(void)
+	ConstructL__27CCMSEncapsulatedContentInfoRC7TDesC16PC6TDesC8 @ 50 NONAME R3UNUSED ; CCMSEncapsulatedContentInfo::ConstructL(TDesC16 const &, TDesC8 const *)
+	ConstructL__27CCMSX509AlgorithmIdentifierRC12TAlgorithmId @ 51 NONAME R3UNUSED ; CCMSX509AlgorithmIdentifier::ConstructL(TAlgorithmId const &)
+	ConstructL__27CCMSX509AlgorithmIdentifierRC20CAlgorithmIdentifier @ 52 NONAME R3UNUSED ; CCMSX509AlgorithmIdentifier::ConstructL(CAlgorithmIdentifier const &)
+	ConstructL__28CCMSX509AttributeCertificate @ 53 NONAME R3UNUSED ; CCMSX509AttributeCertificate::ConstructL(void)
+	ConstructL__28CCMSX509AttributeCertificateRC32CCMSX509AttributeCertificateInfoRC27CCMSX509AlgorithmIdentifierRC6TDesC8 @ 54 NONAME ; CCMSX509AttributeCertificate::ConstructL(CCMSX509AttributeCertificateInfo const &, CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	ConstructL__28CCMSX509SubjectPublicKeyInfo @ 55 NONAME R3UNUSED ; CCMSX509SubjectPublicKeyInfo::ConstructL(void)
+	ConstructL__28CCMSX509SubjectPublicKeyInfoRC21CSubjectPublicKeyInfo @ 56 NONAME R3UNUSED ; CCMSX509SubjectPublicKeyInfo::ConstructL(CSubjectPublicKeyInfo const &)
+	ConstructL__28CCMSX509SubjectPublicKeyInfoRC27CCMSX509AlgorithmIdentifierRC6TDesC8 @ 57 NONAME R3UNUSED ; CCMSX509SubjectPublicKeyInfo::ConstructL(CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	ConstructL__29CCMSOriginatorIdentifierOrKeyRC23CCMSOriginatorPublicKey @ 58 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::ConstructL(CCMSOriginatorPublicKey const &)
+	ConstructL__29CCMSOriginatorIdentifierOrKeyRC25CCMSIssuerAndSerialNumber @ 59 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::ConstructL(CCMSIssuerAndSerialNumber const &)
+	ConstructL__29CCMSOriginatorIdentifierOrKeyRC6TDesC8 @ 60 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::ConstructL(TDesC8 const &)
+	ConstructL__32CCMSX509AttributeCertificateInfo @ 61 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::ConstructL(void)
+	ConstructL__32CCMSX509AttributeCertificateInfoRC20CCMSX509GeneralNamesT1RC27CCMSX509AlgorithmIdentifieriRC5TTimeT5RCt9CArrayPtr1Z13CCMSAttribute @ 62 NONAME ; CCMSX509AttributeCertificateInfo::ConstructL(CCMSX509GeneralNames const &, CCMSX509GeneralNames const &, CCMSX509AlgorithmIdentifier const &, int, TTime const &, TTime const &, CArrayPtr<CCMSAttribute> const &)
+	ConstructL__32CCMSX509AttributeCertificateInfoRC20CCMSX509IssuerSerialRC20CCMSX509GeneralNamesRC27CCMSX509AlgorithmIdentifieriRC5TTimeT5RCt9CArrayPtr1Z13CCMSAttribute @ 63 NONAME ; CCMSX509AttributeCertificateInfo::ConstructL(CCMSX509IssuerSerial const &, CCMSX509GeneralNames const &, CCMSX509AlgorithmIdentifier const &, int, TTime const &, TTime const &, CArrayPtr<CCMSAttribute> const &)
+	ContentType__C15CCMSContentInfo @ 64 NONAME R3UNUSED ; CCMSContentInfo::ContentType(void) const
+	Content__C27CCMSEncapsulatedContentInfo @ 65 NONAME R3UNUSED ; CCMSEncapsulatedContentInfo::Content(void) const
+	CreateDerEncodingL__12CCMSSequenceP12CASN1EncBase @ 66 NONAME R3UNUSED ; CCMSSequence::CreateDerEncodingL(CASN1EncBase *)
+	Crls__C18CCMSOriginatorInfo @ 67 NONAME R3UNUSED ; CCMSOriginatorInfo::Crls(void) const
+	Data__C19CCMSX509GeneralName @ 68 NONAME R3UNUSED ; CCMSX509GeneralName::Data(void) const
+	Date__C17CCMSKeyIdentifier @ 69 NONAME R3UNUSED ; CCMSKeyIdentifier::Date(void) const
+	DecodeSequenceLC__12CCMSSequenceRC6TDesC8 @ 70 NONAME R3UNUSED ; CCMSSequence::DecodeSequenceLC(TDesC8 const &)
+	DecodeSequenceLC__12CCMSSequenceRC6TDesC8ii @ 71 NONAME R3UNUSED ; CCMSSequence::DecodeSequenceLC(TDesC8 const &, int, int)
+	DigestAlgorithmIdentifier__C14CCMSSignerInfo @ 72 NONAME R3UNUSED ; CCMSSignerInfo::DigestAlgorithmIdentifier(void) const
+	DigestAlgorithmIdentifiers__C14CCMSSignedData @ 73 NONAME R3UNUSED ; CCMSSignedData::DigestAlgorithmIdentifiers(void) const
+	DigestAlgorithm__C21CCMSAuthenticatedData @ 74 NONAME R3UNUSED ; CCMSAuthenticatedData::DigestAlgorithm(void) const
+	DigestAlgorithm__C27CCMSX509AlgorithmIdentifier @ 75 NONAME R3UNUSED ; CCMSX509AlgorithmIdentifier::DigestAlgorithm(void) const
+	EncapContentInfo__C21CCMSAuthenticatedData @ 76 NONAME R3UNUSED ; CCMSAuthenticatedData::EncapContentInfo(void) const
+	EncapsulatedContentInfo__C14CCMSSignedData @ 77 NONAME R3UNUSED ; CCMSSignedData::EncapsulatedContentInfo(void) const
+	EncryptedKey__C20CCMSKEKRecipientInfo @ 78 NONAME R3UNUSED ; CCMSKEKRecipientInfo::EncryptedKey(void) const
+	EncryptedKey__C25CCMSKeyTransRecipientInfo @ 79 NONAME R3UNUSED ; CCMSKeyTransRecipientInfo::EncryptedKey(void) const
+	EncryptedKey__C25CCMSRecipientEncryptedKey @ 80 NONAME R3UNUSED ; CCMSRecipientEncryptedKey::EncryptedKey(void) const
+	Encrypted__C14CCMSX509Signed @ 81 NONAME R3UNUSED ; CCMSX509Signed::Encrypted(void) const
+	GeneralNames__C20CCMSX509GeneralNames @ 82 NONAME R3UNUSED ; CCMSX509GeneralNames::GeneralNames(void) const
+	Info__C28CCMSX509AttributeCertificate @ 83 NONAME R3UNUSED ; CCMSX509AttributeCertificate::Info(void) const
+	IssuerAndSerialNumberL__C29CCMSOriginatorIdentifierOrKey @ 84 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::IssuerAndSerialNumberL(void) const
+	IssuerAndSerialNumber__C14CCMSSignerInfo @ 85 NONAME R3UNUSED ; CCMSSignerInfo::IssuerAndSerialNumber(void) const
+	IssuerAndSerialNumber__C25CCMSKeyTransRecipientInfo @ 86 NONAME R3UNUSED ; CCMSKeyTransRecipientInfo::IssuerAndSerialNumber(void) const
+	IssuerAndSerialNumber__C25CCMSRecipientEncryptedKey @ 87 NONAME R3UNUSED ; CCMSRecipientEncryptedKey::IssuerAndSerialNumber(void) const
+	IssuerName__C25CCMSIssuerAndSerialNumber @ 88 NONAME R3UNUSED ; CCMSIssuerAndSerialNumber::IssuerName(void) const
+	IssuerUID__C20CCMSX509IssuerSerial @ 89 NONAME R3UNUSED ; CCMSX509IssuerSerial::IssuerUID(void) const
+	IssuerUniqueID__C32CCMSX509AttributeCertificateInfo @ 90 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::IssuerUniqueID(void) const
+	IssuerUniqueIdentifier__C19CCMSX509Certificate @ 91 NONAME R3UNUSED ; CCMSX509Certificate::IssuerUniqueIdentifier(void) const
+	Issuer__C19CCMSX509Certificate @ 92 NONAME R3UNUSED ; CCMSX509Certificate::Issuer(void) const
+	Issuer__C20CCMSX509IssuerSerial @ 93 NONAME R3UNUSED ; CCMSX509IssuerSerial::Issuer(void) const
+	Issuer__C32CCMSX509AttributeCertificateInfo @ 94 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::Issuer(void) const
+	Kekid__C20CCMSKEKRecipientInfo @ 95 NONAME R3UNUSED ; CCMSKEKRecipientInfo::Kekid(void) const
+	KeyEncryptionAlgorithm__C17CCMSRecipientInfo @ 96 NONAME R3UNUSED ; CCMSRecipientInfo::KeyEncryptionAlgorithm(void) const
+	KeyIdentifier__C17CCMSKeyIdentifier @ 97 NONAME R3UNUSED ; CCMSKeyIdentifier::KeyIdentifier(void) const
+	MacAlgorithm__C21CCMSAuthenticatedData @ 98 NONAME R3UNUSED ; CCMSAuthenticatedData::MacAlgorithm(void) const
+	Mac__C21CCMSAuthenticatedData @ 99 NONAME R3UNUSED ; CCMSAuthenticatedData::Mac(void) const
+	NewLC__13CCMSAttribute @ 100 NONAME R3UNUSED ; CCMSAttribute::NewLC(void)
+	NewLC__13CCMSAttributeRC7TDesC16RC11CDesC8Array @ 101 NONAME R3UNUSED ; CCMSAttribute::NewLC(TDesC16 const &, CDesC8Array const &)
+	NewLC__13CCMSAttributeRC7TDesC16RC6TDesC8 @ 102 NONAME R3UNUSED ; CCMSAttribute::NewLC(TDesC16 const &, TDesC8 const &)
+	NewLC__14CCMSSignedData @ 103 NONAME R3UNUSED ; CCMSSignedData::NewLC(void)
+	NewLC__14CCMSSignedDataRCt9CArrayPtr1Z27CCMSX509AlgorithmIdentifierRC27CCMSEncapsulatedContentInfoRCt9CArrayPtr1Z14CCMSSignerInfo @ 104 NONAME R3UNUSED ; CCMSSignedData::NewLC(CArrayPtr<CCMSX509AlgorithmIdentifier> const &, CCMSEncapsulatedContentInfo const &, CArrayPtr<CCMSSignerInfo> const &)
+	NewLC__14CCMSSignedDataRCt9CArrayPtr1Z27CCMSX509AlgorithmIdentifierRC27CCMSEncapsulatedContentInfoRCt9CArrayPtr1Z14CCMSSignerInfoPCt9CArrayPtr1Z22CCMSCertificateChoicesPCt9CArrayPtr1Z23CCMSX509CertificateList @ 105 NONAME ; CCMSSignedData::NewLC(CArrayPtr<CCMSX509AlgorithmIdentifier> const &, CCMSEncapsulatedContentInfo const &, CArrayPtr<CCMSSignerInfo> const &, CArrayPtr<CCMSCertificateChoices> const *, CArrayPtr<CCMSX509CertificateList> const *)
+	NewLC__20CCMSKEKRecipientInfo @ 106 NONAME R3UNUSED ; CCMSKEKRecipientInfo::NewLC(void)
+	NewLC__21CCMSAuthenticatedData @ 107 NONAME R3UNUSED ; CCMSAuthenticatedData::NewLC(void)
+	NewLC__21CCMSAuthenticatedDataPt9CArrayPtr1Z17CCMSRecipientInfoP27CCMSX509AlgorithmIdentifierP27CCMSEncapsulatedContentInfoRC6TDesC8 @ 108 NONAME ; CCMSAuthenticatedData::NewLC(CArrayPtr<CCMSRecipientInfo> *, CCMSX509AlgorithmIdentifier *, CCMSEncapsulatedContentInfo *, TDesC8 const &)
+	NewLC__22CCMSCertificateChoices @ 109 NONAME R3UNUSED ; CCMSCertificateChoices::NewLC(void)
+	NewLC__22CCMSCertificateChoicesRC19CCMSX509Certificate @ 110 NONAME R3UNUSED ; CCMSCertificateChoices::NewLC(CCMSX509Certificate const &)
+	NewLC__22CCMSCertificateChoicesRC28CCMSX509AttributeCertificate @ 111 NONAME R3UNUSED ; CCMSCertificateChoices::NewLC(CCMSX509AttributeCertificate const &)
+	NewLC__23CCMSOriginatorPublicKeyRC23CCMSOriginatorPublicKey @ 112 NONAME R3UNUSED ; CCMSOriginatorPublicKey::NewLC(CCMSOriginatorPublicKey const &)
+	NewLC__23CCMSOriginatorPublicKeyRC27CCMSX509AlgorithmIdentifierRC6TDesC8 @ 113 NONAME R3UNUSED ; CCMSOriginatorPublicKey::NewLC(CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	NewLC__23CCMSX509CertificateList @ 114 NONAME R3UNUSED ; CCMSX509CertificateList::NewLC(void)
+	NewLC__23CCMSX509CertificateListR33CCMSX509CertificateListParameters @ 115 NONAME R3UNUSED ; CCMSX509CertificateList::NewLC(CCMSX509CertificateListParameters &)
+	NewLC__23CCMSX509CertificateListRC16CX509CertificateRCt13CArrayPtrFlat1Z16CX509Certificate @ 116 NONAME R3UNUSED ; CCMSX509CertificateList::NewLC(CX509Certificate const &, CArrayPtrFlat<CX509Certificate> const &)
+	NewLC__25CCMSKeyAgreeRecipientInfo @ 117 NONAME R3UNUSED ; CCMSKeyAgreeRecipientInfo::NewLC(void)
+	NewLC__25CCMSKeyTransRecipientInfo @ 118 NONAME R3UNUSED ; CCMSKeyTransRecipientInfo::NewLC(void)
+	NewLC__25CCMSKeyTransRecipientInfoRC6TDesC8RC27CCMSX509AlgorithmIdentifierT1 @ 119 NONAME R3UNUSED ; CCMSKeyTransRecipientInfo::NewLC(TDesC8 const &, CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	NewLC__27CCMSEncapsulatedContentInfo @ 120 NONAME R3UNUSED ; CCMSEncapsulatedContentInfo::NewLC(void)
+	NewLC__27CCMSEncapsulatedContentInfoRC7TDesC16PC6TDesC8 @ 121 NONAME R3UNUSED ; CCMSEncapsulatedContentInfo::NewLC(TDesC16 const &, TDesC8 const *)
+	NewL__13CCMSAttribute @ 122 NONAME R3UNUSED ; CCMSAttribute::NewL(void)
+	NewL__13CCMSAttributeRC7TDesC16RC11CDesC8Array @ 123 NONAME R3UNUSED ; CCMSAttribute::NewL(TDesC16 const &, CDesC8Array const &)
+	NewL__13CCMSAttributeRC7TDesC16RC6TDesC8 @ 124 NONAME R3UNUSED ; CCMSAttribute::NewL(TDesC16 const &, TDesC8 const &)
+	NewL__14CCMSSignerInfo @ 125 NONAME R3UNUSED ; CCMSSignerInfo::NewL(void)
+	NewL__14CCMSSignerInfoRC19CCMSX509CertificateRC6TDesC8 @ 126 NONAME R3UNUSED ; CCMSSignerInfo::NewL(CCMSX509Certificate const &, TDesC8 const &)
+	NewL__14CCMSSignerInfoRC6TDesC8N21 @ 127 NONAME R3UNUSED ; CCMSSignerInfo::NewL(TDesC8 const &, TDesC8 const &, TDesC8 const &)
+	NewL__16CCMSX509Validity @ 128 NONAME R3UNUSED ; CCMSX509Validity::NewL(void)
+	NewL__16CCMSX509ValidityRC15CValidityPeriod @ 129 NONAME R3UNUSED ; CCMSX509Validity::NewL(CValidityPeriod const &)
+	NewL__16CCMSX509ValidityRC5TTimeT1 @ 130 NONAME R3UNUSED ; CCMSX509Validity::NewL(TTime const &, TTime const &)
+	NewL__17CCMSKeyIdentifier @ 131 NONAME R3UNUSED ; CCMSKeyIdentifier::NewL(void)
+	NewL__17CCMSKeyIdentifierRC6TDesC8 @ 132 NONAME R3UNUSED ; CCMSKeyIdentifier::NewL(TDesC8 const &)
+	NewL__17CCMSKeyIdentifierRC6TDesC8RC5TTime @ 133 NONAME R3UNUSED ; CCMSKeyIdentifier::NewL(TDesC8 const &, TTime const &)
+	NewL__18CCMSOriginatorInfo @ 134 NONAME R3UNUSED ; CCMSOriginatorInfo::NewL(void)
+	NewL__19CCMSX509Certificate @ 135 NONAME R3UNUSED ; CCMSX509Certificate::NewL(void)
+	NewL__19CCMSX509CertificateRC16CX509Certificate @ 136 NONAME R3UNUSED ; CCMSX509Certificate::NewL(CX509Certificate const &)
+	NewL__19CCMSX509CertificateRC6TDesC8RC27CCMSX509AlgorithmIdentifierRC22CX500DistinguishedNameRC16CCMSX509ValidityT3RC28CCMSX509SubjectPublicKeyInfoT2T1 @ 137 NONAME ; CCMSX509Certificate::NewL(TDesC8 const &, CCMSX509AlgorithmIdentifier const &, CX500DistinguishedName const &, CCMSX509Validity const &, CX500DistinguishedName const &, CCMSX509SubjectPublicKeyInfo const &, CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	NewL__19CCMSX509GeneralName @ 138 NONAME R3UNUSED ; CCMSX509GeneralName::NewL(void)
+	NewL__19CCMSX509GeneralNameUiRC6TDesC8 @ 139 NONAME R3UNUSED ; CCMSX509GeneralName::NewL(unsigned int, TDesC8 const &)
+	NewL__20CCMSKEKRecipientInfo @ 140 NONAME R3UNUSED ; CCMSKEKRecipientInfo::NewL(void)
+	NewL__20CCMSKEKRecipientInfoRC17CCMSKeyIdentifierRC27CCMSX509AlgorithmIdentifierRC6TDesC8 @ 141 NONAME R3UNUSED ; CCMSKEKRecipientInfo::NewL(CCMSKeyIdentifier const &, CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	NewL__20CCMSX509GeneralNames @ 142 NONAME R3UNUSED ; CCMSX509GeneralNames::NewL(void)
+	NewL__20CCMSX509GeneralNamesRC20CCMSX509GeneralNames @ 143 NONAME R3UNUSED ; CCMSX509GeneralNames::NewL(CCMSX509GeneralNames const &)
+	NewL__20CCMSX509GeneralNamesRCt9CArrayPtr1Z19CCMSX509GeneralName @ 144 NONAME R3UNUSED ; CCMSX509GeneralNames::NewL(CArrayPtr<CCMSX509GeneralName> const &)
+	NewL__20CCMSX509IssuerSerial @ 145 NONAME R3UNUSED ; CCMSX509IssuerSerial::NewL(void)
+	NewL__20CCMSX509IssuerSerialRC20CCMSX509GeneralNamesi @ 146 NONAME R3UNUSED ; CCMSX509IssuerSerial::NewL(CCMSX509GeneralNames const &, int)
+	NewL__20CCMSX509IssuerSerialRC20CCMSX509GeneralNamesiRC6TDesC8 @ 147 NONAME R3UNUSED ; CCMSX509IssuerSerial::NewL(CCMSX509GeneralNames const &, int, TDesC8 const &)
+	NewL__22CCMSCertificateChoices @ 148 NONAME R3UNUSED ; CCMSCertificateChoices::NewL(void)
+	NewL__22CCMSCertificateChoicesRC19CCMSX509Certificate @ 149 NONAME R3UNUSED ; CCMSCertificateChoices::NewL(CCMSX509Certificate const &)
+	NewL__22CCMSCertificateChoicesRC28CCMSX509AttributeCertificate @ 150 NONAME R3UNUSED ; CCMSCertificateChoices::NewL(CCMSX509AttributeCertificate const &)
+	NewL__23CCMSOriginatorPublicKey @ 151 NONAME R3UNUSED ; CCMSOriginatorPublicKey::NewL(void)
+	NewL__23CCMSOriginatorPublicKeyRC23CCMSOriginatorPublicKey @ 152 NONAME R3UNUSED ; CCMSOriginatorPublicKey::NewL(CCMSOriginatorPublicKey const &)
+	NewL__23CCMSOriginatorPublicKeyRC27CCMSX509AlgorithmIdentifierRC6TDesC8 @ 153 NONAME R3UNUSED ; CCMSOriginatorPublicKey::NewL(CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	NewL__25CCMSIssuerAndSerialNumber @ 154 NONAME R3UNUSED ; CCMSIssuerAndSerialNumber::NewL(void)
+	NewL__25CCMSIssuerAndSerialNumberRC22CX500DistinguishedNameRC6TDesC8 @ 155 NONAME R3UNUSED ; CCMSIssuerAndSerialNumber::NewL(CX500DistinguishedName const &, TDesC8 const &)
+	NewL__25CCMSKeyAgreeRecipientInfo @ 156 NONAME R3UNUSED ; CCMSKeyAgreeRecipientInfo::NewL(void)
+	NewL__25CCMSKeyAgreeRecipientInfoRC29CCMSOriginatorIdentifierOrKeyRC27CCMSX509AlgorithmIdentifierRCt9CArrayPtr1Z25CCMSRecipientEncryptedKey @ 157 NONAME R3UNUSED ; CCMSKeyAgreeRecipientInfo::NewL(CCMSOriginatorIdentifierOrKey const &, CCMSX509AlgorithmIdentifier const &, CArrayPtr<CCMSRecipientEncryptedKey> const &)
+	NewL__25CCMSKeyAgreeRecipientInfoRC29CCMSOriginatorIdentifierOrKeyRC6TDesC8RC27CCMSX509AlgorithmIdentifierRCt9CArrayPtr1Z25CCMSRecipientEncryptedKey @ 158 NONAME ; CCMSKeyAgreeRecipientInfo::NewL(CCMSOriginatorIdentifierOrKey const &, TDesC8 const &, CCMSX509AlgorithmIdentifier const &, CArrayPtr<CCMSRecipientEncryptedKey> const &)
+	NewL__25CCMSKeyTransRecipientInfo @ 159 NONAME R3UNUSED ; CCMSKeyTransRecipientInfo::NewL(void)
+	NewL__25CCMSKeyTransRecipientInfoRC25CCMSIssuerAndSerialNumberRC27CCMSX509AlgorithmIdentifierRC6TDesC8 @ 160 NONAME R3UNUSED ; CCMSKeyTransRecipientInfo::NewL(CCMSIssuerAndSerialNumber const &, CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	NewL__25CCMSKeyTransRecipientInfoRC6TDesC8RC27CCMSX509AlgorithmIdentifierT1 @ 161 NONAME R3UNUSED ; CCMSKeyTransRecipientInfo::NewL(TDesC8 const &, CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	NewL__25CCMSRecipientEncryptedKey @ 162 NONAME R3UNUSED ; CCMSRecipientEncryptedKey::NewL(void)
+	NewL__25CCMSRecipientEncryptedKeyRC17CCMSKeyIdentifierRC6TDesC8 @ 163 NONAME R3UNUSED ; CCMSRecipientEncryptedKey::NewL(CCMSKeyIdentifier const &, TDesC8 const &)
+	NewL__25CCMSRecipientEncryptedKeyRC25CCMSIssuerAndSerialNumberRC6TDesC8 @ 164 NONAME R3UNUSED ; CCMSRecipientEncryptedKey::NewL(CCMSIssuerAndSerialNumber const &, TDesC8 const &)
+	NewL__27CCMSEncapsulatedContentInfo @ 165 NONAME R3UNUSED ; CCMSEncapsulatedContentInfo::NewL(void)
+	NewL__27CCMSEncapsulatedContentInfoRC7TDesC16PC6TDesC8 @ 166 NONAME R3UNUSED ; CCMSEncapsulatedContentInfo::NewL(TDesC16 const &, TDesC8 const *)
+	NewL__27CCMSX509AlgorithmIdentifier @ 167 NONAME R3UNUSED ; CCMSX509AlgorithmIdentifier::NewL(void)
+	NewL__27CCMSX509AlgorithmIdentifierRC12TAlgorithmId @ 168 NONAME R3UNUSED ; CCMSX509AlgorithmIdentifier::NewL(TAlgorithmId const &)
+	NewL__27CCMSX509AlgorithmIdentifierRC20CAlgorithmIdentifier @ 169 NONAME R3UNUSED ; CCMSX509AlgorithmIdentifier::NewL(CAlgorithmIdentifier const &)
+	NewL__27CCMSX509AlgorithmIdentifierRC20CAlgorithmIdentifierT1 @ 170 NONAME R3UNUSED ; CCMSX509AlgorithmIdentifier::NewL(CAlgorithmIdentifier const &, CAlgorithmIdentifier const &)
+	NewL__28CCMSX509AttributeCertificate @ 171 NONAME R3UNUSED ; CCMSX509AttributeCertificate::NewL(void)
+	NewL__28CCMSX509AttributeCertificateRC32CCMSX509AttributeCertificateInfoRC27CCMSX509AlgorithmIdentifierRC6TDesC8 @ 172 NONAME R3UNUSED ; CCMSX509AttributeCertificate::NewL(CCMSX509AttributeCertificateInfo const &, CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	NewL__28CCMSX509SubjectPublicKeyInfo @ 173 NONAME R3UNUSED ; CCMSX509SubjectPublicKeyInfo::NewL(void)
+	NewL__28CCMSX509SubjectPublicKeyInfoRC21CSubjectPublicKeyInfo @ 174 NONAME R3UNUSED ; CCMSX509SubjectPublicKeyInfo::NewL(CSubjectPublicKeyInfo const &)
+	NewL__28CCMSX509SubjectPublicKeyInfoRC27CCMSX509AlgorithmIdentifierRC6TDesC8 @ 175 NONAME R3UNUSED ; CCMSX509SubjectPublicKeyInfo::NewL(CCMSX509AlgorithmIdentifier const &, TDesC8 const &)
+	NewL__29CCMSOriginatorIdentifierOrKey @ 176 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::NewL(void)
+	NewL__29CCMSOriginatorIdentifierOrKeyRC23CCMSOriginatorPublicKey @ 177 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::NewL(CCMSOriginatorPublicKey const &)
+	NewL__29CCMSOriginatorIdentifierOrKeyRC25CCMSIssuerAndSerialNumber @ 178 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::NewL(CCMSIssuerAndSerialNumber const &)
+	NewL__29CCMSOriginatorIdentifierOrKeyRC6TDesC8 @ 179 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::NewL(TDesC8 const &)
+	NewL__32CCMSX509AttributeCertificateInfo @ 180 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::NewL(void)
+	NewL__32CCMSX509AttributeCertificateInfoRC20CCMSX509GeneralNamesT1RC27CCMSX509AlgorithmIdentifieriRC5TTimeT5RCt9CArrayPtr1Z13CCMSAttribute @ 181 NONAME ; CCMSX509AttributeCertificateInfo::NewL(CCMSX509GeneralNames const &, CCMSX509GeneralNames const &, CCMSX509AlgorithmIdentifier const &, int, TTime const &, TTime const &, CArrayPtr<CCMSAttribute> const &)
+	NewL__32CCMSX509AttributeCertificateInfoRC20CCMSX509IssuerSerialRC20CCMSX509GeneralNamesRC27CCMSX509AlgorithmIdentifieriRC5TTimeT5RCt9CArrayPtr1Z13CCMSAttribute @ 182 NONAME ; CCMSX509AttributeCertificateInfo::NewL(CCMSX509IssuerSerial const &, CCMSX509GeneralNames const &, CCMSX509AlgorithmIdentifier const &, int, TTime const &, TTime const &, CArrayPtr<CCMSAttribute> const &)
+	NotAfterTime__C32CCMSX509AttributeCertificateInfo @ 183 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::NotAfterTime(void) const
+	NotAfter__C16CCMSX509Validity @ 184 NONAME R3UNUSED ; CCMSX509Validity::NotAfter(void) const
+	NotBeforeTime__C32CCMSX509AttributeCertificateInfo @ 185 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::NotBeforeTime(void) const
+	NotBefore__C16CCMSX509Validity @ 186 NONAME R3UNUSED ; CCMSX509Validity::NotBefore(void) const
+	OriginatorInfo__C21CCMSAuthenticatedData @ 187 NONAME R3UNUSED ; CCMSAuthenticatedData::OriginatorInfo(void) const
+	OriginatorKeyL__C29CCMSOriginatorIdentifierOrKey @ 188 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::OriginatorKeyL(void) const
+	Originator__C25CCMSKeyAgreeRecipientInfo @ 189 NONAME R3UNUSED ; CCMSKeyAgreeRecipientInfo::Originator(void) const
+	Parameters__C23CCMSX509CertificateList @ 190 NONAME R3UNUSED ; CCMSX509CertificateList::Parameters(void) const
+	PublicKey__C23CCMSOriginatorPublicKey @ 191 NONAME R3UNUSED ; CCMSOriginatorPublicKey::PublicKey(void) const
+	RKeyId__C25CCMSRecipientEncryptedKey @ 192 NONAME R3UNUSED ; CCMSRecipientEncryptedKey::RKeyId(void) const
+	RecipientEncryptedKeys__C25CCMSKeyAgreeRecipientInfo @ 193 NONAME R3UNUSED ; CCMSKeyAgreeRecipientInfo::RecipientEncryptedKeys(void) const
+	RecipientInfos__C21CCMSAuthenticatedData @ 194 NONAME R3UNUSED ; CCMSAuthenticatedData::RecipientInfos(void) const
+	RevokedCertificates__C14CCMSSignedData @ 195 NONAME R3UNUSED ; CCMSSignedData::RevokedCertificates(void) const
+	SerialNumber__C19CCMSX509Certificate @ 196 NONAME R3UNUSED ; CCMSX509Certificate::SerialNumber(void) const
+	SerialNumber__C25CCMSIssuerAndSerialNumber @ 197 NONAME R3UNUSED ; CCMSIssuerAndSerialNumber::SerialNumber(void) const
+	SerialNumber__C32CCMSX509AttributeCertificateInfo @ 198 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::SerialNumber(void) const
+	Serial__C20CCMSX509IssuerSerial @ 199 NONAME R3UNUSED ; CCMSX509IssuerSerial::Serial(void) const
+	SetAlgorithmIdentifierL__14CCMSX509SignedRC27CCMSX509AlgorithmIdentifier @ 200 NONAME R3UNUSED ; CCMSX509Signed::SetAlgorithmIdentifierL(CCMSX509AlgorithmIdentifier const &)
+	SetAlgorithmIdentifierL__27CCMSX509AlgorithmIdentifierRC20CAlgorithmIdentifier @ 201 NONAME R3UNUSED ; CCMSX509AlgorithmIdentifier::SetAlgorithmIdentifierL(CAlgorithmIdentifier const &)
+	SetAlgorithmL__23CCMSOriginatorPublicKeyRC27CCMSX509AlgorithmIdentifier @ 202 NONAME R3UNUSED ; CCMSOriginatorPublicKey::SetAlgorithmL(CCMSX509AlgorithmIdentifier const &)
+	SetAlgorithmL__28CCMSX509SubjectPublicKeyInfoRC27CCMSX509AlgorithmIdentifier @ 203 NONAME R3UNUSED ; CCMSX509SubjectPublicKeyInfo::SetAlgorithmL(CCMSX509AlgorithmIdentifier const &)
+	SetAttrCertL__22CCMSCertificateChoicesRC28CCMSX509AttributeCertificate @ 204 NONAME R3UNUSED ; CCMSCertificateChoices::SetAttrCertL(CCMSX509AttributeCertificate const &)
+	SetAttributeTypeL__13CCMSAttributeRC7TDesC16 @ 205 NONAME R3UNUSED ; CCMSAttribute::SetAttributeTypeL(TDesC16 const &)
+	SetAttributeValuesL__13CCMSAttributeRC11CDesC8Array @ 206 NONAME R3UNUSED ; CCMSAttribute::SetAttributeValuesL(CDesC8Array const &)
+	SetAttributesL__32CCMSX509AttributeCertificateInfoRCt9CArrayPtr1Z13CCMSAttribute @ 207 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::SetAttributesL(CArrayPtr<CCMSAttribute> const &)
+	SetAuthenticatedAttributesL__21CCMSAuthenticatedDataPt9CArrayPtr1Z13CCMSAttribute @ 208 NONAME R3UNUSED ; CCMSAuthenticatedData::SetAuthenticatedAttributesL(CArrayPtr<CCMSAttribute> *)
+	SetBaseCertificateIDL__32CCMSX509AttributeCertificateInfoRC20CCMSX509IssuerSerial @ 209 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::SetBaseCertificateIDL(CCMSX509IssuerSerial const &)
+	SetCertificateL__14CCMSSignerInfoRC19CCMSX509Certificate @ 210 NONAME R3UNUSED ; CCMSSignerInfo::SetCertificateL(CCMSX509Certificate const &)
+	SetCertificateL__22CCMSCertificateChoicesRC19CCMSX509Certificate @ 211 NONAME R3UNUSED ; CCMSCertificateChoices::SetCertificateL(CCMSX509Certificate const &)
+	SetCertificateUrlL__14CCMSSignerInfoRC6TDesC8T1 @ 212 NONAME R3UNUSED ; CCMSSignerInfo::SetCertificateUrlL(TDesC8 const &, TDesC8 const &)
+	SetCertificatesL__14CCMSSignedDataPCt9CArrayPtr1Z22CCMSCertificateChoices @ 213 NONAME R3UNUSED ; CCMSSignedData::SetCertificatesL(CArrayPtr<CCMSCertificateChoices> const *)
+	SetCerts__18CCMSOriginatorInfoPt9CArrayPtr1Z22CCMSCertificateChoices @ 214 NONAME R3UNUSED ; CCMSOriginatorInfo::SetCerts(CArrayPtr<CCMSCertificateChoices> *)
+	SetContentL__27CCMSEncapsulatedContentInfoPC6TDesC8 @ 215 NONAME R3UNUSED ; CCMSEncapsulatedContentInfo::SetContentL(TDesC8 const *)
+	SetContentTypeL__15CCMSContentInfoRC7TDesC16 @ 216 NONAME R3UNUSED ; CCMSContentInfo::SetContentTypeL(TDesC16 const &)
+	SetCrls__18CCMSOriginatorInfoPt9CArrayPtr1Z23CCMSX509CertificateList @ 217 NONAME R3UNUSED ; CCMSOriginatorInfo::SetCrls(CArrayPtr<CCMSX509CertificateList> *)
+	SetDataL__19CCMSX509GeneralNameRC6TDesC8 @ 218 NONAME R3UNUSED ; CCMSX509GeneralName::SetDataL(TDesC8 const &)
+	SetDateL__17CCMSKeyIdentifierRC5TTime @ 219 NONAME R3UNUSED ; CCMSKeyIdentifier::SetDateL(TTime const &)
+	SetDigestAlgorithmIdentifier__14CCMSSignerInfoR27CCMSX509AlgorithmIdentifier @ 220 NONAME R3UNUSED ; CCMSSignerInfo::SetDigestAlgorithmIdentifier(CCMSX509AlgorithmIdentifier &)
+	SetDigestAlgorithmIdentifiersL__14CCMSSignedDataRCt9CArrayPtr1Z27CCMSX509AlgorithmIdentifier @ 221 NONAME R3UNUSED ; CCMSSignedData::SetDigestAlgorithmIdentifiersL(CArrayPtr<CCMSX509AlgorithmIdentifier> const &)
+	SetDigestAlgorithmL__21CCMSAuthenticatedDataP27CCMSX509AlgorithmIdentifier @ 222 NONAME R3UNUSED ; CCMSAuthenticatedData::SetDigestAlgorithmL(CCMSX509AlgorithmIdentifier *)
+	SetDigestAlgorithmL__27CCMSX509AlgorithmIdentifierPC20CAlgorithmIdentifier @ 223 NONAME R3UNUSED ; CCMSX509AlgorithmIdentifier::SetDigestAlgorithmL(CAlgorithmIdentifier const *)
+	SetEncapContentInfoL__21CCMSAuthenticatedDataP27CCMSEncapsulatedContentInfo @ 224 NONAME R3UNUSED ; CCMSAuthenticatedData::SetEncapContentInfoL(CCMSEncapsulatedContentInfo *)
+	SetEncapsulatedContentInfoL__14CCMSSignedDataRC27CCMSEncapsulatedContentInfo @ 225 NONAME R3UNUSED ; CCMSSignedData::SetEncapsulatedContentInfoL(CCMSEncapsulatedContentInfo const &)
+	SetEncryptedKeyL__20CCMSKEKRecipientInfoRC6TDesC8 @ 226 NONAME R3UNUSED ; CCMSKEKRecipientInfo::SetEncryptedKeyL(TDesC8 const &)
+	SetEncryptedKeyL__25CCMSKeyTransRecipientInfoRC6TDesC8 @ 227 NONAME R3UNUSED ; CCMSKeyTransRecipientInfo::SetEncryptedKeyL(TDesC8 const &)
+	SetEncryptedKeyL__25CCMSRecipientEncryptedKeyRC6TDesC8 @ 228 NONAME R3UNUSED ; CCMSRecipientEncryptedKey::SetEncryptedKeyL(TDesC8 const &)
+	SetEncryptedL__14CCMSX509SignedRC6TDesC8 @ 229 NONAME R3UNUSED ; CCMSX509Signed::SetEncryptedL(TDesC8 const &)
+	SetGeneralNamesL__20CCMSX509GeneralNamesRCt9CArrayPtr1Z19CCMSX509GeneralName @ 230 NONAME R3UNUSED ; CCMSX509GeneralNames::SetGeneralNamesL(CArrayPtr<CCMSX509GeneralName> const &)
+	SetInfoL__28CCMSX509AttributeCertificateRC32CCMSX509AttributeCertificateInfo @ 231 NONAME R3UNUSED ; CCMSX509AttributeCertificate::SetInfoL(CCMSX509AttributeCertificateInfo const &)
+	SetIssuerAndSerialNumberL__25CCMSKeyTransRecipientInfoRC25CCMSIssuerAndSerialNumber @ 232 NONAME R3UNUSED ; CCMSKeyTransRecipientInfo::SetIssuerAndSerialNumberL(CCMSIssuerAndSerialNumber const &)
+	SetIssuerAndSerialNumberL__25CCMSRecipientEncryptedKeyRC25CCMSIssuerAndSerialNumber @ 233 NONAME R3UNUSED ; CCMSRecipientEncryptedKey::SetIssuerAndSerialNumberL(CCMSIssuerAndSerialNumber const &)
+	SetIssuerAndSerialNumberL__29CCMSOriginatorIdentifierOrKeyRC25CCMSIssuerAndSerialNumber @ 234 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::SetIssuerAndSerialNumberL(CCMSIssuerAndSerialNumber const &)
+	SetIssuerL__19CCMSX509CertificateRC22CX500DistinguishedName @ 235 NONAME R3UNUSED ; CCMSX509Certificate::SetIssuerL(CX500DistinguishedName const &)
+	SetIssuerL__20CCMSX509IssuerSerialRC20CCMSX509GeneralNames @ 236 NONAME R3UNUSED ; CCMSX509IssuerSerial::SetIssuerL(CCMSX509GeneralNames const &)
+	SetIssuerL__32CCMSX509AttributeCertificateInfoRC20CCMSX509GeneralNames @ 237 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::SetIssuerL(CCMSX509GeneralNames const &)
+	SetIssuerNameL__25CCMSIssuerAndSerialNumberRC22CX500DistinguishedName @ 238 NONAME R3UNUSED ; CCMSIssuerAndSerialNumber::SetIssuerNameL(CX500DistinguishedName const &)
+	SetIssuerUIDL__20CCMSX509IssuerSerialRC6TDesC8 @ 239 NONAME R3UNUSED ; CCMSX509IssuerSerial::SetIssuerUIDL(TDesC8 const &)
+	SetIssuerUniqueIDL__32CCMSX509AttributeCertificateInfoRC6TDesC8 @ 240 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::SetIssuerUniqueIDL(TDesC8 const &)
+	SetIssuerUniqueIdentifierL__19CCMSX509CertificateRC6TDesC8 @ 241 NONAME R3UNUSED ; CCMSX509Certificate::SetIssuerUniqueIdentifierL(TDesC8 const &)
+	SetKekidL__20CCMSKEKRecipientInfoRC17CCMSKeyIdentifier @ 242 NONAME R3UNUSED ; CCMSKEKRecipientInfo::SetKekidL(CCMSKeyIdentifier const &)
+	SetKeyEncryptionAlgorithmL__17CCMSRecipientInfoRC27CCMSX509AlgorithmIdentifier @ 243 NONAME R3UNUSED ; CCMSRecipientInfo::SetKeyEncryptionAlgorithmL(CCMSX509AlgorithmIdentifier const &)
+	SetKeyIdentifierL__17CCMSKeyIdentifierRC6TDesC8 @ 244 NONAME R3UNUSED ; CCMSKeyIdentifier::SetKeyIdentifierL(TDesC8 const &)
+	SetMacAlgorithmL__21CCMSAuthenticatedDataP27CCMSX509AlgorithmIdentifier @ 245 NONAME R3UNUSED ; CCMSAuthenticatedData::SetMacAlgorithmL(CCMSX509AlgorithmIdentifier *)
+	SetMacL__21CCMSAuthenticatedDataRC6TDesC8 @ 246 NONAME R3UNUSED ; CCMSAuthenticatedData::SetMacL(TDesC8 const &)
+	SetNotAfterTimeL__32CCMSX509AttributeCertificateInfoRC5TTime @ 247 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::SetNotAfterTimeL(TTime const &)
+	SetNotAfter__16CCMSX509ValidityRC5TTime @ 248 NONAME R3UNUSED ; CCMSX509Validity::SetNotAfter(TTime const &)
+	SetNotBeforeTimeL__32CCMSX509AttributeCertificateInfoRC5TTime @ 249 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::SetNotBeforeTimeL(TTime const &)
+	SetNotBefore__16CCMSX509ValidityRC5TTime @ 250 NONAME R3UNUSED ; CCMSX509Validity::SetNotBefore(TTime const &)
+	SetOriginatorInfoL__21CCMSAuthenticatedDataP18CCMSOriginatorInfo @ 251 NONAME R3UNUSED ; CCMSAuthenticatedData::SetOriginatorInfoL(CCMSOriginatorInfo *)
+	SetOriginatorKeyL__29CCMSOriginatorIdentifierOrKeyRC23CCMSOriginatorPublicKey @ 252 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::SetOriginatorKeyL(CCMSOriginatorPublicKey const &)
+	SetOriginatorL__25CCMSKeyAgreeRecipientInfoRC29CCMSOriginatorIdentifierOrKey @ 253 NONAME R3UNUSED ; CCMSKeyAgreeRecipientInfo::SetOriginatorL(CCMSOriginatorIdentifierOrKey const &)
+	SetParametersL__23CCMSX509CertificateListR33CCMSX509CertificateListParameters @ 254 NONAME R3UNUSED ; CCMSX509CertificateList::SetParametersL(CCMSX509CertificateListParameters &)
+	SetPublicKeyL__23CCMSOriginatorPublicKeyRC6TDesC8 @ 255 NONAME R3UNUSED ; CCMSOriginatorPublicKey::SetPublicKeyL(TDesC8 const &)
+	SetRKeyIdL__25CCMSRecipientEncryptedKeyRC17CCMSKeyIdentifier @ 256 NONAME R3UNUSED ; CCMSRecipientEncryptedKey::SetRKeyIdL(CCMSKeyIdentifier const &)
+	SetRecipientEncryptedKeysL__25CCMSKeyAgreeRecipientInfoRCt9CArrayPtr1Z25CCMSRecipientEncryptedKey @ 257 NONAME R3UNUSED ; CCMSKeyAgreeRecipientInfo::SetRecipientEncryptedKeysL(CArrayPtr<CCMSRecipientEncryptedKey> const &)
+	SetRecipientInfosL__21CCMSAuthenticatedDataPt9CArrayPtr1Z17CCMSRecipientInfo @ 258 NONAME R3UNUSED ; CCMSAuthenticatedData::SetRecipientInfosL(CArrayPtr<CCMSRecipientInfo> *)
+	SetRevokedCertificatesL__14CCMSSignedDataPCt9CArrayPtr1Z23CCMSX509CertificateList @ 259 NONAME R3UNUSED ; CCMSSignedData::SetRevokedCertificatesL(CArrayPtr<CCMSX509CertificateList> const *)
+	SetSerialNumberL__19CCMSX509CertificateRC6TDesC8 @ 260 NONAME R3UNUSED ; CCMSX509Certificate::SetSerialNumberL(TDesC8 const &)
+	SetSerialNumberL__25CCMSIssuerAndSerialNumberRC6TDesC8 @ 261 NONAME R3UNUSED ; CCMSIssuerAndSerialNumber::SetSerialNumberL(TDesC8 const &)
+	SetSerialNumber__32CCMSX509AttributeCertificateInfoi @ 262 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::SetSerialNumber(int)
+	SetSerial__20CCMSX509IssuerSeriali @ 263 NONAME R3UNUSED ; CCMSX509IssuerSerial::SetSerial(int)
+	SetSignatureAlgorithmIdentifier__14CCMSSignerInfoR27CCMSX509AlgorithmIdentifier @ 264 NONAME R3UNUSED ; CCMSSignerInfo::SetSignatureAlgorithmIdentifier(CCMSX509AlgorithmIdentifier &)
+	SetSignatureL__19CCMSX509CertificateRC27CCMSX509AlgorithmIdentifier @ 265 NONAME R3UNUSED ; CCMSX509Certificate::SetSignatureL(CCMSX509AlgorithmIdentifier const &)
+	SetSignatureL__32CCMSX509AttributeCertificateInfoRC27CCMSX509AlgorithmIdentifier @ 266 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::SetSignatureL(CCMSX509AlgorithmIdentifier const &)
+	SetSignatureValueL__14CCMSSignerInfoRC6TDesC8 @ 267 NONAME R3UNUSED ; CCMSSignerInfo::SetSignatureValueL(TDesC8 const &)
+	SetSignedAttributesL__14CCMSSignerInfoRC7TDesC16RC6TDesC8RC5TTimePC6TDesC8 @ 268 NONAME ; CCMSSignerInfo::SetSignedAttributesL(TDesC16 const &, TDesC8 const &, TTime const &, TDesC8 const *)
+	SetSignerInfosL__14CCMSSignedDataRCt9CArrayPtr1Z14CCMSSignerInfo @ 269 NONAME R3UNUSED ; CCMSSignedData::SetSignerInfosL(CArrayPtr<CCMSSignerInfo> const &)
+	SetSubjectKeyIdentifierL__25CCMSKeyTransRecipientInfoRC6TDesC8 @ 270 NONAME R3UNUSED ; CCMSKeyTransRecipientInfo::SetSubjectKeyIdentifierL(TDesC8 const &)
+	SetSubjectKeyIdentifierL__29CCMSOriginatorIdentifierOrKeyRC6TDesC8 @ 271 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::SetSubjectKeyIdentifierL(TDesC8 const &)
+	SetSubjectL__19CCMSX509CertificateRC22CX500DistinguishedName @ 272 NONAME R3UNUSED ; CCMSX509Certificate::SetSubjectL(CX500DistinguishedName const &)
+	SetSubjectNameL__32CCMSX509AttributeCertificateInfoRC20CCMSX509GeneralNames @ 273 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::SetSubjectNameL(CCMSX509GeneralNames const &)
+	SetSubjectPublicKeyInfoL__19CCMSX509CertificateRC28CCMSX509SubjectPublicKeyInfo @ 274 NONAME R3UNUSED ; CCMSX509Certificate::SetSubjectPublicKeyInfoL(CCMSX509SubjectPublicKeyInfo const &)
+	SetSubjectPublicKeyL__28CCMSX509SubjectPublicKeyInfoRC6TDesC8 @ 275 NONAME R3UNUSED ; CCMSX509SubjectPublicKeyInfo::SetSubjectPublicKeyL(TDesC8 const &)
+	SetSubjectUniqueIdentifierL__19CCMSX509CertificateRC6TDesC8 @ 276 NONAME R3UNUSED ; CCMSX509Certificate::SetSubjectUniqueIdentifierL(TDesC8 const &)
+	SetTagL__19CCMSX509GeneralNameUi @ 277 NONAME R3UNUSED ; CCMSX509GeneralName::SetTagL(unsigned int)
+	SetUnauthenticatedAttributesL__21CCMSAuthenticatedDataPt9CArrayPtr1Z13CCMSAttribute @ 278 NONAME R3UNUSED ; CCMSAuthenticatedData::SetUnauthenticatedAttributesL(CArrayPtr<CCMSAttribute> *)
+	SetUnsignedAttributesL__14CCMSSignerInfoRt13CArrayPtrFlat1Z13CCMSAttribute @ 279 NONAME R3UNUSED ; CCMSSignerInfo::SetUnsignedAttributesL(CArrayPtrFlat<CCMSAttribute> &)
+	SetUserKeyingMaterialL__25CCMSKeyAgreeRecipientInfoRC6TDesC8 @ 280 NONAME R3UNUSED ; CCMSKeyAgreeRecipientInfo::SetUserKeyingMaterialL(TDesC8 const &)
+	SetValidityL__19CCMSX509CertificateRC16CCMSX509Validity @ 281 NONAME R3UNUSED ; CCMSX509Certificate::SetValidityL(CCMSX509Validity const &)
+	SetVersion__19CCMSX509Certificatei @ 282 NONAME R3UNUSED ; CCMSX509Certificate::SetVersion(int)
+	SetVersion__21CCMSAuthenticatedDatai @ 283 NONAME R3UNUSED ; CCMSAuthenticatedData::SetVersion(int)
+	SetVersion__32CCMSX509AttributeCertificateInfoi @ 284 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::SetVersion(int)
+	SignatureAlgorithmIdentifier__C14CCMSSignerInfo @ 285 NONAME R3UNUSED ; CCMSSignerInfo::SignatureAlgorithmIdentifier(void) const
+	SignatureValue__C14CCMSSignerInfo @ 286 NONAME R3UNUSED ; CCMSSignerInfo::SignatureValue(void) const
+	Signature__C19CCMSX509Certificate @ 287 NONAME R3UNUSED ; CCMSX509Certificate::Signature(void) const
+	Signature__C32CCMSX509AttributeCertificateInfo @ 288 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::Signature(void) const
+	SignedAttributes__C14CCMSSignerInfo @ 289 NONAME R3UNUSED ; CCMSSignerInfo::SignedAttributes(void) const
+	SignerInfos__C14CCMSSignedData @ 290 NONAME R3UNUSED ; CCMSSignedData::SignerInfos(void) const
+	SubjectKeyIdentifierL__C29CCMSOriginatorIdentifierOrKey @ 291 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::SubjectKeyIdentifierL(void) const
+	SubjectKeyIdentifier__C14CCMSSignerInfo @ 292 NONAME R3UNUSED ; CCMSSignerInfo::SubjectKeyIdentifier(void) const
+	SubjectKeyIdentifier__C25CCMSKeyTransRecipientInfo @ 293 NONAME R3UNUSED ; CCMSKeyTransRecipientInfo::SubjectKeyIdentifier(void) const
+	SubjectName__C32CCMSX509AttributeCertificateInfo @ 294 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::SubjectName(void) const
+	SubjectPublicKeyInfo__C19CCMSX509Certificate @ 295 NONAME R3UNUSED ; CCMSX509Certificate::SubjectPublicKeyInfo(void) const
+	SubjectPublicKey__C28CCMSX509SubjectPublicKeyInfo @ 296 NONAME R3UNUSED ; CCMSX509SubjectPublicKeyInfo::SubjectPublicKey(void) const
+	SubjectUniqueIdentifier__C19CCMSX509Certificate @ 297 NONAME R3UNUSED ; CCMSX509Certificate::SubjectUniqueIdentifier(void) const
+	Subject__C19CCMSX509Certificate @ 298 NONAME R3UNUSED ; CCMSX509Certificate::Subject(void) const
+	Tag__C19CCMSX509GeneralName @ 299 NONAME R3UNUSED ; CCMSX509GeneralName::Tag(void) const
+	Type__C29CCMSOriginatorIdentifierOrKey @ 300 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::Type(void) const
+	UnauthenticatedAttributes__C21CCMSAuthenticatedData @ 301 NONAME R3UNUSED ; CCMSAuthenticatedData::UnauthenticatedAttributes(void) const
+	UnsignedAttributes__C14CCMSSignerInfo @ 302 NONAME R3UNUSED ; CCMSSignerInfo::UnsignedAttributes(void) const
+	UserKeyingMaterial__C25CCMSKeyAgreeRecipientInfo @ 303 NONAME R3UNUSED ; CCMSKeyAgreeRecipientInfo::UserKeyingMaterial(void) const
+	Validity__C19CCMSX509Certificate @ 304 NONAME R3UNUSED ; CCMSX509Certificate::Validity(void) const
+	Version__C14CCMSSignedData @ 305 NONAME R3UNUSED ; CCMSSignedData::Version(void) const
+	Version__C17CCMSRecipientInfo @ 306 NONAME R3UNUSED ; CCMSRecipientInfo::Version(void) const
+	Version__C19CCMSX509Certificate @ 307 NONAME R3UNUSED ; CCMSX509Certificate::Version(void) const
+	Version__C21CCMSAuthenticatedData @ 308 NONAME R3UNUSED ; CCMSAuthenticatedData::Version(void) const
+	Version__C32CCMSX509AttributeCertificateInfo @ 309 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::Version(void) const
+	__13CCMSAttribute @ 310 NONAME R3UNUSED ; CCMSAttribute::CCMSAttribute(void)
+	__14CCMSSignedData @ 311 NONAME R3UNUSED ; CCMSSignedData::CCMSSignedData(void)
+	__14CCMSSignerInfo @ 312 NONAME R3UNUSED ; CCMSSignerInfo::CCMSSignerInfo(void)
+	__15CCMSContentInfo @ 313 NONAME R3UNUSED ; CCMSContentInfo::CCMSContentInfo(void)
+	__16CCMSX509Validity @ 314 NONAME R3UNUSED ; CCMSX509Validity::CCMSX509Validity(void)
+	__16CCMSX509ValidityRC5TTimeT1 @ 315 NONAME R3UNUSED ; CCMSX509Validity::CCMSX509Validity(TTime const &, TTime const &)
+	__17CCMSKeyIdentifier @ 316 NONAME R3UNUSED ; CCMSKeyIdentifier::CCMSKeyIdentifier(void)
+	__18CCMSOriginatorInfo @ 317 NONAME R3UNUSED ; CCMSOriginatorInfo::CCMSOriginatorInfo(void)
+	__19CCMSX509Certificate @ 318 NONAME R3UNUSED ; CCMSX509Certificate::CCMSX509Certificate(void)
+	__19CCMSX509GeneralName @ 319 NONAME R3UNUSED ; CCMSX509GeneralName::CCMSX509GeneralName(void)
+	__20CCMSKEKRecipientInfo @ 320 NONAME R3UNUSED ; CCMSKEKRecipientInfo::CCMSKEKRecipientInfo(void)
+	__20CCMSX509GeneralNames @ 321 NONAME R3UNUSED ; CCMSX509GeneralNames::CCMSX509GeneralNames(void)
+	__20CCMSX509IssuerSeriali @ 322 NONAME R3UNUSED ; CCMSX509IssuerSerial::CCMSX509IssuerSerial(int)
+	__21CCMSAuthenticatedData @ 323 NONAME R3UNUSED ; CCMSAuthenticatedData::CCMSAuthenticatedData(void)
+	__22CCMSCertificateChoices @ 324 NONAME R3UNUSED ; CCMSCertificateChoices::CCMSCertificateChoices(void)
+	__23CCMSOriginatorPublicKey @ 325 NONAME R3UNUSED ; CCMSOriginatorPublicKey::CCMSOriginatorPublicKey(void)
+	__23CCMSX509CertificateList @ 326 NONAME R3UNUSED ; CCMSX509CertificateList::CCMSX509CertificateList(void)
+	__25CCMSIssuerAndSerialNumber @ 327 NONAME R3UNUSED ; CCMSIssuerAndSerialNumber::CCMSIssuerAndSerialNumber(void)
+	__25CCMSKeyAgreeRecipientInfo @ 328 NONAME R3UNUSED ; CCMSKeyAgreeRecipientInfo::CCMSKeyAgreeRecipientInfo(void)
+	__25CCMSKeyTransRecipientInfoi @ 329 NONAME R3UNUSED ; CCMSKeyTransRecipientInfo::CCMSKeyTransRecipientInfo(int)
+	__25CCMSRecipientEncryptedKey @ 330 NONAME R3UNUSED ; CCMSRecipientEncryptedKey::CCMSRecipientEncryptedKey(void)
+	__26CCMSX509RevokedCertificate @ 331 NONAME R3UNUSED ; CCMSX509RevokedCertificate::CCMSX509RevokedCertificate(void)
+	__27CCMSEncapsulatedContentInfo @ 332 NONAME R3UNUSED ; CCMSEncapsulatedContentInfo::CCMSEncapsulatedContentInfo(void)
+	__27CCMSX509AlgorithmIdentifier @ 333 NONAME R3UNUSED ; CCMSX509AlgorithmIdentifier::CCMSX509AlgorithmIdentifier(void)
+	__28CCMSX509AttributeCertificate @ 334 NONAME R3UNUSED ; CCMSX509AttributeCertificate::CCMSX509AttributeCertificate(void)
+	__28CCMSX509SubjectPublicKeyInfo @ 335 NONAME R3UNUSED ; CCMSX509SubjectPublicKeyInfo::CCMSX509SubjectPublicKeyInfo(void)
+	__29CCMSOriginatorIdentifierOrKey @ 336 NONAME R3UNUSED ; CCMSOriginatorIdentifierOrKey::CCMSOriginatorIdentifierOrKey(void)
+	__32CCMSX509AttributeCertificateInfo @ 337 NONAME R3UNUSED ; CCMSX509AttributeCertificateInfo::CCMSX509AttributeCertificateInfo(void)
+	AlgorithmIdentifier__C14CCMSX509Signed @ 338 NONAME R3UNUSED ; CCMSX509Signed::AlgorithmIdentifier(void) const
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/BWINS/CMSU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,347 @@
+EXPORTS
+	??0CCMSAttribute@@IAE@XZ @ 1 NONAME ; CCMSAttribute::CCMSAttribute(void)
+	??0CCMSAuthenticatedData@@IAE@XZ @ 2 NONAME ; CCMSAuthenticatedData::CCMSAuthenticatedData(void)
+	??0CCMSCertificateChoices@@IAE@XZ @ 3 NONAME ; CCMSCertificateChoices::CCMSCertificateChoices(void)
+	??0CCMSContentInfo@@IAE@XZ @ 4 NONAME ; CCMSContentInfo::CCMSContentInfo(void)
+	??0CCMSEncapsulatedContentInfo@@IAE@XZ @ 5 NONAME ; CCMSEncapsulatedContentInfo::CCMSEncapsulatedContentInfo(void)
+	??0CCMSIssuerAndSerialNumber@@IAE@XZ @ 6 NONAME ; CCMSIssuerAndSerialNumber::CCMSIssuerAndSerialNumber(void)
+	??0CCMSKEKRecipientInfo@@IAE@XZ @ 7 NONAME ; CCMSKEKRecipientInfo::CCMSKEKRecipientInfo(void)
+	??0CCMSKeyAgreeRecipientInfo@@IAE@XZ @ 8 NONAME ; CCMSKeyAgreeRecipientInfo::CCMSKeyAgreeRecipientInfo(void)
+	??0CCMSKeyIdentifier@@IAE@XZ @ 9 NONAME ; CCMSKeyIdentifier::CCMSKeyIdentifier(void)
+	??0CCMSKeyTransRecipientInfo@@IAE@H@Z @ 10 NONAME ; CCMSKeyTransRecipientInfo::CCMSKeyTransRecipientInfo(int)
+	??0CCMSOriginatorIdentifierOrKey@@IAE@XZ @ 11 NONAME ; CCMSOriginatorIdentifierOrKey::CCMSOriginatorIdentifierOrKey(void)
+	??0CCMSOriginatorInfo@@IAE@XZ @ 12 NONAME ; CCMSOriginatorInfo::CCMSOriginatorInfo(void)
+	??0CCMSOriginatorPublicKey@@IAE@XZ @ 13 NONAME ; CCMSOriginatorPublicKey::CCMSOriginatorPublicKey(void)
+	??0CCMSRecipientEncryptedKey@@IAE@XZ @ 14 NONAME ; CCMSRecipientEncryptedKey::CCMSRecipientEncryptedKey(void)
+	??0CCMSSignedData@@IAE@XZ @ 15 NONAME ; CCMSSignedData::CCMSSignedData(void)
+	??0CCMSSignerInfo@@IAE@XZ @ 16 NONAME ; CCMSSignerInfo::CCMSSignerInfo(void)
+	??0CCMSX509AlgorithmIdentifier@@IAE@XZ @ 17 NONAME ; CCMSX509AlgorithmIdentifier::CCMSX509AlgorithmIdentifier(void)
+	??0CCMSX509AttributeCertificate@@IAE@XZ @ 18 NONAME ; CCMSX509AttributeCertificate::CCMSX509AttributeCertificate(void)
+	??0CCMSX509AttributeCertificateInfo@@IAE@XZ @ 19 NONAME ; CCMSX509AttributeCertificateInfo::CCMSX509AttributeCertificateInfo(void)
+	??0CCMSX509Certificate@@IAE@XZ @ 20 NONAME ; CCMSX509Certificate::CCMSX509Certificate(void)
+	??0CCMSX509CertificateList@@IAE@XZ @ 21 NONAME ; CCMSX509CertificateList::CCMSX509CertificateList(void)
+	??0CCMSX509CertificateListParameters@@QAE@XZ @ 22 NONAME ; CCMSX509CertificateListParameters::CCMSX509CertificateListParameters(void)
+	??0CCMSX509GeneralName@@IAE@XZ @ 23 NONAME ; CCMSX509GeneralName::CCMSX509GeneralName(void)
+	??0CCMSX509GeneralNames@@IAE@XZ @ 24 NONAME ; CCMSX509GeneralNames::CCMSX509GeneralNames(void)
+	??0CCMSX509IssuerSerial@@IAE@H@Z @ 25 NONAME ; CCMSX509IssuerSerial::CCMSX509IssuerSerial(int)
+	??0CCMSX509RevokedCertificate@@QAE@XZ @ 26 NONAME ; CCMSX509RevokedCertificate::CCMSX509RevokedCertificate(void)
+	??0CCMSX509SubjectPublicKeyInfo@@IAE@XZ @ 27 NONAME ; CCMSX509SubjectPublicKeyInfo::CCMSX509SubjectPublicKeyInfo(void)
+	??0CCMSX509Validity@@IAE@ABVTTime@@0@Z @ 28 NONAME ; CCMSX509Validity::CCMSX509Validity(class TTime const &, class TTime const &)
+	??0CCMSX509Validity@@IAE@XZ @ 29 NONAME ; CCMSX509Validity::CCMSX509Validity(void)
+	?Algorithm@CCMSOriginatorPublicKey@@QBEABVCCMSX509AlgorithmIdentifier@@XZ @ 30 NONAME ; class CCMSX509AlgorithmIdentifier const & CCMSOriginatorPublicKey::Algorithm(void) const
+	?Algorithm@CCMSX509SubjectPublicKeyInfo@@QBEABVCCMSX509AlgorithmIdentifier@@XZ @ 31 NONAME ; class CCMSX509AlgorithmIdentifier const & CCMSX509SubjectPublicKeyInfo::Algorithm(void) const
+	?AlgorithmIdentifier@CCMSX509AlgorithmIdentifier@@QBEABVCAlgorithmIdentifier@@XZ @ 32 NONAME ; class CAlgorithmIdentifier const & CCMSX509AlgorithmIdentifier::AlgorithmIdentifier(void) const
+	?AlgorithmIdentifier@CCMSX509Signed@@QBEABVCCMSX509AlgorithmIdentifier@@XZ @ 33 NONAME ; class CCMSX509AlgorithmIdentifier const & CCMSX509Signed::AlgorithmIdentifier(void) const
+	?AttrCert@CCMSCertificateChoices@@QBEPBVCCMSX509AttributeCertificate@@XZ @ 34 NONAME ; class CCMSX509AttributeCertificate const * CCMSCertificateChoices::AttrCert(void) const
+	?AttributeType@CCMSAttribute@@QBEABVTDesC16@@XZ @ 35 NONAME ; class TDesC16 const & CCMSAttribute::AttributeType(void) const
+	?AttributeValues@CCMSAttribute@@QBEABVCDesC8Array@@XZ @ 36 NONAME ; class CDesC8Array const & CCMSAttribute::AttributeValues(void) const
+	?Attributes@CCMSX509AttributeCertificateInfo@@QBEABV?$CArrayPtr@VCCMSAttribute@@@@XZ @ 37 NONAME ; class CArrayPtr<class CCMSAttribute> const & CCMSX509AttributeCertificateInfo::Attributes(void) const
+	?AuthenticatedAttributes@CCMSAuthenticatedData@@QBEPBV?$CArrayPtr@VCCMSAttribute@@@@XZ @ 38 NONAME ; class CArrayPtr<class CCMSAttribute> const * CCMSAuthenticatedData::AuthenticatedAttributes(void) const
+	?BaseCertificateID@CCMSX509AttributeCertificateInfo@@QBEPBVCCMSX509IssuerSerial@@XZ @ 39 NONAME ; class CCMSX509IssuerSerial const * CCMSX509AttributeCertificateInfo::BaseCertificateID(void) const
+	?CMSVersion@CCMSSignerInfo@@QBEHXZ @ 40 NONAME ; int CCMSSignerInfo::CMSVersion(void) const
+	?Certificate@CCMSCertificateChoices@@QBEPBVCCMSX509Certificate@@XZ @ 41 NONAME ; class CCMSX509Certificate const * CCMSCertificateChoices::Certificate(void) const
+	?Certificates@CCMSSignedData@@QBEPBV?$CArrayPtr@VCCMSCertificateChoices@@@@XZ @ 42 NONAME ; class CArrayPtr<class CCMSCertificateChoices> const * CCMSSignedData::Certificates(void) const
+	?Certs@CCMSOriginatorInfo@@QBEPBV?$CArrayPtr@VCCMSCertificateChoices@@@@XZ @ 43 NONAME ; class CArrayPtr<class CCMSCertificateChoices> const * CCMSOriginatorInfo::Certs(void) const
+	?ConstructL@CCMSAttribute@@IAEXABVTDesC16@@ABVCDesC8Array@@@Z @ 44 NONAME ; void CCMSAttribute::ConstructL(class TDesC16 const &, class CDesC8Array const &)
+	?ConstructL@CCMSAttribute@@IAEXABVTDesC16@@ABVTDesC8@@@Z @ 45 NONAME ; void CCMSAttribute::ConstructL(class TDesC16 const &, class TDesC8 const &)
+	?ConstructL@CCMSAttribute@@IAEXXZ @ 46 NONAME ; void CCMSAttribute::ConstructL(void)
+	?ConstructL@CCMSAuthenticatedData@@IAEXPAV?$CArrayPtr@VCCMSRecipientInfo@@@@PAVCCMSX509AlgorithmIdentifier@@PAVCCMSEncapsulatedContentInfo@@ABVTDesC8@@@Z @ 47 NONAME ; void CCMSAuthenticatedData::ConstructL(class CArrayPtr<class CCMSRecipientInfo> *, class CCMSX509AlgorithmIdentifier *, class CCMSEncapsulatedContentInfo *, class TDesC8 const &)
+	?ConstructL@CCMSAuthenticatedData@@IAEXXZ @ 48 NONAME ; void CCMSAuthenticatedData::ConstructL(void)
+	?ConstructL@CCMSCertificateChoices@@IAEXABVCCMSX509AttributeCertificate@@@Z @ 49 NONAME ; void CCMSCertificateChoices::ConstructL(class CCMSX509AttributeCertificate const &)
+	?ConstructL@CCMSCertificateChoices@@IAEXABVCCMSX509Certificate@@@Z @ 50 NONAME ; void CCMSCertificateChoices::ConstructL(class CCMSX509Certificate const &)
+	?ConstructL@CCMSContentInfo@@IAEXABVTDesC16@@@Z @ 51 NONAME ; void CCMSContentInfo::ConstructL(class TDesC16 const &)
+	?ConstructL@CCMSContentInfo@@IAEXABVTDesC16@@ABVTDesC8@@@Z @ 52 NONAME ; void CCMSContentInfo::ConstructL(class TDesC16 const &, class TDesC8 const &)
+	?ConstructL@CCMSContentInfo@@IAEXXZ @ 53 NONAME ; void CCMSContentInfo::ConstructL(void)
+	?ConstructL@CCMSEncapsulatedContentInfo@@IAEXABVTDesC16@@PBVTDesC8@@@Z @ 54 NONAME ; void CCMSEncapsulatedContentInfo::ConstructL(class TDesC16 const &, class TDesC8 const *)
+	?ConstructL@CCMSEncapsulatedContentInfo@@IAEXXZ @ 55 NONAME ; void CCMSEncapsulatedContentInfo::ConstructL(void)
+	?ConstructL@CCMSIssuerAndSerialNumber@@IAEXABVCX500DistinguishedName@@ABVTDesC8@@@Z @ 56 NONAME ; void CCMSIssuerAndSerialNumber::ConstructL(class CX500DistinguishedName const &, class TDesC8 const &)
+	?ConstructL@CCMSKEKRecipientInfo@@IAEXABVCCMSKeyIdentifier@@ABVCCMSX509AlgorithmIdentifier@@ABVTDesC8@@@Z @ 57 NONAME ; void CCMSKEKRecipientInfo::ConstructL(class CCMSKeyIdentifier const &, class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?ConstructL@CCMSKeyAgreeRecipientInfo@@IAEXABVCCMSOriginatorIdentifierOrKey@@ABVCCMSX509AlgorithmIdentifier@@ABV?$CArrayPtr@VCCMSRecipientEncryptedKey@@@@@Z @ 58 NONAME ; void CCMSKeyAgreeRecipientInfo::ConstructL(class CCMSOriginatorIdentifierOrKey const &, class CCMSX509AlgorithmIdentifier const &, class CArrayPtr<class CCMSRecipientEncryptedKey> const &)
+	?ConstructL@CCMSKeyAgreeRecipientInfo@@IAEXABVCCMSOriginatorIdentifierOrKey@@ABVTDesC8@@ABVCCMSX509AlgorithmIdentifier@@ABV?$CArrayPtr@VCCMSRecipientEncryptedKey@@@@@Z @ 59 NONAME ; void CCMSKeyAgreeRecipientInfo::ConstructL(class CCMSOriginatorIdentifierOrKey const &, class TDesC8 const &, class CCMSX509AlgorithmIdentifier const &, class CArrayPtr<class CCMSRecipientEncryptedKey> const &)
+	?ConstructL@CCMSKeyAgreeRecipientInfo@@IAEXXZ @ 60 NONAME ; void CCMSKeyAgreeRecipientInfo::ConstructL(void)
+	?ConstructL@CCMSKeyIdentifier@@IAEXABVTDesC8@@@Z @ 61 NONAME ; void CCMSKeyIdentifier::ConstructL(class TDesC8 const &)
+	?ConstructL@CCMSKeyIdentifier@@IAEXABVTDesC8@@ABVTTime@@@Z @ 62 NONAME ; void CCMSKeyIdentifier::ConstructL(class TDesC8 const &, class TTime const &)
+	?ConstructL@CCMSKeyTransRecipientInfo@@IAEXABVCCMSIssuerAndSerialNumber@@ABVCCMSX509AlgorithmIdentifier@@ABVTDesC8@@@Z @ 63 NONAME ; void CCMSKeyTransRecipientInfo::ConstructL(class CCMSIssuerAndSerialNumber const &, class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?ConstructL@CCMSKeyTransRecipientInfo@@IAEXABVTDesC8@@ABVCCMSX509AlgorithmIdentifier@@0@Z @ 64 NONAME ; void CCMSKeyTransRecipientInfo::ConstructL(class TDesC8 const &, class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?ConstructL@CCMSOriginatorIdentifierOrKey@@IAEXABVCCMSIssuerAndSerialNumber@@@Z @ 65 NONAME ; void CCMSOriginatorIdentifierOrKey::ConstructL(class CCMSIssuerAndSerialNumber const &)
+	?ConstructL@CCMSOriginatorIdentifierOrKey@@IAEXABVCCMSOriginatorPublicKey@@@Z @ 66 NONAME ; void CCMSOriginatorIdentifierOrKey::ConstructL(class CCMSOriginatorPublicKey const &)
+	?ConstructL@CCMSOriginatorIdentifierOrKey@@IAEXABVTDesC8@@@Z @ 67 NONAME ; void CCMSOriginatorIdentifierOrKey::ConstructL(class TDesC8 const &)
+	?ConstructL@CCMSOriginatorPublicKey@@IAEXABVCCMSX509AlgorithmIdentifier@@ABVTDesC8@@@Z @ 68 NONAME ; void CCMSOriginatorPublicKey::ConstructL(class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?ConstructL@CCMSRecipientEncryptedKey@@IAEXABVCCMSIssuerAndSerialNumber@@ABVTDesC8@@@Z @ 69 NONAME ; void CCMSRecipientEncryptedKey::ConstructL(class CCMSIssuerAndSerialNumber const &, class TDesC8 const &)
+	?ConstructL@CCMSRecipientEncryptedKey@@IAEXABVCCMSKeyIdentifier@@ABVTDesC8@@@Z @ 70 NONAME ; void CCMSRecipientEncryptedKey::ConstructL(class CCMSKeyIdentifier const &, class TDesC8 const &)
+	?ConstructL@CCMSSignedData@@IAEXABV?$CArrayPtr@VCCMSX509AlgorithmIdentifier@@@@ABVCCMSEncapsulatedContentInfo@@ABV?$CArrayPtr@VCCMSSignerInfo@@@@PBV?$CArrayPtr@VCCMSCertificateChoices@@@@PBV?$CArrayPtr@VCCMSX509CertificateList@@@@@Z @ 71 NONAME ; void CCMSSignedData::ConstructL(class CArrayPtr<class CCMSX509AlgorithmIdentifier> const &, class CCMSEncapsulatedContentInfo const &, class CArrayPtr<class CCMSSignerInfo> const &, class CArrayPtr<class CCMSCertificateChoices> const *, class CArrayPtr<class CCMSX509CertificateList> const *)
+	?ConstructL@CCMSSignedData@@IAEXXZ @ 72 NONAME ; void CCMSSignedData::ConstructL(void)
+	?ConstructL@CCMSSignerInfo@@IAEXABVCCMSX509Certificate@@ABVTDesC8@@@Z @ 73 NONAME ; void CCMSSignerInfo::ConstructL(class CCMSX509Certificate const &, class TDesC8 const &)
+	?ConstructL@CCMSSignerInfo@@IAEXABVTDesC8@@00@Z @ 74 NONAME ; void CCMSSignerInfo::ConstructL(class TDesC8 const &, class TDesC8 const &, class TDesC8 const &)
+	?ConstructL@CCMSX509AlgorithmIdentifier@@IAEXABVCAlgorithmIdentifier@@@Z @ 75 NONAME ; void CCMSX509AlgorithmIdentifier::ConstructL(class CAlgorithmIdentifier const &)
+	?ConstructL@CCMSX509AlgorithmIdentifier@@IAEXABW4TAlgorithmId@@@Z @ 76 NONAME ; void CCMSX509AlgorithmIdentifier::ConstructL(enum TAlgorithmId const &)
+	?ConstructL@CCMSX509AttributeCertificate@@IAEXABVCCMSX509AttributeCertificateInfo@@ABVCCMSX509AlgorithmIdentifier@@ABVTDesC8@@@Z @ 77 NONAME ; void CCMSX509AttributeCertificate::ConstructL(class CCMSX509AttributeCertificateInfo const &, class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?ConstructL@CCMSX509AttributeCertificate@@IAEXXZ @ 78 NONAME ; void CCMSX509AttributeCertificate::ConstructL(void)
+	?ConstructL@CCMSX509AttributeCertificateInfo@@IAEXABVCCMSX509GeneralNames@@0ABVCCMSX509AlgorithmIdentifier@@HABVTTime@@2ABV?$CArrayPtr@VCCMSAttribute@@@@@Z @ 79 NONAME ; void CCMSX509AttributeCertificateInfo::ConstructL(class CCMSX509GeneralNames const &, class CCMSX509GeneralNames const &, class CCMSX509AlgorithmIdentifier const &, int, class TTime const &, class TTime const &, class CArrayPtr<class CCMSAttribute> const &)
+	?ConstructL@CCMSX509AttributeCertificateInfo@@IAEXABVCCMSX509IssuerSerial@@ABVCCMSX509GeneralNames@@ABVCCMSX509AlgorithmIdentifier@@HABVTTime@@3ABV?$CArrayPtr@VCCMSAttribute@@@@@Z @ 80 NONAME ; void CCMSX509AttributeCertificateInfo::ConstructL(class CCMSX509IssuerSerial const &, class CCMSX509GeneralNames const &, class CCMSX509AlgorithmIdentifier const &, int, class TTime const &, class TTime const &, class CArrayPtr<class CCMSAttribute> const &)
+	?ConstructL@CCMSX509AttributeCertificateInfo@@IAEXXZ @ 81 NONAME ; void CCMSX509AttributeCertificateInfo::ConstructL(void)
+	?ConstructL@CCMSX509Certificate@@IAEXABVCX509Certificate@@@Z @ 82 NONAME ; void CCMSX509Certificate::ConstructL(class CX509Certificate const &)
+	?ConstructL@CCMSX509Certificate@@IAEXABVTDesC8@@ABVCCMSX509AlgorithmIdentifier@@ABVCX500DistinguishedName@@ABVCCMSX509Validity@@2ABVCCMSX509SubjectPublicKeyInfo@@10@Z @ 83 NONAME ; void CCMSX509Certificate::ConstructL(class TDesC8 const &, class CCMSX509AlgorithmIdentifier const &, class CX500DistinguishedName const &, class CCMSX509Validity const &, class CX500DistinguishedName const &, class CCMSX509SubjectPublicKeyInfo const &, class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?ConstructL@CCMSX509Certificate@@IAEXXZ @ 84 NONAME ; void CCMSX509Certificate::ConstructL(void)
+	?ConstructL@CCMSX509CertificateList@@IAEXABVCX509Certificate@@ABV?$CArrayPtrFlat@VCX509Certificate@@@@@Z @ 85 NONAME ; void CCMSX509CertificateList::ConstructL(class CX509Certificate const &, class CArrayPtrFlat<class CX509Certificate> const &)
+	?ConstructL@CCMSX509CertificateList@@IAEXXZ @ 86 NONAME ; void CCMSX509CertificateList::ConstructL(void)
+	?ConstructL@CCMSX509GeneralName@@IAEXIABVTDesC8@@@Z @ 87 NONAME ; void CCMSX509GeneralName::ConstructL(unsigned int, class TDesC8 const &)
+	?ConstructL@CCMSX509GeneralNames@@IAEXABV?$CArrayPtr@VCCMSX509GeneralName@@@@@Z @ 88 NONAME ; void CCMSX509GeneralNames::ConstructL(class CArrayPtr<class CCMSX509GeneralName> const &)
+	?ConstructL@CCMSX509IssuerSerial@@IAEXABVCCMSX509GeneralNames@@@Z @ 89 NONAME ; void CCMSX509IssuerSerial::ConstructL(class CCMSX509GeneralNames const &)
+	?ConstructL@CCMSX509IssuerSerial@@IAEXABVCCMSX509GeneralNames@@ABVTDesC8@@@Z @ 90 NONAME ; void CCMSX509IssuerSerial::ConstructL(class CCMSX509GeneralNames const &, class TDesC8 const &)
+	?ConstructL@CCMSX509SubjectPublicKeyInfo@@IAEXABVCCMSX509AlgorithmIdentifier@@ABVTDesC8@@@Z @ 91 NONAME ; void CCMSX509SubjectPublicKeyInfo::ConstructL(class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?ConstructL@CCMSX509SubjectPublicKeyInfo@@IAEXABVCSubjectPublicKeyInfo@@@Z @ 92 NONAME ; void CCMSX509SubjectPublicKeyInfo::ConstructL(class CSubjectPublicKeyInfo const &)
+	?ConstructL@CCMSX509SubjectPublicKeyInfo@@IAEXXZ @ 93 NONAME ; void CCMSX509SubjectPublicKeyInfo::ConstructL(void)
+	?Content@CCMSContentInfo@@QBEABVTDesC8@@XZ @ 94 NONAME ; class TDesC8 const & CCMSContentInfo::Content(void) const
+	?Content@CCMSEncapsulatedContentInfo@@QBEPBVTDesC8@@XZ @ 95 NONAME ; class TDesC8 const * CCMSEncapsulatedContentInfo::Content(void) const
+	?ContentType@CCMSContentInfo@@QBEABVTDesC16@@XZ @ 96 NONAME ; class TDesC16 const & CCMSContentInfo::ContentType(void) const
+	?CreateDerEncodingL@CCMSSequence@@KAPAVHBufC8@@PAVCASN1EncBase@@@Z @ 97 NONAME ; class HBufC8 * CCMSSequence::CreateDerEncodingL(class CASN1EncBase *)
+	?Crls@CCMSOriginatorInfo@@QBEPBV?$CArrayPtr@VCCMSX509CertificateList@@@@XZ @ 98 NONAME ; class CArrayPtr<class CCMSX509CertificateList> const * CCMSOriginatorInfo::Crls(void) const
+	?Data@CCMSX509GeneralName@@QBEABVTDesC8@@XZ @ 99 NONAME ; class TDesC8 const & CCMSX509GeneralName::Data(void) const
+	?Date@CCMSKeyIdentifier@@QBEPBVTTime@@XZ @ 100 NONAME ; class TTime const * CCMSKeyIdentifier::Date(void) const
+	?DecodeSequenceLC@CCMSSequence@@KAPAV?$CArrayPtr@VTASN1DecGeneric@@@@ABVTDesC8@@@Z @ 101 NONAME ; class CArrayPtr<class TASN1DecGeneric> * CCMSSequence::DecodeSequenceLC(class TDesC8 const &)
+	?DecodeSequenceLC@CCMSSequence@@KAPAV?$CArrayPtr@VTASN1DecGeneric@@@@ABVTDesC8@@HH@Z @ 102 NONAME ; class CArrayPtr<class TASN1DecGeneric> * CCMSSequence::DecodeSequenceLC(class TDesC8 const &, int, int)
+	?DigestAlgorithm@CCMSAuthenticatedData@@QBEPBVCCMSX509AlgorithmIdentifier@@XZ @ 103 NONAME ; class CCMSX509AlgorithmIdentifier const * CCMSAuthenticatedData::DigestAlgorithm(void) const
+	?DigestAlgorithm@CCMSX509AlgorithmIdentifier@@QBEPBVCAlgorithmIdentifier@@XZ @ 104 NONAME ; class CAlgorithmIdentifier const * CCMSX509AlgorithmIdentifier::DigestAlgorithm(void) const
+	?DigestAlgorithmIdentifier@CCMSSignerInfo@@QBEABVCCMSX509AlgorithmIdentifier@@XZ @ 105 NONAME ; class CCMSX509AlgorithmIdentifier const & CCMSSignerInfo::DigestAlgorithmIdentifier(void) const
+	?DigestAlgorithmIdentifiers@CCMSSignedData@@QBEABV?$CArrayPtr@VCCMSX509AlgorithmIdentifier@@@@XZ @ 106 NONAME ; class CArrayPtr<class CCMSX509AlgorithmIdentifier> const & CCMSSignedData::DigestAlgorithmIdentifiers(void) const
+	?EncapContentInfo@CCMSAuthenticatedData@@QBEABVCCMSEncapsulatedContentInfo@@XZ @ 107 NONAME ; class CCMSEncapsulatedContentInfo const & CCMSAuthenticatedData::EncapContentInfo(void) const
+	?EncapsulatedContentInfo@CCMSSignedData@@QBEABVCCMSEncapsulatedContentInfo@@XZ @ 108 NONAME ; class CCMSEncapsulatedContentInfo const & CCMSSignedData::EncapsulatedContentInfo(void) const
+	?Encrypted@CCMSX509Signed@@QBEABVTDesC8@@XZ @ 109 NONAME ; class TDesC8 const & CCMSX509Signed::Encrypted(void) const
+	?EncryptedKey@CCMSKEKRecipientInfo@@QBEABVTDesC8@@XZ @ 110 NONAME ; class TDesC8 const & CCMSKEKRecipientInfo::EncryptedKey(void) const
+	?EncryptedKey@CCMSKeyTransRecipientInfo@@QBEABVTDesC8@@XZ @ 111 NONAME ; class TDesC8 const & CCMSKeyTransRecipientInfo::EncryptedKey(void) const
+	?EncryptedKey@CCMSRecipientEncryptedKey@@QBEABVTDesC8@@XZ @ 112 NONAME ; class TDesC8 const & CCMSRecipientEncryptedKey::EncryptedKey(void) const
+	?GeneralNames@CCMSX509GeneralNames@@QBEABV?$CArrayPtr@VCCMSX509GeneralName@@@@XZ @ 113 NONAME ; class CArrayPtr<class CCMSX509GeneralName> const & CCMSX509GeneralNames::GeneralNames(void) const
+	?Info@CCMSX509AttributeCertificate@@QBEABVCCMSX509AttributeCertificateInfo@@XZ @ 114 NONAME ; class CCMSX509AttributeCertificateInfo const & CCMSX509AttributeCertificate::Info(void) const
+	?Issuer@CCMSX509AttributeCertificateInfo@@QBEABVCCMSX509GeneralNames@@XZ @ 115 NONAME ; class CCMSX509GeneralNames const & CCMSX509AttributeCertificateInfo::Issuer(void) const
+	?Issuer@CCMSX509Certificate@@QBEABVCX500DistinguishedName@@XZ @ 116 NONAME ; class CX500DistinguishedName const & CCMSX509Certificate::Issuer(void) const
+	?Issuer@CCMSX509IssuerSerial@@QBEABVCCMSX509GeneralNames@@XZ @ 117 NONAME ; class CCMSX509GeneralNames const & CCMSX509IssuerSerial::Issuer(void) const
+	?IssuerAndSerialNumber@CCMSKeyTransRecipientInfo@@QBEPBVCCMSIssuerAndSerialNumber@@XZ @ 118 NONAME ; class CCMSIssuerAndSerialNumber const * CCMSKeyTransRecipientInfo::IssuerAndSerialNumber(void) const
+	?IssuerAndSerialNumber@CCMSRecipientEncryptedKey@@QBEPBVCCMSIssuerAndSerialNumber@@XZ @ 119 NONAME ; class CCMSIssuerAndSerialNumber const * CCMSRecipientEncryptedKey::IssuerAndSerialNumber(void) const
+	?IssuerAndSerialNumber@CCMSSignerInfo@@QBEPBVCCMSIssuerAndSerialNumber@@XZ @ 120 NONAME ; class CCMSIssuerAndSerialNumber const * CCMSSignerInfo::IssuerAndSerialNumber(void) const
+	?IssuerAndSerialNumberL@CCMSOriginatorIdentifierOrKey@@QBEABVCCMSIssuerAndSerialNumber@@XZ @ 121 NONAME ; class CCMSIssuerAndSerialNumber const & CCMSOriginatorIdentifierOrKey::IssuerAndSerialNumberL(void) const
+	?IssuerName@CCMSIssuerAndSerialNumber@@QBEABVCX500DistinguishedName@@XZ @ 122 NONAME ; class CX500DistinguishedName const & CCMSIssuerAndSerialNumber::IssuerName(void) const
+	?IssuerUID@CCMSX509IssuerSerial@@QBEPBVTDesC8@@XZ @ 123 NONAME ; class TDesC8 const * CCMSX509IssuerSerial::IssuerUID(void) const
+	?IssuerUniqueID@CCMSX509AttributeCertificateInfo@@QBEPBVTDesC8@@XZ @ 124 NONAME ; class TDesC8 const * CCMSX509AttributeCertificateInfo::IssuerUniqueID(void) const
+	?IssuerUniqueIdentifier@CCMSX509Certificate@@QBEPBVTDesC8@@XZ @ 125 NONAME ; class TDesC8 const * CCMSX509Certificate::IssuerUniqueIdentifier(void) const
+	?Kekid@CCMSKEKRecipientInfo@@QBEABVCCMSKeyIdentifier@@XZ @ 126 NONAME ; class CCMSKeyIdentifier const & CCMSKEKRecipientInfo::Kekid(void) const
+	?KeyEncryptionAlgorithm@CCMSRecipientInfo@@QBEABVCCMSX509AlgorithmIdentifier@@XZ @ 127 NONAME ; class CCMSX509AlgorithmIdentifier const & CCMSRecipientInfo::KeyEncryptionAlgorithm(void) const
+	?KeyIdentifier@CCMSKeyIdentifier@@QBEABVTDesC8@@XZ @ 128 NONAME ; class TDesC8 const & CCMSKeyIdentifier::KeyIdentifier(void) const
+	?Mac@CCMSAuthenticatedData@@QBEABVTDesC8@@XZ @ 129 NONAME ; class TDesC8 const & CCMSAuthenticatedData::Mac(void) const
+	?MacAlgorithm@CCMSAuthenticatedData@@QBEABVCCMSX509AlgorithmIdentifier@@XZ @ 130 NONAME ; class CCMSX509AlgorithmIdentifier const & CCMSAuthenticatedData::MacAlgorithm(void) const
+	?NewL@CCMSAttribute@@SAPAV1@ABVTDesC16@@ABVCDesC8Array@@@Z @ 131 NONAME ; class CCMSAttribute * CCMSAttribute::NewL(class TDesC16 const &, class CDesC8Array const &)
+	?NewL@CCMSAttribute@@SAPAV1@ABVTDesC16@@ABVTDesC8@@@Z @ 132 NONAME ; class CCMSAttribute * CCMSAttribute::NewL(class TDesC16 const &, class TDesC8 const &)
+	?NewL@CCMSAttribute@@SAPAV1@XZ @ 133 NONAME ; class CCMSAttribute * CCMSAttribute::NewL(void)
+	?NewL@CCMSCertificateChoices@@SAPAV1@ABVCCMSX509AttributeCertificate@@@Z @ 134 NONAME ; class CCMSCertificateChoices * CCMSCertificateChoices::NewL(class CCMSX509AttributeCertificate const &)
+	?NewL@CCMSCertificateChoices@@SAPAV1@ABVCCMSX509Certificate@@@Z @ 135 NONAME ; class CCMSCertificateChoices * CCMSCertificateChoices::NewL(class CCMSX509Certificate const &)
+	?NewL@CCMSCertificateChoices@@SAPAV1@XZ @ 136 NONAME ; class CCMSCertificateChoices * CCMSCertificateChoices::NewL(void)
+	?NewL@CCMSEncapsulatedContentInfo@@SAPAV1@ABVTDesC16@@PBVTDesC8@@@Z @ 137 NONAME ; class CCMSEncapsulatedContentInfo * CCMSEncapsulatedContentInfo::NewL(class TDesC16 const &, class TDesC8 const *)
+	?NewL@CCMSEncapsulatedContentInfo@@SAPAV1@XZ @ 138 NONAME ; class CCMSEncapsulatedContentInfo * CCMSEncapsulatedContentInfo::NewL(void)
+	?NewL@CCMSIssuerAndSerialNumber@@SAPAV1@ABVCX500DistinguishedName@@ABVTDesC8@@@Z @ 139 NONAME ; class CCMSIssuerAndSerialNumber * CCMSIssuerAndSerialNumber::NewL(class CX500DistinguishedName const &, class TDesC8 const &)
+	?NewL@CCMSIssuerAndSerialNumber@@SAPAV1@XZ @ 140 NONAME ; class CCMSIssuerAndSerialNumber * CCMSIssuerAndSerialNumber::NewL(void)
+	?NewL@CCMSKEKRecipientInfo@@SAPAV1@ABVCCMSKeyIdentifier@@ABVCCMSX509AlgorithmIdentifier@@ABVTDesC8@@@Z @ 141 NONAME ; class CCMSKEKRecipientInfo * CCMSKEKRecipientInfo::NewL(class CCMSKeyIdentifier const &, class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?NewL@CCMSKEKRecipientInfo@@SAPAV1@XZ @ 142 NONAME ; class CCMSKEKRecipientInfo * CCMSKEKRecipientInfo::NewL(void)
+	?NewL@CCMSKeyAgreeRecipientInfo@@SAPAV1@ABVCCMSOriginatorIdentifierOrKey@@ABVCCMSX509AlgorithmIdentifier@@ABV?$CArrayPtr@VCCMSRecipientEncryptedKey@@@@@Z @ 143 NONAME ; class CCMSKeyAgreeRecipientInfo * CCMSKeyAgreeRecipientInfo::NewL(class CCMSOriginatorIdentifierOrKey const &, class CCMSX509AlgorithmIdentifier const &, class CArrayPtr<class CCMSRecipientEncryptedKey> const &)
+	?NewL@CCMSKeyAgreeRecipientInfo@@SAPAV1@ABVCCMSOriginatorIdentifierOrKey@@ABVTDesC8@@ABVCCMSX509AlgorithmIdentifier@@ABV?$CArrayPtr@VCCMSRecipientEncryptedKey@@@@@Z @ 144 NONAME ; class CCMSKeyAgreeRecipientInfo * CCMSKeyAgreeRecipientInfo::NewL(class CCMSOriginatorIdentifierOrKey const &, class TDesC8 const &, class CCMSX509AlgorithmIdentifier const &, class CArrayPtr<class CCMSRecipientEncryptedKey> const &)
+	?NewL@CCMSKeyAgreeRecipientInfo@@SAPAV1@XZ @ 145 NONAME ; class CCMSKeyAgreeRecipientInfo * CCMSKeyAgreeRecipientInfo::NewL(void)
+	?NewL@CCMSKeyIdentifier@@SAPAV1@ABVTDesC8@@@Z @ 146 NONAME ; class CCMSKeyIdentifier * CCMSKeyIdentifier::NewL(class TDesC8 const &)
+	?NewL@CCMSKeyIdentifier@@SAPAV1@ABVTDesC8@@ABVTTime@@@Z @ 147 NONAME ; class CCMSKeyIdentifier * CCMSKeyIdentifier::NewL(class TDesC8 const &, class TTime const &)
+	?NewL@CCMSKeyIdentifier@@SAPAV1@XZ @ 148 NONAME ; class CCMSKeyIdentifier * CCMSKeyIdentifier::NewL(void)
+	?NewL@CCMSKeyTransRecipientInfo@@SAPAV1@ABVCCMSIssuerAndSerialNumber@@ABVCCMSX509AlgorithmIdentifier@@ABVTDesC8@@@Z @ 149 NONAME ; class CCMSKeyTransRecipientInfo * CCMSKeyTransRecipientInfo::NewL(class CCMSIssuerAndSerialNumber const &, class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?NewL@CCMSKeyTransRecipientInfo@@SAPAV1@ABVTDesC8@@ABVCCMSX509AlgorithmIdentifier@@0@Z @ 150 NONAME ; class CCMSKeyTransRecipientInfo * CCMSKeyTransRecipientInfo::NewL(class TDesC8 const &, class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?NewL@CCMSKeyTransRecipientInfo@@SAPAV1@XZ @ 151 NONAME ; class CCMSKeyTransRecipientInfo * CCMSKeyTransRecipientInfo::NewL(void)
+	?NewL@CCMSOriginatorIdentifierOrKey@@SAPAV1@ABVCCMSIssuerAndSerialNumber@@@Z @ 152 NONAME ; class CCMSOriginatorIdentifierOrKey * CCMSOriginatorIdentifierOrKey::NewL(class CCMSIssuerAndSerialNumber const &)
+	?NewL@CCMSOriginatorIdentifierOrKey@@SAPAV1@ABVCCMSOriginatorPublicKey@@@Z @ 153 NONAME ; class CCMSOriginatorIdentifierOrKey * CCMSOriginatorIdentifierOrKey::NewL(class CCMSOriginatorPublicKey const &)
+	?NewL@CCMSOriginatorIdentifierOrKey@@SAPAV1@ABVTDesC8@@@Z @ 154 NONAME ; class CCMSOriginatorIdentifierOrKey * CCMSOriginatorIdentifierOrKey::NewL(class TDesC8 const &)
+	?NewL@CCMSOriginatorIdentifierOrKey@@SAPAV1@XZ @ 155 NONAME ; class CCMSOriginatorIdentifierOrKey * CCMSOriginatorIdentifierOrKey::NewL(void)
+	?NewL@CCMSOriginatorInfo@@SAPAV1@XZ @ 156 NONAME ; class CCMSOriginatorInfo * CCMSOriginatorInfo::NewL(void)
+	?NewL@CCMSOriginatorPublicKey@@SAPAV1@ABV1@@Z @ 157 NONAME ; class CCMSOriginatorPublicKey * CCMSOriginatorPublicKey::NewL(class CCMSOriginatorPublicKey const &)
+	?NewL@CCMSOriginatorPublicKey@@SAPAV1@ABVCCMSX509AlgorithmIdentifier@@ABVTDesC8@@@Z @ 158 NONAME ; class CCMSOriginatorPublicKey * CCMSOriginatorPublicKey::NewL(class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?NewL@CCMSOriginatorPublicKey@@SAPAV1@XZ @ 159 NONAME ; class CCMSOriginatorPublicKey * CCMSOriginatorPublicKey::NewL(void)
+	?NewL@CCMSRecipientEncryptedKey@@SAPAV1@ABVCCMSIssuerAndSerialNumber@@ABVTDesC8@@@Z @ 160 NONAME ; class CCMSRecipientEncryptedKey * CCMSRecipientEncryptedKey::NewL(class CCMSIssuerAndSerialNumber const &, class TDesC8 const &)
+	?NewL@CCMSRecipientEncryptedKey@@SAPAV1@ABVCCMSKeyIdentifier@@ABVTDesC8@@@Z @ 161 NONAME ; class CCMSRecipientEncryptedKey * CCMSRecipientEncryptedKey::NewL(class CCMSKeyIdentifier const &, class TDesC8 const &)
+	?NewL@CCMSRecipientEncryptedKey@@SAPAV1@XZ @ 162 NONAME ; class CCMSRecipientEncryptedKey * CCMSRecipientEncryptedKey::NewL(void)
+	?NewL@CCMSSignerInfo@@SAPAV1@ABVCCMSX509Certificate@@ABVTDesC8@@@Z @ 163 NONAME ; class CCMSSignerInfo * CCMSSignerInfo::NewL(class CCMSX509Certificate const &, class TDesC8 const &)
+	?NewL@CCMSSignerInfo@@SAPAV1@ABVTDesC8@@00@Z @ 164 NONAME ; class CCMSSignerInfo * CCMSSignerInfo::NewL(class TDesC8 const &, class TDesC8 const &, class TDesC8 const &)
+	?NewL@CCMSSignerInfo@@SAPAV1@XZ @ 165 NONAME ; class CCMSSignerInfo * CCMSSignerInfo::NewL(void)
+	?NewL@CCMSX509AlgorithmIdentifier@@SAPAV1@ABVCAlgorithmIdentifier@@0@Z @ 166 NONAME ; class CCMSX509AlgorithmIdentifier * CCMSX509AlgorithmIdentifier::NewL(class CAlgorithmIdentifier const &, class CAlgorithmIdentifier const &)
+	?NewL@CCMSX509AlgorithmIdentifier@@SAPAV1@ABVCAlgorithmIdentifier@@@Z @ 167 NONAME ; class CCMSX509AlgorithmIdentifier * CCMSX509AlgorithmIdentifier::NewL(class CAlgorithmIdentifier const &)
+	?NewL@CCMSX509AlgorithmIdentifier@@SAPAV1@ABW4TAlgorithmId@@@Z @ 168 NONAME ; class CCMSX509AlgorithmIdentifier * CCMSX509AlgorithmIdentifier::NewL(enum TAlgorithmId const &)
+	?NewL@CCMSX509AlgorithmIdentifier@@SAPAV1@XZ @ 169 NONAME ; class CCMSX509AlgorithmIdentifier * CCMSX509AlgorithmIdentifier::NewL(void)
+	?NewL@CCMSX509AttributeCertificate@@SAPAV1@ABVCCMSX509AttributeCertificateInfo@@ABVCCMSX509AlgorithmIdentifier@@ABVTDesC8@@@Z @ 170 NONAME ; class CCMSX509AttributeCertificate * CCMSX509AttributeCertificate::NewL(class CCMSX509AttributeCertificateInfo const &, class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?NewL@CCMSX509AttributeCertificate@@SAPAV1@XZ @ 171 NONAME ; class CCMSX509AttributeCertificate * CCMSX509AttributeCertificate::NewL(void)
+	?NewL@CCMSX509AttributeCertificateInfo@@SAPAV1@ABVCCMSX509GeneralNames@@0ABVCCMSX509AlgorithmIdentifier@@HABVTTime@@2ABV?$CArrayPtr@VCCMSAttribute@@@@@Z @ 172 NONAME ; class CCMSX509AttributeCertificateInfo * CCMSX509AttributeCertificateInfo::NewL(class CCMSX509GeneralNames const &, class CCMSX509GeneralNames const &, class CCMSX509AlgorithmIdentifier const &, int, class TTime const &, class TTime const &, class CArrayPtr<class CCMSAttribute> const &)
+	?NewL@CCMSX509AttributeCertificateInfo@@SAPAV1@ABVCCMSX509IssuerSerial@@ABVCCMSX509GeneralNames@@ABVCCMSX509AlgorithmIdentifier@@HABVTTime@@3ABV?$CArrayPtr@VCCMSAttribute@@@@@Z @ 173 NONAME ; class CCMSX509AttributeCertificateInfo * CCMSX509AttributeCertificateInfo::NewL(class CCMSX509IssuerSerial const &, class CCMSX509GeneralNames const &, class CCMSX509AlgorithmIdentifier const &, int, class TTime const &, class TTime const &, class CArrayPtr<class CCMSAttribute> const &)
+	?NewL@CCMSX509AttributeCertificateInfo@@SAPAV1@XZ @ 174 NONAME ; class CCMSX509AttributeCertificateInfo * CCMSX509AttributeCertificateInfo::NewL(void)
+	?NewL@CCMSX509Certificate@@SAPAV1@ABVCX509Certificate@@@Z @ 175 NONAME ; class CCMSX509Certificate * CCMSX509Certificate::NewL(class CX509Certificate const &)
+	?NewL@CCMSX509Certificate@@SAPAV1@ABVTDesC8@@ABVCCMSX509AlgorithmIdentifier@@ABVCX500DistinguishedName@@ABVCCMSX509Validity@@2ABVCCMSX509SubjectPublicKeyInfo@@10@Z @ 176 NONAME ; class CCMSX509Certificate * CCMSX509Certificate::NewL(class TDesC8 const &, class CCMSX509AlgorithmIdentifier const &, class CX500DistinguishedName const &, class CCMSX509Validity const &, class CX500DistinguishedName const &, class CCMSX509SubjectPublicKeyInfo const &, class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?NewL@CCMSX509Certificate@@SAPAV1@XZ @ 177 NONAME ; class CCMSX509Certificate * CCMSX509Certificate::NewL(void)
+	?NewL@CCMSX509GeneralName@@SAPAV1@IABVTDesC8@@@Z @ 178 NONAME ; class CCMSX509GeneralName * CCMSX509GeneralName::NewL(unsigned int, class TDesC8 const &)
+	?NewL@CCMSX509GeneralName@@SAPAV1@XZ @ 179 NONAME ; class CCMSX509GeneralName * CCMSX509GeneralName::NewL(void)
+	?NewL@CCMSX509GeneralNames@@SAPAV1@ABV1@@Z @ 180 NONAME ; class CCMSX509GeneralNames * CCMSX509GeneralNames::NewL(class CCMSX509GeneralNames const &)
+	?NewL@CCMSX509GeneralNames@@SAPAV1@ABV?$CArrayPtr@VCCMSX509GeneralName@@@@@Z @ 181 NONAME ; class CCMSX509GeneralNames * CCMSX509GeneralNames::NewL(class CArrayPtr<class CCMSX509GeneralName> const &)
+	?NewL@CCMSX509GeneralNames@@SAPAV1@XZ @ 182 NONAME ; class CCMSX509GeneralNames * CCMSX509GeneralNames::NewL(void)
+	?NewL@CCMSX509IssuerSerial@@SAPAV1@ABVCCMSX509GeneralNames@@H@Z @ 183 NONAME ; class CCMSX509IssuerSerial * CCMSX509IssuerSerial::NewL(class CCMSX509GeneralNames const &, int)
+	?NewL@CCMSX509IssuerSerial@@SAPAV1@ABVCCMSX509GeneralNames@@HABVTDesC8@@@Z @ 184 NONAME ; class CCMSX509IssuerSerial * CCMSX509IssuerSerial::NewL(class CCMSX509GeneralNames const &, int, class TDesC8 const &)
+	?NewL@CCMSX509IssuerSerial@@SAPAV1@XZ @ 185 NONAME ; class CCMSX509IssuerSerial * CCMSX509IssuerSerial::NewL(void)
+	?NewL@CCMSX509SubjectPublicKeyInfo@@SAPAV1@ABVCCMSX509AlgorithmIdentifier@@ABVTDesC8@@@Z @ 186 NONAME ; class CCMSX509SubjectPublicKeyInfo * CCMSX509SubjectPublicKeyInfo::NewL(class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?NewL@CCMSX509SubjectPublicKeyInfo@@SAPAV1@ABVCSubjectPublicKeyInfo@@@Z @ 187 NONAME ; class CCMSX509SubjectPublicKeyInfo * CCMSX509SubjectPublicKeyInfo::NewL(class CSubjectPublicKeyInfo const &)
+	?NewL@CCMSX509SubjectPublicKeyInfo@@SAPAV1@XZ @ 188 NONAME ; class CCMSX509SubjectPublicKeyInfo * CCMSX509SubjectPublicKeyInfo::NewL(void)
+	?NewL@CCMSX509Validity@@SAPAV1@ABVCValidityPeriod@@@Z @ 189 NONAME ; class CCMSX509Validity * CCMSX509Validity::NewL(class CValidityPeriod const &)
+	?NewL@CCMSX509Validity@@SAPAV1@ABVTTime@@0@Z @ 190 NONAME ; class CCMSX509Validity * CCMSX509Validity::NewL(class TTime const &, class TTime const &)
+	?NewL@CCMSX509Validity@@SAPAV1@XZ @ 191 NONAME ; class CCMSX509Validity * CCMSX509Validity::NewL(void)
+	?NewLC@CCMSAttribute@@SAPAV1@ABVTDesC16@@ABVCDesC8Array@@@Z @ 192 NONAME ; class CCMSAttribute * CCMSAttribute::NewLC(class TDesC16 const &, class CDesC8Array const &)
+	?NewLC@CCMSAttribute@@SAPAV1@ABVTDesC16@@ABVTDesC8@@@Z @ 193 NONAME ; class CCMSAttribute * CCMSAttribute::NewLC(class TDesC16 const &, class TDesC8 const &)
+	?NewLC@CCMSAttribute@@SAPAV1@XZ @ 194 NONAME ; class CCMSAttribute * CCMSAttribute::NewLC(void)
+	?NewLC@CCMSAuthenticatedData@@SAPAV1@PAV?$CArrayPtr@VCCMSRecipientInfo@@@@PAVCCMSX509AlgorithmIdentifier@@PAVCCMSEncapsulatedContentInfo@@ABVTDesC8@@@Z @ 195 NONAME ; class CCMSAuthenticatedData * CCMSAuthenticatedData::NewLC(class CArrayPtr<class CCMSRecipientInfo> *, class CCMSX509AlgorithmIdentifier *, class CCMSEncapsulatedContentInfo *, class TDesC8 const &)
+	?NewLC@CCMSAuthenticatedData@@SAPAV1@XZ @ 196 NONAME ; class CCMSAuthenticatedData * CCMSAuthenticatedData::NewLC(void)
+	?NewLC@CCMSCertificateChoices@@SAPAV1@ABVCCMSX509AttributeCertificate@@@Z @ 197 NONAME ; class CCMSCertificateChoices * CCMSCertificateChoices::NewLC(class CCMSX509AttributeCertificate const &)
+	?NewLC@CCMSCertificateChoices@@SAPAV1@ABVCCMSX509Certificate@@@Z @ 198 NONAME ; class CCMSCertificateChoices * CCMSCertificateChoices::NewLC(class CCMSX509Certificate const &)
+	?NewLC@CCMSCertificateChoices@@SAPAV1@XZ @ 199 NONAME ; class CCMSCertificateChoices * CCMSCertificateChoices::NewLC(void)
+	?NewLC@CCMSContentInfo@@SAPAV1@ABVTDesC16@@ABVTDesC8@@@Z @ 200 NONAME ; class CCMSContentInfo * CCMSContentInfo::NewLC(class TDesC16 const &, class TDesC8 const &)
+	?NewLC@CCMSContentInfo@@SAPAV1@XZ @ 201 NONAME ; class CCMSContentInfo * CCMSContentInfo::NewLC(void)
+	?NewLC@CCMSEncapsulatedContentInfo@@SAPAV1@ABVTDesC16@@PBVTDesC8@@@Z @ 202 NONAME ; class CCMSEncapsulatedContentInfo * CCMSEncapsulatedContentInfo::NewLC(class TDesC16 const &, class TDesC8 const *)
+	?NewLC@CCMSEncapsulatedContentInfo@@SAPAV1@XZ @ 203 NONAME ; class CCMSEncapsulatedContentInfo * CCMSEncapsulatedContentInfo::NewLC(void)
+	?NewLC@CCMSKEKRecipientInfo@@SAPAV1@XZ @ 204 NONAME ; class CCMSKEKRecipientInfo * CCMSKEKRecipientInfo::NewLC(void)
+	?NewLC@CCMSKeyAgreeRecipientInfo@@SAPAV1@XZ @ 205 NONAME ; class CCMSKeyAgreeRecipientInfo * CCMSKeyAgreeRecipientInfo::NewLC(void)
+	?NewLC@CCMSKeyTransRecipientInfo@@SAPAV1@ABVTDesC8@@ABVCCMSX509AlgorithmIdentifier@@0@Z @ 206 NONAME ; class CCMSKeyTransRecipientInfo * CCMSKeyTransRecipientInfo::NewLC(class TDesC8 const &, class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?NewLC@CCMSKeyTransRecipientInfo@@SAPAV1@XZ @ 207 NONAME ; class CCMSKeyTransRecipientInfo * CCMSKeyTransRecipientInfo::NewLC(void)
+	?NewLC@CCMSOriginatorPublicKey@@SAPAV1@ABV1@@Z @ 208 NONAME ; class CCMSOriginatorPublicKey * CCMSOriginatorPublicKey::NewLC(class CCMSOriginatorPublicKey const &)
+	?NewLC@CCMSOriginatorPublicKey@@SAPAV1@ABVCCMSX509AlgorithmIdentifier@@ABVTDesC8@@@Z @ 209 NONAME ; class CCMSOriginatorPublicKey * CCMSOriginatorPublicKey::NewLC(class CCMSX509AlgorithmIdentifier const &, class TDesC8 const &)
+	?NewLC@CCMSSignedData@@SAPAV1@ABV?$CArrayPtr@VCCMSX509AlgorithmIdentifier@@@@ABVCCMSEncapsulatedContentInfo@@ABV?$CArrayPtr@VCCMSSignerInfo@@@@@Z @ 210 NONAME ; class CCMSSignedData * CCMSSignedData::NewLC(class CArrayPtr<class CCMSX509AlgorithmIdentifier> const &, class CCMSEncapsulatedContentInfo const &, class CArrayPtr<class CCMSSignerInfo> const &)
+	?NewLC@CCMSSignedData@@SAPAV1@ABV?$CArrayPtr@VCCMSX509AlgorithmIdentifier@@@@ABVCCMSEncapsulatedContentInfo@@ABV?$CArrayPtr@VCCMSSignerInfo@@@@PBV?$CArrayPtr@VCCMSCertificateChoices@@@@PBV?$CArrayPtr@VCCMSX509CertificateList@@@@@Z @ 211 NONAME ; class CCMSSignedData * CCMSSignedData::NewLC(class CArrayPtr<class CCMSX509AlgorithmIdentifier> const &, class CCMSEncapsulatedContentInfo const &, class CArrayPtr<class CCMSSignerInfo> const &, class CArrayPtr<class CCMSCertificateChoices> const *, class CArrayPtr<class CCMSX509CertificateList> const *)
+	?NewLC@CCMSSignedData@@SAPAV1@XZ @ 212 NONAME ; class CCMSSignedData * CCMSSignedData::NewLC(void)
+	?NewLC@CCMSX509CertificateList@@SAPAV1@AAVCCMSX509CertificateListParameters@@@Z @ 213 NONAME ; class CCMSX509CertificateList * CCMSX509CertificateList::NewLC(class CCMSX509CertificateListParameters &)
+	?NewLC@CCMSX509CertificateList@@SAPAV1@ABVCX509Certificate@@ABV?$CArrayPtrFlat@VCX509Certificate@@@@@Z @ 214 NONAME ; class CCMSX509CertificateList * CCMSX509CertificateList::NewLC(class CX509Certificate const &, class CArrayPtrFlat<class CX509Certificate> const &)
+	?NewLC@CCMSX509CertificateList@@SAPAV1@XZ @ 215 NONAME ; class CCMSX509CertificateList * CCMSX509CertificateList::NewLC(void)
+	?NotAfter@CCMSX509Validity@@QBEABVTTime@@XZ @ 216 NONAME ; class TTime const & CCMSX509Validity::NotAfter(void) const
+	?NotAfterTime@CCMSX509AttributeCertificateInfo@@QBEABVTTime@@XZ @ 217 NONAME ; class TTime const & CCMSX509AttributeCertificateInfo::NotAfterTime(void) const
+	?NotBefore@CCMSX509Validity@@QBEABVTTime@@XZ @ 218 NONAME ; class TTime const & CCMSX509Validity::NotBefore(void) const
+	?NotBeforeTime@CCMSX509AttributeCertificateInfo@@QBEABVTTime@@XZ @ 219 NONAME ; class TTime const & CCMSX509AttributeCertificateInfo::NotBeforeTime(void) const
+	?Originator@CCMSKeyAgreeRecipientInfo@@QBEABVCCMSOriginatorIdentifierOrKey@@XZ @ 220 NONAME ; class CCMSOriginatorIdentifierOrKey const & CCMSKeyAgreeRecipientInfo::Originator(void) const
+	?OriginatorInfo@CCMSAuthenticatedData@@QBEPBVCCMSOriginatorInfo@@XZ @ 221 NONAME ; class CCMSOriginatorInfo const * CCMSAuthenticatedData::OriginatorInfo(void) const
+	?OriginatorKeyL@CCMSOriginatorIdentifierOrKey@@QBEABVCCMSOriginatorPublicKey@@XZ @ 222 NONAME ; class CCMSOriginatorPublicKey const & CCMSOriginatorIdentifierOrKey::OriginatorKeyL(void) const
+	?Parameters@CCMSX509CertificateList@@QBEABVCCMSX509CertificateListParameters@@XZ @ 223 NONAME ; class CCMSX509CertificateListParameters const & CCMSX509CertificateList::Parameters(void) const
+	?PublicKey@CCMSOriginatorPublicKey@@QBEABVTDesC8@@XZ @ 224 NONAME ; class TDesC8 const & CCMSOriginatorPublicKey::PublicKey(void) const
+	?RKeyId@CCMSRecipientEncryptedKey@@QBEPBVCCMSKeyIdentifier@@XZ @ 225 NONAME ; class CCMSKeyIdentifier const * CCMSRecipientEncryptedKey::RKeyId(void) const
+	?RecipientEncryptedKeys@CCMSKeyAgreeRecipientInfo@@QBEABV?$CArrayPtr@VCCMSRecipientEncryptedKey@@@@XZ @ 226 NONAME ; class CArrayPtr<class CCMSRecipientEncryptedKey> const & CCMSKeyAgreeRecipientInfo::RecipientEncryptedKeys(void) const
+	?RecipientInfos@CCMSAuthenticatedData@@QBEABV?$CArrayPtr@VCCMSRecipientInfo@@@@XZ @ 227 NONAME ; class CArrayPtr<class CCMSRecipientInfo> const & CCMSAuthenticatedData::RecipientInfos(void) const
+	?RevokedCertificates@CCMSSignedData@@QBEPBV?$CArrayPtr@VCCMSX509CertificateList@@@@XZ @ 228 NONAME ; class CArrayPtr<class CCMSX509CertificateList> const * CCMSSignedData::RevokedCertificates(void) const
+	?Serial@CCMSX509IssuerSerial@@QBEHXZ @ 229 NONAME ; int CCMSX509IssuerSerial::Serial(void) const
+	?SerialNumber@CCMSIssuerAndSerialNumber@@QBEABVTDesC8@@XZ @ 230 NONAME ; class TDesC8 const & CCMSIssuerAndSerialNumber::SerialNumber(void) const
+	?SerialNumber@CCMSX509AttributeCertificateInfo@@QBEHXZ @ 231 NONAME ; int CCMSX509AttributeCertificateInfo::SerialNumber(void) const
+	?SerialNumber@CCMSX509Certificate@@QBEABVTDesC8@@XZ @ 232 NONAME ; class TDesC8 const & CCMSX509Certificate::SerialNumber(void) const
+	?SetAlgorithmIdentifierL@CCMSX509AlgorithmIdentifier@@QAEXABVCAlgorithmIdentifier@@@Z @ 233 NONAME ; void CCMSX509AlgorithmIdentifier::SetAlgorithmIdentifierL(class CAlgorithmIdentifier const &)
+	?SetAlgorithmIdentifierL@CCMSX509Signed@@QAEXABVCCMSX509AlgorithmIdentifier@@@Z @ 234 NONAME ; void CCMSX509Signed::SetAlgorithmIdentifierL(class CCMSX509AlgorithmIdentifier const &)
+	?SetAlgorithmL@CCMSOriginatorPublicKey@@QAEXABVCCMSX509AlgorithmIdentifier@@@Z @ 235 NONAME ; void CCMSOriginatorPublicKey::SetAlgorithmL(class CCMSX509AlgorithmIdentifier const &)
+	?SetAlgorithmL@CCMSX509SubjectPublicKeyInfo@@QAEXABVCCMSX509AlgorithmIdentifier@@@Z @ 236 NONAME ; void CCMSX509SubjectPublicKeyInfo::SetAlgorithmL(class CCMSX509AlgorithmIdentifier const &)
+	?SetAttrCertL@CCMSCertificateChoices@@QAEXABVCCMSX509AttributeCertificate@@@Z @ 237 NONAME ; void CCMSCertificateChoices::SetAttrCertL(class CCMSX509AttributeCertificate const &)
+	?SetAttributeTypeL@CCMSAttribute@@QAEXABVTDesC16@@@Z @ 238 NONAME ; void CCMSAttribute::SetAttributeTypeL(class TDesC16 const &)
+	?SetAttributeValuesL@CCMSAttribute@@QAEXABVCDesC8Array@@@Z @ 239 NONAME ; void CCMSAttribute::SetAttributeValuesL(class CDesC8Array const &)
+	?SetAttributesL@CCMSX509AttributeCertificateInfo@@QAEXABV?$CArrayPtr@VCCMSAttribute@@@@@Z @ 240 NONAME ; void CCMSX509AttributeCertificateInfo::SetAttributesL(class CArrayPtr<class CCMSAttribute> const &)
+	?SetAuthenticatedAttributesL@CCMSAuthenticatedData@@QAEXPAV?$CArrayPtr@VCCMSAttribute@@@@@Z @ 241 NONAME ; void CCMSAuthenticatedData::SetAuthenticatedAttributesL(class CArrayPtr<class CCMSAttribute> *)
+	?SetBaseCertificateIDL@CCMSX509AttributeCertificateInfo@@QAEXABVCCMSX509IssuerSerial@@@Z @ 242 NONAME ; void CCMSX509AttributeCertificateInfo::SetBaseCertificateIDL(class CCMSX509IssuerSerial const &)
+	?SetCertificateL@CCMSCertificateChoices@@QAEXABVCCMSX509Certificate@@@Z @ 243 NONAME ; void CCMSCertificateChoices::SetCertificateL(class CCMSX509Certificate const &)
+	?SetCertificateL@CCMSSignerInfo@@QAEXABVCCMSX509Certificate@@@Z @ 244 NONAME ; void CCMSSignerInfo::SetCertificateL(class CCMSX509Certificate const &)
+	?SetCertificateUrlL@CCMSSignerInfo@@QAEXABVTDesC8@@0@Z @ 245 NONAME ; void CCMSSignerInfo::SetCertificateUrlL(class TDesC8 const &, class TDesC8 const &)
+	?SetCertificatesL@CCMSSignedData@@QAEXPBV?$CArrayPtr@VCCMSCertificateChoices@@@@@Z @ 246 NONAME ; void CCMSSignedData::SetCertificatesL(class CArrayPtr<class CCMSCertificateChoices> const *)
+	?SetCerts@CCMSOriginatorInfo@@QAEXPAV?$CArrayPtr@VCCMSCertificateChoices@@@@@Z @ 247 NONAME ; void CCMSOriginatorInfo::SetCerts(class CArrayPtr<class CCMSCertificateChoices> *)
+	?SetContentL@CCMSContentInfo@@QAEXABVTDesC8@@@Z @ 248 NONAME ; void CCMSContentInfo::SetContentL(class TDesC8 const &)
+	?SetContentL@CCMSEncapsulatedContentInfo@@QAEXPBVTDesC8@@@Z @ 249 NONAME ; void CCMSEncapsulatedContentInfo::SetContentL(class TDesC8 const *)
+	?SetContentTypeL@CCMSContentInfo@@QAEXABVTDesC16@@@Z @ 250 NONAME ; void CCMSContentInfo::SetContentTypeL(class TDesC16 const &)
+	?SetCrls@CCMSOriginatorInfo@@QAEXPAV?$CArrayPtr@VCCMSX509CertificateList@@@@@Z @ 251 NONAME ; void CCMSOriginatorInfo::SetCrls(class CArrayPtr<class CCMSX509CertificateList> *)
+	?SetDataL@CCMSX509GeneralName@@QAEXABVTDesC8@@@Z @ 252 NONAME ; void CCMSX509GeneralName::SetDataL(class TDesC8 const &)
+	?SetDateL@CCMSKeyIdentifier@@QAEXABVTTime@@@Z @ 253 NONAME ; void CCMSKeyIdentifier::SetDateL(class TTime const &)
+	?SetDigestAlgorithmIdentifier@CCMSSignerInfo@@QAEXAAVCCMSX509AlgorithmIdentifier@@@Z @ 254 NONAME ; void CCMSSignerInfo::SetDigestAlgorithmIdentifier(class CCMSX509AlgorithmIdentifier &)
+	?SetDigestAlgorithmIdentifiersL@CCMSSignedData@@QAEXABV?$CArrayPtr@VCCMSX509AlgorithmIdentifier@@@@@Z @ 255 NONAME ; void CCMSSignedData::SetDigestAlgorithmIdentifiersL(class CArrayPtr<class CCMSX509AlgorithmIdentifier> const &)
+	?SetDigestAlgorithmL@CCMSAuthenticatedData@@QAEXPAVCCMSX509AlgorithmIdentifier@@@Z @ 256 NONAME ; void CCMSAuthenticatedData::SetDigestAlgorithmL(class CCMSX509AlgorithmIdentifier *)
+	?SetDigestAlgorithmL@CCMSX509AlgorithmIdentifier@@QAEXPBVCAlgorithmIdentifier@@@Z @ 257 NONAME ; void CCMSX509AlgorithmIdentifier::SetDigestAlgorithmL(class CAlgorithmIdentifier const *)
+	?SetEncapContentInfoL@CCMSAuthenticatedData@@QAEXPAVCCMSEncapsulatedContentInfo@@@Z @ 258 NONAME ; void CCMSAuthenticatedData::SetEncapContentInfoL(class CCMSEncapsulatedContentInfo *)
+	?SetEncapsulatedContentInfoL@CCMSSignedData@@QAEXABVCCMSEncapsulatedContentInfo@@@Z @ 259 NONAME ; void CCMSSignedData::SetEncapsulatedContentInfoL(class CCMSEncapsulatedContentInfo const &)
+	?SetEncryptedKeyL@CCMSKEKRecipientInfo@@QAEXABVTDesC8@@@Z @ 260 NONAME ; void CCMSKEKRecipientInfo::SetEncryptedKeyL(class TDesC8 const &)
+	?SetEncryptedKeyL@CCMSKeyTransRecipientInfo@@QAEXABVTDesC8@@@Z @ 261 NONAME ; void CCMSKeyTransRecipientInfo::SetEncryptedKeyL(class TDesC8 const &)
+	?SetEncryptedKeyL@CCMSRecipientEncryptedKey@@QAEXABVTDesC8@@@Z @ 262 NONAME ; void CCMSRecipientEncryptedKey::SetEncryptedKeyL(class TDesC8 const &)
+	?SetEncryptedL@CCMSX509Signed@@QAEXABVTDesC8@@@Z @ 263 NONAME ; void CCMSX509Signed::SetEncryptedL(class TDesC8 const &)
+	?SetGeneralNamesL@CCMSX509GeneralNames@@QAEXABV?$CArrayPtr@VCCMSX509GeneralName@@@@@Z @ 264 NONAME ; void CCMSX509GeneralNames::SetGeneralNamesL(class CArrayPtr<class CCMSX509GeneralName> const &)
+	?SetInfoL@CCMSX509AttributeCertificate@@QAEXABVCCMSX509AttributeCertificateInfo@@@Z @ 265 NONAME ; void CCMSX509AttributeCertificate::SetInfoL(class CCMSX509AttributeCertificateInfo const &)
+	?SetIssuerAndSerialNumberL@CCMSKeyTransRecipientInfo@@QAEXABVCCMSIssuerAndSerialNumber@@@Z @ 266 NONAME ; void CCMSKeyTransRecipientInfo::SetIssuerAndSerialNumberL(class CCMSIssuerAndSerialNumber const &)
+	?SetIssuerAndSerialNumberL@CCMSOriginatorIdentifierOrKey@@QAEXABVCCMSIssuerAndSerialNumber@@@Z @ 267 NONAME ; void CCMSOriginatorIdentifierOrKey::SetIssuerAndSerialNumberL(class CCMSIssuerAndSerialNumber const &)
+	?SetIssuerAndSerialNumberL@CCMSRecipientEncryptedKey@@QAEXABVCCMSIssuerAndSerialNumber@@@Z @ 268 NONAME ; void CCMSRecipientEncryptedKey::SetIssuerAndSerialNumberL(class CCMSIssuerAndSerialNumber const &)
+	?SetIssuerL@CCMSX509AttributeCertificateInfo@@QAEXABVCCMSX509GeneralNames@@@Z @ 269 NONAME ; void CCMSX509AttributeCertificateInfo::SetIssuerL(class CCMSX509GeneralNames const &)
+	?SetIssuerL@CCMSX509Certificate@@QAEXABVCX500DistinguishedName@@@Z @ 270 NONAME ; void CCMSX509Certificate::SetIssuerL(class CX500DistinguishedName const &)
+	?SetIssuerL@CCMSX509IssuerSerial@@QAEXABVCCMSX509GeneralNames@@@Z @ 271 NONAME ; void CCMSX509IssuerSerial::SetIssuerL(class CCMSX509GeneralNames const &)
+	?SetIssuerNameL@CCMSIssuerAndSerialNumber@@QAEXABVCX500DistinguishedName@@@Z @ 272 NONAME ; void CCMSIssuerAndSerialNumber::SetIssuerNameL(class CX500DistinguishedName const &)
+	?SetIssuerUIDL@CCMSX509IssuerSerial@@QAEXABVTDesC8@@@Z @ 273 NONAME ; void CCMSX509IssuerSerial::SetIssuerUIDL(class TDesC8 const &)
+	?SetIssuerUniqueIDL@CCMSX509AttributeCertificateInfo@@QAEXABVTDesC8@@@Z @ 274 NONAME ; void CCMSX509AttributeCertificateInfo::SetIssuerUniqueIDL(class TDesC8 const &)
+	?SetIssuerUniqueIdentifierL@CCMSX509Certificate@@QAEXABVTDesC8@@@Z @ 275 NONAME ; void CCMSX509Certificate::SetIssuerUniqueIdentifierL(class TDesC8 const &)
+	?SetKekidL@CCMSKEKRecipientInfo@@QAEXABVCCMSKeyIdentifier@@@Z @ 276 NONAME ; void CCMSKEKRecipientInfo::SetKekidL(class CCMSKeyIdentifier const &)
+	?SetKeyEncryptionAlgorithmL@CCMSRecipientInfo@@QAEXABVCCMSX509AlgorithmIdentifier@@@Z @ 277 NONAME ; void CCMSRecipientInfo::SetKeyEncryptionAlgorithmL(class CCMSX509AlgorithmIdentifier const &)
+	?SetKeyIdentifierL@CCMSKeyIdentifier@@QAEXABVTDesC8@@@Z @ 278 NONAME ; void CCMSKeyIdentifier::SetKeyIdentifierL(class TDesC8 const &)
+	?SetMacAlgorithmL@CCMSAuthenticatedData@@QAEXPAVCCMSX509AlgorithmIdentifier@@@Z @ 279 NONAME ; void CCMSAuthenticatedData::SetMacAlgorithmL(class CCMSX509AlgorithmIdentifier *)
+	?SetMacL@CCMSAuthenticatedData@@QAEXABVTDesC8@@@Z @ 280 NONAME ; void CCMSAuthenticatedData::SetMacL(class TDesC8 const &)
+	?SetNotAfter@CCMSX509Validity@@QAEXABVTTime@@@Z @ 281 NONAME ; void CCMSX509Validity::SetNotAfter(class TTime const &)
+	?SetNotAfterTimeL@CCMSX509AttributeCertificateInfo@@QAEXABVTTime@@@Z @ 282 NONAME ; void CCMSX509AttributeCertificateInfo::SetNotAfterTimeL(class TTime const &)
+	?SetNotBefore@CCMSX509Validity@@QAEXABVTTime@@@Z @ 283 NONAME ; void CCMSX509Validity::SetNotBefore(class TTime const &)
+	?SetNotBeforeTimeL@CCMSX509AttributeCertificateInfo@@QAEXABVTTime@@@Z @ 284 NONAME ; void CCMSX509AttributeCertificateInfo::SetNotBeforeTimeL(class TTime const &)
+	?SetOriginatorInfoL@CCMSAuthenticatedData@@QAEXPAVCCMSOriginatorInfo@@@Z @ 285 NONAME ; void CCMSAuthenticatedData::SetOriginatorInfoL(class CCMSOriginatorInfo *)
+	?SetOriginatorKeyL@CCMSOriginatorIdentifierOrKey@@QAEXABVCCMSOriginatorPublicKey@@@Z @ 286 NONAME ; void CCMSOriginatorIdentifierOrKey::SetOriginatorKeyL(class CCMSOriginatorPublicKey const &)
+	?SetOriginatorL@CCMSKeyAgreeRecipientInfo@@QAEXABVCCMSOriginatorIdentifierOrKey@@@Z @ 287 NONAME ; void CCMSKeyAgreeRecipientInfo::SetOriginatorL(class CCMSOriginatorIdentifierOrKey const &)
+	?SetParametersL@CCMSX509CertificateList@@QAEXAAVCCMSX509CertificateListParameters@@@Z @ 288 NONAME ; void CCMSX509CertificateList::SetParametersL(class CCMSX509CertificateListParameters &)
+	?SetPublicKeyL@CCMSOriginatorPublicKey@@QAEXABVTDesC8@@@Z @ 289 NONAME ; void CCMSOriginatorPublicKey::SetPublicKeyL(class TDesC8 const &)
+	?SetRKeyIdL@CCMSRecipientEncryptedKey@@QAEXABVCCMSKeyIdentifier@@@Z @ 290 NONAME ; void CCMSRecipientEncryptedKey::SetRKeyIdL(class CCMSKeyIdentifier const &)
+	?SetRecipientEncryptedKeysL@CCMSKeyAgreeRecipientInfo@@QAEXABV?$CArrayPtr@VCCMSRecipientEncryptedKey@@@@@Z @ 291 NONAME ; void CCMSKeyAgreeRecipientInfo::SetRecipientEncryptedKeysL(class CArrayPtr<class CCMSRecipientEncryptedKey> const &)
+	?SetRecipientInfosL@CCMSAuthenticatedData@@QAEXPAV?$CArrayPtr@VCCMSRecipientInfo@@@@@Z @ 292 NONAME ; void CCMSAuthenticatedData::SetRecipientInfosL(class CArrayPtr<class CCMSRecipientInfo> *)
+	?SetRevokedCertificatesL@CCMSSignedData@@QAEXPBV?$CArrayPtr@VCCMSX509CertificateList@@@@@Z @ 293 NONAME ; void CCMSSignedData::SetRevokedCertificatesL(class CArrayPtr<class CCMSX509CertificateList> const *)
+	?SetSerial@CCMSX509IssuerSerial@@QAEXH@Z @ 294 NONAME ; void CCMSX509IssuerSerial::SetSerial(int)
+	?SetSerialNumber@CCMSX509AttributeCertificateInfo@@QAEXH@Z @ 295 NONAME ; void CCMSX509AttributeCertificateInfo::SetSerialNumber(int)
+	?SetSerialNumberL@CCMSIssuerAndSerialNumber@@QAEXABVTDesC8@@@Z @ 296 NONAME ; void CCMSIssuerAndSerialNumber::SetSerialNumberL(class TDesC8 const &)
+	?SetSerialNumberL@CCMSX509Certificate@@QAEXABVTDesC8@@@Z @ 297 NONAME ; void CCMSX509Certificate::SetSerialNumberL(class TDesC8 const &)
+	?SetSignatureAlgorithmIdentifier@CCMSSignerInfo@@QAEXAAVCCMSX509AlgorithmIdentifier@@@Z @ 298 NONAME ; void CCMSSignerInfo::SetSignatureAlgorithmIdentifier(class CCMSX509AlgorithmIdentifier &)
+	?SetSignatureL@CCMSX509AttributeCertificateInfo@@QAEXABVCCMSX509AlgorithmIdentifier@@@Z @ 299 NONAME ; void CCMSX509AttributeCertificateInfo::SetSignatureL(class CCMSX509AlgorithmIdentifier const &)
+	?SetSignatureL@CCMSX509Certificate@@QAEXABVCCMSX509AlgorithmIdentifier@@@Z @ 300 NONAME ; void CCMSX509Certificate::SetSignatureL(class CCMSX509AlgorithmIdentifier const &)
+	?SetSignatureValueL@CCMSSignerInfo@@QAEXABVTDesC8@@@Z @ 301 NONAME ; void CCMSSignerInfo::SetSignatureValueL(class TDesC8 const &)
+	?SetSignedAttributesL@CCMSSignerInfo@@QAEXABVTDesC16@@ABVTDesC8@@ABVTTime@@PBV3@@Z @ 302 NONAME ; void CCMSSignerInfo::SetSignedAttributesL(class TDesC16 const &, class TDesC8 const &, class TTime const &, class TDesC8 const *)
+	?SetSignerInfosL@CCMSSignedData@@QAEXABV?$CArrayPtr@VCCMSSignerInfo@@@@@Z @ 303 NONAME ; void CCMSSignedData::SetSignerInfosL(class CArrayPtr<class CCMSSignerInfo> const &)
+	?SetSubjectKeyIdentifierL@CCMSKeyTransRecipientInfo@@QAEXABVTDesC8@@@Z @ 304 NONAME ; void CCMSKeyTransRecipientInfo::SetSubjectKeyIdentifierL(class TDesC8 const &)
+	?SetSubjectKeyIdentifierL@CCMSOriginatorIdentifierOrKey@@QAEXABVTDesC8@@@Z @ 305 NONAME ; void CCMSOriginatorIdentifierOrKey::SetSubjectKeyIdentifierL(class TDesC8 const &)
+	?SetSubjectL@CCMSX509Certificate@@QAEXABVCX500DistinguishedName@@@Z @ 306 NONAME ; void CCMSX509Certificate::SetSubjectL(class CX500DistinguishedName const &)
+	?SetSubjectNameL@CCMSX509AttributeCertificateInfo@@QAEXABVCCMSX509GeneralNames@@@Z @ 307 NONAME ; void CCMSX509AttributeCertificateInfo::SetSubjectNameL(class CCMSX509GeneralNames const &)
+	?SetSubjectPublicKeyInfoL@CCMSX509Certificate@@QAEXABVCCMSX509SubjectPublicKeyInfo@@@Z @ 308 NONAME ; void CCMSX509Certificate::SetSubjectPublicKeyInfoL(class CCMSX509SubjectPublicKeyInfo const &)
+	?SetSubjectPublicKeyL@CCMSX509SubjectPublicKeyInfo@@QAEXABVTDesC8@@@Z @ 309 NONAME ; void CCMSX509SubjectPublicKeyInfo::SetSubjectPublicKeyL(class TDesC8 const &)
+	?SetSubjectUniqueIdentifierL@CCMSX509Certificate@@QAEXABVTDesC8@@@Z @ 310 NONAME ; void CCMSX509Certificate::SetSubjectUniqueIdentifierL(class TDesC8 const &)
+	?SetTagL@CCMSX509GeneralName@@QAEXI@Z @ 311 NONAME ; void CCMSX509GeneralName::SetTagL(unsigned int)
+	?SetUnauthenticatedAttributesL@CCMSAuthenticatedData@@QAEXPAV?$CArrayPtr@VCCMSAttribute@@@@@Z @ 312 NONAME ; void CCMSAuthenticatedData::SetUnauthenticatedAttributesL(class CArrayPtr<class CCMSAttribute> *)
+	?SetUnsignedAttributesL@CCMSSignerInfo@@QAEXAAV?$CArrayPtrFlat@VCCMSAttribute@@@@@Z @ 313 NONAME ; void CCMSSignerInfo::SetUnsignedAttributesL(class CArrayPtrFlat<class CCMSAttribute> &)
+	?SetUserKeyingMaterialL@CCMSKeyAgreeRecipientInfo@@QAEXABVTDesC8@@@Z @ 314 NONAME ; void CCMSKeyAgreeRecipientInfo::SetUserKeyingMaterialL(class TDesC8 const &)
+	?SetValidityL@CCMSX509Certificate@@QAEXABVCCMSX509Validity@@@Z @ 315 NONAME ; void CCMSX509Certificate::SetValidityL(class CCMSX509Validity const &)
+	?SetVersion@CCMSAuthenticatedData@@QAEXH@Z @ 316 NONAME ; void CCMSAuthenticatedData::SetVersion(int)
+	?SetVersion@CCMSX509AttributeCertificateInfo@@QAEXH@Z @ 317 NONAME ; void CCMSX509AttributeCertificateInfo::SetVersion(int)
+	?SetVersion@CCMSX509Certificate@@QAEXH@Z @ 318 NONAME ; void CCMSX509Certificate::SetVersion(int)
+	?Signature@CCMSX509AttributeCertificateInfo@@QBEABVCCMSX509AlgorithmIdentifier@@XZ @ 319 NONAME ; class CCMSX509AlgorithmIdentifier const & CCMSX509AttributeCertificateInfo::Signature(void) const
+	?Signature@CCMSX509Certificate@@QBEABVCCMSX509AlgorithmIdentifier@@XZ @ 320 NONAME ; class CCMSX509AlgorithmIdentifier const & CCMSX509Certificate::Signature(void) const
+	?SignatureAlgorithmIdentifier@CCMSSignerInfo@@QBEABVCCMSX509AlgorithmIdentifier@@XZ @ 321 NONAME ; class CCMSX509AlgorithmIdentifier const & CCMSSignerInfo::SignatureAlgorithmIdentifier(void) const
+	?SignatureValue@CCMSSignerInfo@@QBEABVTDesC8@@XZ @ 322 NONAME ; class TDesC8 const & CCMSSignerInfo::SignatureValue(void) const
+	?SignedAttributes@CCMSSignerInfo@@QBEABV?$CArrayPtrFlat@VCCMSAttribute@@@@XZ @ 323 NONAME ; class CArrayPtrFlat<class CCMSAttribute> const & CCMSSignerInfo::SignedAttributes(void) const
+	?SignerInfos@CCMSSignedData@@QBEABV?$CArrayPtr@VCCMSSignerInfo@@@@XZ @ 324 NONAME ; class CArrayPtr<class CCMSSignerInfo> const & CCMSSignedData::SignerInfos(void) const
+	?Subject@CCMSX509Certificate@@QBEABVCX500DistinguishedName@@XZ @ 325 NONAME ; class CX500DistinguishedName const & CCMSX509Certificate::Subject(void) const
+	?SubjectKeyIdentifier@CCMSKeyTransRecipientInfo@@QBEPBVTDesC8@@XZ @ 326 NONAME ; class TDesC8 const * CCMSKeyTransRecipientInfo::SubjectKeyIdentifier(void) const
+	?SubjectKeyIdentifier@CCMSSignerInfo@@QBEPBVTDesC8@@XZ @ 327 NONAME ; class TDesC8 const * CCMSSignerInfo::SubjectKeyIdentifier(void) const
+	?SubjectKeyIdentifierL@CCMSOriginatorIdentifierOrKey@@QBEABVTDesC8@@XZ @ 328 NONAME ; class TDesC8 const & CCMSOriginatorIdentifierOrKey::SubjectKeyIdentifierL(void) const
+	?SubjectName@CCMSX509AttributeCertificateInfo@@QBEPBVCCMSX509GeneralNames@@XZ @ 329 NONAME ; class CCMSX509GeneralNames const * CCMSX509AttributeCertificateInfo::SubjectName(void) const
+	?SubjectPublicKey@CCMSX509SubjectPublicKeyInfo@@QBEABVTDesC8@@XZ @ 330 NONAME ; class TDesC8 const & CCMSX509SubjectPublicKeyInfo::SubjectPublicKey(void) const
+	?SubjectPublicKeyInfo@CCMSX509Certificate@@QBEABVCCMSX509SubjectPublicKeyInfo@@XZ @ 331 NONAME ; class CCMSX509SubjectPublicKeyInfo const & CCMSX509Certificate::SubjectPublicKeyInfo(void) const
+	?SubjectUniqueIdentifier@CCMSX509Certificate@@QBEPBVTDesC8@@XZ @ 332 NONAME ; class TDesC8 const * CCMSX509Certificate::SubjectUniqueIdentifier(void) const
+	?Tag@CCMSX509GeneralName@@QBEIXZ @ 333 NONAME ; unsigned int CCMSX509GeneralName::Tag(void) const
+	?ToBeSignedEncoderLC@CCMSX509Certificate@@QBEPAVCASN1EncBase@@XZ @ 334 NONAME ; class CASN1EncBase * CCMSX509Certificate::ToBeSignedEncoderLC(void) const
+	?Type@CCMSOriginatorIdentifierOrKey@@QBE?AW4TType@1@XZ @ 335 NONAME ; enum CCMSOriginatorIdentifierOrKey::TType CCMSOriginatorIdentifierOrKey::Type(void) const
+	?UnauthenticatedAttributes@CCMSAuthenticatedData@@QBEPBV?$CArrayPtr@VCCMSAttribute@@@@XZ @ 336 NONAME ; class CArrayPtr<class CCMSAttribute> const * CCMSAuthenticatedData::UnauthenticatedAttributes(void) const
+	?UnsignedAttributes@CCMSSignerInfo@@QBEABV?$CArrayPtrFlat@VCCMSAttribute@@@@XZ @ 337 NONAME ; class CArrayPtrFlat<class CCMSAttribute> const & CCMSSignerInfo::UnsignedAttributes(void) const
+	?UserKeyingMaterial@CCMSKeyAgreeRecipientInfo@@QBEPBVTDesC8@@XZ @ 338 NONAME ; class TDesC8 const * CCMSKeyAgreeRecipientInfo::UserKeyingMaterial(void) const
+	?Validity@CCMSX509Certificate@@QBEABVCCMSX509Validity@@XZ @ 339 NONAME ; class CCMSX509Validity const & CCMSX509Certificate::Validity(void) const
+	?Version@CCMSAuthenticatedData@@QBEHXZ @ 340 NONAME ; int CCMSAuthenticatedData::Version(void) const
+	?Version@CCMSRecipientInfo@@QBEHXZ @ 341 NONAME ; int CCMSRecipientInfo::Version(void) const
+	?Version@CCMSSignedData@@QBEHXZ @ 342 NONAME ; int CCMSSignedData::Version(void) const
+	?Version@CCMSX509AttributeCertificateInfo@@QBEHXZ @ 343 NONAME ; int CCMSX509AttributeCertificateInfo::Version(void) const
+	?Version@CCMSX509Certificate@@QBEHXZ @ 344 NONAME ; int CCMSX509Certificate::Version(void) const
+	?SignedAttributesEncodedL@CCMSSignerInfo@@QBEPAVHBufC8@@XZ @ 345 NONAME ; class HBufC8 * CCMSSignerInfo::SignedAttributesEncodedL(void) const
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/EABI/CMSU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,437 @@
+EXPORTS
+	_ZN12CCMSSequence16DecodeSequenceLCERK6TDesC8 @ 1 NONAME
+	_ZN12CCMSSequence16DecodeSequenceLCERK6TDesC8ii @ 2 NONAME
+	_ZN12CCMSSequence18CreateDerEncodingLEP12CASN1EncBase @ 3 NONAME
+	_ZN13CCMSAttribute10ConstructLERK7TDesC16RK11CDesC8Array @ 4 NONAME
+	_ZN13CCMSAttribute10ConstructLERK7TDesC16RK6TDesC8 @ 5 NONAME
+	_ZN13CCMSAttribute10ConstructLEv @ 6 NONAME
+	_ZN13CCMSAttribute17SetAttributeTypeLERK7TDesC16 @ 7 NONAME
+	_ZN13CCMSAttribute19SetAttributeValuesLERK11CDesC8Array @ 8 NONAME
+	_ZN13CCMSAttribute4NewLERK7TDesC16RK11CDesC8Array @ 9 NONAME
+	_ZN13CCMSAttribute4NewLERK7TDesC16RK6TDesC8 @ 10 NONAME
+	_ZN13CCMSAttribute4NewLEv @ 11 NONAME
+	_ZN13CCMSAttribute5NewLCERK7TDesC16RK11CDesC8Array @ 12 NONAME
+	_ZN13CCMSAttribute5NewLCERK7TDesC16RK6TDesC8 @ 13 NONAME
+	_ZN13CCMSAttribute5NewLCEv @ 14 NONAME
+	_ZN13CCMSAttributeC1Ev @ 15 NONAME
+	_ZN13CCMSAttributeC2Ev @ 16 NONAME
+	_ZN14CCMSSignedData10ConstructLERK9CArrayPtrI27CCMSX509AlgorithmIdentifierERK27CCMSEncapsulatedContentInfoRKS0_I14CCMSSignerInfoEPKS0_I22CCMSCertificateChoicesEPKS0_I23CCMSX509CertificateListE @ 17 NONAME
+	_ZN14CCMSSignedData10ConstructLEv @ 18 NONAME
+	_ZN14CCMSSignedData15SetSignerInfosLERK9CArrayPtrI14CCMSSignerInfoE @ 19 NONAME
+	_ZN14CCMSSignedData16SetCertificatesLEPK9CArrayPtrI22CCMSCertificateChoicesE @ 20 NONAME
+	_ZN14CCMSSignedData23SetRevokedCertificatesLEPK9CArrayPtrI23CCMSX509CertificateListE @ 21 NONAME
+	_ZN14CCMSSignedData27SetEncapsulatedContentInfoLERK27CCMSEncapsulatedContentInfo @ 22 NONAME
+	_ZN14CCMSSignedData30SetDigestAlgorithmIdentifiersLERK9CArrayPtrI27CCMSX509AlgorithmIdentifierE @ 23 NONAME
+	_ZN14CCMSSignedData5NewLCERK9CArrayPtrI27CCMSX509AlgorithmIdentifierERK27CCMSEncapsulatedContentInfoRKS0_I14CCMSSignerInfoE @ 24 NONAME
+	_ZN14CCMSSignedData5NewLCERK9CArrayPtrI27CCMSX509AlgorithmIdentifierERK27CCMSEncapsulatedContentInfoRKS0_I14CCMSSignerInfoEPKS0_I22CCMSCertificateChoicesEPKS0_I23CCMSX509CertificateListE @ 25 NONAME
+	_ZN14CCMSSignedData5NewLCEv @ 26 NONAME
+	_ZN14CCMSSignedDataC1Ev @ 27 NONAME
+	_ZN14CCMSSignedDataC2Ev @ 28 NONAME
+	_ZN14CCMSSignerInfo10ConstructLERK19CCMSX509CertificateRK6TDesC8 @ 29 NONAME
+	_ZN14CCMSSignerInfo10ConstructLERK6TDesC8S2_S2_ @ 30 NONAME
+	_ZN14CCMSSignerInfo15SetCertificateLERK19CCMSX509Certificate @ 31 NONAME
+	_ZN14CCMSSignerInfo18SetCertificateUrlLERK6TDesC8S2_ @ 32 NONAME
+	_ZN14CCMSSignerInfo18SetSignatureValueLERK6TDesC8 @ 33 NONAME
+	_ZN14CCMSSignerInfo20SetSignedAttributesLERK7TDesC16RK6TDesC8RK5TTimePS4_ @ 34 NONAME
+	_ZN14CCMSSignerInfo22SetUnsignedAttributesLER13CArrayPtrFlatI13CCMSAttributeE @ 35 NONAME
+	_ZN14CCMSSignerInfo28SetDigestAlgorithmIdentifierER27CCMSX509AlgorithmIdentifier @ 36 NONAME
+	_ZN14CCMSSignerInfo31SetSignatureAlgorithmIdentifierER27CCMSX509AlgorithmIdentifier @ 37 NONAME
+	_ZN14CCMSSignerInfo4NewLERK19CCMSX509CertificateRK6TDesC8 @ 38 NONAME
+	_ZN14CCMSSignerInfo4NewLERK6TDesC8S2_S2_ @ 39 NONAME
+	_ZN14CCMSSignerInfo4NewLEv @ 40 NONAME
+	_ZN14CCMSSignerInfoC1Ev @ 41 NONAME
+	_ZN14CCMSSignerInfoC2Ev @ 42 NONAME
+	_ZN14CCMSX509Signed13SetEncryptedLERK6TDesC8 @ 43 NONAME
+	_ZN14CCMSX509Signed23SetAlgorithmIdentifierLERK27CCMSX509AlgorithmIdentifier @ 44 NONAME
+	_ZN15CCMSContentInfo10ConstructLERK7TDesC16 @ 45 NONAME
+	_ZN15CCMSContentInfo10ConstructLERK7TDesC16RK6TDesC8 @ 46 NONAME
+	_ZN15CCMSContentInfo10ConstructLEv @ 47 NONAME
+	_ZN15CCMSContentInfo11SetContentLERK6TDesC8 @ 48 NONAME
+	_ZN15CCMSContentInfo15SetContentTypeLERK7TDesC16 @ 49 NONAME
+	_ZN15CCMSContentInfo5NewLCERK7TDesC16RK6TDesC8 @ 50 NONAME
+	_ZN15CCMSContentInfo5NewLCEv @ 51 NONAME
+	_ZN15CCMSContentInfoC1Ev @ 52 NONAME
+	_ZN15CCMSContentInfoC2Ev @ 53 NONAME
+	_ZN16CCMSX509Validity11SetNotAfterERK5TTime @ 54 NONAME
+	_ZN16CCMSX509Validity12SetNotBeforeERK5TTime @ 55 NONAME
+	_ZN16CCMSX509Validity4NewLERK15CValidityPeriod @ 56 NONAME
+	_ZN16CCMSX509Validity4NewLERK5TTimeS2_ @ 57 NONAME
+	_ZN16CCMSX509Validity4NewLEv @ 58 NONAME
+	_ZN16CCMSX509ValidityC1ERK5TTimeS2_ @ 59 NONAME
+	_ZN16CCMSX509ValidityC1Ev @ 60 NONAME
+	_ZN16CCMSX509ValidityC2ERK5TTimeS2_ @ 61 NONAME
+	_ZN16CCMSX509ValidityC2Ev @ 62 NONAME
+	_ZN17CCMSKeyIdentifier10ConstructLERK6TDesC8 @ 63 NONAME
+	_ZN17CCMSKeyIdentifier10ConstructLERK6TDesC8RK5TTime @ 64 NONAME
+	_ZN17CCMSKeyIdentifier17SetKeyIdentifierLERK6TDesC8 @ 65 NONAME
+	_ZN17CCMSKeyIdentifier4NewLERK6TDesC8 @ 66 NONAME
+	_ZN17CCMSKeyIdentifier4NewLERK6TDesC8RK5TTime @ 67 NONAME
+	_ZN17CCMSKeyIdentifier4NewLEv @ 68 NONAME
+	_ZN17CCMSKeyIdentifier8SetDateLERK5TTime @ 69 NONAME
+	_ZN17CCMSKeyIdentifierC1Ev @ 70 NONAME
+	_ZN17CCMSKeyIdentifierC2Ev @ 71 NONAME
+	_ZN17CCMSRecipientInfo26SetKeyEncryptionAlgorithmLERK27CCMSX509AlgorithmIdentifier @ 72 NONAME
+	_ZN18CCMSOriginatorInfo4NewLEv @ 73 NONAME
+	_ZN18CCMSOriginatorInfo7SetCrlsEP9CArrayPtrI23CCMSX509CertificateListE @ 74 NONAME
+	_ZN18CCMSOriginatorInfo8SetCertsEP9CArrayPtrI22CCMSCertificateChoicesE @ 75 NONAME
+	_ZN18CCMSOriginatorInfoC1Ev @ 76 NONAME
+	_ZN18CCMSOriginatorInfoC2Ev @ 77 NONAME
+	_ZN19CCMSX509Certificate10ConstructLERK16CX509Certificate @ 78 NONAME
+	_ZN19CCMSX509Certificate10ConstructLERK6TDesC8RK27CCMSX509AlgorithmIdentifierRK22CX500DistinguishedNameRK16CCMSX509ValidityS8_RK28CCMSX509SubjectPublicKeyInfoS5_S2_ @ 79 NONAME
+	_ZN19CCMSX509Certificate10ConstructLEv @ 80 NONAME
+	_ZN19CCMSX509Certificate10SetIssuerLERK22CX500DistinguishedName @ 81 NONAME
+	_ZN19CCMSX509Certificate10SetVersionEi @ 82 NONAME
+	_ZN19CCMSX509Certificate11SetSubjectLERK22CX500DistinguishedName @ 83 NONAME
+	_ZN19CCMSX509Certificate12SetValidityLERK16CCMSX509Validity @ 84 NONAME
+	_ZN19CCMSX509Certificate13SetSignatureLERK27CCMSX509AlgorithmIdentifier @ 85 NONAME
+	_ZN19CCMSX509Certificate16SetSerialNumberLERK6TDesC8 @ 86 NONAME
+	_ZN19CCMSX509Certificate24SetSubjectPublicKeyInfoLERK28CCMSX509SubjectPublicKeyInfo @ 87 NONAME
+	_ZN19CCMSX509Certificate26SetIssuerUniqueIdentifierLERK6TDesC8 @ 88 NONAME
+	_ZN19CCMSX509Certificate27SetSubjectUniqueIdentifierLERK6TDesC8 @ 89 NONAME
+	_ZN19CCMSX509Certificate4NewLERK16CX509Certificate @ 90 NONAME
+	_ZN19CCMSX509Certificate4NewLERK6TDesC8RK27CCMSX509AlgorithmIdentifierRK22CX500DistinguishedNameRK16CCMSX509ValidityS8_RK28CCMSX509SubjectPublicKeyInfoS5_S2_ @ 91 NONAME
+	_ZN19CCMSX509Certificate4NewLEv @ 92 NONAME
+	_ZN19CCMSX509CertificateC1Ev @ 93 NONAME
+	_ZN19CCMSX509CertificateC2Ev @ 94 NONAME
+	_ZN19CCMSX509GeneralName10ConstructLEjRK6TDesC8 @ 95 NONAME
+	_ZN19CCMSX509GeneralName4NewLEjRK6TDesC8 @ 96 NONAME
+	_ZN19CCMSX509GeneralName4NewLEv @ 97 NONAME
+	_ZN19CCMSX509GeneralName7SetTagLEj @ 98 NONAME
+	_ZN19CCMSX509GeneralName8SetDataLERK6TDesC8 @ 99 NONAME
+	_ZN19CCMSX509GeneralNameC1Ev @ 100 NONAME
+	_ZN19CCMSX509GeneralNameC2Ev @ 101 NONAME
+	_ZN20CCMSKEKRecipientInfo10ConstructLERK17CCMSKeyIdentifierRK27CCMSX509AlgorithmIdentifierRK6TDesC8 @ 102 NONAME
+	_ZN20CCMSKEKRecipientInfo16SetEncryptedKeyLERK6TDesC8 @ 103 NONAME
+	_ZN20CCMSKEKRecipientInfo4NewLERK17CCMSKeyIdentifierRK27CCMSX509AlgorithmIdentifierRK6TDesC8 @ 104 NONAME
+	_ZN20CCMSKEKRecipientInfo4NewLEv @ 105 NONAME
+	_ZN20CCMSKEKRecipientInfo5NewLCEv @ 106 NONAME
+	_ZN20CCMSKEKRecipientInfo9SetKekidLERK17CCMSKeyIdentifier @ 107 NONAME
+	_ZN20CCMSKEKRecipientInfoC1Ev @ 108 NONAME
+	_ZN20CCMSKEKRecipientInfoC2Ev @ 109 NONAME
+	_ZN20CCMSX509GeneralNames10ConstructLERK9CArrayPtrI19CCMSX509GeneralNameE @ 110 NONAME
+	_ZN20CCMSX509GeneralNames16SetGeneralNamesLERK9CArrayPtrI19CCMSX509GeneralNameE @ 111 NONAME
+	_ZN20CCMSX509GeneralNames4NewLERK9CArrayPtrI19CCMSX509GeneralNameE @ 112 NONAME
+	_ZN20CCMSX509GeneralNames4NewLERKS_ @ 113 NONAME
+	_ZN20CCMSX509GeneralNames4NewLEv @ 114 NONAME
+	_ZN20CCMSX509GeneralNamesC1Ev @ 115 NONAME
+	_ZN20CCMSX509GeneralNamesC2Ev @ 116 NONAME
+	_ZN20CCMSX509IssuerSerial10ConstructLERK20CCMSX509GeneralNames @ 117 NONAME
+	_ZN20CCMSX509IssuerSerial10ConstructLERK20CCMSX509GeneralNamesRK6TDesC8 @ 118 NONAME
+	_ZN20CCMSX509IssuerSerial10SetIssuerLERK20CCMSX509GeneralNames @ 119 NONAME
+	_ZN20CCMSX509IssuerSerial13SetIssuerUIDLERK6TDesC8 @ 120 NONAME
+	_ZN20CCMSX509IssuerSerial4NewLERK20CCMSX509GeneralNamesi @ 121 NONAME
+	_ZN20CCMSX509IssuerSerial4NewLERK20CCMSX509GeneralNamesiRK6TDesC8 @ 122 NONAME
+	_ZN20CCMSX509IssuerSerial4NewLEv @ 123 NONAME
+	_ZN20CCMSX509IssuerSerial9SetSerialEi @ 124 NONAME
+	_ZN20CCMSX509IssuerSerialC1Ei @ 125 NONAME
+	_ZN20CCMSX509IssuerSerialC2Ei @ 126 NONAME
+	_ZN21CCMSAuthenticatedData10ConstructLEP9CArrayPtrI17CCMSRecipientInfoEP27CCMSX509AlgorithmIdentifierP27CCMSEncapsulatedContentInfoRK6TDesC8 @ 127 NONAME
+	_ZN21CCMSAuthenticatedData10ConstructLEv @ 128 NONAME
+	_ZN21CCMSAuthenticatedData10SetVersionEi @ 129 NONAME
+	_ZN21CCMSAuthenticatedData16SetMacAlgorithmLEP27CCMSX509AlgorithmIdentifier @ 130 NONAME
+	_ZN21CCMSAuthenticatedData18SetOriginatorInfoLEP18CCMSOriginatorInfo @ 131 NONAME
+	_ZN21CCMSAuthenticatedData18SetRecipientInfosLEP9CArrayPtrI17CCMSRecipientInfoE @ 132 NONAME
+	_ZN21CCMSAuthenticatedData19SetDigestAlgorithmLEP27CCMSX509AlgorithmIdentifier @ 133 NONAME
+	_ZN21CCMSAuthenticatedData20SetEncapContentInfoLEP27CCMSEncapsulatedContentInfo @ 134 NONAME
+	_ZN21CCMSAuthenticatedData27SetAuthenticatedAttributesLEP9CArrayPtrI13CCMSAttributeE @ 135 NONAME
+	_ZN21CCMSAuthenticatedData29SetUnauthenticatedAttributesLEP9CArrayPtrI13CCMSAttributeE @ 136 NONAME
+	_ZN21CCMSAuthenticatedData5NewLCEP9CArrayPtrI17CCMSRecipientInfoEP27CCMSX509AlgorithmIdentifierP27CCMSEncapsulatedContentInfoRK6TDesC8 @ 137 NONAME
+	_ZN21CCMSAuthenticatedData5NewLCEv @ 138 NONAME
+	_ZN21CCMSAuthenticatedData7SetMacLERK6TDesC8 @ 139 NONAME
+	_ZN21CCMSAuthenticatedDataC1Ev @ 140 NONAME
+	_ZN21CCMSAuthenticatedDataC2Ev @ 141 NONAME
+	_ZN22CCMSCertificateChoices10ConstructLERK19CCMSX509Certificate @ 142 NONAME
+	_ZN22CCMSCertificateChoices10ConstructLERK28CCMSX509AttributeCertificate @ 143 NONAME
+	_ZN22CCMSCertificateChoices12SetAttrCertLERK28CCMSX509AttributeCertificate @ 144 NONAME
+	_ZN22CCMSCertificateChoices15SetCertificateLERK19CCMSX509Certificate @ 145 NONAME
+	_ZN22CCMSCertificateChoices4NewLERK19CCMSX509Certificate @ 146 NONAME
+	_ZN22CCMSCertificateChoices4NewLERK28CCMSX509AttributeCertificate @ 147 NONAME
+	_ZN22CCMSCertificateChoices4NewLEv @ 148 NONAME
+	_ZN22CCMSCertificateChoices5NewLCERK19CCMSX509Certificate @ 149 NONAME
+	_ZN22CCMSCertificateChoices5NewLCERK28CCMSX509AttributeCertificate @ 150 NONAME
+	_ZN22CCMSCertificateChoices5NewLCEv @ 151 NONAME
+	_ZN22CCMSCertificateChoicesC1Ev @ 152 NONAME
+	_ZN22CCMSCertificateChoicesC2Ev @ 153 NONAME
+	_ZN23CCMSOriginatorPublicKey10ConstructLERK27CCMSX509AlgorithmIdentifierRK6TDesC8 @ 154 NONAME
+	_ZN23CCMSOriginatorPublicKey13SetAlgorithmLERK27CCMSX509AlgorithmIdentifier @ 155 NONAME
+	_ZN23CCMSOriginatorPublicKey13SetPublicKeyLERK6TDesC8 @ 156 NONAME
+	_ZN23CCMSOriginatorPublicKey4NewLERK27CCMSX509AlgorithmIdentifierRK6TDesC8 @ 157 NONAME
+	_ZN23CCMSOriginatorPublicKey4NewLERKS_ @ 158 NONAME
+	_ZN23CCMSOriginatorPublicKey4NewLEv @ 159 NONAME
+	_ZN23CCMSOriginatorPublicKey5NewLCERK27CCMSX509AlgorithmIdentifierRK6TDesC8 @ 160 NONAME
+	_ZN23CCMSOriginatorPublicKey5NewLCERKS_ @ 161 NONAME
+	_ZN23CCMSOriginatorPublicKeyC1Ev @ 162 NONAME
+	_ZN23CCMSOriginatorPublicKeyC2Ev @ 163 NONAME
+	_ZN23CCMSX509CertificateList10ConstructLERK16CX509CertificateRK13CArrayPtrFlatIS0_E @ 164 NONAME
+	_ZN23CCMSX509CertificateList10ConstructLEv @ 165 NONAME
+	_ZN23CCMSX509CertificateList14SetParametersLER33CCMSX509CertificateListParameters @ 166 NONAME
+	_ZN23CCMSX509CertificateList5NewLCER33CCMSX509CertificateListParameters @ 167 NONAME
+	_ZN23CCMSX509CertificateList5NewLCERK16CX509CertificateRK13CArrayPtrFlatIS0_E @ 168 NONAME
+	_ZN23CCMSX509CertificateList5NewLCEv @ 169 NONAME
+	_ZN23CCMSX509CertificateListC1Ev @ 170 NONAME
+	_ZN23CCMSX509CertificateListC2Ev @ 171 NONAME
+	_ZN25CCMSIssuerAndSerialNumber10ConstructLERK22CX500DistinguishedNameRK6TDesC8 @ 172 NONAME
+	_ZN25CCMSIssuerAndSerialNumber14SetIssuerNameLERK22CX500DistinguishedName @ 173 NONAME
+	_ZN25CCMSIssuerAndSerialNumber16SetSerialNumberLERK6TDesC8 @ 174 NONAME
+	_ZN25CCMSIssuerAndSerialNumber4NewLERK22CX500DistinguishedNameRK6TDesC8 @ 175 NONAME
+	_ZN25CCMSIssuerAndSerialNumber4NewLEv @ 176 NONAME
+	_ZN25CCMSIssuerAndSerialNumberC1Ev @ 177 NONAME
+	_ZN25CCMSIssuerAndSerialNumberC2Ev @ 178 NONAME
+	_ZN25CCMSKeyAgreeRecipientInfo10ConstructLERK29CCMSOriginatorIdentifierOrKeyRK27CCMSX509AlgorithmIdentifierRK9CArrayPtrI25CCMSRecipientEncryptedKeyE @ 179 NONAME
+	_ZN25CCMSKeyAgreeRecipientInfo10ConstructLERK29CCMSOriginatorIdentifierOrKeyRK6TDesC8RK27CCMSX509AlgorithmIdentifierRK9CArrayPtrI25CCMSRecipientEncryptedKeyE @ 180 NONAME
+	_ZN25CCMSKeyAgreeRecipientInfo10ConstructLEv @ 181 NONAME
+	_ZN25CCMSKeyAgreeRecipientInfo14SetOriginatorLERK29CCMSOriginatorIdentifierOrKey @ 182 NONAME
+	_ZN25CCMSKeyAgreeRecipientInfo22SetUserKeyingMaterialLERK6TDesC8 @ 183 NONAME
+	_ZN25CCMSKeyAgreeRecipientInfo26SetRecipientEncryptedKeysLERK9CArrayPtrI25CCMSRecipientEncryptedKeyE @ 184 NONAME
+	_ZN25CCMSKeyAgreeRecipientInfo4NewLERK29CCMSOriginatorIdentifierOrKeyRK27CCMSX509AlgorithmIdentifierRK9CArrayPtrI25CCMSRecipientEncryptedKeyE @ 185 NONAME
+	_ZN25CCMSKeyAgreeRecipientInfo4NewLERK29CCMSOriginatorIdentifierOrKeyRK6TDesC8RK27CCMSX509AlgorithmIdentifierRK9CArrayPtrI25CCMSRecipientEncryptedKeyE @ 186 NONAME
+	_ZN25CCMSKeyAgreeRecipientInfo4NewLEv @ 187 NONAME
+	_ZN25CCMSKeyAgreeRecipientInfo5NewLCEv @ 188 NONAME
+	_ZN25CCMSKeyAgreeRecipientInfoC1Ev @ 189 NONAME
+	_ZN25CCMSKeyAgreeRecipientInfoC2Ev @ 190 NONAME
+	_ZN25CCMSKeyTransRecipientInfo10ConstructLERK25CCMSIssuerAndSerialNumberRK27CCMSX509AlgorithmIdentifierRK6TDesC8 @ 191 NONAME
+	_ZN25CCMSKeyTransRecipientInfo10ConstructLERK6TDesC8RK27CCMSX509AlgorithmIdentifierS2_ @ 192 NONAME
+	_ZN25CCMSKeyTransRecipientInfo16SetEncryptedKeyLERK6TDesC8 @ 193 NONAME
+	_ZN25CCMSKeyTransRecipientInfo24SetSubjectKeyIdentifierLERK6TDesC8 @ 194 NONAME
+	_ZN25CCMSKeyTransRecipientInfo25SetIssuerAndSerialNumberLERK25CCMSIssuerAndSerialNumber @ 195 NONAME
+	_ZN25CCMSKeyTransRecipientInfo4NewLERK25CCMSIssuerAndSerialNumberRK27CCMSX509AlgorithmIdentifierRK6TDesC8 @ 196 NONAME
+	_ZN25CCMSKeyTransRecipientInfo4NewLERK6TDesC8RK27CCMSX509AlgorithmIdentifierS2_ @ 197 NONAME
+	_ZN25CCMSKeyTransRecipientInfo4NewLEv @ 198 NONAME
+	_ZN25CCMSKeyTransRecipientInfo5NewLCERK6TDesC8RK27CCMSX509AlgorithmIdentifierS2_ @ 199 NONAME
+	_ZN25CCMSKeyTransRecipientInfo5NewLCEv @ 200 NONAME
+	_ZN25CCMSKeyTransRecipientInfoC1Ei @ 201 NONAME
+	_ZN25CCMSKeyTransRecipientInfoC2Ei @ 202 NONAME
+	_ZN25CCMSRecipientEncryptedKey10ConstructLERK17CCMSKeyIdentifierRK6TDesC8 @ 203 NONAME
+	_ZN25CCMSRecipientEncryptedKey10ConstructLERK25CCMSIssuerAndSerialNumberRK6TDesC8 @ 204 NONAME
+	_ZN25CCMSRecipientEncryptedKey10SetRKeyIdLERK17CCMSKeyIdentifier @ 205 NONAME
+	_ZN25CCMSRecipientEncryptedKey16SetEncryptedKeyLERK6TDesC8 @ 206 NONAME
+	_ZN25CCMSRecipientEncryptedKey25SetIssuerAndSerialNumberLERK25CCMSIssuerAndSerialNumber @ 207 NONAME
+	_ZN25CCMSRecipientEncryptedKey4NewLERK17CCMSKeyIdentifierRK6TDesC8 @ 208 NONAME
+	_ZN25CCMSRecipientEncryptedKey4NewLERK25CCMSIssuerAndSerialNumberRK6TDesC8 @ 209 NONAME
+	_ZN25CCMSRecipientEncryptedKey4NewLEv @ 210 NONAME
+	_ZN25CCMSRecipientEncryptedKeyC1Ev @ 211 NONAME
+	_ZN25CCMSRecipientEncryptedKeyC2Ev @ 212 NONAME
+	_ZN26CCMSX509RevokedCertificateC1Ev @ 213 NONAME
+	_ZN26CCMSX509RevokedCertificateC2Ev @ 214 NONAME
+	_ZN27CCMSEncapsulatedContentInfo10ConstructLERK7TDesC16PK6TDesC8 @ 215 NONAME
+	_ZN27CCMSEncapsulatedContentInfo10ConstructLEv @ 216 NONAME
+	_ZN27CCMSEncapsulatedContentInfo11SetContentLEPK6TDesC8 @ 217 NONAME
+	_ZN27CCMSEncapsulatedContentInfo4NewLERK7TDesC16PK6TDesC8 @ 218 NONAME
+	_ZN27CCMSEncapsulatedContentInfo4NewLEv @ 219 NONAME
+	_ZN27CCMSEncapsulatedContentInfo5NewLCERK7TDesC16PK6TDesC8 @ 220 NONAME
+	_ZN27CCMSEncapsulatedContentInfo5NewLCEv @ 221 NONAME
+	_ZN27CCMSEncapsulatedContentInfoC1Ev @ 222 NONAME
+	_ZN27CCMSEncapsulatedContentInfoC2Ev @ 223 NONAME
+	_ZN27CCMSX509AlgorithmIdentifier10ConstructLERK12TAlgorithmId @ 224 NONAME
+	_ZN27CCMSX509AlgorithmIdentifier10ConstructLERK20CAlgorithmIdentifier @ 225 NONAME
+	_ZN27CCMSX509AlgorithmIdentifier19SetDigestAlgorithmLEPK20CAlgorithmIdentifier @ 226 NONAME
+	_ZN27CCMSX509AlgorithmIdentifier23SetAlgorithmIdentifierLERK20CAlgorithmIdentifier @ 227 NONAME
+	_ZN27CCMSX509AlgorithmIdentifier4NewLERK12TAlgorithmId @ 228 NONAME
+	_ZN27CCMSX509AlgorithmIdentifier4NewLERK20CAlgorithmIdentifier @ 229 NONAME
+	_ZN27CCMSX509AlgorithmIdentifier4NewLERK20CAlgorithmIdentifierS2_ @ 230 NONAME
+	_ZN27CCMSX509AlgorithmIdentifier4NewLEv @ 231 NONAME
+	_ZN27CCMSX509AlgorithmIdentifierC1Ev @ 232 NONAME
+	_ZN27CCMSX509AlgorithmIdentifierC2Ev @ 233 NONAME
+	_ZN28CCMSX509AttributeCertificate10ConstructLERK32CCMSX509AttributeCertificateInfoRK27CCMSX509AlgorithmIdentifierRK6TDesC8 @ 234 NONAME
+	_ZN28CCMSX509AttributeCertificate10ConstructLEv @ 235 NONAME
+	_ZN28CCMSX509AttributeCertificate4NewLERK32CCMSX509AttributeCertificateInfoRK27CCMSX509AlgorithmIdentifierRK6TDesC8 @ 236 NONAME
+	_ZN28CCMSX509AttributeCertificate4NewLEv @ 237 NONAME
+	_ZN28CCMSX509AttributeCertificate8SetInfoLERK32CCMSX509AttributeCertificateInfo @ 238 NONAME
+	_ZN28CCMSX509AttributeCertificateC1Ev @ 239 NONAME
+	_ZN28CCMSX509AttributeCertificateC2Ev @ 240 NONAME
+	_ZN28CCMSX509SubjectPublicKeyInfo10ConstructLERK21CSubjectPublicKeyInfo @ 241 NONAME
+	_ZN28CCMSX509SubjectPublicKeyInfo10ConstructLERK27CCMSX509AlgorithmIdentifierRK6TDesC8 @ 242 NONAME
+	_ZN28CCMSX509SubjectPublicKeyInfo10ConstructLEv @ 243 NONAME
+	_ZN28CCMSX509SubjectPublicKeyInfo13SetAlgorithmLERK27CCMSX509AlgorithmIdentifier @ 244 NONAME
+	_ZN28CCMSX509SubjectPublicKeyInfo20SetSubjectPublicKeyLERK6TDesC8 @ 245 NONAME
+	_ZN28CCMSX509SubjectPublicKeyInfo4NewLERK21CSubjectPublicKeyInfo @ 246 NONAME
+	_ZN28CCMSX509SubjectPublicKeyInfo4NewLERK27CCMSX509AlgorithmIdentifierRK6TDesC8 @ 247 NONAME
+	_ZN28CCMSX509SubjectPublicKeyInfo4NewLEv @ 248 NONAME
+	_ZN28CCMSX509SubjectPublicKeyInfoC1Ev @ 249 NONAME
+	_ZN28CCMSX509SubjectPublicKeyInfoC2Ev @ 250 NONAME
+	_ZN29CCMSOriginatorIdentifierOrKey10ConstructLERK23CCMSOriginatorPublicKey @ 251 NONAME
+	_ZN29CCMSOriginatorIdentifierOrKey10ConstructLERK25CCMSIssuerAndSerialNumber @ 252 NONAME
+	_ZN29CCMSOriginatorIdentifierOrKey10ConstructLERK6TDesC8 @ 253 NONAME
+	_ZN29CCMSOriginatorIdentifierOrKey17SetOriginatorKeyLERK23CCMSOriginatorPublicKey @ 254 NONAME
+	_ZN29CCMSOriginatorIdentifierOrKey24SetSubjectKeyIdentifierLERK6TDesC8 @ 255 NONAME
+	_ZN29CCMSOriginatorIdentifierOrKey25SetIssuerAndSerialNumberLERK25CCMSIssuerAndSerialNumber @ 256 NONAME
+	_ZN29CCMSOriginatorIdentifierOrKey4NewLERK23CCMSOriginatorPublicKey @ 257 NONAME
+	_ZN29CCMSOriginatorIdentifierOrKey4NewLERK25CCMSIssuerAndSerialNumber @ 258 NONAME
+	_ZN29CCMSOriginatorIdentifierOrKey4NewLERK6TDesC8 @ 259 NONAME
+	_ZN29CCMSOriginatorIdentifierOrKey4NewLEv @ 260 NONAME
+	_ZN29CCMSOriginatorIdentifierOrKeyC1Ev @ 261 NONAME
+	_ZN29CCMSOriginatorIdentifierOrKeyC2Ev @ 262 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo10ConstructLERK20CCMSX509GeneralNamesS2_RK27CCMSX509AlgorithmIdentifieriRK5TTimeS8_RK9CArrayPtrI13CCMSAttributeE @ 263 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo10ConstructLERK20CCMSX509IssuerSerialRK20CCMSX509GeneralNamesRK27CCMSX509AlgorithmIdentifieriRK5TTimeSB_RK9CArrayPtrI13CCMSAttributeE @ 264 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo10ConstructLEv @ 265 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo10SetIssuerLERK20CCMSX509GeneralNames @ 266 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo10SetVersionEi @ 267 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo13SetSignatureLERK27CCMSX509AlgorithmIdentifier @ 268 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo14SetAttributesLERK9CArrayPtrI13CCMSAttributeE @ 269 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo15SetSerialNumberEi @ 270 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo15SetSubjectNameLERK20CCMSX509GeneralNames @ 271 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo16SetNotAfterTimeLERK5TTime @ 272 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo17SetNotBeforeTimeLERK5TTime @ 273 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo18SetIssuerUniqueIDLERK6TDesC8 @ 274 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo21SetBaseCertificateIDLERK20CCMSX509IssuerSerial @ 275 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo4NewLERK20CCMSX509GeneralNamesS2_RK27CCMSX509AlgorithmIdentifieriRK5TTimeS8_RK9CArrayPtrI13CCMSAttributeE @ 276 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo4NewLERK20CCMSX509IssuerSerialRK20CCMSX509GeneralNamesRK27CCMSX509AlgorithmIdentifieriRK5TTimeSB_RK9CArrayPtrI13CCMSAttributeE @ 277 NONAME
+	_ZN32CCMSX509AttributeCertificateInfo4NewLEv @ 278 NONAME
+	_ZN32CCMSX509AttributeCertificateInfoC1Ev @ 279 NONAME
+	_ZN32CCMSX509AttributeCertificateInfoC2Ev @ 280 NONAME
+	_ZN33CCMSX509CertificateListParametersC1Ev @ 281 NONAME
+	_ZN33CCMSX509CertificateListParametersC2Ev @ 282 NONAME
+	_ZNK13CCMSAttribute13AttributeTypeEv @ 283 NONAME
+	_ZNK13CCMSAttribute15AttributeValuesEv @ 284 NONAME
+	_ZNK14CCMSSignedData11SignerInfosEv @ 285 NONAME
+	_ZNK14CCMSSignedData12CertificatesEv @ 286 NONAME
+	_ZNK14CCMSSignedData19RevokedCertificatesEv @ 287 NONAME
+	_ZNK14CCMSSignedData23EncapsulatedContentInfoEv @ 288 NONAME
+	_ZNK14CCMSSignedData26DigestAlgorithmIdentifiersEv @ 289 NONAME
+	_ZNK14CCMSSignedData7VersionEv @ 290 NONAME
+	_ZNK14CCMSSignerInfo10CMSVersionEv @ 291 NONAME
+	_ZNK14CCMSSignerInfo14SignatureValueEv @ 292 NONAME
+	_ZNK14CCMSSignerInfo16SignedAttributesEv @ 293 NONAME
+	_ZNK14CCMSSignerInfo18UnsignedAttributesEv @ 294 NONAME
+	_ZNK14CCMSSignerInfo20SubjectKeyIdentifierEv @ 295 NONAME
+	_ZNK14CCMSSignerInfo21IssuerAndSerialNumberEv @ 296 NONAME
+	_ZNK14CCMSSignerInfo25DigestAlgorithmIdentifierEv @ 297 NONAME
+	_ZNK14CCMSSignerInfo28SignatureAlgorithmIdentifierEv @ 298 NONAME
+	_ZNK14CCMSX509Signed19AlgorithmIdentifierEv @ 299 NONAME
+	_ZNK14CCMSX509Signed9EncryptedEv @ 300 NONAME
+	_ZNK15CCMSContentInfo11ContentTypeEv @ 301 NONAME
+	_ZNK15CCMSContentInfo7ContentEv @ 302 NONAME
+	_ZNK16CCMSX509Validity8NotAfterEv @ 303 NONAME
+	_ZNK16CCMSX509Validity9NotBeforeEv @ 304 NONAME
+	_ZNK17CCMSKeyIdentifier13KeyIdentifierEv @ 305 NONAME
+	_ZNK17CCMSKeyIdentifier4DateEv @ 306 NONAME
+	_ZNK17CCMSRecipientInfo22KeyEncryptionAlgorithmEv @ 307 NONAME
+	_ZNK17CCMSRecipientInfo7VersionEv @ 308 NONAME
+	_ZNK18CCMSOriginatorInfo4CrlsEv @ 309 NONAME
+	_ZNK18CCMSOriginatorInfo5CertsEv @ 310 NONAME
+	_ZNK19CCMSX509Certificate12SerialNumberEv @ 311 NONAME
+	_ZNK19CCMSX509Certificate20SubjectPublicKeyInfoEv @ 312 NONAME
+	_ZNK19CCMSX509Certificate22IssuerUniqueIdentifierEv @ 313 NONAME
+	_ZNK19CCMSX509Certificate23SubjectUniqueIdentifierEv @ 314 NONAME
+	_ZNK19CCMSX509Certificate6IssuerEv @ 315 NONAME
+	_ZNK19CCMSX509Certificate7SubjectEv @ 316 NONAME
+	_ZNK19CCMSX509Certificate7VersionEv @ 317 NONAME
+	_ZNK19CCMSX509Certificate8ValidityEv @ 318 NONAME
+	_ZNK19CCMSX509Certificate9SignatureEv @ 319 NONAME
+	_ZNK19CCMSX509GeneralName3TagEv @ 320 NONAME
+	_ZNK19CCMSX509GeneralName4DataEv @ 321 NONAME
+	_ZNK20CCMSKEKRecipientInfo12EncryptedKeyEv @ 322 NONAME
+	_ZNK20CCMSKEKRecipientInfo5KekidEv @ 323 NONAME
+	_ZNK20CCMSX509GeneralNames12GeneralNamesEv @ 324 NONAME
+	_ZNK20CCMSX509IssuerSerial6IssuerEv @ 325 NONAME
+	_ZNK20CCMSX509IssuerSerial6SerialEv @ 326 NONAME
+	_ZNK20CCMSX509IssuerSerial9IssuerUIDEv @ 327 NONAME
+	_ZNK21CCMSAuthenticatedData12MacAlgorithmEv @ 328 NONAME
+	_ZNK21CCMSAuthenticatedData14OriginatorInfoEv @ 329 NONAME
+	_ZNK21CCMSAuthenticatedData14RecipientInfosEv @ 330 NONAME
+	_ZNK21CCMSAuthenticatedData15DigestAlgorithmEv @ 331 NONAME
+	_ZNK21CCMSAuthenticatedData16EncapContentInfoEv @ 332 NONAME
+	_ZNK21CCMSAuthenticatedData23AuthenticatedAttributesEv @ 333 NONAME
+	_ZNK21CCMSAuthenticatedData25UnauthenticatedAttributesEv @ 334 NONAME
+	_ZNK21CCMSAuthenticatedData3MacEv @ 335 NONAME
+	_ZNK21CCMSAuthenticatedData7VersionEv @ 336 NONAME
+	_ZNK22CCMSCertificateChoices11CertificateEv @ 337 NONAME
+	_ZNK22CCMSCertificateChoices8AttrCertEv @ 338 NONAME
+	_ZNK23CCMSOriginatorPublicKey9AlgorithmEv @ 339 NONAME
+	_ZNK23CCMSOriginatorPublicKey9PublicKeyEv @ 340 NONAME
+	_ZNK23CCMSX509CertificateList10ParametersEv @ 341 NONAME
+	_ZNK25CCMSIssuerAndSerialNumber10IssuerNameEv @ 342 NONAME
+	_ZNK25CCMSIssuerAndSerialNumber12SerialNumberEv @ 343 NONAME
+	_ZNK25CCMSKeyAgreeRecipientInfo10OriginatorEv @ 344 NONAME
+	_ZNK25CCMSKeyAgreeRecipientInfo18UserKeyingMaterialEv @ 345 NONAME
+	_ZNK25CCMSKeyAgreeRecipientInfo22RecipientEncryptedKeysEv @ 346 NONAME
+	_ZNK25CCMSKeyTransRecipientInfo12EncryptedKeyEv @ 347 NONAME
+	_ZNK25CCMSKeyTransRecipientInfo20SubjectKeyIdentifierEv @ 348 NONAME
+	_ZNK25CCMSKeyTransRecipientInfo21IssuerAndSerialNumberEv @ 349 NONAME
+	_ZNK25CCMSRecipientEncryptedKey12EncryptedKeyEv @ 350 NONAME
+	_ZNK25CCMSRecipientEncryptedKey21IssuerAndSerialNumberEv @ 351 NONAME
+	_ZNK25CCMSRecipientEncryptedKey6RKeyIdEv @ 352 NONAME
+	_ZNK27CCMSEncapsulatedContentInfo7ContentEv @ 353 NONAME
+	_ZNK27CCMSX509AlgorithmIdentifier15DigestAlgorithmEv @ 354 NONAME
+	_ZNK27CCMSX509AlgorithmIdentifier19AlgorithmIdentifierEv @ 355 NONAME
+	_ZNK28CCMSX509AttributeCertificate4InfoEv @ 356 NONAME
+	_ZNK28CCMSX509SubjectPublicKeyInfo16SubjectPublicKeyEv @ 357 NONAME
+	_ZNK28CCMSX509SubjectPublicKeyInfo9AlgorithmEv @ 358 NONAME
+	_ZNK29CCMSOriginatorIdentifierOrKey14OriginatorKeyLEv @ 359 NONAME
+	_ZNK29CCMSOriginatorIdentifierOrKey21SubjectKeyIdentifierLEv @ 360 NONAME
+	_ZNK29CCMSOriginatorIdentifierOrKey22IssuerAndSerialNumberLEv @ 361 NONAME
+	_ZNK29CCMSOriginatorIdentifierOrKey4TypeEv @ 362 NONAME
+	_ZNK32CCMSX509AttributeCertificateInfo10AttributesEv @ 363 NONAME
+	_ZNK32CCMSX509AttributeCertificateInfo11SubjectNameEv @ 364 NONAME
+	_ZNK32CCMSX509AttributeCertificateInfo12NotAfterTimeEv @ 365 NONAME
+	_ZNK32CCMSX509AttributeCertificateInfo12SerialNumberEv @ 366 NONAME
+	_ZNK32CCMSX509AttributeCertificateInfo13NotBeforeTimeEv @ 367 NONAME
+	_ZNK32CCMSX509AttributeCertificateInfo14IssuerUniqueIDEv @ 368 NONAME
+	_ZNK32CCMSX509AttributeCertificateInfo17BaseCertificateIDEv @ 369 NONAME
+	_ZNK32CCMSX509AttributeCertificateInfo6IssuerEv @ 370 NONAME
+	_ZNK32CCMSX509AttributeCertificateInfo7VersionEv @ 371 NONAME
+	_ZNK32CCMSX509AttributeCertificateInfo9SignatureEv @ 372 NONAME
+	_ZTI12CCMSSequence @ 373 NONAME ; #<TI>#
+	_ZTI13CCMSAttribute @ 374 NONAME ; #<TI>#
+	_ZTI14CCMSSignedData @ 375 NONAME ; #<TI>#
+	_ZTI14CCMSSignerInfo @ 376 NONAME ; #<TI>#
+	_ZTI14CCMSX509Signed @ 377 NONAME ; #<TI>#
+	_ZTI15CCMSContentInfo @ 378 NONAME ; #<TI>#
+	_ZTI16CCMSX509Validity @ 379 NONAME ; #<TI>#
+	_ZTI17CCMSKeyIdentifier @ 380 NONAME ; #<TI>#
+	_ZTI17CCMSRecipientInfo @ 381 NONAME ; #<TI>#
+	_ZTI18CCMSOriginatorInfo @ 382 NONAME ; #<TI>#
+	_ZTI19CCMSX509Certificate @ 383 NONAME ; #<TI>#
+	_ZTI19CCMSX509GeneralName @ 384 NONAME ; #<TI>#
+	_ZTI20CCMSKEKRecipientInfo @ 385 NONAME ; #<TI>#
+	_ZTI20CCMSX509GeneralNames @ 386 NONAME ; #<TI>#
+	_ZTI20CCMSX509IssuerSerial @ 387 NONAME ; #<TI>#
+	_ZTI21CCMSAuthenticatedData @ 388 NONAME ; #<TI>#
+	_ZTI22CCMSCertificateChoices @ 389 NONAME ; #<TI>#
+	_ZTI23CCMSOriginatorPublicKey @ 390 NONAME ; #<TI>#
+	_ZTI23CCMSX509CertificateList @ 391 NONAME ; #<TI>#
+	_ZTI25CCMSIssuerAndSerialNumber @ 392 NONAME ; #<TI>#
+	_ZTI25CCMSKeyAgreeRecipientInfo @ 393 NONAME ; #<TI>#
+	_ZTI25CCMSKeyTransRecipientInfo @ 394 NONAME ; #<TI>#
+	_ZTI25CCMSRecipientEncryptedKey @ 395 NONAME ; #<TI>#
+	_ZTI26CCMSX509RevokedCertificate @ 396 NONAME ; #<TI>#
+	_ZTI27CCMSEncapsulatedContentInfo @ 397 NONAME ; #<TI>#
+	_ZTI27CCMSX509AlgorithmIdentifier @ 398 NONAME ; #<TI>#
+	_ZTI28CCMSX509AttributeCertificate @ 399 NONAME ; #<TI>#
+	_ZTI28CCMSX509SubjectPublicKeyInfo @ 400 NONAME ; #<TI>#
+	_ZTI29CCMSOriginatorIdentifierOrKey @ 401 NONAME ; #<TI>#
+	_ZTI32CCMSX509AttributeCertificateInfo @ 402 NONAME ; #<TI>#
+	_ZTI33CCMSX509CertificateListParameters @ 403 NONAME ; #<TI>#
+	_ZTV12CCMSSequence @ 404 NONAME ; #<VT>#
+	_ZTV13CCMSAttribute @ 405 NONAME ; #<VT>#
+	_ZTV14CCMSSignedData @ 406 NONAME ; #<VT>#
+	_ZTV14CCMSSignerInfo @ 407 NONAME ; #<VT>#
+	_ZTV14CCMSX509Signed @ 408 NONAME ; #<VT>#
+	_ZTV15CCMSContentInfo @ 409 NONAME ; #<VT>#
+	_ZTV16CCMSX509Validity @ 410 NONAME ; #<VT>#
+	_ZTV17CCMSKeyIdentifier @ 411 NONAME ; #<VT>#
+	_ZTV17CCMSRecipientInfo @ 412 NONAME ; #<VT>#
+	_ZTV18CCMSOriginatorInfo @ 413 NONAME ; #<VT>#
+	_ZTV19CCMSX509Certificate @ 414 NONAME ; #<VT>#
+	_ZTV19CCMSX509GeneralName @ 415 NONAME ; #<VT>#
+	_ZTV20CCMSKEKRecipientInfo @ 416 NONAME ; #<VT>#
+	_ZTV20CCMSX509GeneralNames @ 417 NONAME ; #<VT>#
+	_ZTV20CCMSX509IssuerSerial @ 418 NONAME ; #<VT>#
+	_ZTV21CCMSAuthenticatedData @ 419 NONAME ; #<VT>#
+	_ZTV22CCMSCertificateChoices @ 420 NONAME ; #<VT>#
+	_ZTV23CCMSOriginatorPublicKey @ 421 NONAME ; #<VT>#
+	_ZTV23CCMSX509CertificateList @ 422 NONAME ; #<VT>#
+	_ZTV25CCMSIssuerAndSerialNumber @ 423 NONAME ; #<VT>#
+	_ZTV25CCMSKeyAgreeRecipientInfo @ 424 NONAME ; #<VT>#
+	_ZTV25CCMSKeyTransRecipientInfo @ 425 NONAME ; #<VT>#
+	_ZTV25CCMSRecipientEncryptedKey @ 426 NONAME ; #<VT>#
+	_ZTV26CCMSX509RevokedCertificate @ 427 NONAME ; #<VT>#
+	_ZTV27CCMSEncapsulatedContentInfo @ 428 NONAME ; #<VT>#
+	_ZTV27CCMSX509AlgorithmIdentifier @ 429 NONAME ; #<VT>#
+	_ZTV28CCMSX509AttributeCertificate @ 430 NONAME ; #<VT>#
+	_ZTV28CCMSX509SubjectPublicKeyInfo @ 431 NONAME ; #<VT>#
+	_ZTV29CCMSOriginatorIdentifierOrKey @ 432 NONAME ; #<VT>#
+	_ZTV32CCMSX509AttributeCertificateInfo @ 433 NONAME ; #<VT>#
+	_ZTV33CCMSX509CertificateListParameters @ 434 NONAME ; #<VT>#
+	_ZNK14CCMSSignerInfo24SignedAttributesEncodedLEv @ 435 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/group/CMS.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,75 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  MMP file for the module
+*
+*/
+
+#include <platform_paths.hrh>
+
+TARGET          CMS.Dll
+TARGETTYPE      DLL
+UID             0x10011111 0x10003232
+
+
+CAPABILITY  CAP_GENERAL_DLL
+VENDORID    VID_DEFAULT
+
+
+SOURCEPATH      ../src
+
+SOURCE    CMS.cpp
+SOURCE    CCMSSequence.cpp
+SOURCE    CCMSIssuerAndSerialNumber.cpp
+SOURCE    CCMSAttribute.cpp
+SOURCE    CCMSX509AlgorithmIdentifier.cpp
+SOURCE    TCMSTimeUtil.cpp
+SOURCE    CCMSSignerInfo.cpp
+SOURCE    CCMSContentInfo.cpp
+SOURCE    CCMSEncapsulatedContentInfo.cpp
+SOURCE    CCMSX509CertificateList.cpp
+SOURCE    CCMSOriginatorPublicKey.cpp
+SOURCE    CCMSOriginatorIdentifierOrKey.cpp
+SOURCE    CCMSKeyIdentifier.cpp
+SOURCE    CCMSRecipientEncryptedKey.cpp
+SOURCE    CCMSRecipientInfo.cpp
+SOURCE    CCMSKeyTransRecipientInfo.cpp
+SOURCE    CCMSKeyAgreeRecipientInfo.cpp
+SOURCE    CCMSKEKRecipientInfo.cpp
+SOURCE    CCMSX509GeneralName.cpp
+SOURCE    CCMSX509GeneralNames.cpp
+SOURCE    CCMSSignedData.cpp
+SOURCE    CCMSX509IssuerSerial.cpp
+SOURCE    CCMSX509AttributeCertificateInfo.cpp
+SOURCE    CCMSX509AttributeCertificate.cpp
+SOURCE    CCMSX509SubjectPublicKeyInfo.cpp
+SOURCE    CCMSX509Signed.cpp
+SOURCE    CCMSX509Validity.cpp
+SOURCE    CCMSX509Certificate.cpp
+SOURCE    CCMSCertificateChoices.cpp
+SOURCE    CCMSOriginatorInfo.cpp
+SOURCE    CCMSAuthenticatedData.cpp
+
+USERINCLUDE     ../inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY       euser.lib
+LIBRARY       asn1.lib
+LIBRARY       x509.lib
+LIBRARY       x500.lib
+LIBRARY       bafl.lib
+LIBRARY       crypto.lib
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/group/Create-UT_CCMSAttribute-Sis.bat	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,70 @@
+@echo off
+rem
+rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+rem All rights reserved.
+rem This component and the accompanying materials are made available
+rem under the terms of "Eclipse Public License v1.0"
+rem which accompanies this distribution, and is available
+rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+rem
+rem Initial Contributors:
+rem Nokia Corporation - initial contribution.
+rem
+rem Contributors:
+rem
+rem Description:
+rem
+
+echo.
+echo ====================================
+echo.
+echo Digia EUnit - Test
+echo.
+echo This BAT copies Test DLL
+echo to local folder and makes SIS file
+echo.
+echo ====================================
+echo.
+
+:CHECK_EPOCROOT
+echo.
+echo - verify epoc root
+set EPOCROOT
+if errorlevel == 1 goto END_ERROR 
+
+:COPY_DLL
+echo.
+echo - copy test dll to current directory
+copy %EPOCROOT%epoc32\release\thumb\urel\UT_CCMSAttribute.dll .
+if errorlevel == 1 goto END_ERROR 
+
+:CREATE_DIR
+echo.
+echo - create Sis folder (created only if needed)
+mkdir ..\Sis
+
+:MAKESIS
+echo.
+echo - makesis UT_CCMSAttribute.pkg ..\sis\UT_CCMSAttribute.sis
+call makesis UT_CCMSAttribute.pkg ..\sis\UT_CCMSAttribute.sis
+if errorlevel == 1 goto END_ERROR
+
+:DELETE_DLL
+echo.
+echo - remove the copied dll from current folder
+del UT_CCMSAttribute.dll
+goto END
+
+:END_ERROR
+echo.
+echo Sis creation failed. 
+goto FINAL_END
+
+:END
+echo.
+echo Sis file created succesfully
+echo ============================
+
+:FINAL_END
+echo.
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/group/Create-UT_CCMSEncapsulatedContentInfo-Sis.bat	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,70 @@
+@echo off
+rem
+rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+rem All rights reserved.
+rem This component and the accompanying materials are made available
+rem under the terms of "Eclipse Public License v1.0"
+rem which accompanies this distribution, and is available
+rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+rem
+rem Initial Contributors:
+rem Nokia Corporation - initial contribution.
+rem
+rem Contributors:
+rem
+rem Description:
+rem
+
+echo.
+echo ====================================
+echo.
+echo Digia EUnit - Test
+echo.
+echo This BAT copies Test DLL
+echo to local folder and makes SIS file
+echo.
+echo ====================================
+echo.
+
+:CHECK_EPOCROOT
+echo.
+echo - verify epoc root
+set EPOCROOT
+if errorlevel == 1 goto END_ERROR 
+
+:COPY_DLL
+echo.
+echo - copy test dll to current directory
+copy %EPOCROOT%epoc32\release\thumb\urel\UT_CCMSEncapsulatedContentInfo.dll .
+if errorlevel == 1 goto END_ERROR 
+
+:CREATE_DIR
+echo.
+echo - create Sis folder (created only if needed)
+mkdir ..\Sis
+
+:MAKESIS
+echo.
+echo - makesis UT_CCMSEncapsulatedContentInfo.pkg ..\sis\UT_CCMSEncapsulatedContentInfo.sis
+call makesis UT_CCMSEncapsulatedContentInfo.pkg ..\sis\UT_CCMSEncapsulatedContentInfo.sis
+if errorlevel == 1 goto END_ERROR
+
+:DELETE_DLL
+echo.
+echo - remove the copied dll from current folder
+del UT_CCMSEncapsulatedContentInfo.dll
+goto END
+
+:END_ERROR
+echo.
+echo Sis creation failed. 
+goto FINAL_END
+
+:END
+echo.
+echo Sis file created succesfully
+echo ============================
+
+:FINAL_END
+echo.
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/group/Create-UT_CCMSIssuerAndSerialNumber-Sis.bat	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,70 @@
+@echo off
+rem
+rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+rem All rights reserved.
+rem This component and the accompanying materials are made available
+rem under the terms of "Eclipse Public License v1.0"
+rem which accompanies this distribution, and is available
+rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+rem
+rem Initial Contributors:
+rem Nokia Corporation - initial contribution.
+rem
+rem Contributors:
+rem
+rem Description:
+rem
+
+echo.
+echo ====================================
+echo.
+echo Digia EUnit - Test
+echo.
+echo This BAT copies Test DLL
+echo to local folder and makes SIS file
+echo.
+echo ====================================
+echo.
+
+:CHECK_EPOCROOT
+echo.
+echo - verify epoc root
+set EPOCROOT
+if errorlevel == 1 goto END_ERROR 
+
+:COPY_DLL
+echo.
+echo - copy test dll to current directory
+copy %EPOCROOT%epoc32\release\thumb\urel\UT_CCMSIssuerAndSerialNumber.dll .
+if errorlevel == 1 goto END_ERROR 
+
+:CREATE_DIR
+echo.
+echo - create Sis folder (created only if needed)
+mkdir ..\Sis
+
+:MAKESIS
+echo.
+echo - makesis UT_CCMSIssuerAndSerialNumber.pkg ..\sis\UT_CCMSIssuerAndSerialNumber.sis
+call makesis UT_CCMSIssuerAndSerialNumber.pkg ..\sis\UT_CCMSIssuerAndSerialNumber.sis
+if errorlevel == 1 goto END_ERROR
+
+:DELETE_DLL
+echo.
+echo - remove the copied dll from current folder
+del UT_CCMSIssuerAndSerialNumber.dll
+goto END
+
+:END_ERROR
+echo.
+echo Sis creation failed. 
+goto FINAL_END
+
+:END
+echo.
+echo Sis file created succesfully
+echo ============================
+
+:FINAL_END
+echo.
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/group/Create-UT_CCMSOriginatorPublicKey-Sis.bat	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,70 @@
+@echo off
+rem
+rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+rem All rights reserved.
+rem This component and the accompanying materials are made available
+rem under the terms of "Eclipse Public License v1.0"
+rem which accompanies this distribution, and is available
+rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+rem
+rem Initial Contributors:
+rem Nokia Corporation - initial contribution.
+rem
+rem Contributors:
+rem
+rem Description:
+rem
+
+echo.
+echo ====================================
+echo.
+echo Digia EUnit - Test
+echo.
+echo This BAT copies Test DLL
+echo to local folder and makes SIS file
+echo.
+echo ====================================
+echo.
+
+:CHECK_EPOCROOT
+echo.
+echo - verify epoc root
+set EPOCROOT
+if errorlevel == 1 goto END_ERROR 
+
+:COPY_DLL
+echo.
+echo - copy test dll to current directory
+copy %EPOCROOT%epoc32\release\thumb\urel\UT_CCMSOriginatorPublicKey.dll .
+if errorlevel == 1 goto END_ERROR 
+
+:CREATE_DIR
+echo.
+echo - create Sis folder (created only if needed)
+mkdir ..\Sis
+
+:MAKESIS
+echo.
+echo - makesis UT_CCMSOriginatorPublicKey.pkg ..\sis\UT_CCMSOriginatorPublicKey.sis
+call makesis UT_CCMSOriginatorPublicKey.pkg ..\sis\UT_CCMSOriginatorPublicKey.sis
+if errorlevel == 1 goto END_ERROR
+
+:DELETE_DLL
+echo.
+echo - remove the copied dll from current folder
+del UT_CCMSOriginatorPublicKey.dll
+goto END
+
+:END_ERROR
+echo.
+echo Sis creation failed. 
+goto FINAL_END
+
+:END
+echo.
+echo Sis file created succesfully
+echo ============================
+
+:FINAL_END
+echo.
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/group/Create-UT_CCMSSignerInfo-Sis.bat	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,70 @@
+@echo off
+rem
+rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+rem All rights reserved.
+rem This component and the accompanying materials are made available
+rem under the terms of "Eclipse Public License v1.0"
+rem which accompanies this distribution, and is available
+rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+rem
+rem Initial Contributors:
+rem Nokia Corporation - initial contribution.
+rem
+rem Contributors:
+rem
+rem Description:
+rem
+
+echo.
+echo ====================================
+echo.
+echo Digia EUnit - Test
+echo.
+echo This BAT copies Test DLL
+echo to local folder and makes SIS file
+echo.
+echo ====================================
+echo.
+
+:CHECK_EPOCROOT
+echo.
+echo - verify epoc root
+set EPOCROOT
+if errorlevel == 1 goto END_ERROR 
+
+:COPY_DLL
+echo.
+echo - copy test dll to current directory
+copy %EPOCROOT%epoc32\release\thumb\urel\UT_CCMSSignerInfo.dll .
+if errorlevel == 1 goto END_ERROR 
+
+:CREATE_DIR
+echo.
+echo - create Sis folder (created only if needed)
+mkdir ..\Sis
+
+:MAKESIS
+echo.
+echo - makesis UT_CCMSSignerInfo.pkg ..\sis\UT_CCMSSignerInfo.sis
+call makesis UT_CCMSSignerInfo.pkg ..\sis\UT_CCMSSignerInfo.sis
+if errorlevel == 1 goto END_ERROR
+
+:DELETE_DLL
+echo.
+echo - remove the copied dll from current folder
+del UT_CCMSSignerInfo.dll
+goto END
+
+:END_ERROR
+echo.
+echo Sis creation failed. 
+goto FINAL_END
+
+:END
+echo.
+echo Sis file created succesfully
+echo ============================
+
+:FINAL_END
+echo.
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/group/Create-UT_CCMSX509AlgorithmIdentifier-Sis.bat	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,70 @@
+@echo off
+rem
+rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+rem All rights reserved.
+rem This component and the accompanying materials are made available
+rem under the terms of "Eclipse Public License v1.0"
+rem which accompanies this distribution, and is available
+rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+rem
+rem Initial Contributors:
+rem Nokia Corporation - initial contribution.
+rem
+rem Contributors:
+rem
+rem Description:
+rem
+
+echo.
+echo ====================================
+echo.
+echo Digia EUnit - Test
+echo.
+echo This BAT copies Test DLL
+echo to local folder and makes SIS file
+echo.
+echo ====================================
+echo.
+
+:CHECK_EPOCROOT
+echo.
+echo - verify epoc root
+set EPOCROOT
+if errorlevel == 1 goto END_ERROR 
+
+:COPY_DLL
+echo.
+echo - copy test dll to current directory
+copy %EPOCROOT%epoc32\release\thumb\urel\UT_CCMSX509AlgorithmIdentifier.dll .
+if errorlevel == 1 goto END_ERROR 
+
+:CREATE_DIR
+echo.
+echo - create Sis folder (created only if needed)
+mkdir ..\Sis
+
+:MAKESIS
+echo.
+echo - makesis UT_CCMSX509AlgorithmIdentifier.pkg ..\sis\UT_CCMSX509AlgorithmIdentifier.sis
+call makesis UT_CCMSX509AlgorithmIdentifier.pkg ..\sis\UT_CCMSX509AlgorithmIdentifier.sis
+if errorlevel == 1 goto END_ERROR
+
+:DELETE_DLL
+echo.
+echo - remove the copied dll from current folder
+del UT_CCMSX509AlgorithmIdentifier.dll
+goto END
+
+:END_ERROR
+echo.
+echo Sis creation failed. 
+goto FINAL_END
+
+:END
+echo.
+echo Sis file created succesfully
+echo ============================
+
+:FINAL_END
+echo.
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/group/UT_CCMSAttribute.pkg	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+;
+; Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+
+; Supported languages
+&en
+
+; Package header (one name for each supported language)
+#{"UT_CCMSAttribute"},(0x01700000),0,10,0
+
+; Package signature
+
+
+; Options line not supported currently
+
+; Conditions blocks not supported currently
+
+; Language independent files that are always installed
+"UT_CCMSAttribute.dll"-"!:\DigiaEUnit\Tests\UT_CCMSAttribute.dll"
+
+; Language dependent files 
+
+
+; Requisites (of type: (UID),Major,Minor,Build-Number,{"Requisite Name1", "Requisite Name2"})
+(0x101F6F88), 0, 0, 0, {"Series60ProductID"}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/group/UT_CCMSEncapsulatedContentInfo.pkg	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+;
+; Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+
+; Supported languages
+&en
+
+; Package header (one name for each supported language)
+#{"UT_CCMSEncapsulatedContentInfo"},(0x01700000),0,10,0
+
+; Package signature
+
+
+; Options line not supported currently
+
+; Conditions blocks not supported currently
+
+; Language independent files that are always installed
+"UT_CCMSEncapsulatedContentInfo.dll"-"!:\DigiaEUnit\Tests\UT_CCMSEncapsulatedContentInfo.dll"
+
+; Language dependent files 
+
+
+; Requisites (of type: (UID),Major,Minor,Build-Number,{"Requisite Name1", "Requisite Name2"})
+(0x101F6F88), 0, 0, 0, {"Series60ProductID"}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/group/UT_CCMSIssuerAndSerialNumber.pkg	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+;
+; Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+
+; Supported languages
+&en
+
+; Package header (one name for each supported language)
+#{"UT_CCMSIssuerAndSerialNumber"},(0x01700000),0,10,0
+
+; Package signature
+
+
+; Options line not supported currently
+
+; Conditions blocks not supported currently
+
+; Language independent files that are always installed
+"UT_CCMSIssuerAndSerialNumber.dll"-"!:\DigiaEUnit\Tests\UT_CCMSIssuerAndSerialNumber.dll"
+
+; Language dependent files 
+
+
+; Requisites (of type: (UID),Major,Minor,Build-Number,{"Requisite Name1", "Requisite Name2"})
+(0x101F6F88), 0, 0, 0, {"Series60ProductID"}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/group/UT_CCMSOriginatorPublicKey.pkg	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+;
+; Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+
+; Supported languages
+&en
+
+; Package header (one name for each supported language)
+#{"UT_CCMSOriginatorPublicKey"},(0x01700000),0,10,0
+
+; Package signature
+
+
+; Options line not supported currently
+
+; Conditions blocks not supported currently
+
+; Language independent files that are always installed
+"UT_CCMSOriginatorPublicKey.dll"-"!:\DigiaEUnit\Tests\UT_CCMSOriginatorPublicKey.dll"
+
+; Language dependent files 
+
+
+; Requisites (of type: (UID),Major,Minor,Build-Number,{"Requisite Name1", "Requisite Name2"})
+(0x101F6F88), 0, 0, 0, {"Series60ProductID"}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/group/UT_CCMSSignerInfo.pkg	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+;
+; Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+
+; Supported languages
+&en
+
+; Package header (one name for each supported language)
+#{"UT_CCMSSignerInfo"},(0x01700000),0,10,0
+
+; Package signature
+
+
+; Options line not supported currently
+
+; Conditions blocks not supported currently
+
+; Language independent files that are always installed
+"UT_CCMSSignerInfo.dll"-"!:\DigiaEUnit\Tests\UT_CCMSSignerInfo.dll"
+
+; Language dependent files 
+
+
+; Requisites (of type: (UID),Major,Minor,Build-Number,{"Requisite Name1", "Requisite Name2"})
+(0x101F6F88), 0, 0, 0, {"Series60ProductID"}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/group/UT_CCMSX509AlgorithmIdentifier.pkg	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+;
+; Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+
+; Supported languages
+&en
+
+; Package header (one name for each supported language)
+#{"UT_CCMSX509AlgorithmIdentifier"},(0x01700000),0,10,0
+
+; Package signature
+
+
+; Options line not supported currently
+
+; Conditions blocks not supported currently
+
+; Language independent files that are always installed
+"UT_CCMSX509AlgorithmIdentifier.dll"-"!:\DigiaEUnit\Tests\UT_CCMSX509AlgorithmIdentifier.dll"
+
+; Language dependent files 
+
+
+; Requisites (of type: (UID),Major,Minor,Build-Number,{"Requisite Name1", "Requisite Name2"})
+(0x101F6F88), 0, 0, 0, {"Series60ProductID"}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  CMS module
+*
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+../rom/CMS.iby CORE_MW_LAYER_IBY_EXPORT_PATH( CMS.iby )
+
+PRJ_MMPFILES
+    CMS.mmp
+
+PRJ_TESTEXPORTS
+
+PRJ_TESTMMPFILES
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/inc/TCMSTimeUtil.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef TCMSTimeUtil_H
+#define TCMSTimeUtil_H
+
+//  INCLUDES
+#include 	<asn1enc.h>
+
+// CLASS DECLARATION
+/**
+*  This util is used for creating either
+*  UTCTime or Generalized time from TTime
+*  depending on date
+*
+*  Dates between 1 January 1950 and 31 December 2049 (inclusive) must be
+*  encoded as UTCTime.  Any dates with year values before 1950 or after
+*  2049 must be encoded as GeneralizedTime.
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class TCMSTimeUtil
+    {
+    public:  // Constructors and destructor
+		/**
+        * Conversion util
+        * @param aTime to be converted
+        * @return given TTime in as encoder
+        */
+        static CASN1EncBase* ConvertToEncoderLC( const TTime& aTime );
+		
+		/**
+        * Conversion util
+        * @param aSource DER encoded source to be converted
+        * @return source converted to TTime
+        */
+		static TTime ConvertToTimeL( const TDesC8& aSource );
+    };
+
+#endif      // TCMSTimeUtil_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/rom/CMS.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ROM description for CMS component.
+*
+*/
+
+
+#ifndef __CMS_IBY__
+#define __CMS_IBY__
+
+file=ABI_DIR\BUILD_DIR\CMS.dll                  \SHARED_LIB_DIR\CMS.dll
+
+#endif // __CMS_IBY__
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSAttribute.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,347 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSAttribute.h"
+#include "TCMSTimeUtil.h"
+#include <x500dn.h>
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KMaxNumberOfSubModules = 3;
+const TInt KMinNumberOfSubModules = 2;
+const TInt KDefaultGranularity = 1;
+
+// CMS SignedAttributes useful types
+_LIT( KContentTypeOID, "1.2.840.113549.1.9.3" );
+_LIT( KMessageDigestOID, "1.2.840.113549.1.9.4" );
+_LIT( KSignTimeOID, "1.2.840.113549.1.9.5" );
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CMSCreateEncoderLC Creates an encoder based on the gived OID value.
+// Returns: Encoder for the given encoding
+// -----------------------------------------------------------------------------
+//
+CASN1EncBase* CMSCreateEncoderLC( const TDesC& aAttributeType, const TDesC8& aEncoding )
+    {
+    CASN1EncBase* retVal = NULL;
+    if( aAttributeType == KContentTypeOID )
+        {
+        // encoding data, have to decode it before encoding it again
+        // because CASN1EncEncoding changes TagType to Constructed
+        TASN1DecObjectIdentifier dataDec;
+        TInt pos = 0;
+        HBufC* data = dataDec.DecodeDERL( aEncoding, pos );
+        CleanupStack::PushL( data );
+        retVal = CASN1EncObjectIdentifier::NewL( *data );
+        CleanupStack::PopAndDestroy( data );
+        CleanupStack::PushL( retVal );
+        }
+    else if( aAttributeType == KMessageDigestOID )
+        {
+        TASN1DecOctetString dataDec;
+        TInt pos = 0;
+        HBufC8* data = dataDec.DecodeDERL( aEncoding, pos );
+        CleanupStack::PushL( data );
+        retVal = CASN1EncOctetString::NewL( *data );
+        CleanupStack::PopAndDestroy( data );
+        CleanupStack::PushL( retVal );
+        }
+    else if( aAttributeType == KSignTimeOID )
+        {
+        TTime time = TCMSTimeUtil::ConvertToTimeL( aEncoding );
+        retVal = TCMSTimeUtil::ConvertToEncoderLC( time );
+        }
+    else
+        {
+        // default is to wrap inside encencoder
+        retVal = CASN1EncEncoding::NewLC( aEncoding );
+        }
+    return retVal;
+    }
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::CCMSAttribute
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSAttribute::CCMSAttribute()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSAttribute::ConstructL()
+    {
+	// creating with empty values
+	iAttributeType = KNullDesC().AllocL();
+
+	iAttributeValues =
+		new(ELeave) CDesC8ArrayFlat( KDefaultGranularity );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSAttribute::ConstructL(
+	const TDesC& aAttributeType,
+	const CDesC8Array& aAttributeValues )
+    {
+	SetAttributeTypeL( aAttributeType );
+	SetAttributeValuesL( aAttributeValues );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSAttribute::ConstructL(
+	const TDesC& aAttributeType,
+	const TDesC8& aAttributeValue )
+    {
+	SetAttributeTypeL( aAttributeType );
+	iAttributeValues =
+		new(ELeave) CDesC8ArrayFlat( KDefaultGranularity );
+	iAttributeValues->AppendL( aAttributeValue );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSAttribute* CCMSAttribute::NewLC()
+	{
+	CCMSAttribute* self = new( ELeave ) CCMSAttribute();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSAttribute* CCMSAttribute::NewL()
+	{
+	CCMSAttribute* self = NewLC();
+    CleanupStack::Pop( self );
+    return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSAttribute* CCMSAttribute::NewL(
+	const TDesC& aAttributeType,
+	const CDesC8Array& aAttributeValues )
+	{
+	CCMSAttribute* self = NewLC( aAttributeType, aAttributeValues );
+	CleanupStack::Pop( self );
+    return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSAttribute* CCMSAttribute::NewLC(
+	const TDesC& aAttributeType,
+	const CDesC8Array& aAttributeValues )
+    {
+    CCMSAttribute* self = new( ELeave ) CCMSAttribute();
+    CleanupStack::PushL( self );
+    self->ConstructL( aAttributeType, aAttributeValues );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSAttribute* CCMSAttribute::NewLC(
+	const TDesC& aAttributeType,
+	const TDesC8& aAttributeValue )
+	{
+	CCMSAttribute* self = new( ELeave ) CCMSAttribute();
+	CleanupStack::PushL( self );
+	self->ConstructL( aAttributeType, aAttributeValue );
+    return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSAttribute* CCMSAttribute::NewL(
+	const TDesC& aAttributeType,
+	const TDesC8& aAttributeValue )
+	{
+	CCMSAttribute* self = NewLC( aAttributeType, aAttributeValue );
+	CleanupStack::Pop( self );
+    return self;
+	}
+
+// Destructor
+CCMSAttribute::~CCMSAttribute()
+    {
+	delete iAttributeType;
+	delete iAttributeValues;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSAttribute::DecodeL( const TDesC8& aRawData )
+	{
+	CArrayPtr<TASN1DecGeneric>* itemsData =
+        DecodeSequenceLC( aRawData,
+                          KMinNumberOfSubModules,
+                          KMaxNumberOfSubModules );
+	// we would not get this far if there is not 2 or 3 elements
+	// decoding attribute type
+	TASN1DecObjectIdentifier decOid;
+	HBufC* oid = decOid.DecodeDERL( *itemsData->At( 0 ) );
+	delete iAttributeType;
+	iAttributeType = oid;
+
+	// deocoding attribute values
+	TASN1DecSet decSet;
+	CArrayPtrFlat<TASN1DecGeneric>* attValues =
+					decSet.DecodeDERLC( *itemsData->At( 1 ) );
+	TInt numOfAttValues = attValues->Count();
+	CDesC8ArrayFlat* tmpArray = new( ELeave ) CDesC8ArrayFlat( numOfAttValues );
+	CleanupStack::PushL( tmpArray );
+	for( TInt i = 0; i < numOfAttValues; i++ )
+		{
+		tmpArray->AppendL( attValues->At( i )->Encoding() );
+		}
+	delete iAttributeValues;
+	iAttributeValues = tmpArray;
+	// compress to get rid of possible unneccessary slots
+	iAttributeValues->Compress();
+
+    // possible context values are ignored
+
+	CleanupStack::Pop( tmpArray );
+	CleanupStack::PopAndDestroy( attValues );
+	CleanupStack::PopAndDestroy( itemsData );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSAttribute::EncoderLC() const
+	{
+	CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+	// add attribute type
+	CASN1EncObjectIdentifier* oid = CASN1EncObjectIdentifier::NewLC( *iAttributeType );
+	root->AddAndPopChildL( oid );
+
+	// add attribute values
+	CASN1EncSequence* values = CASN1EncSequence::NewLC();
+
+	// change tag to SET
+	values->SetTag( EASN1Set, EUniversal );
+
+	TInt numOfValues = iAttributeValues->Count();
+	for( TInt i = 0; i < numOfValues; i++ )
+		{
+        CASN1EncBase* enc = CMSCreateEncoderLC( *iAttributeType, ( *iAttributeValues )[ i ] );
+		values->AddAndPopChildL( enc );
+		}
+
+	root->AddAndPopChildL( values );
+	return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::AttributeType
+// Getter for attribute type
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC& CCMSAttribute::AttributeType() const
+	{
+	return *iAttributeType;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::AttributeValues
+// Getter for attribute values
+// -----------------------------------------------------------------------------
+EXPORT_C const CDesC8Array& CCMSAttribute::AttributeValues() const
+	{
+	return *iAttributeValues;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::SetAttributeTypeL
+// Setter for attribute type, takes copy
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSAttribute::SetAttributeTypeL( const TDesC& aAttributeType )
+	{
+	HBufC* tmp = aAttributeType.AllocL();
+	delete iAttributeType;
+	iAttributeType = tmp;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAttribute::SetAttributeTypeL
+// Setter for attribute values, takes copy
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSAttribute::SetAttributeValuesL(
+	const CDesC8Array& aAttributeValues )
+	{
+	TInt numOfValues = aAttributeValues.Count();
+	// Making 1 extra slot
+	CDesC8ArrayFlat* tmp = new(ELeave) CDesC8ArrayFlat( numOfValues + 1 );
+	CleanupStack::PushL( tmp );
+	for( TInt i = 0; i < numOfValues; i++ )
+		{
+		tmp->AppendL( aAttributeValues[ i ] );
+		}
+
+	// Compressing
+	tmp->Compress();
+	CleanupStack::Pop( tmp );
+	delete iAttributeValues;
+	iAttributeValues = tmp;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSAuthenticatedData.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,629 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSAuthenticatedData.h"
+#include "CCMSX509AlgorithmIdentifier.h"
+#include "CCMSOriginatorInfo.h"
+#include "CCMSRecipientInfo.h"
+#include "CCMSKeyTransRecipientInfo.h"
+#include "CCMSKeyAgreeRecipientInfo.h"
+#include "CCMSKEKRecipientInfo.h"
+#include "CCMSAttribute.h"
+#include "CCMSX509Certificate.h"
+#include "CCMSCertificateChoices.h"
+#include "CCMSX509CertificateList.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KDefaultGranularity = 1;
+const TInt KMinNumberOfSubModules = 5;
+const TInt KMaxNumberOfSubModules = 9;
+const TTagType KOriginatorInfoTag = 0;
+const TTagType KDigestAlgorithmTag = 1;
+const TTagType KAuthenticatedAttributesTag = 2;
+const TTagType KUnauthenticatedAttributesTag = 3;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// Destructor
+CCMSAuthenticatedData::CAuthenticatedDataData::~CAuthenticatedDataData()
+    {
+    delete iOriginatorInfo;
+    if( iRecipientInfos )
+        {
+        iRecipientInfos->ResetAndDestroy();
+        delete iRecipientInfos;
+        }
+    delete iMacAlgorithm;
+    delete iDigestAlgorithm;
+    delete iEncapContentInfo;
+    if( iAuthenticatedAttributes )
+        {
+        iAuthenticatedAttributes->ResetAndDestroy();
+        delete iAuthenticatedAttributes;
+        }
+    delete iMac;
+    if( iUnauthenticatedAttributes )
+        {
+        iUnauthenticatedAttributes->ResetAndDestroy();
+        delete iUnauthenticatedAttributes;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::CCMSAuthenticatedData
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSAuthenticatedData::CCMSAuthenticatedData( )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSAuthenticatedData::ConstructL(
+    CArrayPtr< CCMSRecipientInfo >* aRecipientInfos,
+    CCMSX509AlgorithmIdentifier* aMacAlgorithm,
+    CCMSEncapsulatedContentInfo* aEncapContentInfo,
+    const TDesC8& aMac )
+    {
+    iData = new( ELeave ) CAuthenticatedDataData;
+    iData->iMac = aMac.AllocL();
+    
+    // all memory allocations have been done, we can take ownerships
+    iData->iRecipientInfos = aRecipientInfos;
+    iData->iMacAlgorithm = aMacAlgorithm;
+    iData->iEncapContentInfo = aEncapContentInfo;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSAuthenticatedData::ConstructL( )
+    {
+    // creating empty/default values
+    iData = new( ELeave ) CAuthenticatedDataData;
+    iData->iRecipientInfos =
+        new( ELeave ) CArrayPtrFlat< CCMSRecipientInfo >( KDefaultGranularity );
+    iData->iMacAlgorithm = CCMSX509AlgorithmIdentifier::NewL();
+    iData->iEncapContentInfo = CCMSEncapsulatedContentInfo::NewL();
+    iData->iMac = KNullDesC8().AllocL();
+    }
+    
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSAuthenticatedData*
+CCMSAuthenticatedData::NewLC()
+	{
+	// creating with empty values
+    CCMSAuthenticatedData* self =
+        new( ELeave ) CCMSAuthenticatedData();
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSAuthenticatedData*
+CCMSAuthenticatedData::NewLC(
+    CArrayPtr< CCMSRecipientInfo >* aRecipientInfos,
+    CCMSX509AlgorithmIdentifier* aMacAlgorithm,
+    CCMSEncapsulatedContentInfo* aEncapContentInfo,
+    const TDesC8& aMac )
+    {
+    CCMSAuthenticatedData* self =
+        new( ELeave ) CCMSAuthenticatedData();
+    CleanupStack::PushL( self );
+    self->ConstructL( aRecipientInfos, aMacAlgorithm, aEncapContentInfo, aMac );
+
+    return self;
+    }
+
+// Destructor
+CCMSAuthenticatedData::~CCMSAuthenticatedData()
+    {
+	delete iData;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSAuthenticatedData::DecodeL( const TDesC8& aRawData )
+	{
+    CArrayPtr< TASN1DecGeneric >* items = DecodeSequenceLC(
+        aRawData, KMinNumberOfSubModules, KMaxNumberOfSubModules );
+
+    // now we know that there are at least 5 items
+    TInt itemCount = items->Count();
+    __ASSERT_DEBUG( itemCount >= KMinNumberOfSubModules, User::Invariant() );
+    
+    TInt sequenceCounter = 0;
+
+    CAuthenticatedDataData* data = new( ELeave ) CAuthenticatedDataData;
+    CleanupStack::PushL( data );
+    
+    // decode version
+    TASN1DecInteger intDecoder;
+    data->iVersion =
+        intDecoder.DecodeDERShortL( *items->At( sequenceCounter++ ) );
+
+    // decode originatorInfo, if exist
+    TASN1DecGeneric* originatorInfoDecoder = items->At( sequenceCounter );
+    if( originatorInfoDecoder->Tag() == KOriginatorInfoTag )
+        {
+        data->iOriginatorInfo = CCMSOriginatorInfo::NewL();
+        data->iOriginatorInfo->DecodeImplicitTagL(
+            originatorInfoDecoder->Encoding(), KOriginatorInfoTag );
+        sequenceCounter++;
+        }
+
+    // decode recipientInfos
+    CArrayPtr< TASN1DecGeneric >* recipientInfos = DecodeSequenceLC(
+        items->At( sequenceCounter++)->Encoding() );
+    TInt recipientInfoCount = recipientInfos->Count();
+    data->iRecipientInfos =
+        new( ELeave ) CArrayPtrFlat< CCMSRecipientInfo >( recipientInfoCount );
+    for( TInt i = 0; i < recipientInfoCount; i++ )
+        {
+        TASN1DecGeneric* recipientInfoDecoder = recipientInfos->At( i );
+        CCMSRecipientInfo* recipientInfo = NULL;
+        switch( recipientInfoDecoder->Tag() )
+            {
+            case EASN1Sequence:
+                {
+                recipientInfo = CCMSKeyTransRecipientInfo::NewLC();
+                recipientInfo->DecodeL( recipientInfoDecoder->Encoding() );
+                break;
+                }
+            case KCMSKeyAgreeRecipientInfoTag:
+                {
+                recipientInfo = CCMSKeyAgreeRecipientInfo::NewLC();
+                recipientInfo->DecodeL( recipientInfoDecoder->Encoding() );
+                break;
+                }
+            case KCMSKEKRecipientInfoTag:
+                {
+                recipientInfo = CCMSKEKRecipientInfo::NewLC();
+                recipientInfo->DecodeL( recipientInfoDecoder->Encoding() );
+                break;
+                }
+            default:
+                {
+                User::Leave( KErrArgument );
+                }
+            }
+        data->iRecipientInfos->AppendL( recipientInfo );
+        CleanupStack::Pop( recipientInfo );
+        }
+    CleanupStack::PopAndDestroy( recipientInfos );
+    
+    // decode macAlgorithm
+    data->iMacAlgorithm = CCMSX509AlgorithmIdentifier::NewL();
+    data->iMacAlgorithm->DecodeL( items->At( sequenceCounter++)->Encoding() );
+
+    // decode digestAlgorithm, if exist
+    TASN1DecGeneric* digestAlgorithmDec = items->At( sequenceCounter );
+    if( digestAlgorithmDec->Tag() == KDigestAlgorithmTag )
+        {
+        data->iDigestAlgorithm = CCMSX509AlgorithmIdentifier::NewL();
+        data->iDigestAlgorithm->DecodeL( digestAlgorithmDec->GetContentDER() );
+        sequenceCounter++;
+        }
+
+    // decode encapContentInfo
+    if( sequenceCounter == itemCount )
+        {
+        User::Leave( KErrArgument );
+        }
+    data->iEncapContentInfo = CCMSEncapsulatedContentInfo::NewL();
+    data->iEncapContentInfo->DecodeL(
+        items->At( sequenceCounter++)->Encoding() );
+
+    // decode authenticatedAttributes, if exist
+    if( sequenceCounter == itemCount )
+        {
+        User::Leave( KErrArgument );
+        }
+    TASN1DecGeneric* authAttributesDec = items->At( sequenceCounter );
+    if( authAttributesDec->Tag() == KAuthenticatedAttributesTag )
+        {
+        data->iAuthenticatedAttributes = DecodeAttributesL( authAttributesDec );
+        sequenceCounter++;
+        }
+
+    // decode mac
+    if( sequenceCounter == itemCount )
+        {
+        User::Leave( KErrArgument );
+        }
+    TASN1DecOctetString octetStrDec;
+    data->iMac = octetStrDec.DecodeDERL( *( items->At( sequenceCounter++ ) ) );
+
+    // decode unauthenticatedAttributes, if exist
+    if( itemCount > sequenceCounter )
+        {
+        TASN1DecGeneric* unauthAttributesDec = items->At( sequenceCounter );
+        if( unauthAttributesDec->Tag() != KUnauthenticatedAttributesTag )
+            {
+            User::Leave( KErrArgument );
+            }
+        data->iUnauthenticatedAttributes =
+            DecodeAttributesL( unauthAttributesDec );
+        }
+
+    // all done, change state
+    CleanupStack::Pop( data );
+    CleanupStack::PopAndDestroy( items );
+    delete iData;
+    iData = data;
+	}
+
+
+
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+CASN1EncBase* CCMSAuthenticatedData::EncoderLC() const
+	{
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+    // encode version
+    CASN1EncInt* version = CASN1EncInt::NewLC( iData->iVersion );
+    root->AddAndPopChildL( version );
+
+    // encode originatorInfo, if exist
+    if( iData->iOriginatorInfo )
+        {
+        CASN1EncBase* originatorInfo = iData->iOriginatorInfo->EncoderLC();
+        originatorInfo->SetTag( KOriginatorInfoTag );
+        root->AddAndPopChildL( originatorInfo );
+        }
+
+    // encode recipientInfos ::= SET OF RecipientInfo
+    CASN1EncSequence* recipientInfos = CASN1EncSequence::NewLC();
+    TInt recipientInfoCount = iData->iRecipientInfos->Count();
+    TInt i = 0;
+    for( ; i < recipientInfoCount; i++ )
+        {
+        CASN1EncBase* recipientInfo =
+            iData->iRecipientInfos->At( i )->TaggedEncoderLC();
+        recipientInfos->AddAndPopChildL( recipientInfo );
+        }
+    recipientInfos->SetTag( EASN1Set, EUniversal );
+    root->AddAndPopChildL( recipientInfos );
+    
+    // encode macAlgorithm
+    CASN1EncBase* macAlgorithm = iData->iMacAlgorithm->EncoderLC();
+    root->AddAndPopChildL( macAlgorithm );
+
+    // encode digestAlgorithm, if exist
+    if( iData->iDigestAlgorithm )
+        {
+        CASN1EncBase* digestAlgorithm = iData->iDigestAlgorithm->EncoderLC();
+        CleanupStack::Pop( digestAlgorithm );
+        
+        // CASN1EncExplicitTag takes ownership of the parameter, even
+        // if the method leaves.
+        CASN1EncExplicitTag* taggedDigestAlgorithm =
+            CASN1EncExplicitTag::NewLC( digestAlgorithm, KDigestAlgorithmTag );
+        root->AddAndPopChildL( taggedDigestAlgorithm );
+        }
+
+    // encode encapContentInfo
+    CASN1EncBase* encapContentInfo = iData->iEncapContentInfo->EncoderLC();
+    root->AddAndPopChildL( encapContentInfo );
+
+    // encode authenticatedAttributes, if exist
+    if( iData->iAuthenticatedAttributes )
+        {
+        CASN1EncSequence* authAttributes = CASN1EncSequence::NewLC();
+        TInt authAttributeCount = iData->iAuthenticatedAttributes->Count();
+        for( i = 0; i < authAttributeCount; i++ )
+            {
+            CASN1EncBase* attribute =
+                iData->iAuthenticatedAttributes->At( i )->EncoderLC();
+            authAttributes->AddAndPopChildL( attribute );
+            }
+        authAttributes->SetTag( KAuthenticatedAttributesTag );
+        root->AddAndPopChildL( authAttributes );
+        }
+
+    // encode mac
+    CASN1EncOctetString* mac = CASN1EncOctetString::NewLC( *iData->iMac );
+    root->AddAndPopChildL( mac );
+    
+    // encode unauthenticatedAttributes, if exist
+    if( iData->iUnauthenticatedAttributes )
+        {
+        CASN1EncSequence* unauthAttributes = CASN1EncSequence::NewLC();
+        TInt unauthAttributeCount = iData->iUnauthenticatedAttributes->Count();
+        for( i = 0; i < unauthAttributeCount; i++ )
+            {
+            CASN1EncBase* attribute =
+                iData->iUnauthenticatedAttributes->At( i )->EncoderLC();
+            unauthAttributes->AddAndPopChildL( attribute );
+            }
+        unauthAttributes->SetTag( KUnauthenticatedAttributesTag );
+        root->AddAndPopChildL( unauthAttributes );
+        }
+    
+    return root;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::Version()
+// Getter for Version
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCMSAuthenticatedData::Version() const
+	{
+	return iData->iVersion;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::OriginatorInfo()
+// Getter for OriginatorInfo
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSOriginatorInfo* CCMSAuthenticatedData::OriginatorInfo() const
+	{
+	return iData->iOriginatorInfo;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::RecipientInfos()
+// Getter for recipientInfos
+// -----------------------------------------------------------------------------
+EXPORT_C const CArrayPtr< CCMSRecipientInfo >&
+CCMSAuthenticatedData::RecipientInfos() const
+	{
+	return *( iData->iRecipientInfos );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::MacAlgorithm()
+// Getter for macAlgorithm
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509AlgorithmIdentifier&
+CCMSAuthenticatedData::MacAlgorithm() const
+	{
+	return *( iData->iMacAlgorithm );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::DigestAlgorithm()
+// Getter for digestAlgorithm
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509AlgorithmIdentifier*
+CCMSAuthenticatedData::DigestAlgorithm() const
+	{
+	return iData->iDigestAlgorithm;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::EncapContentInfo()
+// Getter for encapContentInfo
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSEncapsulatedContentInfo&
+CCMSAuthenticatedData::EncapContentInfo() const
+	{
+	return *( iData->iEncapContentInfo );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::AuthenticatedAttributes()
+// Getter for authenticatedAttributes
+// -----------------------------------------------------------------------------
+EXPORT_C const CArrayPtr< CCMSAttribute >*
+CCMSAuthenticatedData::AuthenticatedAttributes() const
+	{
+	return iData->iAuthenticatedAttributes;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::Mac()
+// Getter for mac
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8& CCMSAuthenticatedData::Mac() const
+	{
+	return *( iData->iMac );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::UnauthenticatedAttributes()
+// Getter for unauthenticatedAttributes
+// -----------------------------------------------------------------------------
+EXPORT_C const CArrayPtr< CCMSAttribute >*
+CCMSAuthenticatedData::UnauthenticatedAttributes() const
+	{
+	return iData->iUnauthenticatedAttributes;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::SetVersion()
+// Setter for version
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSAuthenticatedData::SetVersion( TInt aVersion )
+	{
+    iData->iVersion = aVersion;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::SetOriginatorInfoL()
+// Setter for OriginatorInfo
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSAuthenticatedData::SetOriginatorInfoL(
+    CCMSOriginatorInfo* aOriginatorInfo )
+	{
+    delete iData->iOriginatorInfo;
+    iData->iOriginatorInfo = aOriginatorInfo;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::SetRecipientInfosL()
+// Setter for recipientInfos
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSAuthenticatedData::SetRecipientInfosL(
+    CArrayPtr< CCMSRecipientInfo >* aRecipientInfos )
+	{
+    if( ( !aRecipientInfos ) || ( aRecipientInfos->Count() == 0 ) )
+        {
+        User::Leave( KErrArgument );
+        }
+    
+    if( iData->iRecipientInfos )
+        {
+        iData->iRecipientInfos->ResetAndDestroy();
+        delete iData->iRecipientInfos;
+        }
+    iData->iRecipientInfos = aRecipientInfos;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::SetMacAlgorithmL()
+// Setter for macAlgorithm
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSAuthenticatedData::SetMacAlgorithmL(
+    CCMSX509AlgorithmIdentifier* aMacAlgorithm )
+	{
+    if( !aMacAlgorithm )
+        {
+        User::Leave( KErrArgument );
+        }
+    delete iData->iMacAlgorithm;
+    iData->iMacAlgorithm = aMacAlgorithm;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::SetDigestAlgorithmL()
+// Setter for digestAlgorithm
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSAuthenticatedData::SetDigestAlgorithmL(
+    CCMSX509AlgorithmIdentifier* aDigestAlgorithm )
+	{
+    delete iData->iDigestAlgorithm;
+    iData->iDigestAlgorithm = aDigestAlgorithm;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::SetEncapContentInfoL()
+// Setter for encapContentInfo
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSAuthenticatedData::SetEncapContentInfoL(
+    CCMSEncapsulatedContentInfo* aEncapContentInfo )
+	{
+    if( !aEncapContentInfo )
+        {
+        User::Leave( KErrArgument );
+        }
+    delete iData->iEncapContentInfo;
+    iData->iEncapContentInfo = aEncapContentInfo;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::SetAuthenticatedAttributesL()
+// Setter for authenticatedAttributes
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSAuthenticatedData::SetAuthenticatedAttributesL(
+    CArrayPtr< CCMSAttribute >* aAuthenticatedAttributes )
+	{
+    if( iData->iAuthenticatedAttributes )
+        {
+        iData->iAuthenticatedAttributes->ResetAndDestroy();
+        delete iData->iAuthenticatedAttributes;
+        }
+    iData->iAuthenticatedAttributes = aAuthenticatedAttributes;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::SetMacL
+// Setter for mac
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSAuthenticatedData::SetMacL(
+    const TDesC8& aMac)
+	{
+    HBufC8* mac = aMac.AllocL();
+    delete iData->iMac;
+    iData->iMac = mac;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::SetUnauthenticatedAttributesL()
+// Setter for unauthenticatedAttributes
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSAuthenticatedData::SetUnauthenticatedAttributesL(
+    CArrayPtr< CCMSAttribute >* aUnauthenticatedAttributes )
+	{
+    if( iData->iUnauthenticatedAttributes )
+        {
+        iData->iUnauthenticatedAttributes->ResetAndDestroy();
+        delete iData->iUnauthenticatedAttributes;
+        }
+    iData->iUnauthenticatedAttributes = aUnauthenticatedAttributes;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSAuthenticatedData::DecodeAttributesL
+// Decodes an array of attributes
+// -----------------------------------------------------------------------------
+CArrayPtrFlat< CCMSAttribute >* CCMSAuthenticatedData::DecodeAttributesL(
+    TASN1DecGeneric* aAttributesDec ) // generic decoder for the sequence
+    {
+    TASN1DecSequence sequenceDecoder;
+    CArrayPtr< TASN1DecGeneric >* attributes =
+        sequenceDecoder.DecodeDERLC( *aAttributesDec );
+    TInt attributeCount = attributes->Count();
+    if( attributeCount <  1 )
+        {
+        User::Leave( KErrArgument );
+        }
+    CArrayPtrFlat< CCMSAttribute >* retVal =
+        new( ELeave ) CArrayPtrFlat< CCMSAttribute >( attributeCount );
+    CleanupStack::PushL( retVal );
+    for( TInt i = 0; i < attributeCount; i++ )
+        {
+        CCMSAttribute* attribute = CCMSAttribute::NewLC();
+        attribute->DecodeL( attributes->At( i )->Encoding() );
+        retVal->AppendL( attribute );
+        // attribute is left in cleanup stack, as retVal has not been pushed
+        // with ResetAndDestroyPushL
+        }
+    CleanupStack::Pop( attributeCount ); // all attributes
+    CleanupStack::Pop( retVal );
+    CleanupStack::PopAndDestroy( attributes );
+    return retVal;
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSCertificateChoices.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,326 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSCertificateChoices.h"
+#include "CCMSX509Certificate.h"
+#include "CCMSX509AttributeCertificate.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::CCMSCertificateChoices
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSCertificateChoices::CCMSCertificateChoices()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSCertificateChoices::ConstructL(
+    const CCMSX509Certificate& aCertificate )
+    {
+    SetCertificateL( aCertificate );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSCertificateChoices::ConstructL(
+    const CCMSX509AttributeCertificate& aAttrCert )
+    {
+    SetAttrCertL( aAttrCert );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSCertificateChoices* CCMSCertificateChoices::NewL()
+	{
+	// creating with empty/default values
+    CCMSX509Certificate* certificate = CCMSX509Certificate::NewL( );
+	CleanupStack::PushL( certificate );
+	CCMSCertificateChoices* self = NewL( *certificate );
+	CleanupStack::PopAndDestroy( certificate );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSCertificateChoices* CCMSCertificateChoices::NewLC()
+	{
+	// creating with empty/default values
+    CCMSX509Certificate* certificate = CCMSX509Certificate::NewL( );
+	CleanupStack::PushL( certificate );
+	CCMSCertificateChoices* self = NewL( *certificate );
+	CleanupStack::PopAndDestroy( certificate );
+    CleanupStack::PushL( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSCertificateChoices* CCMSCertificateChoices::NewL(
+    const CCMSX509Certificate& aCertificate )
+    {
+    CCMSCertificateChoices* self = NewLC( aCertificate );
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSCertificateChoices* CCMSCertificateChoices::NewLC(
+    const CCMSX509Certificate& aCertificate )
+    {
+    CCMSCertificateChoices* self =
+    	new( ELeave ) CCMSCertificateChoices();
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aCertificate );
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSCertificateChoices* CCMSCertificateChoices::NewL(
+    const CCMSX509AttributeCertificate& aAttrCert )
+    {
+    CCMSCertificateChoices* self = NewLC( aAttrCert );
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSCertificateChoices* CCMSCertificateChoices::NewLC(
+    const CCMSX509AttributeCertificate& aAttrCert )
+    {
+    CCMSCertificateChoices* self =
+    	new( ELeave ) CCMSCertificateChoices();
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aAttrCert );
+
+    return self;
+    }
+
+// Destructor
+CCMSCertificateChoices::~CCMSCertificateChoices()
+    {
+    delete iCertificate;
+    delete iAttrCert;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSCertificateChoices::DecodeL( const TDesC8& aRawData )
+	{
+    
+    TASN1DecGeneric decGen( aRawData );
+    decGen.InitL();
+    switch( decGen.Tag() )
+        {
+        case EASN1Sequence:
+            {
+            // check class and decode certificate
+            if( decGen.Class() != EUniversal )
+                {
+                User::Leave( KErrArgument );
+                }
+            CCMSX509Certificate* certificate = CCMSX509Certificate::NewL();
+            CleanupStack::PushL( certificate );
+            certificate->DecodeL( aRawData );
+            delete iAttrCert;
+            iAttrCert = NULL;
+            delete iCertificate;
+            iCertificate = certificate;
+            CleanupStack::Pop( certificate );
+            break;
+            }
+        case KCMSAttrCertTag:
+            {
+            // check class and decode attrCert
+            if( decGen.Class() != EContextSpecific )
+                {
+                User::Leave( KErrArgument );
+                }
+            CCMSX509AttributeCertificate* attrCert =
+                CCMSX509AttributeCertificate::NewL();
+            CleanupStack::PushL( attrCert );
+            attrCert->DecodeImplicitTagL( aRawData, KCMSAttrCertTag );
+            delete iCertificate;
+            iCertificate = NULL;
+            delete iAttrCert;
+            iAttrCert = attrCert;
+            CleanupStack::Pop( attrCert );
+            break;
+            }
+        default:
+            {
+            User::Leave( KErrArgument );
+            }
+        }
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::EncodeL
+// Encrypts this instance to descriptor
+// -----------------------------------------------------------------------------
+
+void CCMSCertificateChoices::EncodeL( HBufC8*& aResult ) const
+	{
+	CASN1EncBase* root = EncoderLC();
+
+	// encode the object in a DER encoding
+    HBufC8* der = HBufC8::NewMaxLC( root->LengthDER() );
+    TPtr8 pder( der->Des() );
+    TUint pos = 0;
+    root->WriteDERL( pder, pos );
+    CleanupStack::Pop( der );
+    aResult = der;
+
+	CleanupStack::PopAndDestroy( root );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSCertificateChoices::EncoderLC() const
+	{
+    if( iCertificate )
+        {
+        return iCertificate->EncoderLC();
+        }
+    else
+        {
+        CASN1EncBase* encoder = iAttrCert->EncoderLC();
+        encoder->SetTag( KCMSAttrCertTag );
+        return encoder;
+        }
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::Certificate
+// certificate getter.
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509Certificate*
+CCMSCertificateChoices::Certificate() const
+	{
+	return iCertificate;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::AttrCert
+// attrCert getter.
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509AttributeCertificate*
+CCMSCertificateChoices::AttrCert() const
+	{
+	return iAttrCert;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::SetCertificateL
+// Certificate setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSCertificateChoices::SetCertificateL(
+	const CCMSX509Certificate& aCertificate )
+	{
+    CCMSX509Certificate* certificate = CCMSX509Certificate::NewL(
+        aCertificate.SerialNumber(),
+        aCertificate.Signature(),
+        aCertificate.Issuer(),
+        aCertificate.Validity(),
+        aCertificate.Subject(),
+        aCertificate.SubjectPublicKeyInfo(),
+        aCertificate.AlgorithmIdentifier(),
+        aCertificate.Encrypted() );
+    CleanupStack::PushL( certificate );
+    certificate->SetVersion( aCertificate.Version() );
+    const TDesC8* issuerUniqueIdentifier = aCertificate.IssuerUniqueIdentifier();
+    if( issuerUniqueIdentifier )
+        {
+        certificate->SetIssuerUniqueIdentifierL( *issuerUniqueIdentifier );
+        }
+    const TDesC8* subjectUniqueIdentifier =
+        aCertificate.SubjectUniqueIdentifier();
+    if( subjectUniqueIdentifier )
+        {
+        certificate->SetSubjectUniqueIdentifierL( *subjectUniqueIdentifier );
+        }
+    delete iAttrCert;
+    iAttrCert = NULL;
+    delete iCertificate;
+    iCertificate = certificate;
+    CleanupStack::Pop( certificate );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSCertificateChoices::SetAttrCertL
+// AttrCert setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSCertificateChoices::SetAttrCertL(
+	const CCMSX509AttributeCertificate& aAttrCert )
+	{
+    CCMSX509AttributeCertificate* attrCert = CCMSX509AttributeCertificate::NewL(
+        aAttrCert.Info(),
+        aAttrCert.AlgorithmIdentifier(),
+        aAttrCert.Encrypted() );
+    delete iCertificate;
+    iCertificate = NULL;
+    delete iAttrCert;
+    iAttrCert = attrCert;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSContentInfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,205 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSContentInfo.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KMinNumberOfSubModules = 2;
+const TInt KMaxNumberOfSubModules = 2;
+const TUint8 KContentTag = 0;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSContentInfo::CCMSContentInfo
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSContentInfo::CCMSContentInfo()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSContentInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSContentInfo::ConstructL()
+    {
+	// creating with empty values
+	SetContentTypeL( KNullDesC() );
+    SetContentL( KNullDesC8() );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSContentInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSContentInfo::ConstructL(
+	const TDesC& aContentType )
+    {
+	SetContentTypeL( aContentType );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSContentInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSContentInfo::ConstructL(
+	const TDesC& aContentType,
+    const TDesC8& aContent )
+    {
+	SetContentTypeL( aContentType );
+    SetContentL( aContent );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSContentInfo::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSContentInfo* CCMSContentInfo::NewLC()
+	{
+    CCMSContentInfo* self = new( ELeave ) CCMSContentInfo();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSContentInfo::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSContentInfo* CCMSContentInfo::NewLC(
+    const TDesC& aContentType,
+    const TDesC8& aContent )
+	{
+    CCMSContentInfo* self = new( ELeave ) CCMSContentInfo();
+    CleanupStack::PushL( self );
+    self->ConstructL( aContentType, aContent );
+    return self;
+	}
+
+// Destructor
+CCMSContentInfo::~CCMSContentInfo()
+    {
+    delete iContent;
+	delete iContentType;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSContentInfo::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSContentInfo::DecodeL( const TDesC8& aRawData )
+	{
+	CArrayPtr<TASN1DecGeneric>* itemsData = DecodeSequenceLC( aRawData,
+															  KMinNumberOfSubModules,
+															  KMaxNumberOfSubModules );
+	// we would not get this far if there is not 2
+	// decoding attribute type
+	TASN1DecObjectIdentifier decOid;
+	HBufC* oid = decOid.DecodeDERL( *itemsData->At( 0 ) );
+	delete iContentType;
+	iContentType = oid;
+
+	// decoding content
+	HBufC8* contDesc = NULL;
+    TASN1DecGeneric taggedContent( *itemsData->At( 1 ) );
+    if( taggedContent.Tag() != KContentTag )
+        {
+        User::Leave( KErrArgument );
+        }
+    contDesc = taggedContent.GetContentDER().AllocL();
+
+	delete iContent;
+	iContent = contDesc;
+	CleanupStack::PopAndDestroy( itemsData );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSContentInfo::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+CASN1EncBase* CCMSContentInfo::EncoderLC() const
+	{
+	CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+	// add attribute type
+	CASN1EncObjectIdentifier* oid = CASN1EncObjectIdentifier::NewLC( *iContentType );
+	root->AddAndPopChildL( oid );
+
+	// add content
+    CASN1EncEncoding* content = CASN1EncEncoding::NewL( *iContent );
+    // explicitly tagged to 0
+    // Takes ownership of the encoder, *including* the case when
+    // this method leaves.
+    CASN1EncExplicitTag* explicitTag =
+        CASN1EncExplicitTag::NewLC( content, KContentTag );
+    root->AddAndPopChildL( explicitTag );
+	return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSContentInfo::Content
+// Getter for content
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8& CCMSContentInfo::Content() const
+	{
+	return *iContent;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSContentInfo::SetContentL
+// Setter for content, takes copy
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSContentInfo::SetContentL( const TDesC8& aContent )
+	{
+	HBufC8* tmp = aContent.AllocL();
+	delete iContent;
+	iContent = tmp;
+	}
+
+
+// -----------------------------------------------------------------------------
+// CCMSContentInfo::ContentType
+// Getter for content type
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC& CCMSContentInfo::ContentType() const
+	{
+	return *iContentType;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSContentInfo::SetContentTypeL
+// Setter for content type, takes copy
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSContentInfo::SetContentTypeL( const TDesC& aContentType )
+	{
+	HBufC* tmp = aContentType.AllocL();
+	delete iContentType;
+	iContentType = tmp;
+	}
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSEncapsulatedContentInfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,209 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSEncapsulatedContentInfo.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KMinNumberOfSubModules = 1;
+const TInt KMaxNumberOfSubModules = 2;
+const TUint8 KContentTag = 0;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSEncapsulatedContentInfo::CCMSEncapsulatedContentInfo
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSEncapsulatedContentInfo::CCMSEncapsulatedContentInfo()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSEncapsulatedContentInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSEncapsulatedContentInfo::ConstructL()
+    {
+	// creating with empty values
+	CCMSContentInfo::ConstructL();
+	SetContentL( NULL );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSEncapsulatedContentInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSEncapsulatedContentInfo::ConstructL(
+	const TDesC& aContentType,
+	const TDesC8* aContent )
+    {
+	CCMSContentInfo::ConstructL( aContentType );
+	SetContentL( aContent );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSEncapsulatedContentInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSEncapsulatedContentInfo* CCMSEncapsulatedContentInfo::NewL()
+	{
+	CCMSEncapsulatedContentInfo* self = NewLC();
+    CleanupStack::Pop( self );
+    return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSEncapsulatedContentInfo::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSEncapsulatedContentInfo* CCMSEncapsulatedContentInfo::NewLC()
+	{
+	CCMSEncapsulatedContentInfo* self = new( ELeave ) CCMSEncapsulatedContentInfo();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSEncapsulatedContentInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSEncapsulatedContentInfo* CCMSEncapsulatedContentInfo::NewL(
+	const TDesC& aContentType,
+	const TDesC8* aContent )
+    {
+    CCMSEncapsulatedContentInfo* self = NewLC( aContentType, aContent );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSEncapsulatedContentInfo::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSEncapsulatedContentInfo* CCMSEncapsulatedContentInfo::NewLC(
+	const TDesC& aContentType,
+	const TDesC8* aContent )
+    {
+    CCMSEncapsulatedContentInfo* self = new( ELeave ) CCMSEncapsulatedContentInfo();
+    CleanupStack::PushL( self );
+    self->ConstructL( aContentType, aContent );
+    return self;
+    }
+
+// Destructor
+CCMSEncapsulatedContentInfo::~CCMSEncapsulatedContentInfo()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSEncapsulatedContentInfo::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSEncapsulatedContentInfo::DecodeL( const TDesC8& aRawData )
+	{
+	CArrayPtr<TASN1DecGeneric>* itemsData = DecodeSequenceLC( aRawData,
+															  KMinNumberOfSubModules,
+															  KMaxNumberOfSubModules );
+	// we would not get this far if there is not atleast one
+	// decoding attribute type
+	TASN1DecObjectIdentifier decOid;
+	HBufC* oid = decOid.DecodeDERL( *itemsData->At( 0 ) );
+	delete iContentType;
+	iContentType = oid;
+
+	// decoding possible content
+	HBufC8* contDesc = NULL;
+	if( itemsData->Count() > 1 )
+		{
+		TASN1DecGeneric taggedContent( *itemsData->At( 1 ) );
+		if( taggedContent.Tag() != KContentTag )
+			{
+			User::Leave( KErrArgument );
+			}
+		TASN1DecOctetString content;
+		TInt pos = 0;
+		contDesc = content.DecodeDERL( taggedContent.GetContentDER(), pos );
+		}
+	delete iContent;
+	iContent = contDesc;
+	CleanupStack::PopAndDestroy( itemsData );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSEncapsulatedContentInfo::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSEncapsulatedContentInfo::EncoderLC() const
+	{
+	CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+	// add attribute type
+	CASN1EncObjectIdentifier* oid = CASN1EncObjectIdentifier::NewLC( *iContentType );
+	root->AddAndPopChildL( oid );
+
+	// add possible content
+	if( iContent )
+		{
+		CASN1EncOctetString* content = CASN1EncOctetString::NewL( *iContent );
+		// explicitly tagged to 0
+		// Takes ownership of the encoder, *including* the case when
+		// this method leaves.
+		CASN1EncExplicitTag* explicitTag =
+			CASN1EncExplicitTag::NewLC( content, KContentTag );
+		root->AddAndPopChildL( explicitTag );
+		}
+	return root;
+	}
+// -----------------------------------------------------------------------------
+// CCMSEncapsulatedContentInfo::Content
+// Getter for content
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8* CCMSEncapsulatedContentInfo::Content() const
+	{
+	return iContent;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSEncapsulatedContentInfo::SetContentL
+// Setter for content, takes copy
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSEncapsulatedContentInfo::SetContentL( const TDesC8* aContent )
+	{
+	HBufC8* tmp = NULL;
+	if( aContent )
+		{
+		tmp = aContent->AllocL();
+		}
+	delete iContent;
+	iContent = tmp;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSIssuerAndSerialNumber.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,189 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSIssuerAndSerialNumber.h"
+#include <x500dn.h>
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KNumberOfSubModules = 2;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSIssuerAndSerialNumber::CCMSIssuerAndSerialNumber
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSIssuerAndSerialNumber::CCMSIssuerAndSerialNumber()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSIssuerAndSerialNumber::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSIssuerAndSerialNumber::ConstructL(
+	const CX500DistinguishedName& aIssuerName,
+	const TDesC8& aSerialNumber )
+    {
+	SetIssuerNameL( aIssuerName );
+	SetSerialNumberL( aSerialNumber );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSIssuerAndSerialNumber::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSIssuerAndSerialNumber* CCMSIssuerAndSerialNumber::NewL()
+	{
+	// creating with empty values
+	CArrayPtr<CX520AttributeTypeAndValue>* empty =
+				new(ELeave) CArrayPtrFlat<CX520AttributeTypeAndValue>( 1 );
+	CleanupStack::PushL( empty );
+	CX500DistinguishedName* issuer = CX500DistinguishedName::NewL( *empty );
+	CleanupStack::PushL( issuer );
+	CCMSIssuerAndSerialNumber* self = NewL( *issuer, KNullDesC8() );
+	CleanupStack::PopAndDestroy( issuer );
+	CleanupStack::PopAndDestroy( empty );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSIssuerAndSerialNumber::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSIssuerAndSerialNumber* CCMSIssuerAndSerialNumber::NewL(
+	const CX500DistinguishedName& aIssuerName,
+	const TDesC8& aSerialNumber )
+    {
+    CCMSIssuerAndSerialNumber* self =
+    	new( ELeave ) CCMSIssuerAndSerialNumber();
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aIssuerName, aSerialNumber );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+
+// Destructor
+CCMSIssuerAndSerialNumber::~CCMSIssuerAndSerialNumber()
+    {
+	delete iIssuerName;
+	delete iSerialNumber;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSIssuerAndSerialNumber::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSIssuerAndSerialNumber::DecodeL( const TDesC8& aRawData )
+	{
+	CArrayPtr<TASN1DecGeneric>* itemsData = DecodeSequenceLC( aRawData,
+															  KNumberOfSubModules,
+															  KNumberOfSubModules );
+	// we would not get this far if there is not 2 elements
+
+	// decoding name
+	CX500DistinguishedName* name =
+			CX500DistinguishedName::NewL( itemsData->At( 0 )->Encoding() );
+	delete iIssuerName;
+	iIssuerName = name;
+
+	// deocoding serial number
+	TASN1DecGeneric gen( *itemsData->At( 1 ) );
+	gen.InitL();
+	HBufC8* tmp = gen.GetContentDER().AllocL();
+	delete iSerialNumber;
+	iSerialNumber = tmp;
+
+	CleanupStack::PopAndDestroy( itemsData );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSIssuerAndSerialNumber::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSIssuerAndSerialNumber::EncoderLC() const
+	{
+	CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+	// add issuer name
+	CASN1EncSequence* issuerName = iIssuerName->EncodeASN1LC();
+	root->AddAndPopChildL( issuerName );
+
+	// add serial number
+	CASN1EncOctetString* serial = CASN1EncOctetString::NewLC( *iSerialNumber );
+	// changing tag to integer
+	serial->SetTag( EASN1Integer, EUniversal );
+	root->AddAndPopChildL( serial );
+	return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSIssuerAndSerialNumber::IssuerName
+// Issuer name getter
+// -----------------------------------------------------------------------------
+EXPORT_C const CX500DistinguishedName& CCMSIssuerAndSerialNumber::IssuerName() const
+	{
+	return *iIssuerName;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSIssuerAndSerialNumber::SerialNumber
+// Serial number getter
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8& CCMSIssuerAndSerialNumber::SerialNumber() const
+	{
+	return *iSerialNumber;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSIssuerAndSerialNumber::SetIssuerNameL
+// Issuer name setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSIssuerAndSerialNumber::SetIssuerNameL(
+	const CX500DistinguishedName& aIssuerName )
+	{
+	CX500DistinguishedName* name = CX500DistinguishedName::NewL( aIssuerName );
+	delete iIssuerName;
+	iIssuerName = name;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSIssuerAndSerialNumber::SetSerialNumber
+// Serial number setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSIssuerAndSerialNumber::SetSerialNumberL(
+	const TDesC8& aSerialNumber )
+	{
+	HBufC8* tmp = aSerialNumber.AllocL();
+	delete iSerialNumber;
+	iSerialNumber = tmp;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSKEKRecipientInfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,268 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSKEKRecipientInfo.h"
+#include "CCMSX509AlgorithmIdentifier.h"
+#include "CCMSKeyIdentifier.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KNumberOfSubModules = 4;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSKEKRecipientInfo::CCMSKEKRecipientInfo
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKEKRecipientInfo::CCMSKEKRecipientInfo( )
+    : CCMSRecipientInfo( KCMSKEKRecipientInfoVersion )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKEKRecipientInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSKEKRecipientInfo::ConstructL(
+    const CCMSKeyIdentifier& aKekid,
+    const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+	const TDesC8& aEncryptedKey )
+    {
+    BaseConstructL( aKeyEncryptionAlgorithm );
+    SetKekidL( aKekid );
+	SetEncryptedKeyL( aEncryptedKey );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKEKRecipientInfo::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKEKRecipientInfo* CCMSKEKRecipientInfo::NewLC()
+	{
+	CCMSKEKRecipientInfo* self =
+    	new( ELeave ) CCMSKEKRecipientInfo( );
+
+    CleanupStack::PushL( self );
+    // creating with empty/default values
+    CCMSX509AlgorithmIdentifier* algorithmIdentifier =
+        CCMSX509AlgorithmIdentifier::NewL();
+    CleanupStack::PushL( algorithmIdentifier );
+    CCMSKeyIdentifier* kekid = CCMSKeyIdentifier::NewL();
+    CleanupStack::PushL( kekid );
+	self->ConstructL( *kekid, *algorithmIdentifier, KNullDesC8() );
+    CleanupStack::PopAndDestroy( 2 ); // kekid, algorithmIdentifier
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKEKRecipientInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKEKRecipientInfo* CCMSKEKRecipientInfo::NewL()
+	{
+    CCMSKEKRecipientInfo* self = NewLC();
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKEKRecipientInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKEKRecipientInfo* CCMSKEKRecipientInfo::NewL(
+    const CCMSKeyIdentifier& aKekid,
+    const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+    const TDesC8& aEncryptedKey )
+	{
+    CCMSKEKRecipientInfo* self =
+    	new( ELeave ) CCMSKEKRecipientInfo( );
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aKekid, aKeyEncryptionAlgorithm,
+                      aEncryptedKey );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// Destructor
+CCMSKEKRecipientInfo::~CCMSKEKRecipientInfo()
+    {
+	delete iEncryptedKey;
+    delete iKekid;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKEKRecipientInfo::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSKEKRecipientInfo::DecodeL( const TDesC8& aRawData )
+	{
+    TASN1DecGeneric decGen( aRawData );
+    decGen.InitL();
+    // accept only sequence or implicit [2] tag
+    if( ( decGen.Tag() != EASN1Sequence ) &&
+        ( decGen.Tag() != KCMSKEKRecipientInfoTag ) )
+        {
+        User::Leave( KErrArgument );
+        }
+    TASN1DecSequence decSeq;
+    CArrayPtr< TASN1DecGeneric >* itemsData = decSeq.DecodeDERLC( decGen );
+    TInt count = itemsData->Count();
+    if( count != KNumberOfSubModules )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    // Decode version
+    TASN1DecGeneric versionDec( *itemsData->At( 0 ) );
+    versionDec.InitL();
+    TASN1DecInteger intDecoder;
+    TInt version = intDecoder.DecodeDERShortL( versionDec );
+
+    // decode kekid KEKIdentifier
+    CCMSKeyIdentifier* keyId = CCMSKeyIdentifier::NewL();
+    CleanupStack::PushL( keyId );
+    keyId->DecodeL( itemsData->At( 1 )->Encoding() );
+
+    // decode keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier
+    CCMSX509AlgorithmIdentifier* algId = CCMSX509AlgorithmIdentifier::NewL();
+    CleanupStack::PushL( algId );
+    algId->DecodeL( itemsData->At( 2 )->Encoding() );
+
+    // decode encryptedKey
+    TASN1DecGeneric keyDecoder( *itemsData->At( 3 ) );
+    TASN1DecOctetString octetStringDecoder;
+    keyDecoder.InitL();
+    HBufC8* tmp = octetStringDecoder.DecodeDERL( keyDecoder );
+
+    // now we have created all new members, so we can change state
+    iVersion = version;
+    delete iKekid;
+    iKekid = keyId;
+    delete iKeyEncryptionAlgorithm;
+    iKeyEncryptionAlgorithm = algId;
+    delete iEncryptedKey;
+    iEncryptedKey = tmp;
+    CleanupStack::Pop( 2 ); // algId, keyId
+    CleanupStack::PopAndDestroy( itemsData );
+	}
+
+
+// -----------------------------------------------------------------------------
+// CCMSKEKRecipientInfo::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSKEKRecipientInfo::EncoderLC() const
+	{
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+    // encode version
+    AddVersionL( root );
+
+    // encode kekid
+    HBufC8* encodedKekId = NULL;
+    iKekid->EncodeL( encodedKekId );
+    CleanupStack::PushL( encodedKekId );
+    CASN1EncEncoding* kekId = CASN1EncEncoding::NewLC( *encodedKekId );
+    root->AddAndPopChildL( kekId );
+    CleanupStack::PopAndDestroy( encodedKekId );
+
+    // encode keyEncryptionAlgorithm
+    AddKeyEncryptionAlgorithmL( root );
+
+    // encode encryptedKey
+    CASN1EncOctetString* encryptedKey =
+        CASN1EncOctetString::NewLC( *iEncryptedKey );
+    root->AddAndPopChildL( encryptedKey );
+
+    return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKEKRecipientInfo::TaggedEncoderLC
+// Returns ASN1 encoder for this instance inside tag
+// -----------------------------------------------------------------------------
+CASN1EncBase* CCMSKEKRecipientInfo::TaggedEncoderLC() const
+    {
+    CASN1EncBase* encoder = EncoderLC();
+    encoder->SetTag( KCMSKEKRecipientInfoTag );
+    return encoder;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKEKRecipientInfo::EncryptedKey
+// EncryptedKey getter
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8&
+CCMSKEKRecipientInfo::EncryptedKey() const
+	{
+	return *iEncryptedKey;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKEKRecipientInfo::Kekid
+// KEKIdentifier getter
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSKeyIdentifier&
+CCMSKEKRecipientInfo::Kekid() const
+	{
+	return *iKekid;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKEKRecipientInfo::SetEncryptedKeyL
+// EncryptedKey setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSKEKRecipientInfo::SetEncryptedKeyL(
+	const TDesC8& aEncryptedKey )
+	{
+    HBufC8* encryptedKey = aEncryptedKey.AllocL();
+    delete iEncryptedKey;
+    iEncryptedKey = encryptedKey;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKEKRecipientInfo::SetKekidL
+// iKekid setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSKEKRecipientInfo::SetKekidL(
+	const CCMSKeyIdentifier& aKekid )
+	{
+    CCMSKeyIdentifier* keyId = CCMSKeyIdentifier::NewL( aKekid.KeyIdentifier() );
+    CleanupStack::PushL( keyId );
+    const TTime* date = keyId->Date();
+    if( date )
+        {
+        keyId->SetDateL( *date );
+        }
+    CleanupStack::Pop( keyId );
+    delete iKekid;
+    iKekid = keyId;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSKeyAgreeRecipientInfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,482 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSKeyAgreeRecipientInfo.h"
+#include "CCMSX509AlgorithmIdentifier.h"
+#include "CCMSOriginatorIdentifierOrKey.h"
+#include "CCMSRecipientEncryptedKey.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KMinNumberOfSubModules = 4;
+const TInt KMaxNumberOfSubModules = 5;
+const TTagType KOriginatorTag = 0;
+const TTagType KUkmTag = 1;
+const TInt KDefaultGranularity = 1;
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::CCMSKeyAgreeRecipientInfo
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyAgreeRecipientInfo::CCMSKeyAgreeRecipientInfo( )
+    : CCMSRecipientInfo( KCMSKeyAgreeRecipientInfoVersion )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSKeyAgreeRecipientInfo::ConstructL( )
+    {
+    // creates empty/default values
+    CCMSX509AlgorithmIdentifier* algorithm = CCMSX509AlgorithmIdentifier::NewL( );
+    CleanupStack::PushL( algorithm );
+    BaseConstructL( *algorithm );
+    CleanupStack::PopAndDestroy( algorithm );
+
+    iOriginator = CCMSOriginatorIdentifierOrKey::NewL( );
+    iRecipientEncryptedKeys = new( ELeave )
+        CArrayPtrFlat< CCMSRecipientEncryptedKey >( KDefaultGranularity );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSKeyAgreeRecipientInfo::ConstructL(
+    const CCMSOriginatorIdentifierOrKey& aOriginator,
+    const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+    const CArrayPtr< CCMSRecipientEncryptedKey >& aRecipientEncryptedKeys )
+    {
+    BaseConstructL( aKeyEncryptionAlgorithm );
+    SetOriginatorL( aOriginator );
+    SetRecipientEncryptedKeysL( aRecipientEncryptedKeys );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSKeyAgreeRecipientInfo::ConstructL(
+    const CCMSOriginatorIdentifierOrKey& aOriginator,
+    const TDesC8& aUkm,
+    const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+    const CArrayPtr< CCMSRecipientEncryptedKey >& aRecipientEncryptedKeys )
+    {
+    ConstructL( aOriginator, aKeyEncryptionAlgorithm, aRecipientEncryptedKeys );
+    SetUserKeyingMaterialL( aUkm );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyAgreeRecipientInfo* CCMSKeyAgreeRecipientInfo::NewLC()
+	{
+	// creating with empty/default values
+    CCMSKeyAgreeRecipientInfo* self = new( ELeave ) CCMSKeyAgreeRecipientInfo( );
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyAgreeRecipientInfo* CCMSKeyAgreeRecipientInfo::NewL()
+	{
+	// creating with empty/default values
+    CCMSKeyAgreeRecipientInfo* self = NewLC();
+    CleanupStack::Pop( self );
+    return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyAgreeRecipientInfo* CCMSKeyAgreeRecipientInfo::NewL(
+    const CCMSOriginatorIdentifierOrKey& aOriginator,
+    const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+    const CArrayPtr< CCMSRecipientEncryptedKey >& aRecipientEncryptedKeys )
+	{
+    CCMSKeyAgreeRecipientInfo* self =
+    	new( ELeave ) CCMSKeyAgreeRecipientInfo( );
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aOriginator, aKeyEncryptionAlgorithm,
+                      aRecipientEncryptedKeys );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyAgreeRecipientInfo* CCMSKeyAgreeRecipientInfo::NewL(
+    const CCMSOriginatorIdentifierOrKey& aOriginator,
+    const TDesC8& aUkm,
+    const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+    const CArrayPtr< CCMSRecipientEncryptedKey >& aRecipientEncryptedKeys )
+	{
+    CCMSKeyAgreeRecipientInfo* self =
+    	new( ELeave ) CCMSKeyAgreeRecipientInfo( );
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aOriginator,aUkm, aKeyEncryptionAlgorithm,
+                      aRecipientEncryptedKeys );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+
+// Destructor
+CCMSKeyAgreeRecipientInfo::~CCMSKeyAgreeRecipientInfo()
+    {
+	delete iOriginator;
+    delete iKeyEncryptionAlgorithm;
+    if( iRecipientEncryptedKeys )
+        {
+        iRecipientEncryptedKeys->ResetAndDestroy();
+        delete iRecipientEncryptedKeys;
+        }
+    delete iUserKeyingMaterial;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSKeyAgreeRecipientInfo::DecodeL( const TDesC8& aRawData )
+	{
+    TASN1DecGeneric decGen( aRawData );
+    decGen.InitL();
+    // accept only sequence or implicit [1] tag
+    if( ( decGen.Tag() != EASN1Sequence ) &&
+        ( decGen.Tag() != KCMSKeyAgreeRecipientInfoTag ) )
+        {
+        User::Leave( KErrArgument );
+        }
+    TASN1DecSequence decSeq;
+    CArrayPtr< TASN1DecGeneric >* itemsData = decSeq.DecodeDERLC( decGen );
+    TInt count = itemsData->Count();
+    if( ( count < KMinNumberOfSubModules ) ||
+        ( count > KMaxNumberOfSubModules ) )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    TInt sequenceCounter = 0;
+
+    // Decode version
+    TASN1DecGeneric versionDec( *itemsData->At( sequenceCounter++ ) );
+    versionDec.InitL();
+    TASN1DecInteger intDecoder;
+    TInt version = intDecoder.DecodeDERShortL( versionDec );
+
+    // decode originator [0] EXPLICIT OriginatorIdentifierOrKey
+    TASN1DecGeneric taggedOriginatorDec( *itemsData->At( sequenceCounter++ ) );
+    if( taggedOriginatorDec.Tag() != KOriginatorTag )
+        {
+        User::Leave( KErrArgument );
+        }
+    CCMSOriginatorIdentifierOrKey* originator =
+        CCMSOriginatorIdentifierOrKey::NewL();
+    CleanupStack::PushL( originator );
+    originator->DecodeL( taggedOriginatorDec.GetContentDER() );
+
+    // decode ukm [1] EXPLICIT UserKeyingMaterial OPTIONAL
+    HBufC8* ukm = NULL;
+    TASN1DecGeneric taggedUkmDec( *itemsData->At( sequenceCounter ) );
+    if( taggedUkmDec.Tag() == KUkmTag )
+        {
+        TASN1DecOctetString octetStringDecoder;
+        TASN1DecGeneric ukmDec( taggedUkmDec.GetContentDER() );
+        ukmDec.InitL();
+        ukm = octetStringDecoder.DecodeDERL( ukmDec );
+        CleanupStack::PushL( ukm );
+        sequenceCounter++;
+        if( itemsData->Count() < KMaxNumberOfSubModules )
+            {
+            User::Leave( KErrArgument );
+            }
+        }
+
+    // decode keyEncryptionAlgorithm
+    CCMSX509AlgorithmIdentifier* algId = CCMSX509AlgorithmIdentifier::NewL();
+    CleanupStack::PushL( algId );
+    algId->DecodeL( itemsData->At( sequenceCounter++ )->Encoding() );
+
+    // decode recipientEncryptedKeys
+    CArrayPtr< TASN1DecGeneric >* keysData =
+        DecodeSequenceLC( itemsData->At( sequenceCounter )->Encoding() );
+    TInt keyCount = keysData->Count();
+    CArrayPtr< CCMSRecipientEncryptedKey >* keys = NULL;
+    if( keyCount > 0 )
+        {
+        keys = new( ELeave ) CArrayPtrFlat< CCMSRecipientEncryptedKey >(
+            keyCount );
+        CleanupStack::PushL( keys );
+
+        for( TInt i = 0; i < keyCount; i++ )
+            {
+            CCMSRecipientEncryptedKey* key = CCMSRecipientEncryptedKey::NewL();
+            CleanupStack::PushL( key );
+            key->DecodeL( keysData->At( i )->Encoding() );
+            keys->AppendL( key );
+            }
+        CleanupStack::Pop( keyCount ); // key
+        }
+    else
+        {
+        keys = new( ELeave ) CArrayPtrFlat< CCMSRecipientEncryptedKey >( 1 );
+        CleanupStack::PushL( keys );
+        }
+
+    // everything has been decoded, now we can change state
+    iVersion = version;
+    delete iOriginator;
+    iOriginator = originator;
+    delete iUserKeyingMaterial;
+    iUserKeyingMaterial = ukm;
+    delete iKeyEncryptionAlgorithm;
+    iKeyEncryptionAlgorithm = algId;
+    if( iRecipientEncryptedKeys )
+        {
+        iRecipientEncryptedKeys->ResetAndDestroy();
+        delete iRecipientEncryptedKeys;
+        }
+    iRecipientEncryptedKeys = keys;
+
+    CleanupStack::Pop( keys );
+    CleanupStack::PopAndDestroy( keysData );
+    CleanupStack::Pop( algId );
+    if( ukm )
+        {
+        CleanupStack::Pop( ukm );
+        }
+    CleanupStack::Pop( originator );
+    CleanupStack::PopAndDestroy( itemsData );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSKeyAgreeRecipientInfo::EncoderLC() const
+	{
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+    // encode version
+    AddVersionL( root );
+
+    // encode originator [0] EXPLICIT OriginatorIdentifierOrKey,
+    CASN1EncBase* originator = iOriginator->EncoderLC();
+
+    // CASN1EncExplicitTag takes ownership of originator even when leaving
+    CleanupStack::Pop( originator );
+    CASN1EncExplicitTag* taggedOriginator =
+        CASN1EncExplicitTag::NewLC( originator, KOriginatorTag );
+    root->AddAndPopChildL( taggedOriginator );
+
+    // encode ukm [1] EXPLICIT UserKeyingMaterial OPTIONAL
+    if( iUserKeyingMaterial )
+        {
+        CASN1EncOctetString* ukm =
+            CASN1EncOctetString::NewL( *iUserKeyingMaterial );
+        CASN1EncExplicitTag* taggedUkm =
+            CASN1EncExplicitTag::NewLC( ukm, KUkmTag );
+        root->AddAndPopChildL( taggedUkm );
+        }
+
+    // encode keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier
+    AddKeyEncryptionAlgorithmL( root );
+
+    // encode RecipientEncryptedKeys ::= SEQUENCE OF RecipientEncryptedKey
+    CASN1EncSequence* recipientEncryptedKeys = CASN1EncSequence::NewLC();
+    TInt keyCount = iRecipientEncryptedKeys->Count();
+    for( TInt i = 0; i < keyCount; i++ )
+        {
+        HBufC8* encodedKey = NULL;
+        iRecipientEncryptedKeys->At( i )->EncodeL( encodedKey );
+        CleanupStack::PushL( encodedKey );
+        CASN1EncEncoding* singleKey = CASN1EncEncoding::NewLC( *encodedKey );
+        recipientEncryptedKeys->AddAndPopChildL( singleKey );
+        CleanupStack::PopAndDestroy( encodedKey );
+        }
+    root->AddAndPopChildL( recipientEncryptedKeys );
+
+    return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::TaggedEncoderLC
+// Returns ASN1 encoder for this instance inside tag
+// -----------------------------------------------------------------------------
+CASN1EncBase* CCMSKeyAgreeRecipientInfo::TaggedEncoderLC() const
+    {
+    CASN1EncBase* encoder = EncoderLC();
+    encoder->SetTag( KCMSKeyAgreeRecipientInfoTag );
+    return encoder;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::Originator
+// Originator getter
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSOriginatorIdentifierOrKey&
+CCMSKeyAgreeRecipientInfo::Originator() const
+	{
+	return *iOriginator;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::RecipientEncryptedKeys
+// RecipientEncryptedKeys getter
+// -----------------------------------------------------------------------------
+EXPORT_C const CArrayPtr< CCMSRecipientEncryptedKey >&
+CCMSKeyAgreeRecipientInfo::RecipientEncryptedKeys() const
+	{
+	return *iRecipientEncryptedKeys;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::UserKeyingMaterial
+// UserKeyingMaterial getter
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8*
+CCMSKeyAgreeRecipientInfo::UserKeyingMaterial() const
+	{
+	return iUserKeyingMaterial;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::SetOriginatorL
+// Originator setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSKeyAgreeRecipientInfo::SetOriginatorL(
+	const CCMSOriginatorIdentifierOrKey& aOriginator )
+	{
+    CCMSOriginatorIdentifierOrKey* originator = NULL;
+    switch( aOriginator.Type() )
+        {
+        case CCMSOriginatorIdentifierOrKey::ESubjectKeyIdentifier:
+            {
+            originator = CCMSOriginatorIdentifierOrKey::NewL(
+                aOriginator.SubjectKeyIdentifierL() );
+            break;
+            }
+        case CCMSOriginatorIdentifierOrKey::EOriginatorKey:
+            {
+            originator = CCMSOriginatorIdentifierOrKey::NewL(
+                aOriginator.OriginatorKeyL() );
+            break;
+            }
+        case CCMSOriginatorIdentifierOrKey::EIssuerAndSerialNumber:
+            {
+            originator = CCMSOriginatorIdentifierOrKey::NewL(
+                aOriginator.IssuerAndSerialNumberL() );
+            break;
+            }
+        default:
+            {
+            User::Leave( KErrArgument );
+            }
+        }
+    delete iOriginator;
+    iOriginator = originator;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::SetRecipientEncryptedKeysL
+// RecipientEncryptedKeys setter, deep copy
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSKeyAgreeRecipientInfo::SetRecipientEncryptedKeysL(
+	const CArrayPtr< CCMSRecipientEncryptedKey >& aRecipientEncryptedKeys )
+	{
+    TInt keyCount = aRecipientEncryptedKeys.Count();
+    CArrayPtr< CCMSRecipientEncryptedKey >* keys = NULL;
+    if( keyCount > 0 )
+        {
+        keys = new( ELeave ) CArrayPtrFlat< CCMSRecipientEncryptedKey >(
+            keyCount );
+        CleanupStack::PushL( keys );
+        for( TInt i = 0; i < keyCount; i++ )
+            {
+            const CCMSRecipientEncryptedKey* key = aRecipientEncryptedKeys[ i ];
+            const CCMSIssuerAndSerialNumber* issuer = key->IssuerAndSerialNumber();
+            const TDesC8& encryptedKey = key->EncryptedKey();
+            CCMSRecipientEncryptedKey* newKey = NULL;
+            if( issuer )
+                {
+                newKey = CCMSRecipientEncryptedKey::NewL(
+                    *issuer, encryptedKey );
+                }
+            else
+                {
+                newKey = CCMSRecipientEncryptedKey::NewL( *( key->RKeyId() ),
+                                                          encryptedKey );
+                }
+            CleanupStack::PushL( newKey );
+            keys->AppendL( newKey );
+            }
+        CleanupStack::Pop( keyCount ); // newKeys
+        CleanupStack::Pop( keys );
+        }
+    else
+        {
+        keys = new( ELeave ) CArrayPtrFlat< CCMSRecipientEncryptedKey >( 1 );
+        }
+    if( iRecipientEncryptedKeys )
+        {
+        iRecipientEncryptedKeys->ResetAndDestroy();
+        delete iRecipientEncryptedKeys;
+        }
+    iRecipientEncryptedKeys = keys;
+    }
+// -----------------------------------------------------------------------------
+// CCMSKeyAgreeRecipientInfo::SetUserKeyingMaterialL
+// UserKeyingMaterial setter.
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSKeyAgreeRecipientInfo::SetUserKeyingMaterialL(
+	const TDesC8& aUkm )
+	{
+    HBufC8* ukm = aUkm.AllocL();
+    delete iUserKeyingMaterial;
+    iUserKeyingMaterial = ukm;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSKeyIdentifier.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,267 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSKeyIdentifier.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KMinNumberOfSubModules = 1;
+const TInt KMaxNumberOfSubModules = 3;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSKeyIdentifier::CCMSKeyIdentifier
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyIdentifier::CCMSKeyIdentifier()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyIdentifier::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSKeyIdentifier::ConstructL(
+	const TDesC8& aKeyIdentifier )
+    {
+	SetKeyIdentifierL( aKeyIdentifier );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyIdentifier::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSKeyIdentifier::ConstructL(
+	const TDesC8& aKeyIdentifier,
+    const TTime& aDate )
+    {
+	SetKeyIdentifierL( aKeyIdentifier );
+    SetDateL( aDate );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyIdentifier::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyIdentifier* CCMSKeyIdentifier::NewL()
+	{
+	// creating with empty/default values
+	CCMSKeyIdentifier* self = NewL( KNullDesC8() );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyIdentifier::NewL
+// Two-phased copy constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyIdentifier* CCMSKeyIdentifier::NewL(
+    const TDesC8& aKeyIdentifier )
+	{
+    CCMSKeyIdentifier* self =
+    	new( ELeave ) CCMSKeyIdentifier();
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aKeyIdentifier );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyIdentifier::NewL
+// Two-phased copy constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyIdentifier* CCMSKeyIdentifier::NewL(
+    const TDesC8& aKeyIdentifier,
+    const TTime& aDate )
+	{
+    CCMSKeyIdentifier* self =
+    	new( ELeave ) CCMSKeyIdentifier();
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aKeyIdentifier, aDate );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// Destructor
+CCMSKeyIdentifier::~CCMSKeyIdentifier()
+    {
+	delete iKeyIdentifier;
+	delete iDate;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyIdentifier::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSKeyIdentifier::DecodeL( const TDesC8& aRawData )
+	{
+    CArrayPtr< TASN1DecGeneric >* itemsData =
+        DecodeSequenceLC( aRawData, KMinNumberOfSubModules,
+                          KMaxNumberOfSubModules );
+
+    DecodeArrayL( itemsData );
+
+    CleanupStack::PopAndDestroy( itemsData );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyIdentifier::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSKeyIdentifier::EncoderLC() const
+	{
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+    // encode the subjectKeyIdentifier
+    CASN1EncOctetString* subjectKeyIdentifier =
+        CASN1EncOctetString::NewLC( *iKeyIdentifier );
+    root->AddAndPopChildL( subjectKeyIdentifier );
+
+    // encode date if existing
+    if( iDate )
+        {
+        CASN1EncGeneralizedTime* date =
+            CASN1EncGeneralizedTime::NewLC( *iDate );
+        root->AddAndPopChildL( date );
+        }
+
+    return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyIdentifier::KeyIdentifier
+// Subject Key identifier getter
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8&
+CCMSKeyIdentifier::KeyIdentifier() const
+	{
+	return *iKeyIdentifier;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyIdentifier::Date
+// Date getter
+// -----------------------------------------------------------------------------
+EXPORT_C const TTime* CCMSKeyIdentifier::Date() const
+	{
+	return iDate;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyIdentifier::SetKeyIdentifierL
+// KeyIdentifier setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSKeyIdentifier::SetKeyIdentifierL(
+	const TDesC8& aKeyIdentifier )
+	{
+    HBufC8* subjectKeyIdentifier = aKeyIdentifier.AllocL();
+    delete iKeyIdentifier;
+    iKeyIdentifier = subjectKeyIdentifier;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyIdentifier::SetDateL
+// Date setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSKeyIdentifier::SetDateL(
+	const TTime& aDate )
+	{
+    TTime* date = new( ELeave ) TTime( aDate );
+    delete iDate;
+    iDate = date;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyIdentifier::DecodeImplicitTagL
+// Decrypts raw data with implicit tag
+// -----------------------------------------------------------------------------
+void CCMSKeyIdentifier::DecodeImplicitTagL(
+    const TDesC8& aRawData,
+    const TTagType aImplicitTag )
+    {
+    CArrayPtr< TASN1DecGeneric >* items = NULL;
+
+    // Check the tag
+    TASN1DecGeneric decGen( aRawData );
+    decGen.InitL();
+    // Accept only given tag
+    if( decGen.Tag() != aImplicitTag )
+        {
+        User::Leave( KErrArgument );
+        }
+    TASN1DecSequence decSeq;
+    items = decSeq.DecodeDERLC( decGen );
+    TInt itemCount = items->Count();
+    if( ( itemCount > KMaxNumberOfSubModules ) ||
+        ( itemCount < KMinNumberOfSubModules ) )
+        {
+        User::Leave( KErrArgument );
+        }
+    DecodeArrayL( items );
+    CleanupStack::PopAndDestroy( items );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyIdentifier::DecodeArrayL
+// Decodes data from an array of decoders
+// -----------------------------------------------------------------------------
+void CCMSKeyIdentifier::DecodeArrayL(
+    CArrayPtr< TASN1DecGeneric >* aItems )
+    {
+    // Caller should have made sure that there is at least one item
+    __ASSERT_DEBUG( ( aItems->Count() > 0 ), User::Invariant() );
+    
+    // decode subjectKeyIdentifier
+    TASN1DecGeneric gen( *aItems->At( 0 ) );
+    gen.InitL();
+    TASN1DecOctetString octetStringDecoder;
+    HBufC8* tmp =
+        octetStringDecoder.DecodeDERL( gen );
+    delete iKeyIdentifier;
+    iKeyIdentifier = tmp;
+
+    // decode date if exists
+    if( aItems->Count() > 1 )
+        {
+        TInt pos = 0;
+        TASN1DecGeneralizedTime dateDec;
+        TTime date = dateDec.DecodeDERL( aItems->At( 1 )->Encoding(), pos );
+        SetDateL( date );
+        }
+    else
+        {
+        delete iDate;
+        iDate = NULL;
+        }
+
+    // possible OtherKeyAttribute is not supported / ignored.
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSKeyTransRecipientInfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,373 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSKeyTransRecipientInfo.h"
+#include "CCMSIssuerAndSerialNumber.h"
+#include "CCMSX509AlgorithmIdentifier.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KNumberOfSubModules = 4;
+const TTagType KSubjectKeyIdentifierTag = 0;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::CCMSKeyTransRecipientInfo
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyTransRecipientInfo::CCMSKeyTransRecipientInfo( TInt aVersion)
+    : CCMSRecipientInfo( aVersion )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSKeyTransRecipientInfo::ConstructL(
+    const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber,
+    const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+	const TDesC8& aEncryptedKey )
+    {
+    BaseConstructL( aKeyEncryptionAlgorithm );
+    SetIssuerAndSerialNumberL( aIssuerAndSerialNumber );
+	SetEncryptedKeyL( aEncryptedKey );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSKeyTransRecipientInfo::ConstructL(
+    const TDesC8& aSubjectKeyIdentifier,
+    const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+	const TDesC8& aEncryptedKey )
+    {
+    BaseConstructL( aKeyEncryptionAlgorithm );
+    SetSubjectKeyIdentifierL( aSubjectKeyIdentifier );
+	SetEncryptedKeyL( aEncryptedKey );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyTransRecipientInfo* CCMSKeyTransRecipientInfo::NewLC()
+	{
+	// creating with empty/default values
+    CCMSKeyTransRecipientInfo* self =
+    	new( ELeave ) CCMSKeyTransRecipientInfo(
+            KCMSKeyTransRecipientInfoSubjectKeyIdentifierVersion );
+    CleanupStack::PushL( self );
+    CCMSX509AlgorithmIdentifier* algorithmIdentifier =
+        CCMSX509AlgorithmIdentifier::NewL();
+    CleanupStack::PushL( algorithmIdentifier );
+	self->ConstructL( KNullDesC8(), *algorithmIdentifier, KNullDesC8() );
+    CleanupStack::PopAndDestroy( algorithmIdentifier );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyTransRecipientInfo* CCMSKeyTransRecipientInfo::NewL()
+	{
+	// creating with empty/default values
+	CCMSKeyTransRecipientInfo* self = NewLC();
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyTransRecipientInfo* CCMSKeyTransRecipientInfo::NewL(
+    const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber,
+    const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+    const TDesC8& aEncryptedKey )
+	{
+    CCMSKeyTransRecipientInfo* self =
+    	new( ELeave ) CCMSKeyTransRecipientInfo(
+            KCMSKeyTransRecipientInfoIssuerAndSerialNumberVersion );
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aIssuerAndSerialNumber, aKeyEncryptionAlgorithm,
+                      aEncryptedKey );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyTransRecipientInfo* CCMSKeyTransRecipientInfo::NewLC(
+    const TDesC8& aSubjectKeyIdentifier,
+    const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+    const TDesC8& aEncryptedKey )
+	{
+    CCMSKeyTransRecipientInfo* self =
+    	new( ELeave ) CCMSKeyTransRecipientInfo(
+            KCMSKeyTransRecipientInfoSubjectKeyIdentifierVersion );
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aSubjectKeyIdentifier, aKeyEncryptionAlgorithm,
+                      aEncryptedKey );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSKeyTransRecipientInfo* CCMSKeyTransRecipientInfo::NewL(
+    const TDesC8& aSubjectKeyIdentifier,
+    const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+    const TDesC8& aEncryptedKey )
+	{
+    CCMSKeyTransRecipientInfo* self =
+        NewLC( aSubjectKeyIdentifier, aKeyEncryptionAlgorithm, aEncryptedKey );
+
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+
+// Destructor
+CCMSKeyTransRecipientInfo::~CCMSKeyTransRecipientInfo()
+    {
+	delete iEncryptedKey;
+    delete iIssuerAndSerialNumber;
+    delete iSubjectKeyIdentifier;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSKeyTransRecipientInfo::DecodeL( const TDesC8& aRawData )
+	{
+    CArrayPtr< TASN1DecGeneric >* itemsData =
+        DecodeSequenceLC( aRawData, KNumberOfSubModules, KNumberOfSubModules );
+
+    // Decode version
+    TASN1DecGeneric versionDec( *itemsData->At( 0 ) );
+    versionDec.InitL();
+    TASN1DecInteger intDecoder;
+    TInt version = intDecoder.DecodeDERShortL( versionDec );
+
+    // decode rid RecipientIdentifier
+    TASN1DecOctetString octetStringDecoder;
+    TASN1DecGeneric ridDec( *itemsData->At( 1 ) );
+    HBufC8* keyIdentifier = NULL;
+    CCMSIssuerAndSerialNumber* issuer = NULL;
+    switch( version )
+        {
+        case KCMSKeyTransRecipientInfoSubjectKeyIdentifierVersion:
+            {
+            if( ridDec.Tag() != KSubjectKeyIdentifierTag )
+                {
+                User::Leave( KErrArgument );
+                }
+            TInt pos = 0;
+            keyIdentifier = octetStringDecoder.DecodeDERL(
+                ridDec.GetContentDER(), pos );
+            CleanupStack::PushL( keyIdentifier );
+            break;
+            }
+        case KCMSKeyTransRecipientInfoIssuerAndSerialNumberVersion:
+            {
+            issuer = CCMSIssuerAndSerialNumber::NewL();
+            CleanupStack::PushL( issuer );
+            issuer->DecodeL( ridDec.Encoding() );
+            break;
+            }
+        default:
+            {
+            User::Leave( KErrArgument );
+            }
+        }
+
+    // decode keyEncryptionAlgorithm
+    CCMSX509AlgorithmIdentifier* algId = CCMSX509AlgorithmIdentifier::NewL();
+    CleanupStack::PushL( algId );
+    algId->DecodeL( itemsData->At( 2 )->Encoding() );
+
+    // decode encryptedKey
+    TASN1DecGeneric keyDecoder( *itemsData->At( 3 ) );
+    keyDecoder.InitL();
+    HBufC8* tmp = octetStringDecoder.DecodeDERL( keyDecoder );
+
+    // now we have created all new members, so we can change state
+    iVersion = version;
+    delete iSubjectKeyIdentifier;
+    iSubjectKeyIdentifier = keyIdentifier;
+    delete iIssuerAndSerialNumber;
+    iIssuerAndSerialNumber = issuer;
+    delete iKeyEncryptionAlgorithm;
+    iKeyEncryptionAlgorithm = algId;
+    delete iEncryptedKey;
+    iEncryptedKey = tmp;
+    CleanupStack::Pop( 2 ); // keyIdentifier/issuer, algId
+    CleanupStack::PopAndDestroy( itemsData );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSKeyTransRecipientInfo::EncoderLC() const
+	{
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+    // encode version
+    AddVersionL( root );
+
+    // encode rid RecipientIdentifier
+    if( iIssuerAndSerialNumber )
+        {
+        // encode issuerAndSerialNumber
+        HBufC8* encodedIssuer = NULL;
+        iIssuerAndSerialNumber->EncodeL( encodedIssuer );
+        CleanupStack::PushL( encodedIssuer );
+        CASN1EncEncoding* issuer = CASN1EncEncoding::NewLC( *encodedIssuer );
+        root->AddAndPopChildL( issuer );
+        CleanupStack::PopAndDestroy( encodedIssuer );
+        }
+    else
+        {
+        // encode subjectKeyIdentifier [0] SubjectKeyIdentifier
+        CASN1EncOctetString* subjectKeyIdentifier =
+            CASN1EncOctetString::NewL( *iSubjectKeyIdentifier );
+        CASN1EncExplicitTag* taggedIdentifier =
+            CASN1EncExplicitTag::NewLC( subjectKeyIdentifier, KSubjectKeyIdentifierTag );
+        root->AddAndPopChildL( taggedIdentifier );
+        }
+
+    // encode keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier
+    AddKeyEncryptionAlgorithmL( root );
+
+    // encode encryptedKey
+    CASN1EncOctetString* encryptedKey =
+        CASN1EncOctetString::NewLC( *iEncryptedKey );
+    root->AddAndPopChildL( encryptedKey );
+
+    return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::TaggedEncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+CASN1EncBase* CCMSKeyTransRecipientInfo::TaggedEncoderLC() const
+    {
+    return EncoderLC();
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::EncryptedKey
+// EncryptedKey getter
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8&
+CCMSKeyTransRecipientInfo::EncryptedKey() const
+	{
+	return *iEncryptedKey;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::IssuerAndSerialNumber
+// IssuerAndSerialNumber getter
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSIssuerAndSerialNumber*
+CCMSKeyTransRecipientInfo::IssuerAndSerialNumber() const
+	{
+	return iIssuerAndSerialNumber;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::SubjectKeyIdentifier
+// SubjectKeyIdentifier getter
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8*
+CCMSKeyTransRecipientInfo::SubjectKeyIdentifier() const
+	{
+	return iSubjectKeyIdentifier;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::SetEncryptedKeyL
+// EncryptedKey setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSKeyTransRecipientInfo::SetEncryptedKeyL(
+	const TDesC8& aEncryptedKey )
+	{
+    HBufC8* encryptedKey = aEncryptedKey.AllocL();
+    delete iEncryptedKey;
+    iEncryptedKey = encryptedKey;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::SetIssuerAndSerialNumberL
+// IssuerAndSerialNumber setter, deletes also SubjectKeyIdentifier and
+// sets version to KVersionIssuerAndSerialNumber
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSKeyTransRecipientInfo::SetIssuerAndSerialNumberL(
+	const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber )
+	{
+    CCMSIssuerAndSerialNumber* issuer = CCMSIssuerAndSerialNumber::NewL(
+        aIssuerAndSerialNumber.IssuerName(),
+        aIssuerAndSerialNumber.SerialNumber() );
+    delete iSubjectKeyIdentifier;
+    iSubjectKeyIdentifier = NULL;
+    delete iIssuerAndSerialNumber;
+    iIssuerAndSerialNumber = issuer;
+    iVersion = KCMSKeyTransRecipientInfoIssuerAndSerialNumberVersion;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSKeyTransRecipientInfo::SetSubjectKeyIdentifierL
+// SubjectKeyIdentifier setter. Copies parameters, deletes also
+// IssuerAndSerialNumber and set version to KVersionSubjectKeyIdentifier
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSKeyTransRecipientInfo::SetSubjectKeyIdentifierL(
+	const TDesC8& aSubjectKeyIdentifier )
+	{
+    HBufC8* identifier = aSubjectKeyIdentifier.AllocL();
+    delete iIssuerAndSerialNumber;
+    iIssuerAndSerialNumber = NULL;
+    delete iSubjectKeyIdentifier;
+    iSubjectKeyIdentifier = identifier;
+    iVersion = KCMSKeyTransRecipientInfoSubjectKeyIdentifierVersion;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSOriginatorIdentifierOrKey.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,422 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSOriginatorIdentifierOrKey.h"
+#include "CCMSIssuerAndSerialNumber.h"
+#include "CCMSOriginatorPublicKey.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::CCMSOriginatorIdentifierOrKey
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSOriginatorIdentifierOrKey::CCMSOriginatorIdentifierOrKey()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSOriginatorIdentifierOrKey::ConstructL(
+    const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber )
+    {
+    SetIssuerAndSerialNumberL( aIssuerAndSerialNumber );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSOriginatorIdentifierOrKey::ConstructL(
+    const TDesC8& aSubjectKeyIdentifier )
+    {
+    SetSubjectKeyIdentifierL( aSubjectKeyIdentifier );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSOriginatorIdentifierOrKey::ConstructL(
+    const CCMSOriginatorPublicKey& aOriginatorKey )
+    {
+    SetOriginatorKeyL( aOriginatorKey );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSOriginatorIdentifierOrKey* CCMSOriginatorIdentifierOrKey::NewL()
+	{
+	// creating with empty/default values
+    CCMSIssuerAndSerialNumber* issuer = CCMSIssuerAndSerialNumber::NewL( );
+	CleanupStack::PushL( issuer );
+	CCMSOriginatorIdentifierOrKey* self = NewL( *issuer );
+	CleanupStack::PopAndDestroy( issuer );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSOriginatorIdentifierOrKey* CCMSOriginatorIdentifierOrKey::NewL(
+    const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber)
+    {
+    CCMSOriginatorIdentifierOrKey* self =
+    	new( ELeave ) CCMSOriginatorIdentifierOrKey();
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aIssuerAndSerialNumber );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSOriginatorIdentifierOrKey* CCMSOriginatorIdentifierOrKey::NewL(
+    const TDesC8& aSubjectKeyIdentifier )
+    {
+    CCMSOriginatorIdentifierOrKey* self =
+    	new( ELeave ) CCMSOriginatorIdentifierOrKey();
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aSubjectKeyIdentifier );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSOriginatorIdentifierOrKey* CCMSOriginatorIdentifierOrKey::NewL(
+    const CCMSOriginatorPublicKey& aOriginatorKey )
+    {
+    CCMSOriginatorIdentifierOrKey* self =
+    	new( ELeave ) CCMSOriginatorIdentifierOrKey();
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aOriginatorKey );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// Destructor
+CCMSOriginatorIdentifierOrKey::~CCMSOriginatorIdentifierOrKey()
+    {
+    delete iIssuerAndSerialNumber;
+    delete iSubjectKeyIdentifier;
+    delete iOriginatorKey;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSOriginatorIdentifierOrKey::DecodeL( const TDesC8& aRawData )
+	{
+    TASN1DecGeneric decGen( aRawData );
+    decGen.InitL();
+    switch( decGen.Tag() )
+        {
+        case EASN1Sequence:
+            {
+            // check class and decode iasn
+            if( decGen.Class() != EUniversal )
+                {
+                User::Leave( KErrArgument );
+                }
+            CCMSIssuerAndSerialNumber* issuerAndSerialNumber =
+                CCMSIssuerAndSerialNumber::NewL();
+            CleanupStack::PushL( issuerAndSerialNumber );
+            issuerAndSerialNumber->DecodeL( aRawData );
+            DeleteOldValueAndChangeTypeL( EIssuerAndSerialNumber );
+            iIssuerAndSerialNumber = issuerAndSerialNumber;
+            CleanupStack::Pop( issuerAndSerialNumber );
+            break;
+            }
+        case ESubjectKeyIdentifier:
+            {
+            // check class and decode ski
+            if( decGen.Class() != EContextSpecific )
+                {
+                User::Leave( KErrArgument );
+                }
+            TASN1DecOctetString octetDecoder;
+            TInt pos = 0;
+            HBufC8* subjectKeyIdentifier =
+                octetDecoder.DecodeDERL( aRawData, pos );
+            CleanupStack::PushL( subjectKeyIdentifier );
+            DeleteOldValueAndChangeTypeL( ESubjectKeyIdentifier );
+            iSubjectKeyIdentifier = subjectKeyIdentifier;
+            CleanupStack::Pop( subjectKeyIdentifier );
+            break;
+            }
+        case EOriginatorKey:
+            {
+            // check class and decode originatorKey
+            if( decGen.Class() != EContextSpecific )
+                {
+                User::Leave( KErrArgument );
+                }
+            CCMSOriginatorPublicKey* originatorKey =
+                CCMSOriginatorPublicKey::NewL();
+            CleanupStack::PushL( originatorKey );
+            originatorKey->DecodeL( aRawData );
+            DeleteOldValueAndChangeTypeL( EOriginatorKey );
+            iOriginatorKey = originatorKey;
+            CleanupStack::Pop( originatorKey );
+            break;
+            }
+        default:
+            {
+            User::Leave( KErrArgument );
+            }
+        }
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::EncodeL
+// Encrypts this instance to descriptor
+// -----------------------------------------------------------------------------
+
+void CCMSOriginatorIdentifierOrKey::EncodeL( HBufC8*& aResult ) const
+	{
+	CASN1EncBase* root = EncoderLC();
+
+	// encode the object in a DER encoding
+    HBufC8* der = HBufC8::NewMaxLC( root->LengthDER() );
+    TPtr8 pder( der->Des() );
+    TUint pos = 0;
+    root->WriteDERL( pder, pos );
+    CleanupStack::Pop( der );
+    aResult = der;
+
+	CleanupStack::PopAndDestroy( root );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSOriginatorIdentifierOrKey::EncoderLC() const
+	{
+    switch( iType )
+        {
+        case EIssuerAndSerialNumber:
+            {
+            return iIssuerAndSerialNumber->EncoderLC();
+            }
+        case ESubjectKeyIdentifier:
+            {
+            return EncoderSubjectKeyIdentifierLC();
+            }
+        case EOriginatorKey:
+            {
+            return EncoderOriginatorKeyLC();
+            }
+        default:
+            {
+            User::Leave( KErrCorrupt );
+			return NULL;
+            }
+        }
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::Type
+// Type getter.
+// -----------------------------------------------------------------------------
+EXPORT_C CCMSOriginatorIdentifierOrKey::TType
+CCMSOriginatorIdentifierOrKey::Type() const
+	{
+	return iType;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::IssuerAndSerialNumberL
+// IssuerAndSerialNumber getter.
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSIssuerAndSerialNumber&
+CCMSOriginatorIdentifierOrKey::IssuerAndSerialNumberL() const
+	{
+    if( !iIssuerAndSerialNumber )
+        {
+        User::Leave( KErrNotFound );
+        }
+	return *iIssuerAndSerialNumber;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::SubjectKeyIdentifierL
+// SubjectKeyIdentifier getter.
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8&
+CCMSOriginatorIdentifierOrKey::SubjectKeyIdentifierL() const
+	{
+    if( !iSubjectKeyIdentifier )
+        {
+        User::Leave( KErrNotFound );
+        }
+	return *iSubjectKeyIdentifier;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::SubjectKeyIdentifierL
+// SubjectKeyIdentifier getter.
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSOriginatorPublicKey&
+CCMSOriginatorIdentifierOrKey::OriginatorKeyL() const
+	{
+    if( !iOriginatorKey )
+        {
+        User::Leave( KErrNotFound );
+        }
+	return *iOriginatorKey;
+	}
+
+
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::SetIssuerAndSerialNumberL
+// IssuerAndSerialNumber setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSOriginatorIdentifierOrKey::SetIssuerAndSerialNumberL(
+	const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber )
+	{
+    CCMSIssuerAndSerialNumber* issuerAndSerialNumber =
+        CCMSIssuerAndSerialNumber::NewL(
+            aIssuerAndSerialNumber.IssuerName(),
+            aIssuerAndSerialNumber.SerialNumber() );
+    CleanupStack::PushL( issuerAndSerialNumber );
+    DeleteOldValueAndChangeTypeL( EIssuerAndSerialNumber );
+    iIssuerAndSerialNumber = issuerAndSerialNumber;
+    CleanupStack::Pop( issuerAndSerialNumber );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::SetSubjectKeyIdentifierL
+// SubjectKeyIdentifier setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSOriginatorIdentifierOrKey::SetSubjectKeyIdentifierL(
+	const TDesC8& aSubjectKeyIdentifier )
+	{
+    HBufC8* subjectKeyIdentifier = aSubjectKeyIdentifier.AllocLC();
+    DeleteOldValueAndChangeTypeL( ESubjectKeyIdentifier );
+    iSubjectKeyIdentifier = subjectKeyIdentifier;
+    CleanupStack::Pop( subjectKeyIdentifier );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::SetOriginatorKeyL
+// OriginatorKey setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSOriginatorIdentifierOrKey::SetOriginatorKeyL(
+	const CCMSOriginatorPublicKey& aOriginatorKey )
+	{
+    CCMSOriginatorPublicKey* originatorKey =
+        CCMSOriginatorPublicKey::NewLC( aOriginatorKey );
+    DeleteOldValueAndChangeTypeL( EOriginatorKey );
+    iOriginatorKey = originatorKey;
+    CleanupStack::Pop( originatorKey );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::DeleteOldValueAndChangeType
+// Deletes old value and changes type
+// -----------------------------------------------------------------------------
+void CCMSOriginatorIdentifierOrKey::DeleteOldValueAndChangeTypeL(
+	CCMSOriginatorIdentifierOrKey::TType aNewType )
+	{
+    switch( iType )
+        {
+        case EIssuerAndSerialNumber:
+            {
+            delete iIssuerAndSerialNumber;
+            iIssuerAndSerialNumber = NULL;
+            break;
+            }
+        case ESubjectKeyIdentifier:
+            {
+            delete iSubjectKeyIdentifier;
+            iSubjectKeyIdentifier = NULL;
+            break;
+            }
+        case EOriginatorKey:
+            {
+            delete iOriginatorKey;
+            iOriginatorKey = NULL;
+            break;
+            }
+        default:
+            {
+            User::Leave( KErrCorrupt );
+            }
+        }
+    iType = aNewType;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::EncoderSubjectKeyIdentifierLC
+// returns encoder for the subjectKeyIdentifier
+// -----------------------------------------------------------------------------
+CASN1EncBase*
+CCMSOriginatorIdentifierOrKey::EncoderSubjectKeyIdentifierLC() const
+	{
+    CASN1EncOctetString* subjectKeyIdentifier =
+        CASN1EncOctetString::NewLC( *iSubjectKeyIdentifier );
+    subjectKeyIdentifier->SetTag( ESubjectKeyIdentifier );
+
+	return subjectKeyIdentifier;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorIdentifierOrKey::EncoderOriginatorKeyL
+// Returns encoder for the OriginatorKey value
+// -----------------------------------------------------------------------------
+CASN1EncBase* CCMSOriginatorIdentifierOrKey::EncoderOriginatorKeyLC() const
+	{
+    CASN1EncBase* originatorKey = iOriginatorKey->EncoderLC();
+    originatorKey->SetTag( EOriginatorKey );
+
+    return originatorKey;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSOriginatorInfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,296 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSOriginatorInfo.h"
+#include "TCMSTimeUtil.h"
+#include "CCMSCertificateChoices.h"
+#include "CCMSX509CertificateList.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KMinNumberOfSubModules = 0;
+const TInt KMaxNumberOfSubModules = 2;
+const TTagType KCertsTag = 0;
+const TTagType KCrlsTag = 1;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorInfo::CCMSOriginatorInfo
+// C++ constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSOriginatorInfo::CCMSOriginatorInfo( )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSOriginatorInfo*
+CCMSOriginatorInfo::NewL()
+	{
+	// creating with empty values
+    CCMSOriginatorInfo* self =
+        new( ELeave ) CCMSOriginatorInfo();
+	return self;
+	}
+
+// Destructor
+CCMSOriginatorInfo::~CCMSOriginatorInfo()
+    {
+    if( iCerts )
+        {
+        iCerts->ResetAndDestroy();
+        delete iCerts;
+        }
+    if( iCrls )
+        {
+        iCrls->ResetAndDestroy();
+        delete iCrls;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorInfo::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSOriginatorInfo::DecodeL( const TDesC8& aRawData )
+	{
+    CArrayPtr< TASN1DecGeneric >* itemList = DecodeSequenceLC(
+        aRawData, KMinNumberOfSubModules, KMaxNumberOfSubModules );
+
+    DecodeArrayL( itemList );
+
+    CleanupStack::PopAndDestroy( itemList );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorInfo::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSOriginatorInfo::EncoderLC() const
+	{
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+    if( iCerts )
+        {
+        // encode certs [0] IMPLICIT CertificateSet OPTIONAL
+        CASN1EncSequence* certs = CASN1EncSequence::NewLC();
+        TInt certCount = iCerts->Count();
+        for( TInt i = 0; i < certCount; i++ )
+            {
+            CASN1EncBase* certEncoder = iCerts->At( i )->EncoderLC();
+            certs->AddAndPopChildL( certEncoder );
+            }
+        certs->SetTag( KCertsTag );
+        root->AddAndPopChildL( certs );
+        }
+
+    if( iCrls )
+        {
+        // encode crls [1] IMPLICIT CertificateRevocationLists OPTIONAL
+        CASN1EncSequence* crls = CASN1EncSequence::NewLC();
+        TInt crlCount = iCrls->Count();
+        for( TInt i = 0; i < crlCount; i++ )
+            {
+            CASN1EncBase* crlEncoder = iCrls->At( i )->EncoderLC();
+            crls->AddAndPopChildL( crlEncoder );
+            }
+        crls->SetTag( KCrlsTag );
+        root->AddAndPopChildL( crls );
+        }
+    
+    return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorInfo::Certs()
+// Getter for certs
+// -----------------------------------------------------------------------------
+EXPORT_C const CArrayPtr< CCMSCertificateChoices >*
+CCMSOriginatorInfo::Certs() const
+	{
+	return iCerts;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorInfo::Crls()
+// Getter for crls
+// -----------------------------------------------------------------------------
+EXPORT_C const CArrayPtr< CCMSX509CertificateList >*
+CCMSOriginatorInfo::Crls() const
+	{
+	return iCrls;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorInfo::SetCertsL()
+// Setter for certs
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSOriginatorInfo::SetCerts(
+    CArrayPtr< CCMSCertificateChoices >* aCerts )
+	{
+    delete iCerts;
+    iCerts = aCerts;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorInfo::SetCrlsL()
+// Setter for Crls
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSOriginatorInfo::SetCrls(
+    CArrayPtr< CCMSX509CertificateList >* aCrls )
+	{
+    delete iCrls;
+    iCrls = aCrls;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorInfo::DecodeImplicitTagL
+// Decrypts raw data with implicit tag
+// -----------------------------------------------------------------------------
+void CCMSOriginatorInfo::DecodeImplicitTagL(
+    const TDesC8& aRawData,
+    const TTagType aImplicitTag )
+    {
+    // Check the tag
+    TASN1DecGeneric decGen( aRawData );
+    decGen.InitL();
+    // Accept only given tag
+    if( decGen.Tag() != aImplicitTag )
+        {
+        User::Leave( KErrArgument );
+        }
+    TASN1DecSequence decSeq;
+    CArrayPtr< TASN1DecGeneric >* items = decSeq.DecodeDERLC( decGen );
+    TInt itemCount = items->Count();
+    if( ( itemCount > KMaxNumberOfSubModules ) ||
+        ( itemCount < KMinNumberOfSubModules ) )
+        {
+        User::Leave( KErrArgument );
+        }
+    DecodeArrayL( items );
+    CleanupStack::PopAndDestroy( items );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorInfo::DecodeArrayL
+// Decodes data from an array of decoders
+// -----------------------------------------------------------------------------
+void CCMSOriginatorInfo::DecodeArrayL(
+    CArrayPtr< TASN1DecGeneric >* aItems )
+    {
+    TInt itemCount = aItems->Count();
+    
+    TInt sequenceCounter = 0;
+
+    TASN1DecSequence decSeq;
+    
+    CArrayPtr< CCMSCertificateChoices >* certs = NULL;
+    TInt certCount = 0;
+    if( sequenceCounter < itemCount )
+        {
+        TASN1DecGeneric* certsGenericDecoder = aItems->At( sequenceCounter );
+        if( certsGenericDecoder->Tag() == KCertsTag )
+            {
+            CArrayPtr< TASN1DecGeneric >* certList =
+                decSeq.DecodeDERLC( *certsGenericDecoder );
+
+            certCount = certList->Count();
+            
+            certs = new( ELeave ) CArrayPtrFlat< CCMSCertificateChoices >(
+                certCount );
+
+            CleanupStack::PushL( certs );
+            
+            for( TInt i = 0; i < certCount; i++ )
+                {
+                CCMSCertificateChoices* choices = CCMSCertificateChoices::NewL();
+                CleanupStack::PushL( choices );
+                choices->DecodeL( certList->At( i )->Encoding() );
+                certs->AppendL( choices );
+                }
+                
+            sequenceCounter++;
+            }
+        }
+
+    CArrayPtr< CCMSX509CertificateList >* crls = NULL;
+    TInt crlCount = 0;
+    if( sequenceCounter < itemCount )
+        {
+        TASN1DecGeneric* crlsGenericDecoder = aItems->At( sequenceCounter );
+        if( crlsGenericDecoder->Tag() != KCrlsTag )
+            {
+            User::Leave( KErrArgument );
+            }
+        CArrayPtr< TASN1DecGeneric >* crlList =
+            decSeq.DecodeDERLC( *crlsGenericDecoder );
+
+        crlCount = crlList->Count();
+
+        crls = new( ELeave ) CArrayPtrFlat< CCMSX509CertificateList >(
+            crlCount );
+
+        CleanupStack::PushL( crls );
+
+        for( TInt i = 0; i < crlCount; i++ )
+            {
+            CCMSX509CertificateList* cList = CCMSX509CertificateList::NewLC();
+            cList->DecodeL( crlList->At( i )->Encoding() );
+            crls->AppendL( cList );
+            }
+        }
+
+    if( iCerts )
+        {
+        iCerts->ResetAndDestroy();
+        delete iCerts;
+        }
+    iCerts = certs;
+    if( iCrls )
+        {
+        iCrls->ResetAndDestroy();
+        delete iCrls;
+        }
+    iCrls = crls;
+
+    if( crls )
+        {
+        CleanupStack::Pop( crlCount );
+        CleanupStack::Pop( crls );
+        CleanupStack::PopAndDestroy( ); // crlList
+        }
+    if( certs )
+        {
+        CleanupStack::Pop( certCount );
+        CleanupStack::Pop( certs );
+        CleanupStack::PopAndDestroy( ); // certList
+        }
+    
+    }
+
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSOriginatorPublicKey.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,260 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSOriginatorPublicKey.h"
+#include "CCMSX509AlgorithmIdentifier.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KNumberOfSubModules = 2;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorPublicKey::CCMSOriginatorPublicKey
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSOriginatorPublicKey::CCMSOriginatorPublicKey()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorPublicKey::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSOriginatorPublicKey::ConstructL(
+	const CCMSX509AlgorithmIdentifier& aAlgorithm,
+	const TDesC8& aPublicKey )
+    {
+	SetAlgorithmL( aAlgorithm );
+	SetPublicKeyL( aPublicKey );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorPublicKey::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSOriginatorPublicKey* CCMSOriginatorPublicKey::NewL()
+	{
+	// creating with empty/default values
+	CCMSX509AlgorithmIdentifier* algorithm =
+        CCMSX509AlgorithmIdentifier::NewL( );
+	CleanupStack::PushL( algorithm );
+	CCMSOriginatorPublicKey* self = NewL( *algorithm, KNullDesC8() );
+	CleanupStack::PopAndDestroy( algorithm );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorPublicKey::NewL
+// Two-phased copy constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSOriginatorPublicKey* CCMSOriginatorPublicKey::NewL(
+    const CCMSOriginatorPublicKey& aOriginatorPublicKey )
+	{
+	CCMSOriginatorPublicKey* self = NewLC( aOriginatorPublicKey );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorPublicKey::NewLC
+// Two-phased copy constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSOriginatorPublicKey* CCMSOriginatorPublicKey::NewLC(
+    const CCMSOriginatorPublicKey& aOriginatorPublicKey )
+	{
+	CCMSOriginatorPublicKey* self = NewLC(
+        aOriginatorPublicKey.Algorithm(), aOriginatorPublicKey.PublicKey() );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorPublicKey::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSOriginatorPublicKey* CCMSOriginatorPublicKey::NewL(
+	const CCMSX509AlgorithmIdentifier& aAlgorithm,
+	const TDesC8& aPublicKey )
+    {
+    CCMSOriginatorPublicKey* self = NewLC( aAlgorithm, aPublicKey );
+    CleanupStack::Pop();
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorPublicKey::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSOriginatorPublicKey* CCMSOriginatorPublicKey::NewLC(
+	const CCMSX509AlgorithmIdentifier& aAlgorithm,
+	const TDesC8& aPublicKey )
+    {
+    CCMSOriginatorPublicKey* self =
+    	new( ELeave ) CCMSOriginatorPublicKey();
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aAlgorithm, aPublicKey );
+    return self;
+    }
+
+
+// Destructor
+CCMSOriginatorPublicKey::~CCMSOriginatorPublicKey()
+    {
+	delete iAlgorithm;
+	delete iPublicKey;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorPublicKey::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSOriginatorPublicKey::DecodeL( const TDesC8& aRawData )
+	{
+    TASN1DecGeneric decGen( aRawData );
+    decGen.InitL();
+    TASN1DecSequence decSeq;
+    CArrayPtr< TASN1DecGeneric >* itemsData =
+        decSeq.DecodeDERLC( decGen );
+    TInt count = itemsData->Count();
+    if( count != KNumberOfSubModules )
+        {
+        User::Leave( KErrArgument );
+        }
+	// we would not get this far if there is not 2 elements
+
+	// decoding algorithm identifier
+    CCMSX509AlgorithmIdentifier* algorithm =
+        CCMSX509AlgorithmIdentifier::NewL( );
+    CleanupStack::PushL( algorithm );
+    algorithm->DecodeL( itemsData->At( 0 )->Encoding() );
+    CleanupStack::Pop( algorithm );
+    delete iAlgorithm;
+    iAlgorithm = algorithm;
+
+	// decoding public key
+	TASN1DecGeneric gen( *itemsData->At( 1 ) );
+	gen.InitL();
+    // Symbian decoder can't handle zero length bit strings
+    if( gen.LengthDERContent() > 1 )
+        {
+        TASN1DecBitString bitStringDecoder;
+        HBufC8* tmp = bitStringDecoder.ExtractOctetStringL( gen );
+        delete iPublicKey;
+        iPublicKey = tmp;
+        }
+    else
+        {
+        HBufC8* tmp = KNullDesC8().AllocL();
+        delete iPublicKey;
+        iPublicKey = tmp;
+        }
+
+	CleanupStack::PopAndDestroy( itemsData );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorPublicKey::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSOriginatorPublicKey::EncoderLC() const
+	{
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+    // encode the algorithm identifier
+    HBufC8* encodedAlgorithm = NULL;
+    iAlgorithm->EncodeL( encodedAlgorithm );
+    CleanupStack::PushL( encodedAlgorithm );
+    CASN1EncEncoding* algorithm = CASN1EncEncoding::NewLC( *encodedAlgorithm );
+    root->AddAndPopChildL( algorithm );
+    CleanupStack::PopAndDestroy( encodedAlgorithm );
+
+    // add public key
+    CASN1EncBitString* publicKey = CASN1EncBitString::NewLC( *iPublicKey );
+    root->AddAndPopChildL( publicKey );
+
+	return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorPublicKey::Algorithm
+// Algorithm identifier getter
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509AlgorithmIdentifier&
+CCMSOriginatorPublicKey::Algorithm() const
+	{
+	return *iAlgorithm;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorPublicKey::PublicKey
+// PublicKey getter
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8& CCMSOriginatorPublicKey::PublicKey() const
+	{
+	return *iPublicKey;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorPublicKey::SetAlgorithmL
+// Algorithm setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSOriginatorPublicKey::SetAlgorithmL(
+	const CCMSX509AlgorithmIdentifier& aAlgorithm )
+	{
+	CCMSX509AlgorithmIdentifier* algorithm = NULL;
+    const CAlgorithmIdentifier& algorithmId = aAlgorithm.AlgorithmIdentifier();
+    const CAlgorithmIdentifier* digestAlgorithm = aAlgorithm.DigestAlgorithm();
+    if( digestAlgorithm )
+        {
+        algorithm = CCMSX509AlgorithmIdentifier::NewL( algorithmId,
+                                                       *digestAlgorithm );
+        }
+    else
+        {
+        algorithm = CCMSX509AlgorithmIdentifier::NewL( algorithmId );
+        }
+	delete iAlgorithm;
+	iAlgorithm = algorithm;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSOriginatorPublicKey::SetPublicKeyL
+// PublicKey setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSOriginatorPublicKey::SetPublicKeyL(
+	const TDesC8& aPublicKey )
+	{
+	HBufC8* tmp = aPublicKey.AllocL();
+	delete iPublicKey;
+	iPublicKey = tmp;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSRecipientEncryptedKey.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,299 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSRecipientEncryptedKey.h"
+#include "CCMSIssuerAndSerialNumber.h"
+#include "CCMSKeyIdentifier.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KNumberOfSubModules = 2;
+const TTagType KRKeyIdTag = 0;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientEncryptedKey::CCMSRecipientEncryptedKey
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSRecipientEncryptedKey::CCMSRecipientEncryptedKey()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientEncryptedKey::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSRecipientEncryptedKey::ConstructL(
+    const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber,
+	const TDesC8& aEncryptedKey )
+    {
+    SetIssuerAndSerialNumberL( aIssuerAndSerialNumber );
+	SetEncryptedKeyL( aEncryptedKey );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientEncryptedKey::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSRecipientEncryptedKey::ConstructL(
+    const CCMSKeyIdentifier& aRKeyId,
+	const TDesC8& aEncryptedKey )
+    {
+    SetRKeyIdL( aRKeyId );
+	SetEncryptedKeyL( aEncryptedKey );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientEncryptedKey::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSRecipientEncryptedKey* CCMSRecipientEncryptedKey::NewL()
+	{
+	// creating with empty/default values
+    CCMSIssuerAndSerialNumber* issuer = CCMSIssuerAndSerialNumber::NewL();
+    CleanupStack::PushL( issuer );
+	CCMSRecipientEncryptedKey* self = NewL( *issuer, KNullDesC8() );
+    CleanupStack::PopAndDestroy( issuer );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientEncryptedKey::NewL
+// Two-phased copy constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSRecipientEncryptedKey* CCMSRecipientEncryptedKey::NewL(
+    const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber,
+    const TDesC8& aEncryptedKey )
+	{
+    CCMSRecipientEncryptedKey* self =
+    	new( ELeave ) CCMSRecipientEncryptedKey();
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aIssuerAndSerialNumber, aEncryptedKey );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientEncryptedKey::NewL
+// Two-phased copy constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSRecipientEncryptedKey* CCMSRecipientEncryptedKey::NewL(
+    const CCMSKeyIdentifier& aRKeyId,
+    const TDesC8& aEncryptedKey )
+	{
+    CCMSRecipientEncryptedKey* self =
+    	new( ELeave ) CCMSRecipientEncryptedKey();
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aRKeyId, aEncryptedKey );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+
+// Destructor
+CCMSRecipientEncryptedKey::~CCMSRecipientEncryptedKey()
+    {
+	delete iEncryptedKey;
+    delete iIssuerAndSerialNumber;
+    delete iRKeyId;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientEncryptedKey::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSRecipientEncryptedKey::DecodeL( const TDesC8& aRawData )
+	{
+    CArrayPtr< TASN1DecGeneric >* itemsData =
+        DecodeSequenceLC( aRawData, KNumberOfSubModules, KNumberOfSubModules );
+
+    // decode rid KeyAgreeRecipientIdentifier
+    TASN1DecGeneric gen( *itemsData->At( 0 ) );
+    gen.InitL();
+    if( gen.Tag() == KRKeyIdTag )
+        {
+        // decode rKeyId
+        CCMSKeyIdentifier* keyId = CCMSKeyIdentifier::NewL();
+        CleanupStack::PushL( keyId );
+        keyId->DecodeImplicitTagL( gen.Encoding(), KRKeyIdTag );
+        CleanupStack::Pop( keyId );
+        delete iIssuerAndSerialNumber;
+        iIssuerAndSerialNumber = NULL;
+        delete iRKeyId;
+        iRKeyId = keyId;
+        }
+    else
+        {
+        // delete issuerAndSerialNumber
+        CCMSIssuerAndSerialNumber* issuer = CCMSIssuerAndSerialNumber::NewL();
+        CleanupStack::PushL( issuer );
+        issuer->DecodeL( gen.Encoding() );
+        CleanupStack::Pop( issuer );
+        delete iRKeyId;
+        iRKeyId = NULL;
+        delete iIssuerAndSerialNumber;
+        iIssuerAndSerialNumber = issuer;
+        }
+
+    //decode encryptedKey
+    TASN1DecGeneric keyDecoder( *itemsData->At( 1 ) );
+    keyDecoder.InitL();
+    TASN1DecOctetString octetStringDecoder;
+    HBufC8* tmp = octetStringDecoder.DecodeDERL( keyDecoder );
+    delete iEncryptedKey;
+    iEncryptedKey = tmp;
+    CleanupStack::PopAndDestroy( itemsData );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientEncryptedKey::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSRecipientEncryptedKey::EncoderLC() const
+	{
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+    // encode rid KeyAgreeRecipientIdentifier
+    if( iIssuerAndSerialNumber )
+        {
+        // encode issuerAndSerialNumber
+        HBufC8* encodedIssuer = NULL;
+        iIssuerAndSerialNumber->EncodeL( encodedIssuer );
+        CleanupStack::PushL( encodedIssuer );
+        CASN1EncEncoding* issuer = CASN1EncEncoding::NewLC( *encodedIssuer );
+        root->AddAndPopChildL( issuer );
+        CleanupStack::PopAndDestroy( encodedIssuer );
+        }
+    else
+        {
+        // encode rKeyId [0] IMPLICIT RecipientKeyIdentifier
+        HBufC8* encodedRKeyId = NULL;
+        iRKeyId->EncodeL( encodedRKeyId );
+        CleanupStack::PushL( encodedRKeyId );
+        CASN1EncEncoding* rKeyId = CASN1EncEncoding::NewLC( *encodedRKeyId );
+        rKeyId->SetTag( KRKeyIdTag );
+        root->AddAndPopChildL( rKeyId );
+        CleanupStack::PopAndDestroy( encodedRKeyId );
+        }
+
+    // encode encryptedKey
+    CASN1EncOctetString* encryptedKey =
+        CASN1EncOctetString::NewLC( *iEncryptedKey );
+    root->AddAndPopChildL( encryptedKey );
+
+    return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientEncryptedKey::EncryptedKey
+// EncryptedKey getter
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8&
+CCMSRecipientEncryptedKey::EncryptedKey() const
+	{
+	return *iEncryptedKey;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientEncryptedKey::IssuerAndSerialNumber
+// IssuerAndSerialNumber getter
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSIssuerAndSerialNumber*
+CCMSRecipientEncryptedKey::IssuerAndSerialNumber() const
+	{
+	return iIssuerAndSerialNumber;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientEncryptedKey::RecipientKeyIdentifier
+// RecipientKeyIdentifier getter
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSKeyIdentifier*
+CCMSRecipientEncryptedKey::RKeyId() const
+	{
+	return iRKeyId;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientEncryptedKey::SetEncryptedKeyL
+// EncryptedKey setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSRecipientEncryptedKey::SetEncryptedKeyL(
+	const TDesC8& aEncryptedKey )
+	{
+    HBufC8* encryptedKey = aEncryptedKey.AllocL();
+    delete iEncryptedKey;
+    iEncryptedKey = encryptedKey;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientEncryptedKey::SetIssuerAndSerialNumberL
+// IssuerAndSerialNumber setter, deletes also rKeyId
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSRecipientEncryptedKey::SetIssuerAndSerialNumberL(
+	const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber )
+	{
+    CCMSIssuerAndSerialNumber* issuer = CCMSIssuerAndSerialNumber::NewL(
+        aIssuerAndSerialNumber.IssuerName(),
+        aIssuerAndSerialNumber.SerialNumber() );
+    delete iRKeyId;
+    iRKeyId = NULL;
+    delete iIssuerAndSerialNumber;
+    iIssuerAndSerialNumber = issuer;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientEncryptedKey::SetRKeyIdL
+// rKeyId setter, deletes also IssuerAndSerialNumber
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSRecipientEncryptedKey::SetRKeyIdL(
+	const CCMSKeyIdentifier& aRKeyId )
+	{
+    CCMSKeyIdentifier* keyId = NULL;
+    const TTime* keyIdDate = aRKeyId.Date();
+    if( keyIdDate )
+        {
+        keyId = CCMSKeyIdentifier::NewL(
+            aRKeyId.KeyIdentifier(), *keyIdDate );
+        }
+    else
+        {
+        keyId = CCMSKeyIdentifier::NewL(
+            aRKeyId.KeyIdentifier() );
+        }
+    delete iIssuerAndSerialNumber;
+    iIssuerAndSerialNumber = NULL;
+    delete iRKeyId;
+    iRKeyId = keyId;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSRecipientInfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,129 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSRecipientInfo.h"
+#include "CCMSX509AlgorithmIdentifier.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientInfo::CCMSRecipientInfo
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CCMSRecipientInfo::CCMSRecipientInfo( TInt aVersion )
+    : iVersion( aVersion )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientInfo::BaseConstructL
+// Constructs the member variables. Makes a copy of aKeyEncryptionAlgorithm.
+// -----------------------------------------------------------------------------
+//
+void CCMSRecipientInfo::BaseConstructL(
+    const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm )
+    {
+    SetKeyEncryptionAlgorithmL( aKeyEncryptionAlgorithm );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientInfo::AddVersionL
+// Adds version encoding to root sequence
+// -----------------------------------------------------------------------------
+//
+void CCMSRecipientInfo::AddVersionL( CASN1EncSequence* aRoot ) const
+    {
+    CASN1EncInt* version = CASN1EncInt::NewLC( iVersion );
+    aRoot->AddAndPopChildL( version );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientInfo::AddKeyEncryptionAlgorithmL
+// Adds KeyEncryptionAlgorithm encoding to root sequence
+// -----------------------------------------------------------------------------
+//
+void CCMSRecipientInfo::AddKeyEncryptionAlgorithmL( CASN1EncSequence* aRoot ) const
+    {
+    HBufC8* encodedKeyEncryptionAlgorithm = NULL;
+    iKeyEncryptionAlgorithm->EncodeL( encodedKeyEncryptionAlgorithm );
+    CleanupStack::PushL( encodedKeyEncryptionAlgorithm );
+    CASN1EncEncoding* keyEncryptionAlgorithm =
+        CASN1EncEncoding::NewLC( *encodedKeyEncryptionAlgorithm );
+    aRoot->AddAndPopChildL( keyEncryptionAlgorithm );
+    CleanupStack::PopAndDestroy( encodedKeyEncryptionAlgorithm );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientInfo::~CCMSRecipientInfo
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CCMSRecipientInfo::~CCMSRecipientInfo()
+    {
+    delete iKeyEncryptionAlgorithm;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientInfo::Version
+// Version getter
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CCMSRecipientInfo::Version() const
+    {
+    return iVersion;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientInfo::KeyEncryptionAlgorithm
+// KeyEncryptionAlgorithm getter
+// -----------------------------------------------------------------------------
+//
+EXPORT_C const CCMSX509AlgorithmIdentifier&
+CCMSRecipientInfo::KeyEncryptionAlgorithm() const
+    {
+    return *iKeyEncryptionAlgorithm;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSRecipientInfo::SetKeyEncryptionAlgorithmL
+// KeyEncryptionAlgorithm setter
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSRecipientInfo::SetKeyEncryptionAlgorithmL(
+    const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm )
+    {
+    CCMSX509AlgorithmIdentifier* algorithmIdentifier =
+        CCMSX509AlgorithmIdentifier::NewL(
+            aKeyEncryptionAlgorithm.AlgorithmIdentifier() );
+    CleanupStack::PushL( algorithmIdentifier );
+    const CAlgorithmIdentifier* digestAlgorithm =
+        aKeyEncryptionAlgorithm.DigestAlgorithm();
+    if( digestAlgorithm )
+        {
+        algorithmIdentifier->SetDigestAlgorithmL( digestAlgorithm );
+        }
+    CleanupStack::Pop( algorithmIdentifier );
+    delete iKeyEncryptionAlgorithm;
+    iKeyEncryptionAlgorithm = algorithmIdentifier;
+    }
+
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSSequence.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,114 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSSequence.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSSequence::CCMSSequence
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CCMSSequence::CCMSSequence()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSSequence::DecodeSequenceLC
+// Decodes raw-data to ASN.1 modules, pushes items to cleanupstack
+// -----------------------------------------------------------------------------
+
+EXPORT_C CArrayPtr<TASN1DecGeneric>* CCMSSequence::DecodeSequenceLC( const TDesC8& aRawData )
+	{
+	CArrayPtr<TASN1DecGeneric>* items = NULL;
+
+	// Check we've got a sequence
+	TASN1DecGeneric decGen( aRawData );
+	decGen.InitL();
+	// Accept only sequences or sets
+	if( ( decGen.Tag() != EASN1Sequence ) &&
+		( decGen.Tag() != EASN1Set ) )
+		{
+		User::Leave(KErrArgument);
+		}
+	else
+		{
+		// Decode the sequence
+		TASN1DecSequence decSeq;
+		items = decSeq.DecodeDERLC( decGen );
+		}
+	return items;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSequence::DecodeSequenceLC
+// Decodes raw-data to ASN.1 modules, pushes items to cleanupstack
+// Validates that there is right number of modules, leaves with KErrArgument if
+// not.
+// -----------------------------------------------------------------------------
+
+EXPORT_C CArrayPtr<TASN1DecGeneric>* CCMSSequence::DecodeSequenceLC( const TDesC8& aRawData,
+														 const TInt aMinTerms,
+														 const TInt aMaxTerms)
+	{
+	CArrayPtr<TASN1DecGeneric>* items = DecodeSequenceLC(aRawData);
+	TInt count = items->Count();
+	if( ( count < aMinTerms ) ||
+		( count > aMaxTerms ) )
+		{
+		// not in the range, leave
+		User::Leave( KErrArgument );
+		}
+
+	return items;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSequence::EncodeL
+// Encrypts this instance to descriptor
+// -----------------------------------------------------------------------------
+
+void CCMSSequence::EncodeL( HBufC8*& aResult ) const
+	{
+	CASN1EncBase* root = EncoderLC();
+
+	// encode the object in a DER encoding
+	HBufC8* der = CreateDerEncodingL( root );
+	CleanupStack::PopAndDestroy( root );
+
+	aResult = der;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSequence::CreateDerEncodingLC()
+// Creates DER encoding
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC8* CCMSSequence::CreateDerEncodingL( CASN1EncBase* aEncoding )
+	{
+	// encode the object in a DER encoding
+	HBufC8* der = HBufC8::NewMaxLC( aEncoding->LengthDER() );
+	TPtr8 pder( der->Des() );
+	TUint pos = 0;
+	aEncoding->WriteDERL( pder, pos );
+	CleanupStack::Pop( der );
+	return der;
+	}
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSSignedData.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,706 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include <x500dn.h>
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+#include "CCMSSignedData.h"
+
+// CONSTANTS
+const TInt KMinNumberOfSubModules = 4;
+const TInt KMaxNumberOfSubModules = 6;
+const TInt KDefaultGranularity = 1;
+const TInt KDefaultVersion = 1;
+const TInt KAlternativeVersion = 3;
+const TUint8 KCertificateSetTag = 0;
+const TUint8 KRevokedCertificatesTag = 1;
+
+// Defaulta id-data oid
+_LIT( KIDDataOID, "1.2.840.113549.1.7.1" );
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::CCMSSignedData
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSSignedData::CCMSSignedData()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSSignedData::ConstructL()
+    {
+	iVersion = KDefaultVersion;
+	iDigestAlgorithmIdentifiers =
+				new( ELeave )CArrayPtrFlat< CCMSX509AlgorithmIdentifier >
+														( KDefaultGranularity );
+	iContentInfo = CCMSEncapsulatedContentInfo::NewLC();
+	CleanupStack::Pop( iContentInfo );
+	iSignerInfos =
+				new( ELeave )CArrayPtrFlat< CCMSSignerInfo >
+														( KDefaultGranularity );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSSignedData::ConstructL(
+	const CArrayPtr< CCMSX509AlgorithmIdentifier >& aDigestAlgorithmIdentifiers,
+   	const CCMSEncapsulatedContentInfo& aContentInfo,
+   	const CArrayPtr< CCMSSignerInfo >& aSignerInfos,
+   	const CArrayPtr< CCMSCertificateChoices >* aCertificates,
+   	const CArrayPtr< CCMSX509CertificateList >* aRevokedCertificates )
+    {
+	SetSignerInfosL( aSignerInfos );
+	SetDigestAlgorithmIdentifiersL( aDigestAlgorithmIdentifiers );
+	SetEncapsulatedContentInfoL( aContentInfo );
+
+	SetCertificatesL( aCertificates );
+	SetRevokedCertificatesL( aRevokedCertificates );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSSignedData* CCMSSignedData::NewLC()
+	{
+	CCMSSignedData* self = new( ELeave ) CCMSSignedData();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSSignedData* CCMSSignedData::NewLC(
+	const CArrayPtr< CCMSX509AlgorithmIdentifier >& aDigestAlgorithmIdentifiers,
+   	const CCMSEncapsulatedContentInfo& aContentInfo,
+   	const CArrayPtr< CCMSSignerInfo >& aSignerInfos )
+    {
+    CCMSSignedData* self = new( ELeave ) CCMSSignedData();
+    CleanupStack::PushL( self );
+    self->ConstructL( aDigestAlgorithmIdentifiers,
+    				  aContentInfo,
+    				  aSignerInfos,
+    				  NULL,
+    				  NULL );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSSignedData* CCMSSignedData::NewLC(
+	const CArrayPtr< CCMSX509AlgorithmIdentifier >& aDigestAlgorithmIdentifiers,
+   	const CCMSEncapsulatedContentInfo& aContentInfo,
+   	const CArrayPtr< CCMSSignerInfo >& aSignerInfos,
+   	const CArrayPtr< CCMSCertificateChoices >* aCertificates,
+   	const CArrayPtr< CCMSX509CertificateList >* aRevokedCertificates )
+    {
+    CCMSSignedData* self = new( ELeave ) CCMSSignedData();
+    CleanupStack::PushL( self );
+    self->ConstructL( aDigestAlgorithmIdentifiers,
+    				  aContentInfo,
+    				  aSignerInfos,
+    				  aCertificates,
+    				  aRevokedCertificates );
+    return self;
+    }
+
+// Destructor
+CCMSSignedData::~CCMSSignedData()
+    {
+	if( iDigestAlgorithmIdentifiers )
+		{
+		iDigestAlgorithmIdentifiers->ResetAndDestroy();
+		delete iDigestAlgorithmIdentifiers;
+		}
+	delete iContentInfo;
+	if( iSignerInfos )
+		{
+		iSignerInfos->ResetAndDestroy();
+		delete iSignerInfos;
+		}
+	if( iCertificates )
+		{
+		iCertificates->ResetAndDestroy();
+		delete iCertificates;
+		}
+	if( iRevokedCertificates )
+		{
+		iRevokedCertificates->ResetAndDestroy();
+		delete iRevokedCertificates;
+		}
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSSignedData::DecodeL( const TDesC8& aRawData )
+	{
+	CArrayPtr<TASN1DecGeneric>* itemsData =
+							DecodeSequenceLC( aRawData,
+											  KMinNumberOfSubModules,
+											  KMaxNumberOfSubModules );
+	TInt pos = 0;
+	// decode Version
+	TASN1DecInteger version;
+	TInt tmpVersion;
+	tmpVersion = version.DecodeDERShortL( *itemsData->At( pos++ ) );
+
+	// decode digest algorithms
+	CArrayPtrFlat< CCMSX509AlgorithmIdentifier >* tmpAlgs =
+		new( ELeave )CArrayPtrFlat< CCMSX509AlgorithmIdentifier >
+													( KDefaultGranularity );
+	CleanupStack::PushL( tmpAlgs );
+	CleanupResetAndDestroyPushL( *tmpAlgs );
+
+	//there must be atleast 1 algorithm
+	CArrayPtr<TASN1DecGeneric>* digestAlgorithms =
+		DecodeSequenceLC( itemsData->At( pos++ )->Encoding(),
+						  1,
+						  KMaxTInt );
+	TInt algCount = digestAlgorithms->Count();
+	for( TInt i = 0; i < algCount; i++ )
+		{
+		CCMSX509AlgorithmIdentifier* alg =
+										CCMSX509AlgorithmIdentifier::NewL();
+		CleanupStack::PushL( alg );
+		alg->DecodeL( digestAlgorithms->At( i )->Encoding() );
+		tmpAlgs->AppendL( alg );
+		CleanupStack::Pop( alg );
+		}
+	CleanupStack::PopAndDestroy( digestAlgorithms );
+
+	// decode encapsulated content info
+	CCMSEncapsulatedContentInfo* tmpInfo = CCMSEncapsulatedContentInfo::NewLC();
+	tmpInfo->DecodeL( itemsData->At( pos++ )->Encoding() );
+
+	CArrayPtrFlat< CCMSCertificateChoices >* tmpCerts = NULL;
+
+	// decode possible certificate set
+	if( itemsData->At( pos )->Tag() == KCertificateSetTag )
+		{
+		tmpCerts =
+			new( ELeave )CArrayPtrFlat< CCMSCertificateChoices >
+													( KDefaultGranularity );
+		CleanupStack::PushL( tmpCerts );
+		CleanupResetAndDestroyPushL( *tmpCerts );
+		TASN1DecSequence decSeq;
+		CArrayPtr<TASN1DecGeneric>* certs =
+			decSeq.DecodeDERLC( *itemsData->At( pos++ ) );
+		TInt certCount = certs->Count();
+		for( TInt i = 0; i < certCount; i++ )
+			{
+			CCMSCertificateChoices* tmpCert =
+				CCMSCertificateChoices::NewLC();
+			tmpCert->DecodeL( certs->At( i )->Encoding() );
+			tmpCerts->AppendL( tmpCert );
+			CleanupStack::Pop( tmpCert );
+			}
+		CleanupStack::PopAndDestroy( certs );
+		}
+
+	// decode possible revoked certificates
+	CArrayPtrFlat< CCMSX509CertificateList >* tmpRevokedCertificates = NULL;
+	if( ( pos < itemsData->Count() ) &&
+		( itemsData->At( pos )->Tag() == KRevokedCertificatesTag ) )
+		{
+		tmpRevokedCertificates =
+			new( ELeave )CArrayPtrFlat< CCMSX509CertificateList >
+													( KDefaultGranularity );
+		CleanupStack::PushL( tmpRevokedCertificates );
+		CleanupResetAndDestroyPushL( *tmpRevokedCertificates );
+
+		TASN1DecSequence decSeq;
+		CArrayPtr<TASN1DecGeneric>* certs =
+			decSeq.DecodeDERLC( *itemsData->At( pos++ ) );
+
+		TInt certCount = certs->Count();
+		for( TInt i = 0; i < certCount; i++ )
+			{
+			CCMSX509CertificateList* tmpCert = CCMSX509CertificateList::NewLC();
+			tmpCert->DecodeL( certs->At( i )->Encoding() );
+			tmpRevokedCertificates->AppendL( tmpCert );
+			CleanupStack::Pop( tmpCert );
+			}
+		CleanupStack::PopAndDestroy( certs );
+		}
+
+	// decode Signer Infos
+	if( pos >= itemsData->Count() )
+		{
+		// Missing mandatory signer infos
+		User::Leave( KErrArgument );
+		}
+
+	CArrayPtrFlat< CCMSSignerInfo >* tmpSignerInfos =
+		new( ELeave )CArrayPtrFlat< CCMSSignerInfo >( KDefaultGranularity );
+	CleanupStack::PushL( tmpSignerInfos );
+	CleanupResetAndDestroyPushL( *tmpSignerInfos );
+
+	CArrayPtr<TASN1DecGeneric>* sInfos =
+		DecodeSequenceLC( itemsData->At( pos )->Encoding() );
+
+	TInt sInfoCount = sInfos->Count();
+	for( TInt j = 0; j < sInfoCount; j++ )
+		{
+		CCMSSignerInfo* tmpInfo = CCMSSignerInfo::NewL();
+		CleanupStack::PushL( tmpInfo );
+		tmpInfo->DecodeL( sInfos->At( j )->Encoding() );
+		tmpSignerInfos->AppendL( tmpInfo );
+		CleanupStack::Pop( tmpInfo );
+		}
+	CleanupStack::PopAndDestroy( sInfos );
+
+	// All done, setting new values
+	iSignerInfos->ResetAndDestroy();
+	delete iSignerInfos;
+	iSignerInfos = tmpSignerInfos;
+
+	CleanupStack::Pop( tmpSignerInfos ); // ResetAndDestroy
+	CleanupStack::Pop( tmpSignerInfos ); // Normal cleanup
+
+	if( iRevokedCertificates )
+		{
+		iRevokedCertificates->ResetAndDestroy();
+		delete iRevokedCertificates;
+		}
+	iRevokedCertificates = tmpRevokedCertificates;
+	if( tmpRevokedCertificates )
+		{
+		CleanupStack::Pop( tmpRevokedCertificates ); // ResetAndDestroy
+		CleanupStack::Pop( tmpRevokedCertificates ); // Normal cleanup
+		}
+
+	if( iCertificates )
+		{
+		iCertificates->ResetAndDestroy();
+		delete iCertificates;
+		}
+	iCertificates = tmpCerts;
+	if( tmpCerts )
+		{
+		CleanupStack::Pop( tmpCerts ); // ResetAndDestory
+		CleanupStack::Pop( tmpCerts ); // Normal cleanup
+		}
+
+	delete iContentInfo;
+	iContentInfo = tmpInfo;
+	CleanupStack::Pop( tmpInfo );
+
+	iDigestAlgorithmIdentifiers->ResetAndDestroy();
+	delete iDigestAlgorithmIdentifiers;
+	iDigestAlgorithmIdentifiers = tmpAlgs;
+	CleanupStack::Pop( tmpAlgs ); // ResetAndDestroy
+	CleanupStack::Pop( tmpAlgs ); // Normal cleanup
+
+	iVersion = tmpVersion;
+
+	CleanupStack::PopAndDestroy( itemsData );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSSignedData::EncoderLC() const
+	{
+	CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+	// Add version
+	CASN1EncInt* version = CASN1EncInt::NewLC( iVersion );
+	root->AddAndPopChildL( version );
+
+	// Add digest algorithms
+	CASN1EncSequence* digestAlgorithms = CASN1EncSequence::NewLC();
+	digestAlgorithms->SetTag( EASN1Set, EUniversal );
+	TInt count = iDigestAlgorithmIdentifiers->Count();
+	if( count == 0 )
+		{
+		// there is no mandatory algorithms
+		User::Leave( KErrArgument );
+		}
+	for( TInt i = 0; i < count; i++ )
+		{
+		CCMSX509AlgorithmIdentifier* alg =
+			iDigestAlgorithmIdentifiers->At( i );
+		CASN1EncBase* algEnc = alg->EncoderLC();
+		digestAlgorithms->AddAndPopChildL( algEnc );
+		}
+	root->AddAndPopChildL( digestAlgorithms );
+
+	// add encapsulated content info
+	CASN1EncBase* encContentInfo = iContentInfo->EncoderLC();
+	root->AddAndPopChildL( encContentInfo );
+
+	// add possible certificates
+	if( iCertificates &&
+		iCertificates->Count() > 0 )
+		{
+		CASN1EncSequence* certificates = CASN1EncSequence::NewLC();
+		certificates->SetTag( KCertificateSetTag );
+		TInt certCount = iCertificates->Count();
+		for( TInt i = 0; i < certCount; i++ )
+			{
+			CCMSCertificateChoices* cert = iCertificates->At( i );
+			CASN1EncBase* certEnc = cert->EncoderLC();
+			certificates->AddAndPopChildL( certEnc );
+			}
+		root->AddAndPopChildL( certificates );
+		}
+
+	// add possible revoked certificates
+	if( iRevokedCertificates &&
+		iRevokedCertificates->Count() > 0 )
+		{
+		CASN1EncSequence* certificates = CASN1EncSequence::NewLC();
+		certificates->SetTag( KRevokedCertificatesTag );
+		TInt certCount = iRevokedCertificates->Count();
+		for( TInt i = 0; i < certCount; i++ )
+			{
+			CCMSX509CertificateList* list = iRevokedCertificates->At( i );
+			CASN1EncBase* rCerts = list->EncoderLC();
+			certificates->AddAndPopChildL( rCerts );
+			}
+		root->AddAndPopChildL( certificates );
+		}
+
+	// add signer infos
+	CASN1EncSequence* signerInfos = CASN1EncSequence::NewLC();
+	signerInfos->SetTag( EASN1Set, EUniversal );
+	TInt sCount = iSignerInfos->Count();
+	if( sCount == 0 )
+		{
+		// there is no mandatory signer infos
+		User::Leave( KErrArgument );
+		}
+
+	for( TInt j = 0; j < sCount; j++ )
+		{
+		CASN1EncBase* sInfo = iSignerInfos->At( j )->EncoderLC();
+		signerInfos->AddAndPopChildL( sInfo );
+		}
+	root->AddAndPopChildL( signerInfos );
+	return root;
+	}
+// -----------------------------------------------------------------------------
+// CCMSSignedData::Version
+// Getter for Version
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCMSSignedData::Version() const
+	{
+	return iVersion;
+	}
+// -----------------------------------------------------------------------------
+// CCMSSignedData::DigestAlgorithmIdentifiers
+// Getter for DigestAlgorithmIdentifiers
+// -----------------------------------------------------------------------------
+EXPORT_C const CArrayPtr< CCMSX509AlgorithmIdentifier >&
+	CCMSSignedData::DigestAlgorithmIdentifiers() const
+	{
+	return *iDigestAlgorithmIdentifiers;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::EncapsulatedContentInfo
+// Getter for EncapsulatedContentInfo
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSEncapsulatedContentInfo&
+	CCMSSignedData::EncapsulatedContentInfo() const
+	{
+	return *iContentInfo;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::SignerInfos
+// Getter for SignerInfos
+// -----------------------------------------------------------------------------
+EXPORT_C const CArrayPtr< CCMSSignerInfo >&
+	CCMSSignedData::SignerInfos() const
+	{
+	return *iSignerInfos;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::Certificates
+// Getter for Certificates
+// -----------------------------------------------------------------------------
+EXPORT_C const CArrayPtr< CCMSCertificateChoices >*
+	CCMSSignedData::Certificates() const
+	{
+	return iCertificates;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::RevokedCertificates
+// Getter for RevokedCertificates
+// -----------------------------------------------------------------------------
+EXPORT_C const CArrayPtr< CCMSX509CertificateList >*
+	CCMSSignedData::RevokedCertificates() const
+	{
+	return iRevokedCertificates;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::SetDigestAlgorithmIdentifiersL
+// Setter for DigestAlgorithmIdentifiers, takes copy
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSSignedData::SetDigestAlgorithmIdentifiersL(
+	const CArrayPtr< CCMSX509AlgorithmIdentifier >& aDigestAlgorithmIdentifiers )
+	{
+	CArrayPtrFlat< CCMSX509AlgorithmIdentifier >* tmpAlgs =
+		new( ELeave )CArrayPtrFlat< CCMSX509AlgorithmIdentifier >( KDefaultGranularity );
+	CleanupStack::PushL( tmpAlgs );
+	TInt algCount = aDigestAlgorithmIdentifiers.Count();
+	for( TInt i = 0; i < algCount; i++ )
+		{
+		CCMSX509AlgorithmIdentifier* origAlg = aDigestAlgorithmIdentifiers[ i ];
+		CCMSX509AlgorithmIdentifier* tmpAlg = NULL;
+		if( origAlg->DigestAlgorithm() )
+			{
+			tmpAlg =
+			CCMSX509AlgorithmIdentifier::NewL( origAlg->AlgorithmIdentifier(),
+											   *origAlg->DigestAlgorithm() );
+			}
+		else
+			{
+			tmpAlg =
+			CCMSX509AlgorithmIdentifier::NewL( origAlg->AlgorithmIdentifier() );
+			}
+		CleanupStack::PushL( tmpAlg );
+		tmpAlgs->AppendL( tmpAlg );
+		CleanupStack::Pop( tmpAlg );
+		}
+	delete iDigestAlgorithmIdentifiers;
+	iDigestAlgorithmIdentifiers = tmpAlgs;
+	CleanupStack::Pop( tmpAlgs );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::SetEncapsulatedContentInfoL
+// Setter for EncapsulatedContentInfo, takes copy
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSSignedData::SetEncapsulatedContentInfoL(
+	const CCMSEncapsulatedContentInfo& aContentInfo )
+	{
+	CCMSEncapsulatedContentInfo* copy =
+		CCMSEncapsulatedContentInfo::NewLC( aContentInfo.ContentType(),
+											aContentInfo.Content() );
+	delete iContentInfo;
+	iContentInfo = copy;
+	CleanupStack::Pop( copy );
+	ValidateVersion();
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::SetSignerInfosL
+// Setter for SignerInfos, takes copy
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSSignedData::SetSignerInfosL(
+	const CArrayPtr< CCMSSignerInfo >& aSignerInfos )
+	{
+	TInt sigCount = aSignerInfos.Count();
+	// creating right size array directly, adding 1 to avoid panic in case that
+	// sigCount is zero.
+	CArrayPtrFlat< CCMSSignerInfo >* tmpSignInfos =
+		new( ELeave )CArrayPtrFlat< CCMSSignerInfo >( sigCount + 1 );
+	CleanupStack::PushL( tmpSignInfos );
+	CleanupResetAndDestroyPushL( *tmpSignInfos );
+	for( TInt i = 0; i < sigCount; i++ )
+		{
+		HBufC8* tmpEncoding;
+		aSignerInfos[ i ]->EncodeL( tmpEncoding );
+		CleanupStack::PushL( tmpEncoding );
+		CCMSSignerInfo* tmpSig = CCMSSignerInfo::NewL();
+		CleanupStack::PushL( tmpSig );
+		tmpSig->DecodeL( *tmpEncoding );
+		tmpSignInfos->AppendL( tmpSig );
+		CleanupStack::Pop( tmpSig );
+		CleanupStack::PopAndDestroy( tmpEncoding );
+		}
+	if( iSignerInfos )
+		{
+		iSignerInfos->ResetAndDestroy();
+		delete iSignerInfos;
+		}
+	iSignerInfos = tmpSignInfos;
+	CleanupStack::Pop( tmpSignInfos ); // ResetAndDestroy
+	CleanupStack::Pop( tmpSignInfos ); // normal cleanup
+	ValidateVersion();
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::SetCertificatesL
+// Setter for Certificates, takes copy
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSSignedData::SetCertificatesL(
+	const CArrayPtr< CCMSCertificateChoices >* aCertificates )
+	{
+	CArrayPtrFlat< CCMSCertificateChoices >* tmpCertificates = NULL;
+	if( aCertificates )
+		{
+		TInt certCount = aCertificates->Count();
+		// creating right size array directly, adding 1 to avoid panic in case 
+		// that certCount is zero.
+		tmpCertificates =
+			new( ELeave )CArrayPtrFlat< CCMSCertificateChoices >( certCount + 1 );
+		CleanupStack::PushL( tmpCertificates );
+		CleanupResetAndDestroyPushL( *tmpCertificates );
+		for( TInt i = 0; i < certCount; i++ )
+			{
+			CCMSCertificateChoices* copy =
+				CCMSCertificateChoices::NewLC();
+			CCMSCertificateChoices* orig = aCertificates->At( i );
+			if( orig->AttrCert() )
+				{
+				copy->SetAttrCertL( *orig->AttrCert() );
+				}
+			else if( orig->Certificate() )
+				{
+				copy->SetCertificateL( *orig->Certificate() );
+				}
+			else
+				{
+				User::Leave( KErrArgument );
+				}
+			tmpCertificates->AppendL( copy );
+			CleanupStack::Pop( copy );
+			}
+		CleanupStack::Pop( tmpCertificates ); // ResetAndDestroy
+		CleanupStack::Pop( tmpCertificates ); // Normal cleanup
+		}
+	if( iCertificates )
+		{
+		iCertificates->ResetAndDestroy();
+		delete iCertificates;
+		}
+	iCertificates = tmpCertificates;
+	ValidateVersion();
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::SetRevokedCertificatesL
+// Setter for RevokedCertificates, takes copy
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSSignedData::SetRevokedCertificatesL(
+	const CArrayPtr< CCMSX509CertificateList >* aRevokedCertificates )
+	{
+	CArrayPtrFlat< CCMSX509CertificateList >* tmpCerts = NULL;
+	if( aRevokedCertificates )
+		{
+		TInt certCount = aRevokedCertificates->Count();
+		// creating right size array directly, adding 1 to avoid panic in case 
+		// that certCount is zero.
+		tmpCerts =
+			new( ELeave )CArrayPtrFlat< CCMSX509CertificateList >
+														( certCount + 1 );
+		CleanupStack::PushL( tmpCerts );
+		CleanupResetAndDestroyPushL( *tmpCerts );
+		for( TInt i = 0; i < certCount; i++ )
+			{
+			CCMSX509CertificateList* copy =
+				CCMSX509CertificateList::NewLC();
+
+			HBufC8* tmpData;
+			aRevokedCertificates->At( i )->EncodeL( tmpData );
+			CleanupStack::PushL( tmpData );
+			copy->DecodeL( *tmpData );
+			CleanupStack::PopAndDestroy( tmpData );
+			tmpCerts->AppendL( copy );
+			CleanupStack::Pop( copy );
+			}
+		CleanupStack::Pop( tmpCerts ); // ResetAndDestroy
+		CleanupStack::Pop( tmpCerts ); // Normal cleanup
+		}
+
+	if( iRevokedCertificates )
+		{
+		iRevokedCertificates->ResetAndDestroy();
+		delete iRevokedCertificates;
+		}
+	iRevokedCertificates = tmpCerts;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignedData::ValidateVersion
+// Validates that iVersion is correct
+// -----------------------------------------------------------------------------
+void CCMSSignedData::ValidateVersion()
+	{
+	iVersion = KDefaultVersion;
+	// if the encapsulated content type is other than id-data
+	// then the value of version shall be 3.
+	if( iContentInfo &&
+		( iContentInfo->ContentType() != KIDDataOID ) )
+		{
+		iVersion = KAlternativeVersion;
+		return; // no reason to continue
+		}
+
+	// if any of the elements of SignerInfos are version 3,
+	// then the value of version shall be 3.
+	if( iSignerInfos->Count() )
+		{
+		TInt sigCount = iSignerInfos->Count();
+		for( TInt i = 0; i < sigCount; i++ )
+			{
+			if( iSignerInfos->At( i )->CMSVersion() == KAlternativeVersion )
+				{
+				iVersion = KAlternativeVersion;
+				return; // no reason to continue
+				}
+			}
+		}
+
+	// if attribute certificates are present, the
+	// then the value of version shall be 3.
+	if( iCertificates )
+		{
+		TInt certCount = iCertificates->Count();
+		for( TInt i = 0; i < certCount; i++ )
+			{
+			if( iCertificates->At( i )->AttrCert() )
+				{
+				iVersion = KAlternativeVersion;
+				return; // no reason to continue
+				}
+			}
+		}
+	}
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSSignerInfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,662 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSSignerInfo.h"
+#include    "TCMSTimeUtil.h"
+
+#include <x500dn.h>
+#include <asn1dec.h>
+#include <asn1enc.h>
+#include <signed.h>
+
+// CONSTANTS
+const TInt KMinNumberOfSubModules = 5;
+const TInt KMaxNumberOfSubModules = 7;
+const TInt KDefaultGranularity = 2;
+const TInt KCMSVersion1 = 1;
+const TInt KCMSVersion3 = 3;
+const TInt KSignedAttrsTag = 0;
+const TInt KUnsignedAttrsTag = 1;
+
+// CMS SignedAttributes useful types
+_LIT( KContentTypeOID, "1.2.840.113549.1.9.3" );
+_LIT( KMessageDigestOID, "1.2.840.113549.1.9.4" );
+_LIT( KSignTimeOID, "1.2.840.113549.1.9.5" );
+
+// Additional oid for adding certificates
+_LIT( KPKCS9SigCertOID, "1.2.840.113549.1.9.16.2.12" );
+
+// X509 URL certificate OID
+_LIT( KURLCertificateOID, "2.23.43.2.1" );
+
+// Defaulta id-data oid
+_LIT( KIDDataOID, "1.2.840.113549.1.7.1" );
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// Destructor
+CCMSSignerInfo::CSignerInfoData::~CSignerInfoData()
+    {
+	delete iIssuerAndSerial;
+	delete iSubjectKeyIdentifier;
+
+ 	if( iSignedAttributes )
+ 		{
+ 		iSignedAttributes->ResetAndDestroy();
+		delete iSignedAttributes;
+		}
+
+	if( iUnsignedAttributes )
+		{
+		iUnsignedAttributes->ResetAndDestroy();
+		delete iUnsignedAttributes;
+		}
+
+	delete iDigestAI;
+	delete iSignatureAI;
+	delete iSignatureValue;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::CCMSSignerInfo
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSSignerInfo::CCMSSignerInfo()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSSignerInfo::ConstructL(
+	const TDesC8& aCertificateUrl,
+	const TDesC8& aSubjectKeyID,
+	const TDesC8& aMessageDigest )
+    {
+	iData = new(ELeave) CSignerInfoData();
+	BaseConstructL( aMessageDigest );
+	SetCertificateUrlL( aCertificateUrl, aSubjectKeyID );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSSignerInfo::ConstructL(
+	const CCMSX509Certificate& aCertificate,
+	const TDesC8& aMessageDigest )
+    {
+	iData = new(ELeave) CSignerInfoData();
+	BaseConstructL( aMessageDigest );
+	SetCertificateL( aCertificate );
+    }
+
+void CCMSSignerInfo::BaseConstructL( const TDesC8& aMessageDigest )
+	{
+	iData->iDigestAI = CCMSX509AlgorithmIdentifier::NewL( ESHA1 );
+	iData->iSignatureAI = CCMSX509AlgorithmIdentifier::NewL();
+	TTime time;
+	time.UniversalTime();
+	iData->iSignedAttributes = new(ELeave)CArrayPtrFlat<CCMSAttribute>( KDefaultGranularity );
+	SetSignedAttributesL( KIDDataOID(),
+						  aMessageDigest,
+						  time,
+						  NULL );
+	iData->iUnsignedAttributes = new(ELeave)CArrayPtrFlat<CCMSAttribute>( KDefaultGranularity );
+    SetSignatureValueL( aMessageDigest );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSSignerInfo* CCMSSignerInfo::NewL()
+	{
+	// creating with empty values
+	CCMSSignerInfo* self = NewL( KNullDesC8(),
+								 KNullDesC8(),
+								 KNullDesC8() );
+
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSSignerInfo* CCMSSignerInfo::NewL(
+	const TDesC8& aCertificateUrl,
+	const TDesC8& aSubjectKeyID,
+	const TDesC8& aMessageDigest )
+    {
+    CCMSSignerInfo* self = new( ELeave ) CCMSSignerInfo();
+    CleanupStack::PushL( self );
+    self->ConstructL( aCertificateUrl, aSubjectKeyID, aMessageDigest );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSSignerInfo* CCMSSignerInfo::NewL(
+	const CCMSX509Certificate& aCertificate,
+	const TDesC8& aMessageDigest )
+    {
+    CCMSSignerInfo* self = new( ELeave ) CCMSSignerInfo();
+    CleanupStack::PushL( self );
+    self->ConstructL( aCertificate, aMessageDigest );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// Destructor
+CCMSSignerInfo::~CCMSSignerInfo()
+    {
+	delete iData;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSSignerInfo::DecodeL( const TDesC8& aRawData )
+	{
+	CSignerInfoData* tmpData = new(ELeave) CSignerInfoData();
+	CleanupStack::PushL( tmpData );
+	CArrayPtr<TASN1DecGeneric>* signerInfo = DecodeSequenceLC( aRawData,
+															  KMinNumberOfSubModules,
+															  KMaxNumberOfSubModules );
+	// we would not get this far if there is not min 5 elements
+	TInt pos = 0;
+	// decode Version
+	TASN1DecInteger version;
+	tmpData->iVersion = version.DecodeDERShortL( *signerInfo->At( pos++ ) );
+
+	if( tmpData->iVersion == KCMSVersion1 )
+		{
+		// decode IssuerAndSerialNumber
+		tmpData->iIssuerAndSerial =
+			CCMSIssuerAndSerialNumber::NewL();
+		tmpData->iIssuerAndSerial->DecodeL( signerInfo->At( pos++ )->Encoding() );
+		}
+	else
+		{
+		// decode SubjectKeyIdentifier
+		TASN1DecOctetString subjectKey;
+		tmpData->iSubjectKeyIdentifier =
+			subjectKey.DecodeDERL( *signerInfo->At( pos++ ) );
+		}
+
+	// decode DigestAlgorithIdentifier
+	tmpData->iDigestAI = CCMSX509AlgorithmIdentifier::NewL();
+	tmpData->iDigestAI->DecodeL( signerInfo->At( pos++ )->Encoding() );
+
+	// decode possible SignedAttributes
+	tmpData->iSignedAttributes =
+		new( ELeave )CArrayPtrFlat<CCMSAttribute>( KDefaultGranularity );
+	if( signerInfo->At( pos )->Tag() == KSignedAttrsTag )
+		{
+		DecodeAttributesL( signerInfo->At( pos++ )->Encoding(),
+						   tmpData->iSignedAttributes );
+		}
+
+	// decode SignatureAlgorithIdentifier
+	tmpData->iSignatureAI = CCMSX509AlgorithmIdentifier::NewL();
+	tmpData->iSignatureAI->DecodeL( signerInfo->At( pos++ )->Encoding() );
+
+	// check that we have enough parameters for mandatory fields
+	if( pos >= signerInfo->Count() )
+		{
+		User::Leave( KErrArgument );
+		}
+
+	// decode SignatureValue
+	TASN1DecOctetString signValue;
+	tmpData->iSignatureValue = signValue.DecodeDERL( *signerInfo->At( pos++ ) );
+
+	// decode possible UnsignedAttributes
+	tmpData->iUnsignedAttributes =
+		new( ELeave )CArrayPtrFlat<CCMSAttribute>( KDefaultGranularity );
+	if( ( pos < signerInfo->Count() ) &&
+		( signerInfo->At( pos )->Tag() == KUnsignedAttrsTag ) )
+		{
+		DecodeAttributesL( signerInfo->At( pos++ )->Encoding(),
+						   tmpData->iUnsignedAttributes );
+		}
+
+	CleanupStack::PopAndDestroy( signerInfo );
+
+	delete iData;
+	iData = tmpData;
+	CleanupStack::Pop( tmpData );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSSignerInfo::EncoderLC() const
+	{
+	CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+	// Add version
+	CASN1EncInt* version = CASN1EncInt::NewLC( iData->iVersion );
+	root->AddAndPopChildL( version );
+
+	// Add IssuerAndSerialNumber or SubjectKeyIdentifier
+	if( iData->iIssuerAndSerial )
+		{
+		CASN1EncBase* issuer = iData->iIssuerAndSerial->EncoderLC();
+		root->AddAndPopChildL( issuer );
+		}
+	else
+		{
+		CASN1EncOctetString* subjectKey =
+			CASN1EncOctetString::NewLC( *iData->iSubjectKeyIdentifier );
+		root->AddAndPopChildL( subjectKey );
+		}
+
+	// Add DigestAlgorithmIdentifier
+	CASN1EncBase* digestAlg = iData->iDigestAI->EncoderLC();
+	root->AddAndPopChildL( digestAlg );
+
+	// Add SignedAttributes if they exists
+	TInt signedAttributes = iData->iSignedAttributes->Count();
+	if( signedAttributes > 0 )
+		{
+		CASN1EncSequence* signedAttributesSet
+				= CASN1EncSequence::NewLC();
+		signedAttributesSet->SetTag( KSignedAttrsTag );
+
+		for( TInt i = 0; i < signedAttributes; i++ )
+			{
+			CASN1EncBase* attribute = iData->iSignedAttributes->At( i )->EncoderLC();
+			signedAttributesSet->AddAndPopChildL( attribute );
+			}
+		root->AddAndPopChildL( signedAttributesSet );
+		}
+
+	// Add SignatureAlgorithmIdentifier
+	CASN1EncBase* signatureAlg =  iData->iSignatureAI->EncoderLC();
+	root->AddAndPopChildL( signatureAlg );
+
+	// Add SignatureValue
+	CASN1EncOctetString* signValue =
+			CASN1EncOctetString::NewLC( *iData->iSignatureValue );
+	root->AddAndPopChildL( signValue );
+
+	// Add UnsignedAttributes if they exists
+	TInt unsignedAttributes = iData->iUnsignedAttributes->Count();
+	if( unsignedAttributes > 0 )
+		{
+		CASN1EncSequence* unsignedAttributesSet
+			= CASN1EncSequence::NewLC();
+		unsignedAttributesSet->SetTag( KUnsignedAttrsTag );
+
+		for( TInt i = 0; i < unsignedAttributes; i++ )
+			{
+			CASN1EncBase* attribute = iData->iUnsignedAttributes->At( i )->EncoderLC();
+			unsignedAttributesSet->AddAndPopChildL( attribute );
+			}
+		root->AddAndPopChildL( unsignedAttributesSet );
+		}
+
+	return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::CMSVersion()
+// Getter for Version
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCMSSignerInfo::CMSVersion() const
+	{
+	return iData->iVersion;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::IssuerAndSerialNumber()
+// Getter for IssuerAndSerialNumber
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSIssuerAndSerialNumber* CCMSSignerInfo::IssuerAndSerialNumber() const
+	{
+	return iData->iIssuerAndSerial;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::SubjectKeyIdentifier()
+// Getter for SubjectKeyIdentifier
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8* CCMSSignerInfo::SubjectKeyIdentifier() const
+	{
+	return iData->iSubjectKeyIdentifier;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::DigestAlgorithmIdentifier()
+// Getter for DigestAlgorithmIdentifier
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509AlgorithmIdentifier& CCMSSignerInfo::DigestAlgorithmIdentifier() const
+	{
+	return *iData->iDigestAI;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::SignedAttributes()
+// Getter for SignedAttributes
+// -----------------------------------------------------------------------------
+EXPORT_C const CArrayPtrFlat<CCMSAttribute>& CCMSSignerInfo::SignedAttributes() const
+	{
+	return *iData->iSignedAttributes;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::SignedAttributesEncodedL()
+// Getter for encoded SignedAttributes
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC8* CCMSSignerInfo::SignedAttributesEncodedL() const
+	{
+    HBufC8* retVal = NULL;
+	TInt signedAttributes = iData->iSignedAttributes->Count();
+	if( signedAttributes > 0 )
+		{
+		CASN1EncSequence* signedAttributesSet
+				= CASN1EncSequence::NewLC();
+		signedAttributesSet->SetTag( EASN1Set, EUniversal );
+
+		for( TInt i = 0; i < signedAttributes; i++ )
+			{
+			CASN1EncBase* attribute = iData->iSignedAttributes->At( i )->EncoderLC();
+			signedAttributesSet->AddAndPopChildL( attribute );
+			}
+        retVal = CreateDerEncodingL( signedAttributesSet );
+        CleanupStack::PopAndDestroy( signedAttributesSet );
+		}
+    return retVal;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::SignatureAlgorithmIdentifier()
+// Getter for SignatureAlgorithmIdentifier
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509AlgorithmIdentifier& CCMSSignerInfo::SignatureAlgorithmIdentifier() const
+	{
+	return *iData->iSignatureAI;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::SignatureValue()
+// Getter for SignatureValue
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8& CCMSSignerInfo::SignatureValue()	 const
+	{
+	return *iData->iSignatureValue;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::UnsignedAttributes()
+// Getter for UnsignedAttributes
+// -----------------------------------------------------------------------------
+EXPORT_C const CArrayPtrFlat<CCMSAttribute>& CCMSSignerInfo::UnsignedAttributes() const
+	{
+	return *iData->iUnsignedAttributes;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::SetCertificateL()
+// Setter for Certificate
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSSignerInfo::SetCertificateL( const CCMSX509Certificate& aCertificate )
+	{
+	// creating Issuer and serial
+	CCMSIssuerAndSerialNumber* tmpIssuer = CCMSIssuerAndSerialNumber::NewL(
+														aCertificate.Issuer(),
+														aCertificate.SerialNumber() );
+
+	delete iData->iIssuerAndSerial;
+	iData->iIssuerAndSerial = tmpIssuer;
+
+	// setting normal certificate, deleting possible certificate url
+	// and subject key identifier
+	TInt unsignedAttCount = iData->iUnsignedAttributes->Count();
+	for( TInt i = 0; i < unsignedAttCount; i++ )
+		{
+		CCMSAttribute* att = iData->iUnsignedAttributes->At( i );
+		if( att->AttributeType() == KURLCertificateOID() )
+			{
+			iData->iUnsignedAttributes->Delete( i );
+			delete att;
+			}
+		}
+	delete iData->iSubjectKeyIdentifier;
+	iData->iSubjectKeyIdentifier = NULL;
+
+	// changing version to 1
+	iData->iVersion = KCMSVersion1;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::SetCertificateUrlL()
+// Setter for certificate URL
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSSignerInfo::SetCertificateUrlL( const TDesC8& aCertificateUrl,
+												  const TDesC8& aSubjectKeyID )
+	{
+	CCMSAttribute* certUrl = CreateCertificateUrlLC( aCertificateUrl );
+	
+	// remove possible URL from unsigned attributes
+	TInt unsignedAttCount = iData->iUnsignedAttributes->Count();
+	for( TInt i = 0; i < unsignedAttCount; i++ )
+		{
+		CCMSAttribute* att = iData->iUnsignedAttributes->At( i );
+		if( att->AttributeType() == KURLCertificateOID() )
+			{
+			iData->iUnsignedAttributes->Delete( i );
+			delete att;
+			}
+		}
+	iData->iUnsignedAttributes->AppendL( certUrl );
+	CleanupStack::Pop( certUrl );
+
+	// taking copy of subject key identifier
+	HBufC8* tmpSubjectKeyID = aSubjectKeyID.AllocL();
+
+	delete iData->iSubjectKeyIdentifier;
+	iData->iSubjectKeyIdentifier = tmpSubjectKeyID;
+
+	// Issuer and serial is only for real certificates
+	delete iData->iIssuerAndSerial;
+	iData->iIssuerAndSerial = NULL;
+
+	// changing version to 3
+	iData->iVersion = KCMSVersion3;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::SetDigestAlgorithmIdentifier()
+// Setter for DigestAlgorithmIdentifier
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSSignerInfo::SetDigestAlgorithmIdentifier(
+				CCMSX509AlgorithmIdentifier& aDigestAI )
+	{
+	delete iData->iDigestAI;
+	iData->iDigestAI = &aDigestAI;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::SetSignatureAlgorithmIdentifier()
+// Setter for SignatureAlgorithmIdentifier
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSSignerInfo::SetSignatureAlgorithmIdentifier(
+				CCMSX509AlgorithmIdentifier& aSignatureAI )
+	{
+	delete iData->iSignatureAI;
+	iData->iSignatureAI = &aSignatureAI;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::SetSignatureValueL()
+// Setter for SignatureValue
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSSignerInfo::SetSignatureValueL( const TDesC8& aSignatureValue )
+	{
+	HBufC8* tmpSignValue = aSignatureValue.AllocL();
+	delete iData->iSignatureValue;
+	iData->iSignatureValue = tmpSignValue;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::SetSignedAttributesL()
+// Setter for Signed attributes
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSSignerInfo::SetSignedAttributesL( const TDesC& aContentType,
+													const TDesC8& aMessageDigest,
+													const TTime& aSigningTime,
+													const TDesC8* aCertHash )
+	{
+	CArrayPtrFlat<CCMSAttribute>* tmpAttributes =
+		new(ELeave)CArrayPtrFlat<CCMSAttribute>( KDefaultGranularity );
+	CleanupStack::PushL( tmpAttributes );
+	CleanupResetAndDestroy< CArrayPtrFlat<CCMSAttribute> >::PushL( *tmpAttributes );
+
+
+	if( aContentType != KNullDesC() )
+		{
+		// creating content type
+		CASN1EncObjectIdentifier* contOid =
+			CASN1EncObjectIdentifier::NewLC( aContentType );
+		HBufC8* contentType = CreateDerEncodingL( contOid );
+		CleanupStack::PushL( contentType );
+		CCMSAttribute* contType = CCMSAttribute::NewLC( KContentTypeOID, *contentType );
+		tmpAttributes->AppendL( contType );
+		CleanupStack::Pop( contType );
+		CleanupStack::PopAndDestroy( contentType );
+		CleanupStack::PopAndDestroy( contOid );
+		}
+
+	if( aMessageDigest != KNullDesC8() )
+		{
+		// creating MessageDigest
+		CASN1EncOctetString* signature =
+			CASN1EncOctetString::NewLC( aMessageDigest );
+		HBufC8* messageDigest = CreateDerEncodingL( signature );
+		CleanupStack::PushL( messageDigest );
+		CCMSAttribute* mDigest = CCMSAttribute::NewLC( KMessageDigestOID, *messageDigest );
+		tmpAttributes->AppendL( mDigest );
+		CleanupStack::Pop( mDigest );
+		CleanupStack::PopAndDestroy( messageDigest );
+		CleanupStack::PopAndDestroy( signature );
+		}
+
+	// creating Signing time
+    CASN1EncBase* signTimeDER = TCMSTimeUtil::ConvertToEncoderLC( aSigningTime );
+	HBufC8* signTime = CreateDerEncodingL( signTimeDER );
+	CleanupStack::PushL( signTime );
+	CCMSAttribute* sTime = CCMSAttribute::NewLC( KSignTimeOID, *signTime );
+	tmpAttributes->AppendL( sTime );
+	CleanupStack::Pop( sTime );
+	CleanupStack::PopAndDestroy( signTime );
+	CleanupStack::PopAndDestroy( signTimeDER );
+
+	// are we adding certificates
+	if( aCertHash )
+		{
+		CCMSAttribute* signingCert = 
+			CCMSAttribute::NewLC( KPKCS9SigCertOID, *aCertHash );
+		tmpAttributes->AppendL( signingCert );
+		CleanupStack::Pop( signingCert );
+		}
+
+	iData->iSignedAttributes->ResetAndDestroy();
+	delete iData->iSignedAttributes;
+	iData->iSignedAttributes = tmpAttributes;
+	CleanupStack::Pop( tmpAttributes ); // ResetAndDestroy
+	CleanupStack::Pop( tmpAttributes );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::SetUnsignedAttributesL()
+// Setter for Unsigned attributes
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSSignerInfo::SetUnsignedAttributesL(
+	CArrayPtrFlat<CCMSAttribute>& aUnsignedAttributes )
+	{
+	iData->iUnsignedAttributes->ResetAndDestroy();
+	delete iData->iUnsignedAttributes;
+	iData->iUnsignedAttributes = &aUnsignedAttributes;
+	}
+
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::DecodeAttributesL()
+// Decodes Attributes to array
+// -----------------------------------------------------------------------------
+void CCMSSignerInfo::DecodeAttributesL(
+	const TDesC8& aRawData,
+	CArrayPtrFlat<CCMSAttribute>* aAttributes )
+	{
+	TASN1DecSet attributeDec;
+	TInt pos = 0;
+	CArrayPtrFlat<TASN1DecGeneric>* attributes =
+		attributeDec.DecodeDERLC( aRawData, pos );
+
+	TInt numOfAttributes = attributes->Count();
+	for( TInt i = 0; i < numOfAttributes; i++ )
+		{
+		CCMSAttribute* att = CCMSAttribute::NewLC();
+		att->DecodeL( attributes->At( i )->Encoding() );
+		aAttributes->AppendL( att );
+		CleanupStack::Pop( att );
+		}
+	CleanupStack::PopAndDestroy( attributes );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSSignerInfo::CreateCertificateUrlLC()
+// Creates certificate url attribute
+// -----------------------------------------------------------------------------
+CCMSAttribute* CCMSSignerInfo::CreateCertificateUrlLC( const TDesC8& aCertificateUrl )
+	{
+	// Add certificate URL to unsigned attributes
+	CASN1EncOctetString* certificateUrlEnc =
+		CASN1EncOctetString::NewLC( aCertificateUrl );
+	//change tag to IA5
+	certificateUrlEnc->SetTag( EASN1IA5String );
+
+	HBufC8* certificateURL = CreateDerEncodingL( certificateUrlEnc );
+	CleanupStack::PushL( certificateURL );
+	CCMSAttribute* certUrl = CCMSAttribute::NewL( KURLCertificateOID, *certificateURL );
+	CleanupStack::PopAndDestroy( certificateURL );
+	CleanupStack::PopAndDestroy( certificateUrlEnc );
+	CleanupStack::PushL( certUrl );
+	return certUrl;
+	}
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSX509AlgorithmIdentifier.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,356 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSX509AlgorithmIdentifier.h"
+#include <x509cert.h>
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+const TInt KMinNumberOfSubModules = 1;
+const TInt KMaxNumberOfSubModules = 2;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSX509AlgorithmIdentifier::CCMSX509AlgorithmIdentifier
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509AlgorithmIdentifier::CCMSX509AlgorithmIdentifier()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AlgorithmIdentifier::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509AlgorithmIdentifier::ConstructL(
+	const TAlgorithmId& aAlgorithmId )
+    {
+	TAlgorithmId id = aAlgorithmId;
+	iAlgorithmIdentifier = CAlgorithmIdentifier::NewL( id, KNullDesC8() );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AlgorithmIdentifier::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509AlgorithmIdentifier::ConstructL(
+	const CAlgorithmIdentifier& aAlgorithmIdentifier )
+    {
+	iAlgorithmIdentifier = CAlgorithmIdentifier::NewL( aAlgorithmIdentifier );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AlgorithmIdentifier::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509AlgorithmIdentifier* CCMSX509AlgorithmIdentifier::NewL()
+	{
+    return NewL( ERSA );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AlgorithmIdentifier::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509AlgorithmIdentifier* CCMSX509AlgorithmIdentifier::NewL(
+	const TAlgorithmId& aAlgorithmId )
+    {
+    CCMSX509AlgorithmIdentifier* self = new( ELeave ) CCMSX509AlgorithmIdentifier();
+    CleanupStack::PushL( self );
+    self->ConstructL( aAlgorithmId );
+	CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AlgorithmIdentifier::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509AlgorithmIdentifier* CCMSX509AlgorithmIdentifier::NewL(
+	const CAlgorithmIdentifier& aAlgorithmIdentifier )
+	{
+	CCMSX509AlgorithmIdentifier* self = new( ELeave ) CCMSX509AlgorithmIdentifier();
+	CleanupStack::PushL( self );
+	self->ConstructL( aAlgorithmIdentifier );
+	CleanupStack::Pop( self );
+    return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AlgorithmIdentifier::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509AlgorithmIdentifier* CCMSX509AlgorithmIdentifier::NewL(
+	const CAlgorithmIdentifier& aAlgorithmIdentifier,
+	const CAlgorithmIdentifier& aDigestIdentifier )
+	{
+	CCMSX509AlgorithmIdentifier* self = new( ELeave ) CCMSX509AlgorithmIdentifier();
+	CleanupStack::PushL( self );
+	self->ConstructL( aAlgorithmIdentifier );
+	self->SetDigestAlgorithmL( &aDigestIdentifier );
+	CleanupStack::Pop( self );
+    return self;
+	}
+
+// Destructor
+CCMSX509AlgorithmIdentifier::~CCMSX509AlgorithmIdentifier()
+    {
+	delete iAlgorithmIdentifier;
+	delete iDigestAlgorithmIdentifier;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AlgorithmIdentifier::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSX509AlgorithmIdentifier::DecodeL( const TDesC8& aRawData )
+	{
+
+    CAlgorithmIdentifier* tmpAlgorithmIdentifier = NULL;
+    CAlgorithmIdentifier* tmpDigestAI = NULL;
+
+    // try simple algorithm
+	TRAPD( error, tmpAlgorithmIdentifier =
+					CX509AlgorithmIdentifier::NewL( aRawData ) ); 
+
+	// it is not simple algorithm identifier, trying with SigningAlgorithm
+	if( error == KErrNotSupported )
+		{
+        CX509SigningAlgorithmIdentifier* tmpSigning = NULL;
+		TRAPD( error2, tmpSigning =
+               CX509SigningAlgorithmIdentifier::NewL( aRawData ) );
+        if( error2 == KErrNone )
+            {
+            CleanupStack::PushL( tmpSigning );
+            tmpAlgorithmIdentifier = CAlgorithmIdentifier::NewLC(
+                tmpSigning->AsymmetricAlgorithm() );
+            tmpDigestAI =
+                CAlgorithmIdentifier::NewL( tmpSigning->DigestAlgorithm() );
+            CleanupStack::Pop( tmpAlgorithmIdentifier );
+            CleanupStack::PopAndDestroy( tmpSigning );
+            }
+        // it is not SigningAlgorithm, decode manually
+        else if( error2 == KErrNotSupported )
+            {
+            CArrayPtr<TASN1DecGeneric>* itemsData =
+							DecodeSequenceLC( aRawData,
+											  KMinNumberOfSubModules,
+											  KMaxNumberOfSubModules );
+            TInt pos = 0;
+            TInt count = itemsData->Count();
+            TASN1DecObjectIdentifier decOID;
+            HBufC* oid = decOID.DecodeDERL( *( itemsData->At( pos++ ) ) );
+            CleanupStack::PushL( oid );
+            if( *oid == KSHA1 )
+                {
+                TAlgorithmId algId( ESHA1 );
+                if( count > pos )
+                    {
+                    TASN1DecGeneric* gen = itemsData->At( pos );
+                    TPtrC8 encodedParams( gen->Encoding() );
+                    tmpAlgorithmIdentifier =
+                        CAlgorithmIdentifier::NewL( algId, encodedParams );
+                    }
+                else
+                    {
+                    TPtrC8 encodedParams( KNullDesC8() );
+                    tmpAlgorithmIdentifier =
+                        CAlgorithmIdentifier::NewL( algId, encodedParams );
+                    }
+                }
+            else
+                {
+                User::Leave( KErrNotSupported );
+                }
+            CleanupStack::PopAndDestroy( 2 ); // oid, itemsData
+            }
+        else
+            {
+            User::Leave( error2 );
+            }
+		}
+	else if( error != KErrNone )
+		{
+		User::Leave( error );
+		}
+	delete iAlgorithmIdentifier;
+	iAlgorithmIdentifier = tmpAlgorithmIdentifier;
+	delete iDigestAlgorithmIdentifier;
+	iDigestAlgorithmIdentifier = tmpDigestAI;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AlgorithmIdentifier::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSX509AlgorithmIdentifier::EncoderLC() const
+	{
+	CASN1EncSequence* root = CASN1EncSequence::NewLC();
+	CASN1EncObjectIdentifier* oid = NULL;
+	if( !iDigestAlgorithmIdentifier )
+		{
+		switch ( iAlgorithmIdentifier->Algorithm() )
+			{
+			case ERSA:
+				{
+				oid = CASN1EncObjectIdentifier::NewLC( KRSA );
+				break;
+				}
+			case EDSA:
+				{
+				oid = CASN1EncObjectIdentifier::NewLC( KDSA );
+				break;
+				}
+			case EDH:
+				{
+				oid = CASN1EncObjectIdentifier::NewLC( KDH );
+				break;
+				}
+			case EMD2:
+				{
+				oid = CASN1EncObjectIdentifier::NewLC( KMD2 );
+				break;
+				}
+			case EMD5:
+				{
+				oid = CASN1EncObjectIdentifier::NewLC( KMD5 );
+				break;
+				}
+			case ESHA1:
+				{
+				oid = CASN1EncObjectIdentifier::NewLC( KSHA1 );
+				break;
+				}
+			default:
+				{
+				User::Leave( KErrArgument );
+				}
+			}
+		}
+	else
+		{
+		// only valid combinations are MD2WithRSA, MD5WithRSA
+		// SHA1WithRSA and DSAWithSHA1
+		if( iAlgorithmIdentifier->Algorithm() == ERSA )
+			{
+			switch ( iDigestAlgorithmIdentifier->Algorithm() )
+				{
+				case EMD2:
+					{
+					oid = CASN1EncObjectIdentifier::NewLC( KMD2WithRSA );
+					break;
+					}
+				case EMD5:
+					{
+					oid = CASN1EncObjectIdentifier::NewLC( KMD5WithRSA );
+					break;
+					}
+				case ESHA1:
+					{
+					oid = CASN1EncObjectIdentifier::NewLC( KSHA1WithRSA );
+					break;
+					}
+				default:
+					{
+					User::Leave( KErrArgument );
+					}
+				}
+			}
+		else if( ( iAlgorithmIdentifier->Algorithm() == EDSA ) &&
+				 ( iDigestAlgorithmIdentifier->Algorithm() == ESHA1 ) )
+			{
+			oid = CASN1EncObjectIdentifier::NewLC( KDSAWithSHA1 );
+			}
+		else
+			{
+			// not valid combination
+			User::Leave( KErrArgument );
+			}
+		}
+
+	// add algorithm id
+	root->AddAndPopChildL( oid );
+
+	// add parameters
+	CASN1EncBase* parameters = NULL;
+	if( iAlgorithmIdentifier->EncodedParams() != KNullDesC8() )
+		{
+		parameters = CASN1EncEncoding::NewLC( iAlgorithmIdentifier->EncodedParams() );
+		}
+	else
+		{
+		parameters = CASN1EncNull::NewLC();
+		}
+	root->AddAndPopChildL( parameters );
+
+	return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AlgorithmIdentifier::AlgorithmIdentifier
+// Getter for AlgorithIdentifier
+// -----------------------------------------------------------------------------
+EXPORT_C const CAlgorithmIdentifier& CCMSX509AlgorithmIdentifier::AlgorithmIdentifier() const
+	{
+	return *iAlgorithmIdentifier;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AlgorithmIdentifier::SetAlgorithmIdentifierL
+// Setter for attribute type, takes copy
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509AlgorithmIdentifier::SetAlgorithmIdentifierL(
+	const CAlgorithmIdentifier& aAlgorithmIdentifier )
+	{
+	CAlgorithmIdentifier* tmpAi = CAlgorithmIdentifier::NewL( aAlgorithmIdentifier );
+	delete iAlgorithmIdentifier;
+	iAlgorithmIdentifier = tmpAi;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AlgorithmIdentifier::DigestAlgorithm
+// Getter for DigestAlgorithIdentifier
+// -----------------------------------------------------------------------------
+EXPORT_C const CAlgorithmIdentifier* CCMSX509AlgorithmIdentifier::DigestAlgorithm() const
+	{
+	return iDigestAlgorithmIdentifier;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AlgorithmIdentifier::SetDigestAlgorithmL
+// Setter for digest algorithm identifier, takes copy
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509AlgorithmIdentifier::SetDigestAlgorithmL(
+	const CAlgorithmIdentifier* aAlgorithmIdentifier )
+	{
+	CAlgorithmIdentifier* tmpAi = CAlgorithmIdentifier::NewL( *aAlgorithmIdentifier );
+	delete iDigestAlgorithmIdentifier;
+	iDigestAlgorithmIdentifier = tmpAi;
+	}
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSX509AttributeCertificate.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,268 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSX509AttributeCertificate.h"
+#include "CCMSX509AttributeCertificateInfo.h"
+#include "CCMSX509AlgorithmIdentifier.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificate::CCMSX509AttributeCertificate
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509AttributeCertificate::CCMSX509AttributeCertificate()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificate::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509AttributeCertificate::ConstructL(
+    const CCMSX509AttributeCertificateInfo& aInfo,
+    const CCMSX509AlgorithmIdentifier& aAlgorithmIdentifier,
+    const TDesC8& aEncrypted )
+    {
+    BaseConstructL( aAlgorithmIdentifier, aEncrypted );
+    SetInfoL( aInfo );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificate::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509AttributeCertificate::ConstructL( )
+    {
+    // creating empty/default values
+    iInfo = CCMSX509AttributeCertificateInfo::NewL();
+    iAlgorithmIdentifier = CCMSX509AlgorithmIdentifier::NewL();
+    iEncrypted = KNullDesC8().AllocL();
+    }
+    
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificate::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509AttributeCertificate*
+CCMSX509AttributeCertificate::NewL()
+	{
+	// creating with empty values
+    CCMSX509AttributeCertificate* self =
+        new( ELeave ) CCMSX509AttributeCertificate();
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificate::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509AttributeCertificate*
+CCMSX509AttributeCertificate::NewL(
+    const CCMSX509AttributeCertificateInfo& aInfo,
+    const CCMSX509AlgorithmIdentifier& aAlgorithmIdentifier,
+    const TDesC8& aEncrypted )
+    {
+    CCMSX509AttributeCertificate* self =
+        new( ELeave ) CCMSX509AttributeCertificate();
+    CleanupStack::PushL( self );
+    self->ConstructL( aInfo, aAlgorithmIdentifier, aEncrypted );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// Destructor
+CCMSX509AttributeCertificate::~CCMSX509AttributeCertificate()
+    {
+	delete iInfo;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificate::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSX509AttributeCertificate::DecodeL( const TDesC8& aRawData )
+	{
+    CCMSX509AlgorithmIdentifier* algId = NULL;
+    HBufC8* encrypted = NULL;
+    TASN1DecGeneric infoDecoder =
+        DecodeSignatureL( aRawData, algId, encrypted );
+
+    CleanupStack::PushL( algId );
+    CleanupStack::PushL( encrypted );
+    
+    // decode info
+    CCMSX509AttributeCertificateInfo* info =
+        CCMSX509AttributeCertificateInfo::NewL( );
+    CleanupStack::PushL( info );
+    info->DecodeL( infoDecoder.Encoding() );
+
+    // all done, change state
+    delete iInfo;
+    iInfo = info;
+    delete iAlgorithmIdentifier;
+    iAlgorithmIdentifier = algId;
+    delete iEncrypted;
+    iEncrypted = encrypted;
+    CleanupStack::Pop( 3 ); // info, encrypted, algId
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificate::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSX509AttributeCertificate::EncoderLC() const
+	{
+    // encode AttributeCertificateInfo
+    CASN1EncBase* info = iInfo->EncoderLC( );
+
+    // sign
+    CASN1EncSequence* root = SignAndPopLC( info );
+
+    return root;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificate::Info()
+// Getter for AttributeCertificateInfo
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509AttributeCertificateInfo&
+CCMSX509AttributeCertificate::Info() const
+	{
+	return *iInfo;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificate::SetInfoL()
+// Setter for AttributeCertificateInfo
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509AttributeCertificate::SetInfoL(
+    const CCMSX509AttributeCertificateInfo& aInfo )
+	{
+    CCMSX509AttributeCertificateInfo* info = NULL;
+    const CCMSX509IssuerSerial* baseCertificateID = aInfo.BaseCertificateID();
+    if( baseCertificateID )
+        {
+        info = CCMSX509AttributeCertificateInfo::NewL(
+            *baseCertificateID,
+            aInfo.Issuer(),
+            aInfo.Signature(),
+            aInfo.SerialNumber(),
+            aInfo.NotBeforeTime(),
+            aInfo.NotAfterTime(),
+            aInfo.Attributes() );
+        }
+    else
+        {
+        info = CCMSX509AttributeCertificateInfo::NewL(
+            *aInfo.SubjectName(),
+            aInfo.Issuer(),
+            aInfo.Signature(),
+            aInfo.SerialNumber(),
+            aInfo.NotBeforeTime(),
+            aInfo.NotAfterTime(),
+            aInfo.Attributes() );
+        }
+    CleanupStack::PushL( info );
+
+    info->SetVersion( aInfo.Version() );
+
+    const TDesC8* issuerUniqueID = aInfo.IssuerUniqueID();
+    if( issuerUniqueID )
+        {
+        info->SetIssuerUniqueIDL( *issuerUniqueID );
+        }
+
+    delete iInfo;
+    iInfo = info;
+    CleanupStack::Pop( info );
+    
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificate::DecodeImplicitTagL
+// Decrypts raw data with implicit tag
+// -----------------------------------------------------------------------------
+void CCMSX509AttributeCertificate::DecodeImplicitTagL(
+    const TDesC8& aRawData,
+    const TTagType aImplicitTag )
+    {
+    CArrayPtr< TASN1DecGeneric >* items = NULL;
+
+    // Check the tag
+    TASN1DecGeneric decGen( aRawData );
+    decGen.InitL();
+    // Accept only given tag
+    if( decGen.Tag() != aImplicitTag )
+        {
+        User::Leave( KErrArgument );
+        }
+    TASN1DecSequence decSeq;
+    items = decSeq.DecodeDERLC( decGen );
+    DecodeArrayL( items );
+    CleanupStack::PopAndDestroy( items );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificate::DecodeArrayL
+// Decodes data from an array of decoders
+// -----------------------------------------------------------------------------
+void CCMSX509AttributeCertificate::DecodeArrayL(
+    CArrayPtr< TASN1DecGeneric >* aItems )
+    {
+    CCMSX509AlgorithmIdentifier* algId = NULL;
+    HBufC8* encrypted = NULL;
+    TASN1DecGeneric infoDecoder =
+        DecodeSignatureArrayL( *aItems, algId, encrypted );
+
+    CleanupStack::PushL( algId );
+    CleanupStack::PushL( encrypted );
+    
+    // decode info
+    CCMSX509AttributeCertificateInfo* info =
+        CCMSX509AttributeCertificateInfo::NewL( );
+    CleanupStack::PushL( info );
+    info->DecodeL( infoDecoder.Encoding() );
+
+    // all done, change state
+    delete iInfo;
+    iInfo = info;
+    delete iAlgorithmIdentifier;
+    iAlgorithmIdentifier = algId;
+    delete iEncrypted;
+    iEncrypted = encrypted;
+    CleanupStack::Pop( 3 ); // info, encrypted, algId
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSX509AttributeCertificateInfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,676 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  X.509 AttributeCertificateInfo type
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSX509AttributeCertificateInfo.h"
+#include "CCMSX509IssuerSerial.h"
+#include "CCMSX509GeneralNames.h"
+#include "CCMSX509AlgorithmIdentifier.h"
+#include "CCMSAttribute.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KMinNumberOfSubModules = 6;
+const TInt KMaxNumberOfSubModules = 9;
+const TInt KValidityPeriodModuleCount = 2;
+const TInt KValidityNotBeforeIndex = 0;
+const TInt KValidityNotAfterIndex = 1;
+const TInt KDefaultGranularity = 1;
+const TInt KDefaultVersion = 0; // v1 == 0
+const TTagType KBaseCertificateIDTag = 0;
+const TTagType KSubjectNameTag = 1;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// Destructor
+CCMSX509AttributeCertificateInfo::CAttributeCertificateData::
+~CAttributeCertificateData()
+    {
+	delete iBaseCertificateID;
+	delete iSubjectName;
+	delete iIssuer;
+	delete iSignature;
+
+ 	if( iAttributes )
+ 		{
+ 		iAttributes->ResetAndDestroy();
+		delete iAttributes;
+		}
+
+    delete iIssuerUniqueID;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::CCMSX509AttributeCertificateInfo
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509AttributeCertificateInfo::CCMSX509AttributeCertificateInfo()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509AttributeCertificateInfo::ConstructL(
+    const CCMSX509IssuerSerial& aBaseCertificateID,
+    const CCMSX509GeneralNames& aIssuer,
+    const CCMSX509AlgorithmIdentifier& aSignature,
+    const TInt aSerialNumber,
+    const TTime& aNotBeforeTime,
+    const TTime& aNotAfterTime,
+    const CArrayPtr< CCMSAttribute >& aAttributes )
+    {
+    iData = new( ELeave ) CAttributeCertificateData();
+    iData->iVersion = KDefaultVersion;
+    SetBaseCertificateIDL( aBaseCertificateID );
+    SetIssuerL( aIssuer );
+    SetSignatureL( aSignature );
+    SetSerialNumber( aSerialNumber );
+    SetNotBeforeTimeL( aNotBeforeTime );
+    SetNotAfterTimeL( aNotAfterTime );
+    SetAttributesL( aAttributes );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509AttributeCertificateInfo::ConstructL(
+    const CCMSX509GeneralNames& aSubjectName,
+    const CCMSX509GeneralNames& aIssuer,
+    const CCMSX509AlgorithmIdentifier& aSignature,
+    const TInt aSerialNumber,
+    const TTime& aNotBeforeTime,
+    const TTime& aNotAfterTime,
+    const CArrayPtr< CCMSAttribute >& aAttributes )
+    {
+    iData = new( ELeave ) CAttributeCertificateData();
+    iData->iVersion = KDefaultVersion;
+    SetSubjectNameL( aSubjectName );
+    SetIssuerL( aIssuer );
+    SetSignatureL( aSignature );
+    SetSerialNumber( aSerialNumber );
+    SetNotBeforeTimeL( aNotBeforeTime );
+    SetNotAfterTimeL( aNotAfterTime );
+    SetAttributesL( aAttributes );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509AttributeCertificateInfo::ConstructL( )
+    {
+    // creating empty/default values
+    CAttributeCertificateData* data = new( ELeave ) CAttributeCertificateData();
+    CleanupStack::PushL( data );
+    data->iVersion = KDefaultVersion;
+    data->iBaseCertificateID = CCMSX509IssuerSerial::NewL();
+    data->iIssuer = CCMSX509GeneralNames::NewL();
+    data->iSignature = CCMSX509AlgorithmIdentifier::NewL();
+    data->iNotBeforeTime.UniversalTime();
+    data->iNotAfterTime.UniversalTime();
+    data->iNotAfterTime+=TTimeIntervalYears( 1 );
+    data->iAttributes = new( ELeave ) CArrayPtrFlat< CCMSAttribute >( 1 );
+    CleanupStack::Pop( data );
+    iData = data;
+    }
+    
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509AttributeCertificateInfo*
+CCMSX509AttributeCertificateInfo::NewL()
+	{
+	// creating with empty values
+    CCMSX509AttributeCertificateInfo* self =
+        new( ELeave ) CCMSX509AttributeCertificateInfo();
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509AttributeCertificateInfo*
+CCMSX509AttributeCertificateInfo::NewL(
+    const CCMSX509IssuerSerial& aBaseCertificateID,
+    const CCMSX509GeneralNames& aIssuer,
+    const CCMSX509AlgorithmIdentifier& aSignature,
+    const TInt aSerialNumber,
+    const TTime& aNotBeforeTime,
+    const TTime& aNotAfterTime,
+    const CArrayPtr< CCMSAttribute >& aAttributes )
+    {
+    CCMSX509AttributeCertificateInfo* self =
+        new( ELeave ) CCMSX509AttributeCertificateInfo();
+    CleanupStack::PushL( self );
+    self->ConstructL( aBaseCertificateID, aIssuer, aSignature, aSerialNumber,
+                      aNotBeforeTime, aNotAfterTime,
+                      aAttributes );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509AttributeCertificateInfo*
+CCMSX509AttributeCertificateInfo::NewL(
+    const CCMSX509GeneralNames& aSubjectName,
+    const CCMSX509GeneralNames& aIssuer,
+    const CCMSX509AlgorithmIdentifier& aSignature,
+    const TInt aSerialNumber,
+    const TTime& aNotBeforeTime,
+    const TTime& aNotAfterTime,
+    const CArrayPtr< CCMSAttribute >& aAttributes )
+    {
+    CCMSX509AttributeCertificateInfo* self =
+        new( ELeave ) CCMSX509AttributeCertificateInfo();
+    CleanupStack::PushL( self );
+    self->ConstructL( aSubjectName, aIssuer, aSignature, aSerialNumber,
+                      aNotBeforeTime, aNotAfterTime,
+                      aAttributes );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// Destructor
+CCMSX509AttributeCertificateInfo::~CCMSX509AttributeCertificateInfo()
+    {
+	delete iData;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSX509AttributeCertificateInfo::DecodeL( const TDesC8& aRawData )
+	{
+    CAttributeCertificateData* data = new( ELeave ) CAttributeCertificateData();
+    CleanupStack::PushL( data );
+    
+    CArrayPtr< TASN1DecGeneric >* itemList = DecodeSequenceLC(
+        aRawData, KMinNumberOfSubModules, KMaxNumberOfSubModules );
+
+    TInt sequenceCounter = 0;
+    
+    // decode version
+    TASN1DecGeneric* version = itemList->At( sequenceCounter );
+    TASN1DecInteger intDecoder;
+    if( ( version->Tag() == EASN1Integer ) &&
+        ( version->Class() == EUniversal ) )
+        {
+        data->iVersion =
+            intDecoder.DecodeDERShortL( *version );
+        sequenceCounter++;
+        }
+    else
+        {
+        data->iVersion = KDefaultVersion;
+        }
+
+    // decode subject
+    TASN1DecGeneric* subject = itemList->At( sequenceCounter++ );
+    subject->InitL( );
+    TTagType subjectTag( subject->Tag() );
+    switch( subjectTag )
+        {
+        case KBaseCertificateIDTag:
+            {
+            data->iBaseCertificateID = CCMSX509IssuerSerial::NewL();
+            data->iBaseCertificateID->DecodeL( subject->GetContentDER() );
+            break;
+            }
+        case KSubjectNameTag:
+            {
+            data->iSubjectName = CCMSX509GeneralNames::NewL();
+            data->iSubjectName->DecodeL( subject->GetContentDER() );
+            break;
+            }
+        default:
+            {
+            User::Leave( KErrArgument );
+            }
+        }
+
+    // decode issuer
+    TASN1DecGeneric* issuer = itemList->At( sequenceCounter++ );
+    issuer->InitL();
+    data->iIssuer = CCMSX509GeneralNames::NewL();
+    data->iIssuer->DecodeL( issuer->Encoding() );
+
+    // decode signature
+    TASN1DecGeneric* signature = itemList->At( sequenceCounter++ );
+    signature->InitL();
+    data->iSignature = CCMSX509AlgorithmIdentifier::NewL();
+    data->iSignature->DecodeL( signature->Encoding() );
+
+    // decode serialNumber
+    data->iSerialNumber =
+        intDecoder.DecodeDERShortL( *( itemList->At( sequenceCounter++ ) ) );
+
+    // decode attCertValidityPeriod
+    TASN1DecGeneric* validityPeriodDecoder = itemList->At( sequenceCounter++ );
+    validityPeriodDecoder->InitL();
+    CArrayPtr< TASN1DecGeneric >* validityPeriod = DecodeSequenceLC(
+        validityPeriodDecoder->Encoding(), KValidityPeriodModuleCount,
+        KValidityPeriodModuleCount );
+    TASN1DecGeneralizedTime timeDecoder;
+    data->iNotBeforeTime = timeDecoder.DecodeDERL(
+        *( validityPeriod->At( KValidityNotBeforeIndex ) ) );
+    data->iNotAfterTime = timeDecoder.DecodeDERL(
+        *( validityPeriod->At( KValidityNotAfterIndex ) ) );
+    CleanupStack::PopAndDestroy( validityPeriod );
+
+    // decode attributes
+    TASN1DecGeneric* attributesDecoder = itemList->At( sequenceCounter++ );
+    attributesDecoder->InitL();
+    CArrayPtr< TASN1DecGeneric >* attributes = DecodeSequenceLC(
+        attributesDecoder->Encoding() );
+    TInt attributeCount = attributes->Count();
+    data->iAttributes = new( ELeave ) CArrayPtrFlat< CCMSAttribute >(
+        attributeCount ? attributeCount : KDefaultGranularity );
+    for( TInt i = 0; i < attributeCount; i++ )
+        {
+        TASN1DecGeneric* attributeDecoder = attributes->At( i );
+        attributeDecoder->InitL();
+        CCMSAttribute* attribute = CCMSAttribute::NewLC();
+        attribute->DecodeL( attributeDecoder->Encoding() );
+        data->iAttributes->AppendL( attribute );
+        CleanupStack::Pop( attribute );
+        }
+    CleanupStack::PopAndDestroy( attributes );
+    
+    // decode issuerUniqueID
+    if( itemList->Count() > sequenceCounter )
+        {
+        TASN1DecBitString bsDecoder;
+        data->iIssuerUniqueID = bsDecoder.ExtractOctetStringL(
+            *( itemList->At( sequenceCounter ) ) );
+        }
+
+    // all decoded, change state
+    CleanupStack::PopAndDestroy( itemList );
+    
+    delete iData;
+    iData = data;
+
+    CleanupStack::Pop( data );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSX509AttributeCertificateInfo::EncoderLC() const
+	{
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+    
+    // encode version
+    CASN1EncInt* version = CASN1EncInt::NewLC( iData->iVersion );
+    root->AddAndPopChildL( version );
+    
+    // encode subject
+    CASN1EncBase* subject = NULL;
+    if( iData->iBaseCertificateID )
+        {
+        // encode baseCertificateID  [0]  IssuerSerial
+        CASN1EncBase* baseCertificateID =
+            iData->iBaseCertificateID->EncoderLC( );
+        CleanupStack::Pop( baseCertificateID );
+        subject = CASN1EncExplicitTag::NewLC(
+            baseCertificateID, KBaseCertificateIDTag );
+        }
+    else
+        {
+        // encode subjectName        [1]  GeneralNames
+        CASN1EncBase* subjectName = iData->iSubjectName->EncoderLC( );
+        CleanupStack::Pop( subjectName );
+        subject = CASN1EncExplicitTag::NewLC( subjectName, KSubjectNameTag );
+        }
+    root->AddAndPopChildL( subject );
+    
+    // encode issuer
+    CASN1EncBase* issuer = iData->iIssuer->EncoderLC();
+    root->AddAndPopChildL( issuer );
+    
+    // encode signature
+    CASN1EncBase* signature = iData->iSignature->EncoderLC();
+    root->AddAndPopChildL( signature );
+    
+    // encode serialNumber
+    CASN1EncInt* serialNumber = CASN1EncInt::NewLC( iData->iSerialNumber );
+    root->AddAndPopChildL( serialNumber );
+    
+    // encode attCertValidityPeriod
+    CASN1EncSequence* validityPeriod = CASN1EncSequence::NewLC( );
+    // encode notBeforeTime
+    CASN1EncGeneralizedTime* notBeforeTime =
+        CASN1EncGeneralizedTime::NewLC( iData->iNotBeforeTime );
+    validityPeriod->AddAndPopChildL( notBeforeTime );
+    //encode notAfterTime
+    CASN1EncGeneralizedTime* notAfterTime =
+        CASN1EncGeneralizedTime::NewLC( iData->iNotAfterTime );
+    validityPeriod->AddAndPopChildL( notAfterTime );
+    root->AddAndPopChildL( validityPeriod );
+    
+    // encode attributes             SEQUENCE OF Attribute
+    CASN1EncSequence* attributes = CASN1EncSequence::NewLC();
+    TInt attributeCount = iData->iAttributes->Count();
+    for( TInt i = 0; i < attributeCount; i++ )
+        {
+        CCMSAttribute* attribute = iData->iAttributes->At( i );
+        CASN1EncBase* attributeEncoder = attribute->EncoderLC( );
+        attributes->AddAndPopChildL( attributeEncoder );
+        }
+    root->AddAndPopChildL( attributes );
+    
+    // encode issuerUniqueID         UniqueIdentifier OPTIONAL
+    if( iData->iIssuerUniqueID )
+        {
+        CASN1EncBitString* uniqueID =
+            CASN1EncBitString::NewLC( *( iData->iIssuerUniqueID ) );
+        root->AddAndPopChildL( uniqueID );
+        }
+    
+    return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::Version()
+// Getter for Version
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCMSX509AttributeCertificateInfo::Version() const
+	{
+	return iData->iVersion;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::BaseCertificateID()
+// Getter for baseCertificateID
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509IssuerSerial*
+CCMSX509AttributeCertificateInfo::BaseCertificateID() const
+	{
+	return iData->iBaseCertificateID;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::SubjectName()
+// Getter for subjectName
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509GeneralNames*
+CCMSX509AttributeCertificateInfo::SubjectName() const
+	{
+	return iData->iSubjectName;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::Issuer()
+// Getter for Issuer
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509GeneralNames&
+CCMSX509AttributeCertificateInfo::Issuer() const
+	{
+	return *iData->iIssuer;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::Signature()
+// Getter for signature
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509AlgorithmIdentifier&
+CCMSX509AttributeCertificateInfo::Signature() const
+	{
+	return *iData->iSignature;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::SerialNumber()
+// Getter for serialNumber
+// -----------------------------------------------------------------------------
+EXPORT_C TInt
+CCMSX509AttributeCertificateInfo::SerialNumber() const
+	{
+	return iData->iSerialNumber;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::NotBeforeTime()
+// Getter for notBeforeTime
+// -----------------------------------------------------------------------------
+EXPORT_C const TTime& CCMSX509AttributeCertificateInfo::NotBeforeTime()	 const
+	{
+	return iData->iNotBeforeTime;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::NotAfterTime()
+// Getter for notAfterTime
+// -----------------------------------------------------------------------------
+EXPORT_C const TTime& CCMSX509AttributeCertificateInfo::NotAfterTime()	 const
+	{
+	return iData->iNotAfterTime;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::Attributes()
+// Getter for Attributes
+// -----------------------------------------------------------------------------
+EXPORT_C const CArrayPtr<CCMSAttribute>&
+CCMSX509AttributeCertificateInfo::Attributes() const
+	{
+	return *iData->iAttributes;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::IssuerUniqueID()
+// Getter for subjectName
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8*
+CCMSX509AttributeCertificateInfo::IssuerUniqueID() const
+	{
+	return iData->iIssuerUniqueID;
+	}
+
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::SetVersion()
+// Setter for version
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509AttributeCertificateInfo::SetVersion(
+    const TInt aVersion )
+	{
+	iData->iVersion = aVersion;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::SetBaseCertificateIDL()
+// Setter for baseCertificateID, deletes also subjectName
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509AttributeCertificateInfo::SetBaseCertificateIDL(
+    const CCMSX509IssuerSerial& aBaseCertificateID )
+	{
+    CCMSX509IssuerSerial* id = CCMSX509IssuerSerial::NewL(
+        aBaseCertificateID.Issuer(), aBaseCertificateID.Serial() );
+    CleanupStack::PushL( id );
+    const TDesC8* uid = aBaseCertificateID.IssuerUID();
+    if( uid )
+        {
+        id->SetIssuerUIDL( *uid );
+        }
+    CleanupStack::Pop( id );
+    delete iData->iBaseCertificateID;
+    iData->iBaseCertificateID = id;
+    delete iData->iSubjectName;
+    iData->iSubjectName = NULL;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::SetSubjectNameL()
+// Setter for subjectName, deletes also baseCertificateID
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509AttributeCertificateInfo::SetSubjectNameL(
+    const CCMSX509GeneralNames& aSubjectName )
+	{
+    CCMSX509GeneralNames* subjectName =
+        CCMSX509GeneralNames::NewL( aSubjectName );
+    delete iData->iSubjectName;
+    iData->iSubjectName = subjectName;
+    delete iData->iBaseCertificateID;
+    iData->iBaseCertificateID = NULL;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::SetIssuerL()
+// Setter for Issuer
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509AttributeCertificateInfo::SetIssuerL(
+    const CCMSX509GeneralNames& aIssuer )
+	{
+    CCMSX509GeneralNames* issuer = CCMSX509GeneralNames::NewL( aIssuer );
+    delete iData->iIssuer;
+    iData->iIssuer = issuer;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::SetSignatureL()
+// Setter for Signature
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509AttributeCertificateInfo::SetSignatureL(
+    const CCMSX509AlgorithmIdentifier& aSignature )
+	{
+    CCMSX509AlgorithmIdentifier* signature =
+        CCMSX509AlgorithmIdentifier::NewL( aSignature.AlgorithmIdentifier() );
+    CleanupStack::PushL( signature );
+    const CAlgorithmIdentifier* digestIdentifier =
+        aSignature.DigestAlgorithm();
+    if( digestIdentifier )
+        {
+        signature->SetDigestAlgorithmL( digestIdentifier );
+        }
+    CleanupStack::Pop( signature );
+    delete iData->iSignature;
+    iData->iSignature = signature;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::SetSerialNumber()
+// Setter for serialNumber
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509AttributeCertificateInfo::SetSerialNumber(
+    const TInt aSerialNumber )
+	{
+    iData->iSerialNumber = aSerialNumber;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::SetNotBeforeTimeL()
+// Setter for notBeforeTime
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509AttributeCertificateInfo::SetNotBeforeTimeL(
+	const TTime& aNotBeforeTime )
+	{
+    iData->iNotBeforeTime = aNotBeforeTime;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::SetNotAfterTimeL()
+// Setter for notAfterTime
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509AttributeCertificateInfo::SetNotAfterTimeL(
+	const TTime& aNotAfterTime )
+	{
+    iData->iNotAfterTime = aNotAfterTime;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::SetAttributesL()
+// Setter for attributes
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509AttributeCertificateInfo::SetAttributesL(
+	const CArrayPtr< CCMSAttribute >& aAttributes )
+	{
+    TInt attributeCount = aAttributes.Count();
+    CArrayPtr< CCMSAttribute >* attributes = NULL;
+    if( attributeCount > 0 )
+        {
+        attributes =
+            new( ELeave ) CArrayPtrFlat< CCMSAttribute >( attributeCount );
+        CleanupStack::PushL( attributes );
+        for( TInt i = 0; i < attributeCount; i++ )
+            {
+            const CCMSAttribute* origAttribute = aAttributes[ i ];
+            CCMSAttribute* attribute =
+                CCMSAttribute::NewLC( origAttribute->AttributeType(),
+                                      origAttribute->AttributeValues() );
+            attributes->AppendL( attribute );
+            }
+    
+        CleanupStack::Pop( attributeCount ); // all attributes
+        CleanupStack::Pop( attributes );
+        }
+    else
+        {
+        attributes =
+            new( ELeave ) CArrayPtrFlat< CCMSAttribute >( KDefaultGranularity );
+        }
+
+
+    if( iData->iAttributes )
+        {
+        iData->iAttributes->ResetAndDestroy();
+        delete iData->iAttributes;
+        }
+    iData->iAttributes = attributes;
+    
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509AttributeCertificateInfo::SetIssuerUniqueIDL()
+// Setter for issuerUniqueID
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509AttributeCertificateInfo::SetIssuerUniqueIDL(
+	const TDesC8& aIssuerUniqueID )
+	{
+    HBufC8* uniqueId = aIssuerUniqueID.AllocL();
+    delete iData->iIssuerUniqueID;
+    iData->iIssuerUniqueID = uniqueId;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSX509Certificate.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,624 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  X.509 Certificate type
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSX509Certificate.h"
+#include "CCMSX509AlgorithmIdentifier.h"
+#include "CCMSX509Validity.h"
+#include "CCMSX509SubjectPublicKeyInfo.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KVersion2 = 1;
+const TInt KVersion3 = 2;
+const TTagType KVersionTag = 0;
+const TTagType KIssuerUniqueIdentifierTag = 1;
+const TTagType KSubjectUniqueIdentifierTag = 2;
+const TInt KToBeSignedItemsMin = 6;
+const TInt KToBeSignedItemsMax = 10;
+const TInt KDefaultGranularity = 1;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// Destructor
+CCMSX509Certificate::CCertificateData::~CCertificateData()
+    {
+    delete iSerialNumber;
+    delete iSignature;
+    delete iIssuer;
+    delete iValidity;
+    delete iSubject;
+    delete iSubjectPublicKeyInfo;
+    delete iIssuerUniqueIdentifier;
+    delete iSubjectUniqueIdentifier;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::CCMSX509Certificate
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509Certificate::CCMSX509Certificate( )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509Certificate::ConstructL(
+    const TDesC8& aSerialNumber,
+    const CCMSX509AlgorithmIdentifier& aSignature,
+    const CX500DistinguishedName& aIssuer,
+    const CCMSX509Validity& aValidity,
+    const CX500DistinguishedName& aSubject,
+    const CCMSX509SubjectPublicKeyInfo& aSubjectPublicKeyInfo,
+    const CCMSX509AlgorithmIdentifier& aAlgorithmIdentifier,
+    const TDesC8& aEncrypted )
+    {
+    BaseConstructL( aAlgorithmIdentifier, aEncrypted );
+    iData = new( ELeave ) CCertificateData;
+    SetSerialNumberL( aSerialNumber );
+    SetSignatureL( aSignature );
+    SetIssuerL( aIssuer );
+    SetValidityL( aValidity );
+    SetSubjectL( aSubject );
+    SetSubjectPublicKeyInfoL( aSubjectPublicKeyInfo );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509Certificate::ConstructL(
+    const CX509Certificate& aCertificate )
+    {
+    SetDataL( aCertificate );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509Certificate::ConstructL( )
+    {
+    // creating empty/default values
+    CArrayPtrFlat< CX520AttributeTypeAndValue >* elements = new( ELeave )
+        CArrayPtrFlat< CX520AttributeTypeAndValue >( KDefaultGranularity );
+    CleanupStack::PushL( elements );
+    
+    iData = new( ELeave ) CCertificateData;
+    iData->iSerialNumber = KNullDesC8().AllocL();
+    iData->iSignature = CCMSX509AlgorithmIdentifier::NewL();
+    iData->iIssuer = CX500DistinguishedName::NewL( *elements );
+    iData->iValidity = CCMSX509Validity::NewL();
+    iData->iSubject = CX500DistinguishedName::NewL( *elements );
+    iData->iSubjectPublicKeyInfo = CCMSX509SubjectPublicKeyInfo::NewL();
+
+    CleanupStack::PopAndDestroy( elements );
+    
+    iAlgorithmIdentifier = CCMSX509AlgorithmIdentifier::NewL();
+    iEncrypted = KNullDesC8().AllocL();
+    
+    }
+    
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509Certificate*
+CCMSX509Certificate::NewL()
+	{
+	// creating with empty values
+    CCMSX509Certificate* self =
+        new( ELeave ) CCMSX509Certificate();
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509Certificate*
+CCMSX509Certificate::NewL(
+    const TDesC8& aSerialNumber,
+    const CCMSX509AlgorithmIdentifier& aSignature,
+    const CX500DistinguishedName& aIssuer,
+    const CCMSX509Validity& aValidity,
+    const CX500DistinguishedName& aSubject,
+    const CCMSX509SubjectPublicKeyInfo& aSubjectPublicKeyInfo,
+    const CCMSX509AlgorithmIdentifier& aAlgorithmIdentifier,
+    const TDesC8& aEncrypted )
+    {
+    CCMSX509Certificate* self =
+        new( ELeave ) CCMSX509Certificate();
+    CleanupStack::PushL( self );
+    self->ConstructL( aSerialNumber, aSignature, aIssuer, aValidity, aSubject,
+                      aSubjectPublicKeyInfo, aAlgorithmIdentifier, aEncrypted );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509Certificate*
+CCMSX509Certificate::NewL(
+    const CX509Certificate& aCertificate )
+    {
+    CCMSX509Certificate* self =
+        new( ELeave ) CCMSX509Certificate();
+    CleanupStack::PushL( self );
+    self->ConstructL( aCertificate );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// Destructor
+CCMSX509Certificate::~CCMSX509Certificate()
+    {
+	delete iData;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSX509Certificate::DecodeL( const TDesC8& aRawData )
+	{
+    CCMSX509AlgorithmIdentifier* algId = NULL;
+    HBufC8* encrypted = NULL;
+    TASN1DecGeneric dataDecoder =
+        DecodeSignatureL( aRawData, algId, encrypted );
+
+    CleanupStack::PushL( algId );
+    CleanupStack::PushL( encrypted );
+    
+    CArrayPtr< TASN1DecGeneric >* itemList = DecodeSequenceLC(
+        dataDecoder.Encoding(), KToBeSignedItemsMin, KToBeSignedItemsMax );
+
+    CCertificateData* data = new( ELeave ) CCertificateData();
+    CleanupStack::PushL( data );
+
+    TInt sequenceCounter = 0;
+
+    // decode version
+    TASN1DecGeneric* taggedVersion = itemList->At( sequenceCounter );
+    if( ( taggedVersion->Tag() == KVersionTag ) &&
+        ( taggedVersion->Class() == EContextSpecific ) )
+        {
+        TASN1DecGeneric version( taggedVersion->GetContentDER() );
+        version.InitL();
+        TASN1DecInteger intDecoder;
+        data->iVersion =
+            intDecoder.DecodeDERShortL( version );
+        sequenceCounter++;
+        }
+
+    // decode serialNumber
+    data->iSerialNumber =
+        itemList->At( sequenceCounter++ )->GetContentDER().AllocL();
+
+    // decode signature
+    data->iSignature = CCMSX509AlgorithmIdentifier::NewL();
+    data->iSignature->DecodeL( itemList->At( sequenceCounter++)->Encoding() );
+
+    // decode issuer
+    data->iIssuer = CX500DistinguishedName::NewL(
+        itemList->At( sequenceCounter++ )->Encoding() );
+
+    // decode validity
+    data->iValidity = CCMSX509Validity::NewL();
+    data->iValidity->DecodeL( itemList->At( sequenceCounter++ )->Encoding() );
+
+    // decode subject
+    data->iSubject = CX500DistinguishedName::NewL(
+        itemList->At( sequenceCounter++ )->Encoding() );
+
+    // decode subjectPublicKeyInfo
+    data->iSubjectPublicKeyInfo = CCMSX509SubjectPublicKeyInfo::NewL();
+    data->iSubjectPublicKeyInfo->DecodeL(
+        itemList->At( sequenceCounter++ )->Encoding() );
+
+    // decode issuerUniqueIdentifier, if it exists
+    TInt itemCount = itemList->Count();
+    TASN1DecBitString bsDecoder;
+    if( sequenceCounter < itemCount )
+        {
+        TASN1DecGeneric* taggedIssuerUniqueIdentifier =
+            itemList->At( sequenceCounter );
+        if( taggedIssuerUniqueIdentifier->Tag() == KIssuerUniqueIdentifierTag )
+            {
+            data->iIssuerUniqueIdentifier =
+                bsDecoder.ExtractOctetStringL( *taggedIssuerUniqueIdentifier );
+            sequenceCounter++;
+            }
+        }
+    
+    // decode subjectUniqueIdentifier, if it exists
+    if( sequenceCounter < itemCount )
+        {
+        TASN1DecGeneric* taggedSubjectUniqueIdentifier =
+            itemList->At( sequenceCounter );
+        if( taggedSubjectUniqueIdentifier->Tag() == KSubjectUniqueIdentifierTag )
+            {
+            data->iSubjectUniqueIdentifier =
+                bsDecoder.ExtractOctetStringL( *taggedSubjectUniqueIdentifier );
+            sequenceCounter++;
+            }
+        }
+
+    // extensions are ignored
+    
+    // all done, change state
+    delete iAlgorithmIdentifier;
+    iAlgorithmIdentifier = algId;
+    delete iEncrypted;
+    iEncrypted = encrypted;
+    delete iData;
+    iData = data;
+    CleanupStack::Pop( data );
+    CleanupStack::PopAndDestroy( itemList );
+    CleanupStack::Pop( encrypted );
+    CleanupStack::Pop( algId );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSX509Certificate::EncoderLC() const
+	{
+
+    // encode ToBeSigned part
+    CASN1EncBase* toBeSigned = ToBeSignedEncoderLC();
+
+    // sign
+    CASN1EncSequence* root = SignAndPopLC( toBeSigned );
+
+    return root;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::Version()
+// Getter for Version
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCMSX509Certificate::Version() const
+	{
+	return iData->iVersion;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::SerialNumber()
+// Getter for SerialNumber
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8& CCMSX509Certificate::SerialNumber() const
+	{
+	return *( iData->iSerialNumber );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::Signature()
+// Getter for signature
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509AlgorithmIdentifier& CCMSX509Certificate::Signature() const
+	{
+	return *( iData->iSignature );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::Issuer()
+// Getter for issuer
+// -----------------------------------------------------------------------------
+EXPORT_C const CX500DistinguishedName& CCMSX509Certificate::Issuer() const
+	{
+	return *( iData->iIssuer );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::Validity()
+// Getter for Validity
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509Validity& CCMSX509Certificate::Validity() const
+	{
+	return *( iData->iValidity );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::Subject()
+// Getter for subject
+// -----------------------------------------------------------------------------
+EXPORT_C const CX500DistinguishedName& CCMSX509Certificate::Subject() const
+	{
+	return *( iData->iSubject );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::SubjectPublicKeyInfo()
+// Getter for subjectPublicKeyInfo
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509SubjectPublicKeyInfo&
+CCMSX509Certificate::SubjectPublicKeyInfo() const
+	{
+	return *( iData->iSubjectPublicKeyInfo );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::IssuerUniqueIdentifier()
+// Getter for issuerUniqueIdentifier
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8* CCMSX509Certificate::IssuerUniqueIdentifier() const
+	{
+	return iData->iIssuerUniqueIdentifier;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::SubjectUniqueIdentifier()
+// Getter for subjectUniqueIdentifier
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8* CCMSX509Certificate::SubjectUniqueIdentifier() const
+	{
+	return iData->iSubjectUniqueIdentifier;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::SetVersion()
+// Setter for version
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509Certificate::SetVersion( const TInt aVersion )
+	{
+    iData->iVersion = aVersion;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::SetSerialNumberL()
+// Setter for serialNumber
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509Certificate::SetSerialNumberL( const TDesC8& aSerialNumber )
+	{
+    HBufC8* serialNumber = aSerialNumber.AllocLC();
+    delete iData->iSerialNumber;
+    iData->iSerialNumber = serialNumber;
+    CleanupStack::Pop( serialNumber );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::SetSignatureL()
+// Setter for signature
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509Certificate::SetSignatureL(
+    const CCMSX509AlgorithmIdentifier& aSignature )
+	{
+    CCMSX509AlgorithmIdentifier* signature =
+        CCMSX509AlgorithmIdentifier::NewL( aSignature.AlgorithmIdentifier() );
+    CleanupStack::PushL( signature );
+    const CAlgorithmIdentifier* digestIdentifier =
+        aSignature.DigestAlgorithm();
+    if( digestIdentifier )
+        {
+        signature->SetDigestAlgorithmL( digestIdentifier );
+        }
+    CleanupStack::Pop( signature );
+    delete iData->iSignature;
+    iData->iSignature = signature;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::SetIssuerL()
+// Setter for issuer
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509Certificate::SetIssuerL(
+    const CX500DistinguishedName& aIssuer )
+	{
+    CX500DistinguishedName* issuer = CX500DistinguishedName::NewL( aIssuer );
+    delete iData->iIssuer;
+    iData->iIssuer = issuer;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::SetValidityL()
+// Setter for validity
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509Certificate::SetValidityL(
+    const CCMSX509Validity& aValidity )
+	{
+    CCMSX509Validity* validity =
+        CCMSX509Validity::NewL( aValidity.NotBefore(), aValidity.NotAfter() );
+    delete iData->iValidity;
+    iData->iValidity = validity;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::SetSubjectL()
+// Setter for subject
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509Certificate::SetSubjectL(
+    const CX500DistinguishedName& aSubject )
+	{
+    CX500DistinguishedName* subject = CX500DistinguishedName::NewL( aSubject );
+    delete iData->iSubject;
+    iData->iSubject = subject;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::SetSubjectPublicKeyInfoL()
+// Setter for subjectPublicKeyInfo
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509Certificate::SetSubjectPublicKeyInfoL(
+    const CCMSX509SubjectPublicKeyInfo& aSubjectPublicKeyInfo )
+	{
+    CCMSX509SubjectPublicKeyInfo* spkInfo = CCMSX509SubjectPublicKeyInfo::NewL(
+        aSubjectPublicKeyInfo.Algorithm(),
+        aSubjectPublicKeyInfo.SubjectPublicKey() );
+    delete iData->iSubjectPublicKeyInfo;
+    iData->iSubjectPublicKeyInfo = spkInfo;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::SetIssuerUniqueIdentifierL()
+// Setter for issuerUniqueIdentifier, make sure version is v2 or v3
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509Certificate::SetIssuerUniqueIdentifierL(
+    const TDesC8& aIssuerUniqueIdentifier )
+	{
+    HBufC8* issuerUniqueIdentifier = aIssuerUniqueIdentifier.AllocL();
+    delete iData->iIssuerUniqueIdentifier;
+    iData->iIssuerUniqueIdentifier = issuerUniqueIdentifier;
+    if( ( iData->iVersion > KVersion3 ) || ( iData->iVersion < KVersion2 ) )
+        {
+        iData->iVersion = KVersion2;
+        }
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::SetSubjectUniqueIdentifierL()
+// Setter for subjectUniqueIdentifier, make sure version is v2 or v3
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509Certificate::SetSubjectUniqueIdentifierL(
+    const TDesC8& aSubjectUniqueIdentifier )
+	{
+    HBufC8* subjectUniqueIdentifier = aSubjectUniqueIdentifier.AllocL();
+    delete iData->iSubjectUniqueIdentifier;
+    iData->iSubjectUniqueIdentifier = subjectUniqueIdentifier;
+    if( ( iData->iVersion > KVersion3 ) || ( iData->iVersion < KVersion2 ) )
+        {
+        iData->iVersion = KVersion2;
+        }
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::ToBeSignedEncoderLC
+// Returns ASN1 encoder for the the ToBeSigned part
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSX509Certificate::ToBeSignedEncoderLC() const
+	{
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+    // encode version
+    CASN1EncInt* version = CASN1EncInt::NewL( iData->iVersion );
+    CASN1EncExplicitTag* taggedVersion =
+        CASN1EncExplicitTag::NewLC( version, KVersionTag );
+    root->AddAndPopChildL( taggedVersion );
+    
+    // encode serialNumber
+    CASN1EncOctetString* serialNumber =
+        CASN1EncOctetString::NewLC( *( iData->iSerialNumber ) );
+    serialNumber->SetTag( EASN1Integer, EUniversal );
+    root->AddAndPopChildL( serialNumber );
+
+    // encode signature
+    CASN1EncBase* signature = iData->iSignature->EncoderLC();
+    root->AddAndPopChildL( signature );
+
+    // encode issuer
+    CASN1EncSequence* issuer = iData->iIssuer->EncodeASN1LC();
+    root->AddAndPopChildL( issuer );
+    
+    // encode validity
+    CASN1EncBase* validity = iData->iValidity->EncoderLC();
+    root->AddAndPopChildL( validity );
+
+    // encode subject
+    CASN1EncSequence* subject = iData->iSubject->EncodeASN1LC();
+    root->AddAndPopChildL( subject );
+
+    // encode subjectPublicKeyInfo
+    CASN1EncBase* spkInfo = iData->iSubjectPublicKeyInfo->EncoderLC();
+    root->AddAndPopChildL( spkInfo );
+
+    if( iData->iIssuerUniqueIdentifier )
+        {
+        CASN1EncBitString* iuIdentifier =
+            CASN1EncBitString::NewLC( *iData->iIssuerUniqueIdentifier );
+        iuIdentifier->SetTag( KIssuerUniqueIdentifierTag );
+        root->AddAndPopChildL( iuIdentifier );
+        }
+    if( iData->iSubjectUniqueIdentifier )
+        {
+        CASN1EncBitString* suIdentifier =
+            CASN1EncBitString::NewLC( *iData->iSubjectUniqueIdentifier );
+        suIdentifier->SetTag( KSubjectUniqueIdentifierTag );
+        root->AddAndPopChildL( suIdentifier );
+        }
+    
+    return root;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Certificate::SetDataL
+// Copies the data from the CX509Certificate object
+// -----------------------------------------------------------------------------
+void CCMSX509Certificate::SetDataL( const CX509Certificate& aCertificate )
+    {
+    const CSigningAlgorithmIdentifier& signingAlgorithm =
+        aCertificate.SigningAlgorithm();
+    CCMSX509AlgorithmIdentifier* algId =
+        CCMSX509AlgorithmIdentifier::NewL( signingAlgorithm.AsymmetricAlgorithm(),
+                                           signingAlgorithm.DigestAlgorithm() );
+    CleanupStack::PushL( algId );
+
+    HBufC8* encrypted = aCertificate.Signature().AllocLC();
+
+    CCertificateData* data = new( ELeave ) CCertificateData();
+    CleanupStack::PushL( data );
+
+    data->iVersion = aCertificate.Version();
+    
+    data->iSerialNumber = aCertificate.SerialNumber().AllocL();
+
+    data->iSignature = CCMSX509AlgorithmIdentifier::NewL(
+        signingAlgorithm.AsymmetricAlgorithm(),
+        signingAlgorithm.DigestAlgorithm() );
+
+    data->iIssuer = CX500DistinguishedName::NewL( aCertificate.IssuerName() );
+    
+    data->iValidity = CCMSX509Validity::NewL( aCertificate.ValidityPeriod() );
+
+    data->iSubject = CX500DistinguishedName::NewL( aCertificate.SubjectName() );
+
+    data->iSubjectPublicKeyInfo = CCMSX509SubjectPublicKeyInfo::NewL(
+        aCertificate.PublicKey() );
+
+    // all done, change state
+    delete iData;
+    iData = data;
+    delete iAlgorithmIdentifier;
+    iAlgorithmIdentifier = algId;
+    delete iEncrypted;
+    iEncrypted = encrypted;
+    CleanupStack::Pop( 3 ); // data, encrypted, algId
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSX509CertificateList.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,605 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSX509CertificateList.h"
+#include    "TCMSTimeUtil.h"
+#include    "CCMSX509AlgorithmIdentifier.h"
+#include <x509cert.h>
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KDefaultGranularity = 1;
+const TInt KCertificateListParams = 3;
+const TInt KMinTBSCertListParams = 3;
+const TInt KMaxTBSCertListParams = 7;
+const TInt KDefaultVersion = 1;
+const TInt KMinRevokedCertParams = 2;
+const TInt KMaxRevokedCertParams = 3;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSX509RevokedCertificate::CCMSX509RevokedCertificate
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+
+EXPORT_C CCMSX509RevokedCertificate::CCMSX509RevokedCertificate()
+	{
+	}
+
+// Destructor
+CCMSX509RevokedCertificate::~CCMSX509RevokedCertificate()
+	{
+	if( iExtensions )
+		{
+		iExtensions->ResetAndDestroy();
+		delete iExtensions;
+		}
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509RevokedCertificate::CCMSX509RevokedCertificate
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+EXPORT_C CCMSX509CertificateListParameters::CCMSX509CertificateListParameters()
+	{
+	}
+
+// Destructor
+CCMSX509CertificateListParameters::~CCMSX509CertificateListParameters()
+	{
+	delete iIssuer;
+	delete iSignatureAlgorithm;
+	delete iSignature;
+	if( iRevokedCertificates )
+		{
+		iRevokedCertificates->ResetAndDestroy();
+		delete iRevokedCertificates;
+		}
+
+	if( iExtensions )
+		{
+		iExtensions->ResetAndDestroy();
+		delete iExtensions;
+		}
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509CertificateList::CCMSX509CertificateList
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509CertificateList::CCMSX509CertificateList()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509CertificateList::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509CertificateList::ConstructL()
+    {
+	iParams = new(ELeave) CCMSX509CertificateListParameters();
+	// version is always v2(1)
+	iParams->iVersion = KDefaultVersion;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509CertificateList::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509CertificateList::ConstructL(
+	const CX509Certificate& aSigningCertificate,
+	const CArrayPtrFlat<CX509Certificate>& aRevokedCertificates )
+    {
+	ConstructL();
+
+	// setting signature
+	const CSigningAlgorithmIdentifier& signAlgorithm =
+		aSigningCertificate.SigningAlgorithm();
+	iParams->iSignatureAlgorithm =
+		CCMSX509AlgorithmIdentifier::NewL( signAlgorithm.AsymmetricAlgorithm(),
+										   signAlgorithm.DigestAlgorithm() );
+
+	// setting issuer
+	iParams->iIssuer =
+		CX500DistinguishedName::NewL( aSigningCertificate.IssuerName() );
+
+	// setting validity
+	const CValidityPeriod& validity = aSigningCertificate.ValidityPeriod();
+	iParams->iThisUpdate = validity.Start();
+	iParams->iNextUpdate = validity.Finish();
+
+
+	// copying revoked certificates
+	TInt revCerts = aRevokedCertificates.Count();
+	if( revCerts > 0 )
+		{
+		iParams->iRevokedCertificates =
+			new( ELeave )CArrayPtrFlat< CCMSX509RevokedCertificate >
+												( KDefaultGranularity );
+		for( TInt i = 0; i < revCerts; i++ )
+			{
+			CX509Certificate* cert = aRevokedCertificates[ i ];
+			CCMSX509RevokedCertificate* tmpRevCer =
+				new(ELeave) CCMSX509RevokedCertificate();
+			CleanupStack::PushL( tmpRevCer );
+			// convert serial from des to int
+            TPtrC8 serialDes = cert->SerialNumber();
+            TInt length = serialDes.Size();
+            const TUint8* ptr = serialDes.Ptr();
+            TInt serial = ( ptr[ 0 ] & 0x80 ) ? -1 : 0;
+            for( TInt j = 0; j < length; j++ )
+                {
+                serial <<= 8;
+                serial += *ptr++;
+                }
+			tmpRevCer->iUserCertificateSerialNumber = serial;
+
+			const CValidityPeriod& reValidity = cert->ValidityPeriod();
+			tmpRevCer->iRevokationDate = reValidity.Start();
+
+			// copying extensions
+			const CArrayPtrFlat<CX509CertExtension>& extensions =
+				cert->Extensions();
+			TInt extensionCount = extensions.Count();
+			if( extensionCount > 0 )
+				{
+				tmpRevCer->iExtensions =
+					new(ELeave) CArrayPtrFlat<CX509CertExtension>
+														( KDefaultGranularity );
+				for( TInt j = 0; j < extensionCount; j++ )
+					{
+					CX509CertExtension* ext = extensions[ j ];
+					CX509CertExtension* tmpExt =
+									CX509CertExtension::NewLC( *ext );
+					tmpRevCer->iExtensions->AppendL( tmpExt );
+					CleanupStack::Pop( tmpExt );
+					}
+				}
+			iParams->iRevokedCertificates->AppendL( tmpRevCer );
+			CleanupStack::Pop( tmpRevCer );
+			}
+		}
+	// copying possible extensions
+	TInt extensionCount = aSigningCertificate.Extensions().Count();
+	if( extensionCount > 0 )
+		{
+		iParams->iExtensions =
+			new( ELeave )CArrayPtrFlat< CX509CertExtension >
+														( KDefaultGranularity );
+		const CArrayPtrFlat< CX509CertExtension >& extensions =
+			aSigningCertificate.Extensions();
+
+		for( TInt i = 0; i < extensionCount; i++ )
+			{
+			CX509CertExtension* copy = CX509CertExtension::NewL( *extensions[ i ] );
+			CleanupStack::PushL( copy );
+			iParams->iExtensions->AppendL( copy );
+			CleanupStack::Pop( copy );
+			}
+		}
+
+	// copying signature
+	iParams->iSignature = aSigningCertificate.Signature().AllocL();
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509CertificateList::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509CertificateList* CCMSX509CertificateList::NewLC()
+	{
+    CCMSX509CertificateList* self = new( ELeave ) CCMSX509CertificateList();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509CertificateList::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509CertificateList* CCMSX509CertificateList::NewLC(
+	const CX509Certificate& aSigningCertificate,
+	const CArrayPtrFlat<CX509Certificate>& aRevokedCertificates  )
+    {
+    CCMSX509CertificateList* self = new( ELeave ) CCMSX509CertificateList();
+    CleanupStack::PushL( self );
+    self->ConstructL( aSigningCertificate,
+    				  aRevokedCertificates );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509CertificateList::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509CertificateList* CCMSX509CertificateList::NewLC(
+	CCMSX509CertificateListParameters& aParameters )
+    {
+    CCMSX509CertificateList* self = new( ELeave ) CCMSX509CertificateList();
+    CleanupStack::PushL( self );
+    self->SetParametersL( aParameters );
+    return self;
+    }
+
+// Destructor
+CCMSX509CertificateList::~CCMSX509CertificateList()
+    {
+	delete iParams;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509CertificateList::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSX509CertificateList::DecodeL( const TDesC8& aRawData )
+	{
+	CCMSX509CertificateListParameters* params =
+		new(ELeave) CCMSX509CertificateListParameters();
+	CleanupStack::PushL( params );
+
+	CArrayPtr<TASN1DecGeneric>* certificateList = DecodeSequenceLC( aRawData,
+															  KCertificateListParams, // 3
+															  KCertificateListParams );
+
+
+	// decode tbsCertList
+	CArrayPtr<TASN1DecGeneric>* tbsCertList =
+		DecodeSequenceLC( certificateList->At( 0 )->Encoding(),
+						  KMinTBSCertListParams,	// 3
+						  KMaxTBSCertListParams );	// 7
+
+	TInt pos = 0;
+	// decode Version (optional)
+	TASN1DecGeneric ver( *tbsCertList->At( pos ) );
+	if( ver.Tag() == EASN1Integer )
+		{
+		TASN1DecInteger version;
+		params->iVersion = version.DecodeDERShortL( ver );
+		pos++;
+		}
+	else
+		{
+		// always ver v2( 1 )
+		params->iVersion = KDefaultVersion;
+		}
+
+	// decode Signature algorithm
+	CCMSX509AlgorithmIdentifier* signAlg = CCMSX509AlgorithmIdentifier::NewL();
+	CleanupStack::PushL( signAlg );
+	signAlg->DecodeL( tbsCertList->At( pos++ )->Encoding() );
+	params->iSignatureAlgorithm = signAlg;
+	CleanupStack::Pop( signAlg );
+
+	// decode Issuer
+	params->iIssuer =
+		CX500DistinguishedName::NewL( tbsCertList->At( pos++ )->Encoding() );
+
+	// check that we have enough parameters for mandatory thisUpdate
+	if( tbsCertList->Count() <= pos )
+		{
+		User::Leave( KErrArgument );
+		}
+
+	// decode thisUpdate
+	params->iThisUpdate = TCMSTimeUtil::ConvertToTimeL(
+									  tbsCertList->At( pos++ )->Encoding() );
+
+	// decode nextUpdate (optional)
+	if( ( tbsCertList->Count() > pos ) &&
+		( ( tbsCertList->At( pos )->Tag() == EASN1UTCTime ) ||
+		  ( tbsCertList->At( pos )->Tag() == EASN1GeneralizedTime ) ) )
+		{
+		params->iNextUpdate = TCMSTimeUtil::ConvertToTimeL(
+									  tbsCertList->At( pos++ )->Encoding() );
+		}
+
+	// decode revokedCerts (optional)
+	if( ( tbsCertList->Count() > pos ) &&
+		( tbsCertList->At( pos )->Tag() == EASN1Sequence ) )
+		{
+		// if it is sequence then it must be set of revoked certificates
+		CArrayPtr<TASN1DecGeneric>* revokedCerts =
+				 DecodeSequenceLC( tbsCertList->At( pos++ )->Encoding() );
+		TInt rCertCount = revokedCerts->Count();
+		params->iRevokedCertificates =
+			new(ELeave)CArrayPtrFlat< CCMSX509RevokedCertificate >
+													( KDefaultGranularity );
+		for( TInt i = 0; i < rCertCount; i++ )
+			{
+			// decode certificate
+			CArrayPtr<TASN1DecGeneric>* rCert =
+					 DecodeSequenceLC( revokedCerts->At( i )->Encoding(),
+					 KMinRevokedCertParams, // 2
+					 KMaxRevokedCertParams ); // 3
+			CCMSX509RevokedCertificate* tmpCert =
+				new( ELeave )CCMSX509RevokedCertificate;
+			CleanupStack::PushL( tmpCert );
+
+			// decode serial number
+			TASN1DecInteger serial;
+			tmpCert->iUserCertificateSerialNumber =
+									serial.DecodeDERShortL( *rCert->At( 0 ) );
+
+			// decode revocationDate
+			tmpCert->iRevokationDate = TCMSTimeUtil::ConvertToTimeL(
+										rCert->At( 1 )->Encoding() );
+
+			// decode possible extensions
+			if( rCert->Count() == KMaxRevokedCertParams )
+				{
+				tmpCert->iExtensions = DecodeExtensionsL( rCert->At( 2 ) );
+				}
+			params->iRevokedCertificates->AppendL( tmpCert );
+
+			CleanupStack::Pop( tmpCert );
+			CleanupStack::PopAndDestroy( rCert );
+			}
+		CleanupStack::PopAndDestroy( revokedCerts );
+		}
+	// decode extensions (optional), tagged with 0
+	if( ( tbsCertList->Count() > pos ) &&
+		( tbsCertList->At( pos )->Tag() == 0 ) )
+		{
+		TASN1DecGeneric extens( tbsCertList->At( pos )->GetContentDER() );
+        extens.InitL();
+		params->iExtensions = DecodeExtensionsL( &extens );
+		}
+
+	CleanupStack::PopAndDestroy( tbsCertList );
+
+	// decode signature algorithm,
+	// just check that it is same as
+	// already set one
+	signAlg = CCMSX509AlgorithmIdentifier::NewL();
+	CleanupStack::PushL( signAlg );
+	signAlg->DecodeL( certificateList->At( 1 )->Encoding() );
+	if( !( signAlg->AlgorithmIdentifier() ==
+		   params->iSignatureAlgorithm->AlgorithmIdentifier() ) )
+		{
+		User::Leave( KErrArgument );
+		}
+	CleanupStack::PopAndDestroy( signAlg );
+
+	// decode signature
+	TASN1DecBitString signature;
+	params->iSignature = signature.ExtractOctetStringL( *certificateList->At( 2 ) );
+	CleanupStack::PopAndDestroy( certificateList );
+
+	delete iParams;
+	iParams = params;
+	CleanupStack::Pop( params );
+	}
+// -----------------------------------------------------------------------------
+// CCMSX509CertificateList::DecodeExtensionsL
+// Decodes Extensions
+// -----------------------------------------------------------------------------
+CArrayPtrFlat<CX509CertExtension>* CCMSX509CertificateList::DecodeExtensionsL(
+	const TASN1DecGeneric* aExtensions )
+	{
+	CArrayPtr<TASN1DecGeneric>* extens =
+			 DecodeSequenceLC( aExtensions->Encoding() );
+	TInt extensionCount = extens->Count();
+	CArrayPtrFlat< CX509CertExtension >* tmpExtensions =
+		new(ELeave)CArrayPtrFlat< CX509CertExtension >( KDefaultGranularity );
+	CleanupStack::PushL( tmpExtensions );
+	CleanupResetAndDestroyPushL( *tmpExtensions );
+	for( TInt j = 0; j < extensionCount; j++ )
+		{
+		CX509CertExtension* extension =
+			CX509CertExtension::NewLC( extens->At( j )->Encoding() );
+		tmpExtensions->AppendL( extension );
+		CleanupStack::Pop( extension );
+		}
+	CleanupStack::Pop( tmpExtensions ); // ResetAndDestroy
+	CleanupStack::Pop( tmpExtensions ); // normal cleanup
+	CleanupStack::PopAndDestroy( extens );
+	return tmpExtensions;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509CertificateList::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSX509CertificateList::EncoderLC() const
+	{
+	CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+	// encoding tbsCertList
+	CASN1EncSequence* tbsCertList = CASN1EncSequence::NewLC();
+
+	// encoding version
+	CASN1EncInt* version = CASN1EncInt::NewLC( KDefaultVersion );
+	tbsCertList->AddAndPopChildL( version );
+
+	// encoding signature
+	HBufC8* signDes;
+	iParams->iSignatureAlgorithm->EncodeL( signDes );
+	CleanupStack::PushL( signDes );
+	CASN1EncEncoding* signatureEnc =
+		CASN1EncEncoding::NewLC( *signDes );
+	tbsCertList->AddAndPopChildL( signatureEnc );
+	CleanupStack::PopAndDestroy( signDes );
+
+	// encoding issuer
+	CASN1EncSequence* issuer = iParams->iIssuer->EncodeASN1LC();
+	tbsCertList->AddAndPopChildL( issuer );
+
+	// encoding thisUpdate
+	CASN1EncBase* thisUpdate =
+		TCMSTimeUtil::ConvertToEncoderLC( iParams->iThisUpdate );
+	tbsCertList->AddAndPopChildL( thisUpdate );
+
+	// encoding nextUpdate
+	CASN1EncBase* nextUpdate =
+		TCMSTimeUtil::ConvertToEncoderLC( iParams->iNextUpdate );
+	tbsCertList->AddAndPopChildL( nextUpdate );
+
+	// encoding possible revokedCerts
+	if( iParams->iRevokedCertificates &&
+		iParams->iRevokedCertificates->Count() )
+		{
+		CASN1EncSequence* revokedCerts = CASN1EncSequence::NewLC();
+		TInt numOfRevokedCerts = iParams->iRevokedCertificates->Count();
+
+		for( TInt i = 0; i < numOfRevokedCerts; i++ )
+			{
+			// encoding certificate
+			CASN1EncSequence* revokedCertificate = CASN1EncSequence::NewLC();
+
+			CCMSX509RevokedCertificate* cert = iParams->iRevokedCertificates->At( i );
+			// encoding serial number
+			CASN1EncInt* serialEnc =
+				CASN1EncInt::NewLC( cert->iUserCertificateSerialNumber );
+			revokedCertificate->AddAndPopChildL( serialEnc );
+
+			// encoding revocationDate
+			CASN1EncBase* revocationDate =
+				TCMSTimeUtil::ConvertToEncoderLC( cert->iRevokationDate );
+			revokedCertificate->AddAndPopChildL( revocationDate );
+
+			// encoding possible extensions
+			CASN1EncSequence* extensions = EncodeExtensionsLC( cert->iExtensions );
+			if( extensions )
+				{
+				revokedCertificate->AddAndPopChildL( extensions );
+				}
+			revokedCerts->AddAndPopChildL( revokedCertificate );
+			}
+		tbsCertList->AddAndPopChildL( revokedCerts );
+		}
+
+	// encoding possible extensions
+	CASN1EncSequence* ext = EncodeExtensionsLC( iParams->iExtensions );
+	if( ext )
+		{
+		CleanupStack::Pop( ext );
+		// this will take ownership of the extensions
+		// tagging extensions with value 0
+		CASN1EncExplicitTag* explExt =
+			CASN1EncExplicitTag::NewLC( ext, 0 );
+		tbsCertList->AddAndPopChildL( explExt );
+		}
+
+	root->AddAndPopChildL( tbsCertList );
+
+	// encoding signatureValue
+	iParams->iSignatureAlgorithm->EncodeL( signDes );
+	CleanupStack::PushL( signDes );
+	signatureEnc =
+		CASN1EncEncoding::NewLC( *signDes );
+	root->AddAndPopChildL( signatureEnc );
+	CleanupStack::PopAndDestroy( signDes );
+
+	// encoding signature
+	CASN1EncBitString* signatureBitString =
+		CASN1EncBitString::NewLC( *iParams->iSignature );
+	root->AddAndPopChildL( signatureBitString );
+
+	return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509CertificateList::EncodeExtensionsLC
+// Encodes Extensions
+// -----------------------------------------------------------------------------
+CASN1EncSequence* CCMSX509CertificateList::EncodeExtensionsLC(
+	const CArrayPtrFlat<CX509CertExtension>* aExtensions ) const
+	{
+	CASN1EncSequence* extensionsEnc = NULL;
+	if(	  aExtensions &&
+		( aExtensions->Count() > 0 ) )
+		{
+		TInt extensionCount = aExtensions->Count();
+		extensionsEnc = CASN1EncSequence::NewLC();
+		for( TInt i = 0; i < extensionCount; i++ )
+			{
+			CASN1EncSequence* extEnc = CASN1EncSequence::NewLC();
+			CX509CertExtension* extension = aExtensions->At( i );
+			// encoding id
+			CASN1EncObjectIdentifier* id =
+				CASN1EncObjectIdentifier::NewLC( extension->Id() );
+			extEnc->AddAndPopChildL( id );
+
+			// encoding possible critical flag
+			if( extension->Critical() )
+				{
+				CASN1EncBoolean* critical =
+					CASN1EncBoolean::NewLC( ETrue );
+				extEnc->AddAndPopChildL( critical );
+				}
+			// encoding data, have to decode it before encoding it again
+			// because CASN1EncEncoding changes TagType to Constructed
+			TASN1DecOctetString dataDec;
+			TInt pos = 0;
+			HBufC8* data = dataDec.DecodeDERL( extension->Data(), pos );
+			CleanupStack::PushL( data );
+			CASN1EncOctetString* dataEnc =
+				CASN1EncOctetString::NewLC( *data );
+			extEnc->AddAndPopChildL( dataEnc );
+			CleanupStack::PopAndDestroy( data );
+
+			extensionsEnc->AddAndPopChildL( extEnc );
+			}
+		}
+	return extensionsEnc;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509CertificateList::Parameters
+// Getter for Signing Certificate
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509CertificateListParameters&
+	CCMSX509CertificateList::Parameters() const
+	{
+	return *iParams;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509CertificateList::SetParametersL
+// Setter for signing certificate, takes ownership
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509CertificateList::SetParametersL(
+	CCMSX509CertificateListParameters& aParameters  )
+	{
+	// some sanity checks
+	if( !aParameters.iIssuer ||
+		!aParameters.iSignature ||
+		!aParameters.iSignatureAlgorithm ||
+	   ( aParameters.iVersion != KDefaultVersion ) )
+		{
+		User::Leave( KErrArgument );
+		}
+	delete iParams;
+	iParams = &aParameters;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSX509GeneralName.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,207 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSX509GeneralName.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TTagType KMaxTag = 8;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralName::CCMSX509GeneralName
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509GeneralName::CCMSX509GeneralName( )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralName::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509GeneralName::ConstructL(
+    const TTagType aTag,
+    const TDesC8& aData )
+    {
+    SetTagL( aTag );
+    SetDataL( aData );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralName::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509GeneralName* CCMSX509GeneralName::NewL()
+	{
+	// creating with empty/default values
+	CCMSX509GeneralName* self = NewL( 0, KNullDesC8() );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralName::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509GeneralName* CCMSX509GeneralName::NewL(
+    const TTagType aTag,
+    const TDesC8& aData )
+    {
+    CCMSX509GeneralName* self =
+    	new( ELeave ) CCMSX509GeneralName( );
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aTag, aData );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// Destructor
+CCMSX509GeneralName::~CCMSX509GeneralName()
+    {
+    delete iData;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralName::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSX509GeneralName::DecodeL( const TDesC8& aRawData )
+	{
+    TASN1DecGeneric decGen( aRawData );
+    decGen.InitL();
+    TTagType tag = decGen.Tag();
+    if( tag > KMaxTag )
+        {
+        User::Leave( KErrArgument );
+        }
+    HBufC8* data = decGen.GetContentDER().AllocL();
+    iTag = tag;
+    delete iData;
+    iData = data;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralName::EncodeL
+// Encrypts this instance to descriptor
+// -----------------------------------------------------------------------------
+
+void CCMSX509GeneralName::EncodeL( HBufC8*& aResult ) const
+	{
+	CASN1EncBase* root = EncoderLC();
+
+	// encode the object in a DER encoding
+    HBufC8* der = HBufC8::NewMaxLC( root->LengthDER() );
+    TPtr8 pder( der->Des() );
+    TUint pos = 0;
+    root->WriteDERL( pder, pos );
+    CleanupStack::Pop( der );
+    aResult = der;
+
+	CleanupStack::PopAndDestroy( root );
+	}
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralName::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSX509GeneralName::EncoderLC() const
+	{
+    TASN1DecGeneric genDec( *iData );
+    genDec.InitL();
+    TTagType dataTag( genDec.Tag() );
+    TASN1Class dataClass( genDec.Class() );
+    TUint8 fullTag = *( iData->Ptr() );
+    CASN1EncBase* baseEnc = NULL;
+
+    // is the data constructed?
+    if( ( fullTag & 0x20 ) != 0 )
+        {
+        baseEnc = CASN1EncEncoding::NewL( *iData );
+        }
+    else
+        {
+        TASN1DecOctetString dataDec;
+        TInt pos = 0;
+        HBufC8* data = dataDec.DecodeDERL( *iData, pos );
+        CleanupStack::PushL( data );
+        baseEnc = CASN1EncOctetString::NewL( *data );
+        CleanupStack::PopAndDestroy( data );
+        }
+    baseEnc->SetTag( dataTag, dataClass );
+    // CASN1EncExplicitTag takes ownership of dataEnc, even when Leaving
+    CASN1EncExplicitTag* taggedEnc =
+        CASN1EncExplicitTag::NewLC( baseEnc, iTag );
+
+    return taggedEnc;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralName::Tag
+// Tag getter.
+// -----------------------------------------------------------------------------
+EXPORT_C TTagType CCMSX509GeneralName::Tag() const
+	{
+	return iTag;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralName::Data
+// Data getter.
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8& CCMSX509GeneralName::Data() const
+	{
+	return *iData;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralName::SetTagL
+// Tag setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509GeneralName::SetTagL(
+	const TTagType aTag )
+	{
+    if( aTag > KMaxTag )
+        {
+        User::Leave( KErrArgument );
+        }
+    iTag = aTag;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralName::SetDataL
+// Data setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509GeneralName::SetDataL(
+	const TDesC8& aData )
+	{
+    HBufC8* data = aData.AllocL();
+    delete iData;
+    iData = data;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSX509GeneralNames.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,211 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  X.509 GeneralNames type
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSX509GeneralNames.h"
+#include "CCMSX509GeneralName.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KCMSGranularity = 1;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralNames::CCMSX509GeneralNames
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509GeneralNames::CCMSX509GeneralNames()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralNames::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509GeneralNames::ConstructL(
+    const CArrayPtr< CCMSX509GeneralName >& aGeneralNames )
+    {
+    SetGeneralNamesL( aGeneralNames );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralNames::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509GeneralNames* CCMSX509GeneralNames::NewL()
+	{
+	// creating with empty/default values
+    CCMSX509GeneralNames* self = new( ELeave ) CCMSX509GeneralNames();
+    CleanupStack::PushL( self );
+    CArrayPtr< CCMSX509GeneralName >* nameArray =
+        new( ELeave ) CArrayPtrFlat< CCMSX509GeneralName >( KCMSGranularity );
+    self->iGeneralNames = nameArray;
+    CleanupStack::Pop( self );
+    return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralNames::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509GeneralNames* CCMSX509GeneralNames::NewL(
+    const CArrayPtr< CCMSX509GeneralName >& aGeneralNames )
+	{
+    CCMSX509GeneralNames* self =
+    	new( ELeave ) CCMSX509GeneralNames();
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aGeneralNames );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralNames::NewL
+// Two-phased copy constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509GeneralNames* CCMSX509GeneralNames::NewL(
+    const CCMSX509GeneralNames& aGeneralNames )
+	{
+    CCMSX509GeneralNames* self =
+    	new( ELeave ) CCMSX509GeneralNames();
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aGeneralNames.GeneralNames() );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// Destructor
+CCMSX509GeneralNames::~CCMSX509GeneralNames()
+    {
+    if( iGeneralNames )
+        {
+        iGeneralNames->ResetAndDestroy();
+        delete iGeneralNames;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralNames::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSX509GeneralNames::DecodeL( const TDesC8& aRawData )
+	{
+    CArrayPtr< TASN1DecGeneric >* nameData =
+        DecodeSequenceLC( aRawData );
+    TInt nameCount = nameData->Count();
+    if( nameCount == 0 )
+        {
+        User::Leave( KErrArgument );
+        }
+    CArrayPtr< CCMSX509GeneralName >* names =
+        new( ELeave ) CArrayPtrFlat< CCMSX509GeneralName >( nameCount );
+    CleanupStack::PushL( names );
+    for( TInt i = 0; i < nameCount; i++ )
+        {
+        CCMSX509GeneralName* name = CCMSX509GeneralName::NewL( );
+        CleanupStack::PushL( name );
+        name->DecodeL( nameData->At( i )->Encoding() );
+        names->AppendL( name );
+        }
+    CleanupStack::Pop( nameCount ); // names
+    CleanupStack::Pop( names );
+    CleanupStack::PopAndDestroy( nameData );
+    if( iGeneralNames )
+        {
+        iGeneralNames->ResetAndDestroy();
+        delete iGeneralNames;
+        }
+    iGeneralNames = names;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralNames::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSX509GeneralNames::EncoderLC() const
+	{
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+    TInt nameCount = iGeneralNames->Count();
+    for( TInt i = 0; i < nameCount; i++ )
+        {
+        HBufC8* encodedName = NULL;
+        iGeneralNames->At( i )->EncodeL( encodedName );
+        CleanupStack::PushL( encodedName );
+        CASN1EncEncoding* singleName = CASN1EncEncoding::NewLC( *encodedName );
+        root->AddAndPopChildL( singleName );
+        CleanupStack::PopAndDestroy( encodedName );
+        }
+
+   	return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralNames::GeneralNames
+// GeneralNames getter
+// -----------------------------------------------------------------------------
+EXPORT_C const CArrayPtr< CCMSX509GeneralName >&
+CCMSX509GeneralNames::GeneralNames() const
+	{
+	return *iGeneralNames;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509GeneralNames::SetGeneralNamesL
+// GeneralNames setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509GeneralNames::SetGeneralNamesL(
+	const CArrayPtr< CCMSX509GeneralName >& aGeneralNames )
+	{
+    TInt nameCount = aGeneralNames.Count();
+    if( nameCount == 0 )
+        {
+        User::Leave ( KErrArgument );
+        }
+    CArrayPtr< CCMSX509GeneralName >* names =
+        new( ELeave ) CArrayPtrFlat< CCMSX509GeneralName >( nameCount );
+    CleanupStack::PushL( names );
+    for( TInt i = 0; i < nameCount; i++ )
+        {
+        CCMSX509GeneralName* origName = aGeneralNames[ i ];
+        CCMSX509GeneralName* name =
+            CCMSX509GeneralName::NewL( origName->Tag(), origName->Data() );
+        CleanupStack::PushL( name );
+        names->AppendL( name );
+        }
+    CleanupStack::Pop( nameCount ); // names
+    CleanupStack::Pop( names );
+    if( iGeneralNames )
+        {
+        iGeneralNames->ResetAndDestroy();
+        delete iGeneralNames;
+        }
+    iGeneralNames = names;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSX509IssuerSerial.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,260 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSX509IssuerSerial.h"
+#include "CCMSX509GeneralNames.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KMinNumberOfSubModules = 2;
+const TInt KMaxNumberOfSubModules = 3;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSX509IssuerSerial::CCMSX509IssuerSerial
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509IssuerSerial::CCMSX509IssuerSerial( const TInt aSerial)
+    : iSerial( aSerial )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509IssuerSerial::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509IssuerSerial::ConstructL(
+    const CCMSX509GeneralNames& aIssuer )
+    {
+    SetIssuerL( aIssuer );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509IssuerSerial::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509IssuerSerial::ConstructL(
+    const CCMSX509GeneralNames& aIssuer,
+    const TDesC8& aIssuerUID )
+    {
+    SetIssuerL( aIssuer );
+    SetIssuerUIDL( aIssuerUID );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCMSX509IssuerSerial::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509IssuerSerial* CCMSX509IssuerSerial::NewL()
+	{
+	// creating with empty/default values
+    CCMSX509IssuerSerial* self = new( ELeave ) CCMSX509IssuerSerial( 0 );
+    CleanupStack::PushL( self );
+    CCMSX509GeneralNames* issuer = CCMSX509GeneralNames::NewL();
+    self->iIssuer = issuer;
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509IssuerSerial::NewL
+// Two-phased copy constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509IssuerSerial* CCMSX509IssuerSerial::NewL(
+    const CCMSX509GeneralNames& aIssuer,
+    const TInt aSerial ) 
+	{
+    CCMSX509IssuerSerial* self =
+    	new( ELeave ) CCMSX509IssuerSerial( aSerial );
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aIssuer );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509IssuerSerial::NewL
+// Two-phased copy constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509IssuerSerial* CCMSX509IssuerSerial::NewL(
+    const CCMSX509GeneralNames& aIssuer,
+    const TInt aSerial,
+    const TDesC8& aIssuerUID )
+	{
+    CCMSX509IssuerSerial* self =
+    	new( ELeave ) CCMSX509IssuerSerial( aSerial );
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aIssuer, aIssuerUID );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+
+// Destructor
+CCMSX509IssuerSerial::~CCMSX509IssuerSerial()
+    {
+	delete iIssuer;
+    delete iIssuerUID;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509IssuerSerial::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSX509IssuerSerial::DecodeL( const TDesC8& aRawData )
+	{
+    CArrayPtr< TASN1DecGeneric >* itemList = DecodeSequenceLC(
+        aRawData, KMinNumberOfSubModules, KMaxNumberOfSubModules );
+
+    TInt sequenceCounter = 0;
+    
+    // decode issuer
+    CCMSX509GeneralNames* issuer = CCMSX509GeneralNames::NewL();
+    CleanupStack::PushL( issuer );
+    issuer->DecodeL( itemList->At( sequenceCounter++ )->Encoding() );
+
+    // decode serial
+    TASN1DecInteger intDecoder;
+    TInt serial =
+        intDecoder.DecodeDERShortL( *( itemList->At( sequenceCounter++ ) ) );
+
+    HBufC8* issuerUID = NULL;
+    // decode issuerUID, if exists
+    if( itemList->Count() > sequenceCounter )
+        {
+        TASN1DecBitString bsDecoder;
+        issuerUID = bsDecoder.ExtractOctetStringL(
+            *( itemList->At( sequenceCounter ) ) );
+        }
+
+    // Everything has been created, we can change state
+    delete iIssuer;
+    iIssuer = issuer;
+    iSerial = serial;
+    delete iIssuerUID;
+    iIssuerUID = issuerUID;
+
+    CleanupStack::Pop( issuer );
+    CleanupStack::PopAndDestroy( itemList );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509IssuerSerial::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSX509IssuerSerial::EncoderLC() const
+	{
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+    // encode issuer
+    CASN1EncBase* issuer = iIssuer->EncoderLC();
+    root->AddAndPopChildL( issuer );
+
+    // encode serial
+    CASN1EncInt* serial = CASN1EncInt::NewLC( iSerial );
+    root->AddAndPopChildL( serial );
+
+    // encode issuerUID
+    if( iIssuerUID )
+        {
+        CASN1EncBitString* issuerUID = CASN1EncBitString::NewLC( *iIssuerUID );
+        root->AddAndPopChildL( issuerUID );
+        }
+    
+    return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509IssuerSerial::Issuer
+// Issuer getter
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509GeneralNames&
+CCMSX509IssuerSerial::Issuer() const
+	{
+	return *iIssuer;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509IssuerSerial::Serial
+// Serial getter
+// -----------------------------------------------------------------------------
+EXPORT_C TInt
+CCMSX509IssuerSerial::Serial() const
+	{
+	return iSerial;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509IssuerSerial::IssuerUID
+// IssuerUID getter
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8*
+CCMSX509IssuerSerial::IssuerUID() const
+	{
+	return iIssuerUID;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509IssuerSerial::SetIssuerL
+// Issuer setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509IssuerSerial::SetIssuerL(
+	const CCMSX509GeneralNames& aIssuer )
+	{
+    CCMSX509GeneralNames* issuer = CCMSX509GeneralNames::NewL( aIssuer );
+    delete iIssuer;
+    iIssuer = issuer;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509IssuerSerial::SetSerial
+// Serial setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509IssuerSerial::SetSerial(
+	const TInt aSerial )
+	{
+    iSerial = aSerial;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509IssuerSerial::SetIssuerUIDL
+// IssuerUID setter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509IssuerSerial::SetIssuerUIDL(
+	const TDesC8& aIssuerUID )
+	{
+    HBufC8* issuerUID = aIssuerUID.AllocL();
+    delete iIssuerUID;
+    iIssuerUID = issuerUID;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSX509Signed.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,199 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSX509Signed.h"
+#include "CCMSX509AlgorithmIdentifier.h"
+// CONSTANTS
+const TInt KNumberOfSubModules = 3;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSX509Signed::CCMSX509Signed
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CCMSX509Signed::CCMSX509Signed( )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Signed::BaseConstructL
+// Constructs the member variables. Makes copies.
+// -----------------------------------------------------------------------------
+//
+void CCMSX509Signed::BaseConstructL(
+    const CCMSX509AlgorithmIdentifier& aAlgorithmIdentifier,
+    const TDesC8& aEncrypted )
+    {
+    SetAlgorithmIdentifierL( aAlgorithmIdentifier );
+    SetEncryptedL( aEncrypted );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Signed::SignAndPopLC
+// Creates a signed encoder.
+// -----------------------------------------------------------------------------
+//
+CASN1EncSequence* CCMSX509Signed::SignAndPopLC(
+    CASN1EncBase* aToBeSigned ) const
+    {
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+    // encode toBeSigned
+    root->AddChildL( aToBeSigned );
+
+    CleanupStack::Pop( 2 ); // root, aToBeSigned
+    CleanupStack::PushL( root );
+    
+    // encode algorithmIdentifier  AlgorithmIdentifier
+    CASN1EncBase* algId = iAlgorithmIdentifier->EncoderLC( );
+    root->AddAndPopChildL( algId );
+
+    // encode encrypted            ENCRYPTED-HASH{ToBeSigned}
+    CASN1EncBitString* encrypted = CASN1EncBitString::NewLC( *iEncrypted );
+    root->AddAndPopChildL( encrypted );
+
+    return root;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Signed::DecodeSignatureL
+// Decodes algorithmIdentifier and encrypted parts from the raw data.
+// -----------------------------------------------------------------------------
+//
+TASN1DecGeneric CCMSX509Signed::DecodeSignatureL(
+    const TDesC8& aRawData,
+    CCMSX509AlgorithmIdentifier*& aAlgorithmIdentifier,
+    HBufC8*& aEncrypted ) const
+    {
+    CArrayPtr< TASN1DecGeneric >* itemList = DecodeSequenceLC(
+        aRawData, KNumberOfSubModules, KNumberOfSubModules );
+
+    TASN1DecGeneric retVal =
+        DecodeSignatureArrayL( *itemList, aAlgorithmIdentifier, aEncrypted );
+    
+    CleanupStack::PopAndDestroy( itemList );
+    
+    return retVal;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Signed::DecodeSignatureArrayL
+// Decodes algorithmIdentifier and encrypted parts from the array.
+// -----------------------------------------------------------------------------
+//
+TASN1DecGeneric CCMSX509Signed::DecodeSignatureArrayL(
+    CArrayPtr< TASN1DecGeneric >& aItemArray,
+    CCMSX509AlgorithmIdentifier*& aAlgorithmIdentifier,
+    HBufC8*& aEncrypted ) const
+    {
+    TInt sequenceCounter = 0;
+
+    // ToBeSigned will be returned
+    TASN1DecGeneric retVal( *aItemArray.At( sequenceCounter++ ) );
+    
+    // decode algorithmIdentifier
+    CCMSX509AlgorithmIdentifier* algId = CCMSX509AlgorithmIdentifier::NewL( );
+    CleanupStack::PushL( algId );
+    algId->DecodeL( aItemArray.At( sequenceCounter++ )->Encoding() );
+    
+    // decode encrypted
+    TASN1DecBitString bsDecoder;
+    HBufC8* encrypted =
+        bsDecoder.ExtractOctetStringL( *( aItemArray.At( sequenceCounter ) ) );
+
+    // change parameter pointers
+    aAlgorithmIdentifier = algId;
+    aEncrypted = encrypted;
+    CleanupStack::Pop( algId );
+    
+    return retVal;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Signed::~CCMSX509Signed
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CCMSX509Signed::~CCMSX509Signed()
+    {
+    delete iAlgorithmIdentifier;
+    delete iEncrypted;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Signed::AlgorithmIdentifier
+// algorithmIdentifier getter
+// -----------------------------------------------------------------------------
+//
+EXPORT_C const CCMSX509AlgorithmIdentifier&
+CCMSX509Signed::AlgorithmIdentifier() const
+    {
+    return *iAlgorithmIdentifier;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Signed::Encrypted
+// encrypted getter
+// -----------------------------------------------------------------------------
+//
+EXPORT_C const TDesC8& CCMSX509Signed::Encrypted() const
+    {
+    return *iEncrypted;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Signed::SetAlgorithmIdentifierL
+// AlgorithmIdentifier setter
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509Signed::SetAlgorithmIdentifierL(
+    const CCMSX509AlgorithmIdentifier& aAlgorithmIdentifier )
+    {
+    CCMSX509AlgorithmIdentifier* algorithmIdentifier =
+        CCMSX509AlgorithmIdentifier::NewL(
+            aAlgorithmIdentifier.AlgorithmIdentifier() );
+    CleanupStack::PushL( algorithmIdentifier );
+    const CAlgorithmIdentifier* digestAlgorithm =
+        aAlgorithmIdentifier.DigestAlgorithm();
+    if( digestAlgorithm )
+        {
+        algorithmIdentifier->SetDigestAlgorithmL( digestAlgorithm );
+        }
+    CleanupStack::Pop( algorithmIdentifier );
+    delete iAlgorithmIdentifier;
+    iAlgorithmIdentifier = algorithmIdentifier;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Signed::SetEncryptedL
+// encrypted setter
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509Signed::SetEncryptedL(
+    const TDesC8& aEncrypted )
+    {
+    HBufC8* encrypted = aEncrypted.AllocL();
+    delete iEncrypted;
+    iEncrypted = encrypted;
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSX509SubjectPublicKeyInfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,250 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSX509SubjectPublicKeyInfo.h"
+#include "CCMSX509AlgorithmIdentifier.h"
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KNumberOfSubModules = 2;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSX509SubjectPublicKeyInfo::CCMSX509SubjectPublicKeyInfo
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509SubjectPublicKeyInfo::CCMSX509SubjectPublicKeyInfo()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509SubjectPublicKeyInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509SubjectPublicKeyInfo::ConstructL(
+    const CCMSX509AlgorithmIdentifier& aAlgorithm,
+    const TDesC8& aSubjectPublicKey )
+    {
+    SetAlgorithmL( aAlgorithm );
+    SetSubjectPublicKeyL( aSubjectPublicKey );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509SubjectPublicKeyInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509SubjectPublicKeyInfo::ConstructL(
+    const CSubjectPublicKeyInfo& aSubjectPublicKeyInfo )
+    {
+    TAlgorithmId algIdType = aSubjectPublicKeyInfo.AlgorithmId();
+    CAlgorithmIdentifier* algId = CAlgorithmIdentifier::NewLC(
+        algIdType,
+        aSubjectPublicKeyInfo.EncodedParams() );
+    CCMSX509AlgorithmIdentifier* cmsAlgId =
+        CCMSX509AlgorithmIdentifier::NewL( *algId );
+    CleanupStack::PushL( cmsAlgId );
+    SetAlgorithmL( *cmsAlgId );
+    CleanupStack::PopAndDestroy( 2 ); // cmsAlgId, algId
+    SetSubjectPublicKeyL( aSubjectPublicKeyInfo.KeyData() );
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509SubjectPublicKeyInfo::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CCMSX509SubjectPublicKeyInfo::ConstructL( )
+    {
+    // creating empty/default values
+    iAlgorithm = CCMSX509AlgorithmIdentifier::NewL();
+    iSubjectPublicKey = KNullDesC8().AllocL();
+    }
+    
+
+// -----------------------------------------------------------------------------
+// CCMSX509SubjectPublicKeyInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509SubjectPublicKeyInfo*
+CCMSX509SubjectPublicKeyInfo::NewL()
+	{
+	// creating with empty values
+    CCMSX509SubjectPublicKeyInfo* self =
+        new( ELeave ) CCMSX509SubjectPublicKeyInfo();
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509SubjectPublicKeyInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509SubjectPublicKeyInfo*
+CCMSX509SubjectPublicKeyInfo::NewL(
+    const CCMSX509AlgorithmIdentifier& aAlgorithm,
+    const TDesC8& aSubjectPublicKey )
+    {
+    CCMSX509SubjectPublicKeyInfo* self =
+        new( ELeave ) CCMSX509SubjectPublicKeyInfo();
+    CleanupStack::PushL( self );
+    self->ConstructL( aAlgorithm, aSubjectPublicKey );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509SubjectPublicKeyInfo::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509SubjectPublicKeyInfo*
+CCMSX509SubjectPublicKeyInfo::NewL(
+    const CSubjectPublicKeyInfo& aSubjectPublicKeyInfo )
+    {
+    CCMSX509SubjectPublicKeyInfo* self =
+        new( ELeave ) CCMSX509SubjectPublicKeyInfo();
+    CleanupStack::PushL( self );
+    self->ConstructL( aSubjectPublicKeyInfo );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// Destructor
+CCMSX509SubjectPublicKeyInfo::~CCMSX509SubjectPublicKeyInfo()
+    {
+	delete iAlgorithm;
+    delete iSubjectPublicKey;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509SubjectPublicKeyInfo::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSX509SubjectPublicKeyInfo::DecodeL( const TDesC8& aRawData )
+	{
+    CArrayPtr< TASN1DecGeneric >* itemList = DecodeSequenceLC(
+        aRawData, KNumberOfSubModules, KNumberOfSubModules );
+
+    TInt sequenceCounter = 0;
+    
+    // decode algorithm
+    CCMSX509AlgorithmIdentifier* algId = CCMSX509AlgorithmIdentifier::NewL( );
+    CleanupStack::PushL( algId );
+    algId->DecodeL( itemList->At( sequenceCounter++ )->Encoding() );
+
+    // decode subjectPublicKey
+    TASN1DecBitString bsDecoder;
+    HBufC8* subjectPublicKey =
+        bsDecoder.ExtractOctetStringL( *( itemList->At( sequenceCounter ) ) );
+
+    // all done, change state
+    delete iAlgorithm;
+    iAlgorithm = algId;
+    delete iSubjectPublicKey;
+    iSubjectPublicKey = subjectPublicKey;
+    CleanupStack::Pop( algId );
+    CleanupStack::PopAndDestroy( itemList );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509SubjectPublicKeyInfo::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSX509SubjectPublicKeyInfo::EncoderLC() const
+	{
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+    // encode algorithm         AlgorithmIdentifier
+    CASN1EncBase* algId = iAlgorithm->EncoderLC();
+    root->AddAndPopChildL( algId );
+
+    // encode subjectPublicKey  BIT STRING
+    CASN1EncBitString* spKey = CASN1EncBitString::NewLC( *iSubjectPublicKey );
+    root->AddAndPopChildL( spKey );
+
+    return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509SubjectPublicKeyInfo::Algorithm()
+// Getter for algorithm
+// -----------------------------------------------------------------------------
+EXPORT_C const CCMSX509AlgorithmIdentifier&
+CCMSX509SubjectPublicKeyInfo::Algorithm() const
+	{
+	return *iAlgorithm;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509SubjectPublicKeyInfo::SubjectPublicKey()
+// Getter for subjectPublicKey
+// -----------------------------------------------------------------------------
+EXPORT_C const TDesC8&
+CCMSX509SubjectPublicKeyInfo::SubjectPublicKey() const
+	{
+	return *iSubjectPublicKey;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509SubjectPublicKeyInfo::SetAlgorithmL()
+// Setter for algorithm
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509SubjectPublicKeyInfo::SetAlgorithmL(
+    const CCMSX509AlgorithmIdentifier& aAlgorithm )
+	{
+    CCMSX509AlgorithmIdentifier* algorithm =
+        CCMSX509AlgorithmIdentifier::NewL( aAlgorithm.AlgorithmIdentifier() );
+    CleanupStack::PushL( algorithm );
+    const CAlgorithmIdentifier* digestIdentifier =
+        aAlgorithm.DigestAlgorithm();
+    if( digestIdentifier )
+        {
+        algorithm->SetDigestAlgorithmL( digestIdentifier );
+        }
+    CleanupStack::Pop( algorithm );
+    delete iAlgorithm;
+    iAlgorithm = algorithm;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509SubjectPublicKeyInfo::SetSubjectPublicKeyL()
+// Setter for subjectPublicKey
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509SubjectPublicKeyInfo::SetSubjectPublicKeyL(
+    const TDesC8& aSubjectPublicKey )
+	{
+    HBufC8* key = aSubjectPublicKey.AllocL();
+    delete iSubjectPublicKey;
+    iSubjectPublicKey = key;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CCMSX509Validity.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,189 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CCMSX509Validity.h"
+#include "TCMSTimeUtil.h"
+#include <signed.h>
+#include <asn1dec.h>
+#include <asn1enc.h>
+
+// CONSTANTS
+const TInt KNumberOfSubModules = 2;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCMSX509Validity::CCMSX509Validity
+// C++ constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509Validity::CCMSX509Validity(
+    const TTime& aNotBefore,
+    const TTime& aNotAfter )
+    : iNotBefore( aNotBefore ), iNotAfter( aNotAfter )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Validity::CCMSX509Validity
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509Validity::CCMSX509Validity( )
+    {
+    // CBase initilises member data to zero, which is good enough
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Validity::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509Validity*
+CCMSX509Validity::NewL()
+	{
+	// creating with empty values
+    CCMSX509Validity* self =
+        new( ELeave ) CCMSX509Validity();
+	return self;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Validity::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509Validity*
+CCMSX509Validity::NewL(
+    const TTime& aNotBefore,
+    const TTime& aNotAfter )
+    {
+    CCMSX509Validity* self =
+        new( ELeave ) CCMSX509Validity( aNotBefore, aNotAfter ); 
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Validity::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCMSX509Validity*
+CCMSX509Validity::NewL( const CValidityPeriod& aValidityPeriod )
+    {
+    CCMSX509Validity* self =
+        new( ELeave ) CCMSX509Validity( aValidityPeriod.Start(),
+                                        aValidityPeriod.Finish() ); 
+    return self;
+    }
+
+// Destructor
+CCMSX509Validity::~CCMSX509Validity()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCMSX509Validity::DecodeL
+// Decrypts raw data to this instance
+// -----------------------------------------------------------------------------
+void CCMSX509Validity::DecodeL( const TDesC8& aRawData )
+	{
+    CArrayPtr< TASN1DecGeneric >* itemList = DecodeSequenceLC(
+        aRawData, KNumberOfSubModules, KNumberOfSubModules );
+
+    TInt sequenceCounter = 0;
+
+    // decode notBefore
+    TTime notBefore = TCMSTimeUtil::ConvertToTimeL(
+        itemList->At( sequenceCounter++ )->Encoding() );
+
+    // decode notAfter
+    TTime notAfter = TCMSTimeUtil::ConvertToTimeL(
+        itemList->At( sequenceCounter )->Encoding() );
+
+    // all done, change state
+    iNotBefore = notBefore;
+    iNotAfter = notAfter;
+
+    CleanupStack::PopAndDestroy( itemList );
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Validity::EncoderLC
+// Returns ASN1 encoder for this instance
+// -----------------------------------------------------------------------------
+
+CASN1EncBase* CCMSX509Validity::EncoderLC() const
+	{
+    CASN1EncSequence* root = CASN1EncSequence::NewLC();
+
+    // encode notBefore
+    CASN1EncBase* notBefore = TCMSTimeUtil::ConvertToEncoderLC( iNotBefore );
+    root->AddAndPopChildL( notBefore );
+
+    // encode notAfter
+    CASN1EncBase* notAfter = TCMSTimeUtil::ConvertToEncoderLC( iNotAfter );
+    root->AddAndPopChildL( notAfter );
+
+    return root;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Validity::NotBefore()
+// Getter for notBefore
+// -----------------------------------------------------------------------------
+EXPORT_C const TTime&
+CCMSX509Validity::NotBefore() const
+	{
+	return iNotBefore;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Validity::NotAfter()
+// Getter for notAfter
+// -----------------------------------------------------------------------------
+EXPORT_C const TTime&
+CCMSX509Validity::NotAfter() const
+	{
+	return iNotAfter;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Validity::SetNotBefore()
+// Setter for notBefore
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509Validity::SetNotBefore(
+    const TTime& aNotBefore )
+	{
+    iNotBefore = aNotBefore;
+	}
+
+// -----------------------------------------------------------------------------
+// CCMSX509Validity::SetNotAfter()
+// Setter for notAfter
+// -----------------------------------------------------------------------------
+EXPORT_C void CCMSX509Validity::SetNotAfter(
+    const TTime& aNotAfter )
+	{
+    iNotAfter = aNotAfter;
+	}
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/CMS.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  DLL entry point (only before EKA2)
+*
+*/
+
+
+#include <e32base.h>
+
+#ifndef EKA2
+GLDEF_C TInt E32Dll( TDllReason )
+	{
+	return KErrNone;
+	}
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cms/src/TCMSTimeUtil.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,86 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include    "TCMSTimeUtil.h"
+#include 	<asn1dec.h>
+
+// CONSTANTS
+// UTC formatting string
+_LIT( KUTCFormatString, "%*Y%3%M%2%D%1%H%T%SZ" );
+const TUint8 KFormatLength = 13;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// TCMSTimeUtil::ConvertToEncoderLC
+// Converts TTime to ASN encoder base
+// -----------------------------------------------------------------------------
+//
+CASN1EncBase* TCMSTimeUtil::ConvertToEncoderLC( const TTime& aTime )
+    {
+	CASN1EncBase* time = NULL;
+	//    Dates between 1 January 1950 and 31 December 2049 (inclusive) must be
+	//    encoded as UTCTime.  Any dates with year values before 1950 or after
+	//    2049 must be encoded as GeneralizedTime.
+	if( aTime.DateTime().Year() >= 1950 &&
+		aTime.DateTime().Year() <= 2049 )
+		{
+		TBuf<KFormatLength> dateString;
+		// Formatting for UTC time
+		aTime.FormatL( dateString, KUTCFormatString );
+		TBuf8<KFormatLength> timeDes;
+		timeDes.Copy( dateString );
+		time = CASN1EncOctetString::NewLC( timeDes );
+		// change type to UTCTime
+		time->SetTag( EASN1UTCTime, EUniversal );
+		}
+	else
+		{
+		time = CASN1EncGeneralizedTime::NewLC( aTime );
+		}
+	return time;
+    }
+
+// -----------------------------------------------------------------------------
+// TCMSTimeUtil::ConvertToTimeL
+// Converts DER encoded source to TTime
+// -----------------------------------------------------------------------------
+//
+TTime TCMSTimeUtil::ConvertToTimeL( const TDesC8& aSource )
+	{
+	TASN1DecGeneric time( aSource );
+	time.InitL();
+	TTime returnValue = 0;
+	if( time.Tag() == EASN1GeneralizedTime )
+		{
+		TASN1DecGeneralizedTime genTime;
+		returnValue = genTime.DecodeDERL( time );
+		}
+	else if( time.Tag() == EASN1UTCTime )
+		{
+		TASN1DecUTCTime utcTime;
+		returnValue = utcTime.DecodeDERL( time );
+		}
+	else
+		{
+		User::Leave( KErrArgument );
+		}
+	return returnValue;
+	}
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncCommonUtils/BWINS/devenccommonutilsu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,33 @@
+EXPORTS
+	?NewSessionL@@YAPAVCDevEncSessionBase@@XZ @ 1 NONAME ; class CDevEncSessionBase * NewSessionL(void)
+	?SetDrive@CDevEncSession@@UAEXW4TDriveNumber@@@Z @ 2 NONAME ; void CDevEncSession::SetDrive(enum TDriveNumber)
+	?StartDiskWipe@CDevEncSession@@UAEHXZ @ 3 NONAME ; int CDevEncSession::StartDiskWipe(void)
+	?DriveLetter@CDevEncDiskUtils@@SAHHAAVTDes16@@@Z @ 4 NONAME ; int CDevEncDiskUtils::DriveLetter(int, class TDes16 &)
+	?DeleteTestFile@CDevEncDiskUtils@@SAXXZ @ 5 NONAME ; void CDevEncDiskUtils::DeleteTestFile(void)
+	?CreateSetKey@CDevEncKeyUtils@@QBEXAAVTRequestStatus@@H@Z @ 6 NONAME ; void CDevEncKeyUtils::CreateSetKey(class TRequestStatus &, int) const
+	??0CDevEncKeyUtils@@QAE@XZ @ 7 NONAME ; CDevEncKeyUtils::CDevEncKeyUtils(void)
+	?DriveNumber@CDevEncSession@@UBE?AW4TDriveNumber@@XZ @ 8 NONAME ; enum TDriveNumber CDevEncSession::DriveNumber(void) const
+	?WriteTestFile@CDevEncDiskUtils@@SAXXZ @ 9 NONAME ; void CDevEncDiskUtils::WriteTestFile(void)
+	?ResetKey@CDevEncKeyUtils@@QBEXAAVTRequestStatus@@@Z @ 10 NONAME ; void CDevEncKeyUtils::ResetKey(class TRequestStatus &) const
+	?VerifyTestFile@CDevEncDiskUtils@@SAXXZ @ 11 NONAME ; void CDevEncDiskUtils::VerifyTestFile(void)
+	?Connected@CDevEncSession@@UBEHXZ @ 12 NONAME ; int CDevEncSession::Connected(void) const
+	?DiskStatus@CDevEncSession@@UBEHAAH@Z @ 13 NONAME ; int CDevEncSession::DiskStatus(int &) const
+	?NewL@CMmcObserver@@SAPAV1@PAVMMemoryCardObserver@@PAVRFs@@@Z @ 14 NONAME ; class CMmcObserver * CMmcObserver::NewL(class MMemoryCardObserver *, class RFs *)
+	?Progress@CDevEncSession@@UBEHAAH@Z @ 15 NONAME ; int CDevEncSession::Progress(int &) const
+	??0CDevEncSession@@QAE@XZ @ 16 NONAME ; CDevEncSession::CDevEncSession(void)
+	??0CDevEncSession@@QAE@W4TDriveNumber@@@Z @ 17 NONAME ; CDevEncSession::CDevEncSession(enum TDriveNumber)
+	?Connect@CDevEncSession@@UAEHXZ @ 18 NONAME ; int CDevEncSession::Connect(void)
+	?SetDevEncControlL@CDevEncSession@@UAEHH@Z @ 19 NONAME ; int CDevEncSession::SetDevEncControlL(int)
+	?Close@CDevEncSession@@UAEXXZ @ 20 NONAME ; void CDevEncSession::Close(void)
+	?DiskFinalize@CDevEncDiskUtils@@SAHW4TDriveNumber@@@Z @ 21 NONAME ; int CDevEncDiskUtils::DiskFinalize(enum TDriveNumber)
+	?DrivePath@CDevEncDiskUtils@@SAXAAVTDes16@@W4TDriveNumber@@@Z @ 22 NONAME ; void CDevEncDiskUtils::DrivePath(class TDes16 &, enum TDriveNumber)
+	?GetDevEncControlL@CDevEncSession@@UAEHAAH@Z @ 23 NONAME ; int CDevEncSession::GetDevEncControlL(int &)
+	?StartDiskDecrypt@CDevEncSession@@UAEHXZ @ 24 NONAME ; int CDevEncSession::StartDiskDecrypt(void)
+	?SetKey@CDevEncKeyUtils@@QBEXAAVTRequestStatus@@ABVTDesC8@@1@Z @ 25 NONAME ; void CDevEncKeyUtils::SetKey(class TRequestStatus &, class TDesC8 const &, class TDesC8 const &) const
+	?StartObserver@CMmcObserver@@QAEXXZ @ 26 NONAME ; void CMmcObserver::StartObserver(void)
+	?CreateSetKey@CDevEncKeyUtils@@QBEXAAVTRequestStatus@@AAPAVHBufC8@@ABVTDesC8@@H@Z @ 27 NONAME ; void CDevEncKeyUtils::CreateSetKey(class TRequestStatus &, class HBufC8 * &, class TDesC8 const &, int) const
+	?StartDiskEncrypt@CDevEncSession@@UAEHXZ @ 28 NONAME ; int CDevEncSession::StartDiskEncrypt(void)
+	?NewL@CDiskStatusObserver@@SAPAV1@PAVMDiskStatusObserver@@W4TDriveNumber@@@Z @ 29 NONAME ; class CDiskStatusObserver * CDiskStatusObserver::NewL(class MDiskStatusObserver *, enum TDriveNumber)
+	?Connect@CDevEncKeyUtils@@QAEHXZ @ 30 NONAME ; int CDevEncKeyUtils::Connect(void)
+	?Close@CDevEncKeyUtils@@QAEXXZ @ 31 NONAME ; void CDevEncKeyUtils::Close(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncCommonUtils/EABI/devenccommonutilsu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,44 @@
+EXPORTS
+	_Z11NewSessionLv @ 1 NONAME
+	_ZN12CMmcObserver13StartObserverEv @ 2 NONAME
+	_ZN12CMmcObserver4NewLEP19MMemoryCardObserverP3RFs @ 3 NONAME
+	_ZN14CDevEncSession13StartDiskWipeEv @ 4 NONAME
+	_ZN14CDevEncSession16StartDiskDecryptEv @ 5 NONAME
+	_ZN14CDevEncSession16StartDiskEncryptEv @ 6 NONAME
+	_ZN14CDevEncSession17GetDevEncControlLERi @ 7 NONAME
+	_ZN14CDevEncSession17SetDevEncControlLEi @ 8 NONAME
+	_ZN14CDevEncSession5CloseEv @ 9 NONAME
+	_ZN14CDevEncSession7ConnectEv @ 10 NONAME
+	_ZN14CDevEncSession8SetDriveE12TDriveNumber @ 11 NONAME
+	_ZN14CDevEncSessionC1E12TDriveNumber @ 12 NONAME
+	_ZN14CDevEncSessionC1Ev @ 13 NONAME
+	_ZN14CDevEncSessionC2E12TDriveNumber @ 14 NONAME
+	_ZN14CDevEncSessionC2Ev @ 15 NONAME
+	_ZN15CDevEncKeyUtilsC1Ev @ 16 NONAME
+	_ZN15CDevEncKeyUtilsC2Ev @ 17 NONAME
+	_ZN16CDevEncDiskUtils11DriveLetterEiR6TDes16 @ 18 NONAME
+	_ZN16CDevEncDiskUtils12DiskFinalizeE12TDriveNumber @ 19 NONAME
+	_ZN16CDevEncDiskUtils13WriteTestFileEv @ 20 NONAME
+	_ZN16CDevEncDiskUtils14DeleteTestFileEv @ 21 NONAME
+	_ZN16CDevEncDiskUtils14VerifyTestFileEv @ 22 NONAME
+	_ZN16CDevEncDiskUtils9DrivePathER6TDes1612TDriveNumber @ 23 NONAME
+	_ZN19CDiskStatusObserver4NewLEP19MDiskStatusObserver12TDriveNumber @ 24 NONAME
+	_ZNK14CDevEncSession10DiskStatusERi @ 25 NONAME
+	_ZNK14CDevEncSession11DriveNumberEv @ 26 NONAME
+	_ZNK14CDevEncSession8ProgressERi @ 27 NONAME
+	_ZNK14CDevEncSession9ConnectedEv @ 28 NONAME
+	_ZNK15CDevEncKeyUtils12CreateSetKeyER14TRequestStatusRP6HBufC8RK6TDesC8i @ 29 NONAME
+	_ZNK15CDevEncKeyUtils12CreateSetKeyER14TRequestStatusi @ 30 NONAME
+	_ZNK15CDevEncKeyUtils6SetKeyER14TRequestStatusRK6TDesC8S4_ @ 31 NONAME
+	_ZNK15CDevEncKeyUtils8ResetKeyER14TRequestStatus @ 32 NONAME
+	_ZTI12CMmcObserver @ 33 NONAME ; #<TI>#
+	_ZTI14CDevEncSession @ 34 NONAME ; #<TI>#
+	_ZTI15CDevEncKeyUtils @ 35 NONAME ; #<TI>#
+	_ZTI19CDiskStatusObserver @ 36 NONAME ; #<TI>#
+	_ZTV12CMmcObserver @ 37 NONAME ; #<VT>#
+	_ZTV14CDevEncSession @ 38 NONAME ; #<VT>#
+	_ZTV15CDevEncKeyUtils @ 39 NONAME ; #<VT>#
+	_ZTV19CDiskStatusObserver @ 40 NONAME ; #<VT>#
+	_ZN15CDevEncKeyUtils5CloseEv @ 41 NONAME
+	_ZN15CDevEncKeyUtils7ConnectEv @ 42 NONAME
+
Binary file devencdiskutils/DevEncCommonUtils/conf/devencui.confml has changed
Binary file devencdiskutils/DevEncCommonUtils/conf/devencui_200025A6.crml has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncCommonUtils/group/DevEncCommonUtils.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project specification file for DevEncCommonUtils
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+#include "../../common/DevEncUids.hrh"
+
+TARGET          devenccommonutils.dll
+TARGETTYPE      dll
+UID             0x1000008d KDevEncCommonUtilsUid
+VENDORID        KDevEncNokiaVID
+CAPABILITY      CAP_GENERAL_DLL
+
+SOURCEPATH      ../src
+SOURCE          DevEncSession.cpp
+SOURCE          DevEncDiskUtils.cpp
+SOURCE          DevEncKeyUtils.cpp
+SOURCE          DevEncMmcObserver.cpp
+SOURCE          DevEncDiskStatusObserver.cpp
+
+SOURCEPATH ../../common
+SOURCE DevEncLog.cpp
+
+USERINCLUDE     ../inc
+USERINCLUDE		../../common
+
+APP_LAYER_SYSTEMINCLUDE
+
+LIBRARY         asn1.lib // for PKCS5
+LIBRARY         cryptography.lib // for PKCS5
+LIBRARY         euser.lib
+LIBRARY         efsrv.lib
+LIBRARY         estor.lib
+LIBRARY         centralrepository.lib 
+LIBRARY         hash.lib // for PKCS5
+LIBRARY         pbe.lib
+LIBRARY         random.lib // for PKCS5
+LIBRARY         x509.lib // for PKCS5
+LIBRARY			imut.lib // for base64 coding
+DEBUGLIBRARY    flogger.lib
+
+// EXPORTUNFROZEN
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncCommonUtils/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*      Provides the information required for building DevEncCommonUtils
+*  Version    : %version: 6 %, %date_modified: Fri Nov 13 11:12:04 2009 % by %derived_by: e0326969 % 
+*/
+
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+// ROM files
+
+// Exported headers
+
+// Central repository files
+../conf/devencui.confml 		APP_LAYER_CONFML(devencui.confml)
+../conf/devencui_200025A6.crml 		APP_LAYER_CRML(devencui_200025A6.crml)
+
+PRJ_MMPFILES
+DevEncCommonUtils.mmp
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncCommonUtils/inc/DevEncCommonUtils.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef DEVENC_COMMONUTILS_HRH
+#define DEVENC_COMMONUTILS_HRH
+
+enum TUiCommandIds
+    {
+    ECmdSelectC = 0x60000,
+    ECmdSelectE,
+    ECmdEncrypt,
+    ECmdDecrypt,
+    ECmdStatus,
+    ECmdWipe,
+    ECmdFinalize,
+    ECmdWriteTestFile,
+    ECmdVerifyTestFile,
+    ECmdDeleteTestFile
+    };
+
+#endif // DEVENC_COMMONUTILS_HRH
+
Binary file devencdiskutils/DevEncCommonUtils/sis/DevEncCommonUtils.SIS has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncCommonUtils/sis/DevEncCommonUtils.pkg	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,34 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+; DevEncCommonUtils.pkg
+;
+;Language - standard language definitions
+&EN
+
+;Standard SIS file header
+#{"DevEncCommonUtils"},(0x200025B7),1,0,0
+
+;Localised Vendor name
+%{"Nokia"}
+
+;Unique Vendor name
+:"Nokia"
+
+;Supports Series 60 v 3.0
+[0x101F7961], 0, 0, 0, {"Series60ProductID"}
+
+;Files to install
+"\epoc32\release\armv5\urel\devenccommonutils.dll"        -"!:\sys\bin\DevEncUi.exe"
Binary file devencdiskutils/DevEncCommonUtils/sis/DevEncCommonUtils.sisx has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncCommonUtils/src/DevEncDiskStatusObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*              Implements a watcher for disk status change events.   
+*
+*
+*/
+
+
+#include <e32base.h>
+#include <f32file.h>
+#include <DevEncEngineConstants.h>
+#include "DevEncDiskStatusObserver.h"
+#include "DevEncLog.h"
+#include "DevEncProtectedPSKey.h"
+
+
+EXPORT_C CDiskStatusObserver* CDiskStatusObserver::NewL( MDiskStatusObserver* aObserver, TDriveNumber aDriveNumber )
+    {
+    DFLOG( "CDiskStatusObserver::NewL" );
+    CDiskStatusObserver* self = new (ELeave) CDiskStatusObserver();
+    CleanupStack::PushL( self );
+    self->ConstructL( aObserver, aDriveNumber );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+void CDiskStatusObserver::ConstructL( MDiskStatusObserver* aObserver, TDriveNumber aDriveNumber )
+    {
+    DFLOG( "CDiskStatusObserver::ConstructL" );
+    TInt err = iNfeStatus.Attach( KEncUtility, ENC_KEY( aDriveNumber, KDEStatusToUiKey ) );
+    if ( err )
+        {
+        DFLOG2( "ERROR: Attach failed, err %d", err );
+        }
+    iObserver = aObserver;
+    iDrive = aDriveNumber;
+    CActiveScheduler::Add( this );
+    iNfeStatus.Subscribe( iStatus );
+    SetActive();
+    }
+
+CDiskStatusObserver::CDiskStatusObserver() : CActive( EPriorityIdle )
+    {
+    }
+
+CDiskStatusObserver::~CDiskStatusObserver()
+    {
+    DFLOG( "CDiskStatusObserver::~CDiskStatusObserver" );
+    Cancel();
+    iNfeStatus.Close();
+    }
+
+void CDiskStatusObserver::DoCancel()
+    {
+    DFLOG( "CDiskStatusObserver::DoCancel" );
+    iNfeStatus.Cancel();
+    }
+
+void CDiskStatusObserver::RunL()
+    {
+    DFLOG( "CDiskStatusObserver::RunL" );
+    iNfeStatus.Subscribe( iStatus );
+    SetActive();
+    
+    TInt nfeStatus;
+    TInt err = iNfeStatus.Get( nfeStatus );
+    if( !err )
+        {
+        TInt status;
+        switch( nfeStatus )
+        	{
+        	case EDecrypting: status = EOpDecrypting;
+        		              break;
+        	case EEncrypting: status = EOpEncrypting;
+        		              break;
+        	default: status = EOpIdle;
+        		     break;
+            }
+        //if a multidrive encryption/decryption is ongoing we cannot change the status of the ps key until
+        //all the drives have concluded the operation. 
+        if( ( status == EOpIdle && !IsEncryptionOperationOngoing() ) || status != EOpIdle )
+            {
+            RProperty::Set( KDevEncProtectedUid, KDevEncOperationKey, status );
+            }
+        iObserver->DiskStatusChangedL( nfeStatus );
+        }
+    }
+
+TBool CDiskStatusObserver::IsEncryptionOperationOngoing()
+    {
+    DFLOG( "CDiskStatusObserver::IsEncryptionOperationOngoing" );
+    TBool ret( EFalse );
+    TBool cont( ETrue );
+    for( TInt i = EDriveA; ( i < KMaxDrives ) && cont; i++ )
+        {
+        TInt status;
+        TInt err = RProperty::Get( KEncUtility, ENC_KEY( (TDriveNumber) i, KDEStatusToUiKey ), status );
+        if( !err )
+            {
+            if( status == EDecrypting || status == EEncrypting )
+                {
+                DFLOG2( "drive %d has an encryption or decryption operation ongoing", i );
+            	ret = ETrue;
+            	cont = EFalse;
+                }
+            else
+                {
+                DFLOG2( "drive %d is in Idle", i );
+                }
+            }
+        else
+        	{
+        	DFLOG3( "ERROR: Get failed for drive %d, err %d", i, err );
+            }
+        }    
+    return ret;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncCommonUtils/src/DevEncDiskUtils.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,356 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#include <e32base.h>
+#include <f32file.h> // for TDriveNumber
+#include <centralrepository.h>
+#include <e32property.h>
+
+#include <UiklafInternalCRKeys.h> // for disc space
+
+#include "DevEncCommonUtils.hrh"
+#include "DevEncDiskUtils.h"
+#include "DevEncLog.h"
+
+/*static const TPtrC KDriveLetter[] = {
+    _L("A"), _L("B"), _L("C"), _L("D"), _L("E"), _L("F"), _L("G"), _L("H"),
+    _L("I"), _L("J"), _L("K"), _L("L"), _L("M"), _L("N"), _L("O"), _L("P"),
+    _L("Q"), _L("R"), _L("S"), _L("T"), _L("U"), _L("V"), _L("W"), _L("X"),
+    _L("Y"), _L("Z") };*/
+
+_LIT( KA, "A"); _LIT( KB, "B");_LIT( KC, "C"); _LIT( KD, "D");
+_LIT( KE, "E"); _LIT( KF, "F"); _LIT( KG, "G"); _LIT( KH, "H");
+_LIT( KI, "I"); _LIT( KJ, "J");_LIT( KK, "K"); _LIT( KL, "L");
+_LIT( KM, "M"); _LIT( KN, "N"); _LIT( KO, "O"); _LIT( KP, "P");
+_LIT( KQ, "Q"); _LIT( KR, "R"); _LIT( KS, "S"); _LIT( KT, "T");
+_LIT( KU, "U"); _LIT( KV, "V"); _LIT( KW, "W"); _LIT( KX, "X");
+_LIT( KY, "Y"); _LIT( KZ, "Z");
+
+_LIT( KContentTestFile, "c:\\content_test.txt" );
+static const TUint32 KTestBlockSizeBt = 1024 * sizeof( TUint32 );
+static const TUint32 KTestBlocks      = 320;
+static const TInt32  KMaxInt          = 2147483647;       
+
+// --------------------------------------------------------------------------
+// CDevEncDiskUtils::DriveLetter()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C TInt CDevEncDiskUtils::DriveLetter( TInt aNumber,
+                                             TDes& aResult )
+    {
+    const TInt KNumOfDriveLetters( 25 );
+    const TPtrC KDriveLetter[] = {
+        KA(), KB(), KC(), KD(), KE(), KF(), KG(), KH(),
+        KI(), KJ(), KK(), KL(), KM(), KN(), KO(), KP(),
+        KQ(), KR(), KS(), KT(), KU(), KV(), KW(), KX(),
+        KY(), KZ() };
+    if ( aNumber > KNumOfDriveLetters )
+        {
+        return KErrOverflow;
+        }
+    aResult.Append( KDriveLetter[ aNumber ] );
+    return KErrNone;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncDiskUtils::DrivePath()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C void CDevEncDiskUtils::DrivePath( TDes& aDes, TDriveNumber aNumber )
+    {
+    DriveLetter( aNumber, aDes );
+    aDes.Append( _L(":\\") );
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncDiskUtils::DoWriteTestFileL()
+// 
+// --------------------------------------------------------------------------
+void CDevEncDiskUtils::DoWriteTestFileL()
+    {
+    RFile file;
+    RFs fs;
+
+    User::LeaveIfError( fs.Connect() );
+    CleanupClosePushL( fs );
+    User::LeaveIfError( file.Replace( fs, KContentTestFile, EFileWrite ) );
+    CleanupClosePushL( file );
+
+    HBufC8* buf = HBufC8::NewL( KTestBlockSizeBt );
+    CleanupStack::PushL( buf );
+
+    TPtr8 pbuf = buf->Des();
+    pbuf.SetLength( KTestBlockSizeBt );
+
+    for( TUint32 i=0; i < KTestBlocks; i++ )
+        {
+        for( TUint32 k=0; k < KTestBlockSizeBt; k++ )
+            pbuf[k] = 0xff;
+
+        User::LeaveIfError( file.Write( pbuf ) );
+        }
+
+    CleanupStack::PopAndDestroy(3);
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncDiskUtils::WriteTestFile()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C void CDevEncDiskUtils::WriteTestFile()
+    {
+    if ( ! RProcess().HasCapability( ECapabilityDiskAdmin ) )
+        {
+        DFLOG( "Process does not have DiskAdmin capability" );
+        return;
+        }
+
+    DFLOG("Writing test file");
+    TRAPD( err, DoWriteTestFileL() );
+    if( err )
+        {
+        DFLOG2("...failed %d", err);
+        }
+    else
+        {
+        DFLOG( "...ok" );
+        }
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncDiskUtils::DoVerifyTestFileL()
+// 
+// --------------------------------------------------------------------------
+void CDevEncDiskUtils::DoVerifyTestFileL()
+    {
+    if ( ! RProcess().HasCapability( ECapabilityDiskAdmin ) )
+        {
+        DFLOG( "Process does not have DiskAdmin capability" );
+        return;
+        }
+
+    RFile file;
+    RFs fs;
+
+    User::LeaveIfError( fs.Connect() );
+    CleanupClosePushL( fs );
+    User::LeaveIfError( file.Open( fs, KContentTestFile, EFileRead ) );
+    CleanupClosePushL( file );
+
+    HBufC8* buf = HBufC8::NewL(KTestBlockSizeBt);
+    CleanupStack::PushL( buf );
+
+    TPtr8 pbuf = buf->Des();
+    pbuf.SetLength( KTestBlockSizeBt );
+
+    for( TUint32 i=0; i < KTestBlocks; i++ )
+        {
+        User::LeaveIfError( file.Read( pbuf ) );
+
+        for( TUint32 k=0; k < KTestBlockSizeBt; k++ )
+            {
+            if( pbuf[k] != 0xff )
+                DFLOG3("pos=%d val=%d", (i * KTestBlockSizeBt + k), pbuf[k]);
+            }
+        }
+
+    CleanupStack::PopAndDestroy(3);
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncDiskUtils::VerifyTestFile()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C void CDevEncDiskUtils::VerifyTestFile()
+    {
+    DFLOG("Verifying test file");
+    TRAPD( err, DoVerifyTestFileL() );
+    if( err )
+        {
+        DFLOG2("...failed %d", err);
+        }
+    else
+        {
+        DFLOG( "..ok" );
+        }
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncDiskUtils::DeleteTestFile()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C void CDevEncDiskUtils::DeleteTestFile()
+    {
+    DFLOG("Deleting test file");
+    RFs fs;
+
+    TInt err = fs.Connect();
+
+    if( !err )
+        {
+        err = fs.Delete( KContentTestFile );
+
+        if( !err || err == KErrNotFound )
+            {
+            DFLOG("...ok");
+            }
+        else
+            {
+            DFLOG2( "...failed %d", err );
+            }
+        }
+    else
+        {
+        DFLOG2( "fs.Connect() failed %d", err );
+        }
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncDiskUtils::DiskFinalize()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C TInt CDevEncDiskUtils::DiskFinalize( TDriveNumber aNumber )
+    {
+    if ( ! RProcess().HasCapability( ECapabilityDiskAdmin ) )
+        {
+        DFLOG( "Process does not have DiskAdmin capability" );
+        return KErrAccessDenied;
+        }
+    
+    DFLOG("Finalizing");
+
+    RArray <TFileName> temps;
+    RArray <RFile> files;
+    RFs fs;
+
+    TInt err = fs.Connect();
+    if( err )
+        DFLOG2( "..fs.Connect fail %d", err);
+
+    TBool freeSpace = ETrue;
+
+    TVolumeInfo volumeInfo;
+    err = fs.Volume( volumeInfo, aNumber );
+    if( err )
+        DFLOG2( "..fs.Volume fail %d", err );
+
+    TInt64 size = 0;
+    TInt64 memoryCriticalSpace(0);
+    TRAP(err, memoryCriticalSpace = FindCriticalLevelTresholdL());
+    if (!err)
+        return err;
+    TInt64 memoryWarningSpace(0);
+    TRAP(err, memoryWarningSpace = FindWarningLevelTresholdL());
+    if (!err)
+        return err;
+    
+    DFLOG2( "CDevEncDiskUtils::DiskFinalize => memoryCriticalSpace = %d", (TInt) memoryCriticalSpace );
+    DFLOG2( "CDevEncDiskUtils::DiskFinalize => memoryWarningSpace = %d", (TInt) memoryWarningSpace );
+    
+    //create the number of files needed to fill the mmc free space
+    while( freeSpace )
+        {
+        /* The real warning space is a percentage of the free space */
+        TInt64 newMemoryWarningSpace = ( TInt64 ) ( volumeInfo.iSize*( 100 - memoryWarningSpace ) ) / 100;
+        DFLOG2( "CDevEncDiskUtils::DiskFinalize => newMemoryWarningSpace = %d", (TInt) newMemoryWarningSpace );
+
+        if( TInt64( volumeInfo.iFree ) > TInt64( KMaxInt ) )
+        	{
+            size = KMaxInt;
+            }
+        else
+        	{
+        	size = Max( 0LL, TInt64( volumeInfo.iFree ) - memoryCriticalSpace - newMemoryWarningSpace );
+        	}
+
+        TFileName temp;
+        RFile file;
+
+        if( !err )
+            {
+            TBuf<8> path;
+            DrivePath( path, aNumber );
+
+            err = file.Temp( fs, path, temp, EFileWrite );
+            if( err )
+                DFLOG2( "..file.Temp fail %d", err );
+            }
+
+        err = file.SetSize( ( TInt ) size );
+        if( err )
+            DFLOG2( "..file.SetSize fail %d", err );
+
+        files.Append( file );
+        temps.Append( temp );
+
+        err = fs.Volume( volumeInfo, aNumber );
+        if( err )
+            DFLOG2( "..fs.Volume fail %d", err );    
+
+        if( TInt64( volumeInfo.iFree ) <= memoryCriticalSpace + newMemoryWarningSpace )
+        	{
+            freeSpace = EFalse;
+            }
+        }
+
+    //delete the created files
+    for( TInt i=0;i < files.Count();i++ )
+    	{
+        files[i].Close();
+        fs.Delete( temps[i] ); // Error value ignored
+        }
+
+    files.Close();
+    temps.Close();
+    fs.Close();
+    return err;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncDiskUtils::FindValueL()
+// 
+// --------------------------------------------------------------------------
+TInt CDevEncDiskUtils::FindValueL( const TUid aRepositoryUid, const TUint aCRKey )
+	{
+	TInt val( 0 );
+    CRepository* repository = CRepository::NewLC( aRepositoryUid );
+    User::LeaveIfError( repository->Get( aCRKey, val ) );
+    CleanupStack::PopAndDestroy( repository );
+
+    return val;
+	}
+
+// --------------------------------------------------------------------------
+// CDevEncDiskUtils::FindCriticalLevelTresholdL()
+// 
+// --------------------------------------------------------------------------
+TInt64 CDevEncDiskUtils::FindCriticalLevelTresholdL()
+	{
+    return (TInt64) FindValueL( KCRUidUiklaf, KUikOODDiskCriticalThreshold );
+	}
+
+// --------------------------------------------------------------------------
+// CDevEncDiskUtils::FindWarningLevelTresholdL()
+// 
+// --------------------------------------------------------------------------
+TInt64 CDevEncDiskUtils::FindWarningLevelTresholdL()
+	{
+	return (TInt64) FindValueL( KCRUidUiklaf, /*KUikOODDiskWarningThreshold*/KUikOODDiskFreeSpaceWarningNoteLevel );
+	}
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncCommonUtils/src/DevEncKeyUtils.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,609 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of CDevEncKeyUtils
+*
+*/
+
+
+// INCLUDE FILES
+
+// Class includes
+#include "DevEncDef.h"
+#include "DevEncKeyUtils.h"
+#include "DevEncLog.h"
+#include "DevEncUids.hrh"
+
+#include <pbe.h>
+#include <pbedata.h>
+//#include <PathInfo.h> // for system path literals
+#include <pkcs5kdf.h>
+#include <s32file.h>
+#include <s32mem.h>
+#include <imcvcodc.h>
+
+#include <DevEncEngineConstants.h>
+#include <DevEncEngineBase.h>
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::Connect()
+//
+// --------------------------------------------------------------------------
+EXPORT_C TInt CDevEncKeyUtils::Connect()
+    {
+    TRAPD( err, LoadDevEncEngineL() );
+    return err;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::Connect()
+//
+// --------------------------------------------------------------------------
+EXPORT_C void CDevEncKeyUtils::Close()
+    {
+    UnloadDevEncEngine();
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::CDevEncKeyUtils()
+//
+// --------------------------------------------------------------------------
+EXPORT_C CDevEncKeyUtils::CDevEncKeyUtils(): iConnect( EFalse )
+    {
+    // No implementation necessary
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::CDevEncKeyUtils()
+//
+// --------------------------------------------------------------------------
+CDevEncKeyUtils::~CDevEncKeyUtils()
+    {
+    
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::CreateSetKey()
+//
+// --------------------------------------------------------------------------
+EXPORT_C void CDevEncKeyUtils::CreateSetKey( TRequestStatus& aStatus,
+                                             HBufC8*& aResult,
+                                             const TDesC8& aPassword,
+                                             const TInt aLength ) const
+    {
+    TInt error( KErrNone );
+    if ( ! ProcessHasCapability( ECapabilityDiskAdmin ) )
+        {
+        DFLOG( "Process does not have DiskAdmin capability" );
+        error = KErrAccessDenied;
+        }
+    else if ( aPassword.Length() > KMaxPasswordLength ||
+              aPassword.Length() < KMinPasswordLength )
+        {
+        DFLOG( "CDevEncKeyUtils::CreateSetKey Invalid password length" );
+        error = KErrArgument;
+        }
+    else if ( aLength > KEncryptionKeyLength )
+        {
+        DFLOG( "CDevEncKeyUtils::CreateSetKey Invalid key length" );
+        error = KErrArgument;
+        }
+    else
+        {
+        TRAP( error, DoCreateSetKeyL( aResult, aPassword, aLength ) );
+        DFLOG2( "CDevEncKeyUtils::CreateSetKey result %d", error );
+        }
+    TRequestStatus* statusPtr = &aStatus;
+    User::RequestComplete( statusPtr, error );
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::CreateSetKey()
+//
+// --------------------------------------------------------------------------
+EXPORT_C void CDevEncKeyUtils::CreateSetKey( TRequestStatus& aStatus,
+                                             const TInt aLength ) const
+    {
+    TInt error( KErrNone );
+
+    HBufC8* password( NULL );
+
+    if ( ! ProcessHasCapability( ECapabilityDiskAdmin ) )
+        {
+        DFLOG( "Process does not have DiskAdmin capability" );
+        error = KErrAccessDenied;
+        }
+    if ( aLength > KEncryptionKeyLength )
+        {
+        DFLOG( "CDevEncKeyUtils::CreateSetKey Invalid key length" );
+        error = KErrArgument;
+        }
+
+    if ( !error )
+        {
+        TRAP( error, password = HBufC8::NewL( KMaxPasswordLength ) );
+        if ( error )
+            {
+            DFLOG2( "Pwd buf alloc error %d", error );
+            }
+        }
+
+    if ( !error )
+        {
+        // Get some random password
+        TPtr8 passwordPtr = password->Des();
+        passwordPtr.SetLength( KMaxPasswordLength );
+        if( iConnect )
+            {
+            iDevEncEngine->RandomDataGet( passwordPtr, KMaxPasswordLength );
+            }
+        
+        DFLOG( "Random password allocated" );
+        
+        TRAP( error, DoCreateSetKeyL( *password,
+                                      aLength ) );
+        DFLOG2( "CDevEncKeyUtils::CreateSetKey result %d", error );
+        }
+
+    // Cleanup on demand
+    if ( password )
+        {
+        delete password;
+        }
+    
+    TRequestStatus* statusPtr = &aStatus;
+    User::RequestComplete( statusPtr, error );
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::DoCreateSetKey()
+//
+// --------------------------------------------------------------------------
+void CDevEncKeyUtils::DoCreateSetKeyL( const TDesC8& aPassword,
+                                       TInt aLength ) const
+    {
+    DFLOG2( ">>CDevEncKeyUtils::DoCreateSetKeyL, length %d", aLength );
+
+    // Get some random key data
+    HBufC8* clearKey = HBufC8::NewLC( aLength );
+    TPtr8 clearKeyPtr = clearKey->Des();
+    clearKeyPtr.SetLength( aLength );
+
+    if( iConnect )
+        {
+        iDevEncEngine->RandomDataGet( clearKeyPtr, KMaxPasswordLength );
+        }
+    
+    // if supply KDF, must also supply salt len and iteration count
+    CPBEncryptElement* encryption = CPBEncryptElement::NewLC( aPassword,
+                                                              ECipherDES_CBC );
+    CPBEncryptor* encryptor = encryption->NewEncryptLC();
+
+    HBufC8* ciphertextTemp = HBufC8::NewLC( encryptor->MaxFinalOutputLength( clearKey->Length() ) ); 
+    TPtr8 ciphertext = ciphertextTemp->Des();   
+    encryptor->ProcessFinalL( *clearKey, ciphertext );
+
+    // ENCRYPTION DONE
+
+    DFLOG( "DoCreateSetKeyL, Key in plaintext:" );
+    RDebug::RawPrint( clearKeyPtr );
+    DFLOG( "DoCreateSetKeyL, Key in ciphertext:" );
+    RDebug::RawPrint( ciphertext );
+    DFLOG( "DoCreateSetKeyL, Password:" );
+    RDebug::RawPrint( aPassword );
+    
+    if( iConnect )
+        {
+        // Take the new key in use
+        iDevEncEngine->TakeKeyInUseL( *clearKey );
+        }
+    
+    // Destroy the evidence
+    CleanupStack::PopAndDestroy( ciphertextTemp );
+    CleanupStack::PopAndDestroy( encryptor );
+    CleanupStack::PopAndDestroy( encryption );
+    CleanupStack::PopAndDestroy( clearKey );
+    };
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::DoCreateSetKey()
+//
+// --------------------------------------------------------------------------
+void CDevEncKeyUtils::DoCreateSetKeyL( HBufC8*& aResult,
+                                       const TDesC8& aPassword,
+                                       TInt aLength ) const
+    {
+    DFLOG2( ">>CDevEncKeyUtils::DoCreateSetKeyL, length %d", aLength );
+
+    // Get some random key data
+    HBufC8* clearKey = HBufC8::NewLC( aLength );
+    TPtr8 clearKeyPtr = clearKey->Des();
+    clearKeyPtr.SetLength( aLength );
+    
+    if( iConnect )
+        {
+        iDevEncEngine->RandomDataGet( clearKeyPtr, KMaxPasswordLength );
+        }
+    
+    // if supply KDF, must also supply salt len and iteration count
+    CPBEncryptElement* encryption = CPBEncryptElement::NewLC( aPassword,
+                                                              ECipherDES_CBC );
+    CPBEncryptor* encryptor = encryption->NewEncryptLC();
+
+    HBufC8* ciphertextTemp = HBufC8::NewLC( encryptor->MaxFinalOutputLength( clearKey->Length() ) ); 
+    TPtr8 ciphertext = ciphertextTemp->Des();   
+    encryptor->ProcessFinalL( *clearKey, ciphertext );
+
+    // ENCRYPTION DONE
+
+    DFLOG( "DoCreateSetKeyL, Key in plaintext:" );
+    RDebug::RawPrint( clearKeyPtr );
+    DFLOG( "DoCreateSetKeyL, Key in ciphertext:" );
+    RDebug::RawPrint( ciphertext );
+    DFLOG( "DoCreateSetKeyL, Password:" );
+    RDebug::RawPrint( aPassword );
+    
+    if( iConnect )
+        {
+        // Take the new key in use
+        iDevEncEngine->TakeKeyInUseL( *clearKey );
+        }
+
+    // If we got this far, the operation was successful.
+    // Give the caller a copy of the encrypted key
+    // Externalize the key data and ciphertext
+    HBufC8* result = HBufC8::NewLC( ciphertext.Length() +
+                                   KMaxPasswordLength +
+                                   50 // should be enough for encryption data
+                                   );
+    TPtr8 resultPtr = result->Des();
+    ExternalizeKeyL( encryption, ciphertext, resultPtr );
+    
+    // Encode key to base64 before returning it
+    aResult = HBufC8::NewL( resultPtr.Length()*4/3+3 );
+    TPtr8 returnPtr = aResult->Des();
+    returnPtr.SetLength( 0 );
+    TImCodecB64 b64codec;
+    b64codec.Initialise();
+    b64codec.Encode( *result, returnPtr );
+    
+    // Destroy the evidence
+    CleanupStack::PopAndDestroy( result );
+    CleanupStack::PopAndDestroy( ciphertextTemp );
+    CleanupStack::PopAndDestroy( encryptor );
+    CleanupStack::PopAndDestroy( encryption );
+    CleanupStack::PopAndDestroy( clearKey );
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::SetKey()
+//
+// --------------------------------------------------------------------------
+EXPORT_C void CDevEncKeyUtils::SetKey( TRequestStatus& aStatus,
+                                       const TDesC8& aPkcs5Key,
+                                       const TDesC8& aPassword ) const
+    {
+    TInt error( KErrNone );
+
+    if ( ! ProcessHasCapability( ECapabilityDiskAdmin ) )
+        {
+        DFLOG( "Process does not have DiskAdmin capability" );
+        error = KErrAccessDenied;
+        }
+    else
+        {
+        TRAP( error, DoSetKeyL( aPkcs5Key, aPassword ) );
+        DFLOG2( "CDevEncKeyUtils::SetKey result %d", error );
+        }
+    TRequestStatus* statusPtr = &aStatus;
+    User::RequestComplete( statusPtr, error );
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::DoSetKey()
+//
+// --------------------------------------------------------------------------
+void CDevEncKeyUtils::DoSetKeyL( const TDesC8& aPkcs5Key,
+                                 const TDesC8& aPassword ) const
+    {
+    // Decode the base64 encoded key
+    HBufC8* decodedKey = HBufC8::NewLC( aPkcs5Key.Length()*3/4 );
+    TPtr8 keyPtr = decodedKey->Des();
+    keyPtr.SetLength( 0 );
+    TImCodecB64 b64codec;
+    b64codec.Initialise();
+    b64codec.Decode( aPkcs5Key, keyPtr );
+
+    // Read the parameters and ciphertext from the input
+    CPBEncryptElement* encryption( NULL );
+    HBufC8* ciphertext( NULL );
+    InternalizeKeyL( encryption, aPassword, ciphertext, *decodedKey );
+    CleanupStack::PopAndDestroy( decodedKey );
+    CleanupStack::PushL( encryption );
+    CleanupStack::PushL( ciphertext );
+
+    // Decrypt and take key in use
+    CPBDecryptor* decryptor = encryption->NewDecryptLC();
+    HBufC8* plaintextTemp =
+        HBufC8::NewLC( decryptor->MaxOutputLength( (*ciphertext).Size() ) ); 
+    TPtr8 plaintext = plaintextTemp->Des(); 
+    decryptor->Process( *ciphertext, plaintext );
+
+    Pkcs5RemovePadding( plaintext );
+    
+    if( iConnect )
+        {
+        // Take the new key in use
+        iDevEncEngine->TakeKeyInUseL( plaintext );
+        }
+
+    DFLOG( "DoSetKeyL, Key in plaintext:" );
+    RDebug::RawPrint( plaintext );
+    DFLOG( "DoSetKeyL, Key in ciphertext:" );
+    RDebug::RawPrint( *ciphertext );
+    DFLOG( "DoSetKeyL, Password:" );
+    RDebug::RawPrint( aPassword );
+
+    
+    CleanupStack::PopAndDestroy( plaintextTemp );
+    CleanupStack::PopAndDestroy( decryptor );
+    CleanupStack::PopAndDestroy( ciphertext );
+    CleanupStack::PopAndDestroy( encryption );
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::ResetKey()
+//
+// --------------------------------------------------------------------------
+EXPORT_C void CDevEncKeyUtils::ResetKey( TRequestStatus& aStatus ) const
+    {
+    TInt error( KErrNone );
+
+    if ( ! ProcessHasCapability( ECapabilityDiskAdmin ) )
+        {
+        DFLOG( "Process does not have DiskAdmin capability" );
+        error = KErrAccessDenied;
+        }
+    else
+        {
+        TBuf8<KEncryptionKeyLength> nullKey;
+        nullKey.FillZ( KEncryptionKeyLength );
+        TRAP( error, 
+        	  if( iConnect )
+                  {
+        		  // Take the new key in use
+        		  iDevEncEngine->TakeKeyInUseL( nullKey );
+        		  }  
+        	);
+        DFLOG2( "CDevEncKeyUtils::TakeKeyInUseL result %d", error );
+        }
+    TRequestStatus* statusPtr = &aStatus;
+    User::RequestComplete( statusPtr, error );
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::GetNewFileStoreL()
+//
+// --------------------------------------------------------------------------
+void CDevEncKeyUtils::GetNewFileStoreL( RFs& aFs,
+                                        TDes& aFileName,
+                                        CFileStore*& aStore ) const
+    {
+    // Leaves with KErrAlreadyExists if file exists from before
+    aStore = CPermanentFileStore::CreateL( aFs,
+                                           aFileName,
+                                           EFileRead | EFileWrite );
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::SaveKeyL()
+//
+// --------------------------------------------------------------------------
+void CDevEncKeyUtils::SaveKeyL( CFileStore* aStore,
+                                const CPBEncryptElement* aElement,
+                                const TDesC8& aCiphertext ) const
+    {
+    RStoreWriteStream write;
+    
+    aStore->SetTypeL( aStore->Layout() );
+    
+    //write the encryption data to a new stream
+    write.CreateLC( *aStore );
+    aElement->EncryptionData().ExternalizeL( write );
+    write.CommitL();
+    CleanupStack::PopAndDestroy(); //CreateLC()
+
+    //write the cyphertext to a new stream
+    write.CreateLC( *aStore );
+    write << aCiphertext;
+    write.CommitL();
+    CleanupStack::PopAndDestroy(); //CreateLC()
+
+    aStore->Commit();
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::LoadKeyLC()
+//
+// --------------------------------------------------------------------------
+void CDevEncKeyUtils::LoadKeyLC( RFs& aFs,
+                                 const TFileName& aFileName,
+                                 CPBEncryptionData*& aData,
+                                 HBufC8*& aCiphertext ) const
+    {
+    //prepare to read the streams back in, creating a new TPBEncryptionData
+    RStoreReadStream read;
+    // open the next PFS
+    CFileStore *store = CPermanentFileStore::OpenLC( aFs,
+                                                 aFileName,
+                                                 EFileRead );
+    TStreamId dataStreamId( 1 ); // we know it was the first stream written
+    read.OpenLC( *store, dataStreamId );
+//    CleanupStack::Pop();
+    //read in Encryption data
+    aData = CPBEncryptionData::NewL( read );
+    CleanupStack::Pop(); // read
+    read.Close();
+    CleanupStack::PushL( aData );
+
+    //read in ciphertext key
+    TStreamId cipherId( 2 ); // we know it was the second stream written
+    read.OpenLC( *store, cipherId );
+    CleanupStack::Pop();
+    aCiphertext = HBufC8::NewL( read, 10000 ); //some large number
+    read.Close();
+
+    CleanupStack::Pop( aData );
+    CleanupStack::PopAndDestroy( store );
+    CleanupStack::PushL( aData );
+    CleanupStack::PushL( aCiphertext );
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::ExternalizeKeyL()
+//
+// --------------------------------------------------------------------------
+void CDevEncKeyUtils::ExternalizeKeyL( const CPBEncryptElement* aElement,
+                                       const TDesC8& aCiphertext,
+                                       //HBufC8*& aResult ) const
+                                       TDes8& aResult ) const
+    {
+    RDesWriteStream write;
+    write.Open( aResult );
+    write.PushL();
+    aElement->EncryptionData().ExternalizeL( write );
+    write << aCiphertext;
+    write.CommitL();
+    write.Pop();
+    write.Close();
+    DFLOG( "CDevEncKeyUtils::ExternalizeKeyL done" );
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::InternalizeKeyL()
+//
+// --------------------------------------------------------------------------
+void CDevEncKeyUtils::InternalizeKeyL( CPBEncryptElement*& aElement,
+                                       const TDesC8& aPassword,
+                                       HBufC8*& aCiphertext,
+                                       const TDesC8& aSource ) const
+    {
+    RDesReadStream read;
+    read.Open( aSource );
+    read.PushL();
+    CPBEncryptionData* data = CPBEncryptionData::NewLC( read );
+    aElement = CPBEncryptElement::NewLC( *data, aPassword );
+    aCiphertext = HBufC8::NewL( aSource.Length() );
+    TPtr8 cipherTextPtr = aCiphertext->Des();
+    read >> cipherTextPtr;
+    CleanupStack::Pop( aElement );
+    CleanupStack::Pop( data );
+    read.Pop();
+    read.Close();
+    DFLOG( "CDevEncKeyUtils::InternalizeKeyL done" );
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::Pkcs5RemovePadding()
+//
+// --------------------------------------------------------------------------
+void CDevEncKeyUtils::Pkcs5RemovePadding( TPtr8& aInput ) const
+    {
+    // From RFC 2898:
+    //    The padding string PS consists of 8-(||M|| mod 8) octets
+    //    each with value 8-(||M|| mod 8). The padding string PS will
+    //    satisfy one of the following statements:
+    //
+    //            PS = 01, if ||M|| mod 8 = 7 ;
+    //            PS = 02 02, if ||M|| mod 8 = 6 ;
+    //            ...
+    //            PS = 08 08 08 08 08 08 08 08, if ||M|| mod 8 = 0.
+    // So the last byte shows how much padding there is
+    DFLOG( "CDevEncKeyUtils::Pkcs5RemovePadding" );
+    TInt paddingBytes = aInput[ aInput.Length() - 1 ];
+    
+    if ( paddingBytes <= 0 ||
+         paddingBytes > 8  ||
+         paddingBytes > aInput.Length() )
+        {
+        return;
+        }
+
+    TInt delPos( aInput.Length() - paddingBytes - 1 );
+    TInt delLen( aInput.Length() - delPos );
+    aInput.Delete( delPos, delLen );
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::ProcessHasCapability()
+//
+// --------------------------------------------------------------------------
+TBool CDevEncKeyUtils::ProcessHasCapability( TCapability aCapability ) const
+    {
+    RProcess process;
+    return process.HasCapability( aCapability );
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::LoadDevEncEngineL()
+//
+// --------------------------------------------------------------------------
+void CDevEncKeyUtils::LoadDevEncEngineL()
+    {
+    FLOG(" CDevEncKeyUtils::LoadDevEncEngineL >> ");
+    
+    if (!iDevEncEngine)
+        {
+         iConnect = EFalse;
+         TInt err = iLibrary.Load(KEncryptionDll);
+         if (err != KErrNone)
+             {
+             FLOG2("Error in finding the library... %d", err);
+             if (err == KErrNotFound)
+                 err = KErrNotSupported;
+             User::Leave(err);
+             }
+         TLibraryFunction entry = iLibrary.Lookup(1);
+         
+         if (!entry)
+             {
+             FLOG("Error in loading the library...");
+             User::Leave(KErrBadLibraryEntryPoint);
+             }
+         iDevEncEngine = (CDevEncEngineBase *) entry();
+         iConnect = ETrue;
+        }
+    FLOG(" CDevEncKeyUtils::LoadDevEncEngineL << ");
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncKeyUtils::UnloadDevEncEngine()
+//
+// --------------------------------------------------------------------------
+void CDevEncKeyUtils::UnloadDevEncEngine()
+    {
+    FLOG(" CDevEncKeyUtils::UnloadDevEncEngineL >> ");
+    
+    if (iDevEncEngine)
+        {
+        iDevEncEngine->Close();
+        delete iDevEncEngine;
+        iDevEncEngine = NULL;
+        iLibrary.Close();
+        }
+    iConnect = EFalse;
+    
+    FLOG(" CDevEncKeyUtils::UnloadDevEncEngineL << ");
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncCommonUtils/src/DevEncMmcObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,76 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*              Implements a watcher for MMC disk change events.   
+*
+*
+*/
+
+
+#include <e32base.h>
+#include <f32file.h>
+#include "DevEncMmcObserver.h"
+
+
+EXPORT_C CMmcObserver* CMmcObserver::NewL( MMemoryCardObserver* aObserver,
+                                  RFs* aFileServerSession )
+    {
+    CMmcObserver* self = new(ELeave) CMmcObserver();
+    CleanupStack::PushL( self );
+    self->ConstructL( aObserver, aFileServerSession );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+void CMmcObserver::ConstructL( MMemoryCardObserver* aObserver,
+                               RFs* aFileServerSession )
+    {
+    iObserver = aObserver;
+    iFsSession = aFileServerSession;
+    CActiveScheduler::Add( this );
+    }
+
+CMmcObserver::CMmcObserver() : CActive( EPriorityIdle )
+    {
+    }
+
+CMmcObserver::~CMmcObserver()
+    {
+    Cancel();
+    }
+
+void CMmcObserver::DoCancel()
+    {
+    iFsSession->NotifyChangeCancel();
+    }
+
+void CMmcObserver::RunL()
+    {
+    //TRACES(RDebug::Print( _L("CMmcObserver::RunL status: %d"), iStatus.Int() ) );
+    iObserver->MMCStatusChangedL();
+    StartObserver();
+    }
+
+EXPORT_C void CMmcObserver::StartObserver()
+    {
+    //TRACES(RDebug::Print(_L("CMmcObserver::StartObserver")));
+    if ( IsActive() ) 
+        {
+        Cancel();
+        }
+    iFsSession->NotifyChange( ENotifyDisk, iStatus );
+    SetActive();
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncCommonUtils/src/DevEncSession.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,288 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+// Class include
+#include <DevEncSession.h>
+
+// User includes
+//#include "DevEncDiskUtils.h"
+#include "DevEncLog.h"
+#include "DevEncProtectedPSKey.h"
+
+// System includes
+#include <DevEncEngineBase.h>
+#include <DevEncEngineConstants.h>
+#include <e32property.h>
+
+#include <centralrepository.h>
+#include <DevEncExternalCRKeys.h>
+
+EXPORT_C CDevEncSessionBase* NewSessionL()
+    {
+    return new (ELeave) CDevEncSession;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncSession::CDevEncSession()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C CDevEncSession::CDevEncSession():
+iDriveNumber( EDriveC )
+	{
+	
+	}
+	
+EXPORT_C CDevEncSession::CDevEncSession( TDriveNumber aNumber ):
+    iConnected (EFalse), iDriveNumber( aNumber ), iDevEncEngine (NULL)
+    {
+    // Derived from CBase -> members zeroed.
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncSession::~CDevEncSession()
+// 
+// --------------------------------------------------------------------------
+CDevEncSession::~CDevEncSession()
+    {
+    if (iConnected)
+        UnloadDevEncEngine();
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncSession::Close()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C void CDevEncSession::Close()
+    {
+    UnloadDevEncEngine();
+    iConnected = EFalse;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncSession::Connect()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C TInt CDevEncSession::Connect()
+    {
+    TRAPD(err,LoadDevEncEngineL());
+    return err;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncSession::StartDiskEncrypt()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C TInt CDevEncSession::StartDiskEncrypt()
+    {
+    FLOG("CDevEncSession::StartDiskEncrypt >>");
+     
+     ASSERT( iConnected );
+
+     TInt err = KErrNone;
+     TInt diskStatus = 0;
+
+     err = DiskStatus( diskStatus );
+
+     if( err )
+         {
+         DFLOG2( "ERROR: Disk status query failed, err %d", err);
+         }
+     else if( EDecrypted == diskStatus )
+         {
+         DFLOG( "Starting encryption" );
+         err = iDevEncEngine->StartDiskOperation( EEncryptDisk );
+         }
+     else
+         {
+         DFLOG2( "Encryption not possible, disk status %d", diskStatus);
+         err = KErrNotReady;
+         }
+     FLOG2("CDevEncSession::StartDiskEncrypt, err = %d <<", err);
+     return err;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncSession::StartDiskDecrypt()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C TInt CDevEncSession::StartDiskDecrypt()
+    {
+    ASSERT( iConnected );
+
+    TInt err = KErrNone;
+    TInt diskStatus = 0;
+
+    err = DiskStatus( diskStatus );
+
+    if( err )
+        {
+        DFLOG2( "ERROR: Disk status query failed, err %d", err);
+        }
+    else if( EEncrypted == diskStatus )
+        {
+        DFLOG( "Starting decryption" );
+        err = iDevEncEngine->StartDiskOperation( EDecryptDisk );
+        }
+    else
+        {
+        DFLOG2( "Encryption not possible, disk status %d", diskStatus);
+        err = KErrNotReady;
+        }
+
+    return err;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncSession::StartDiskWipe()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C TInt CDevEncSession::StartDiskWipe()
+    {
+    ASSERT( iConnected );
+
+    DFLOG( "Starting wiping" );
+    TInt err = iDevEncEngine->StartDiskOperation( EWipeDisk );
+
+    return err;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncSession::DiskStatus()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C TInt CDevEncSession::DiskStatus( TInt& aStatus ) const
+    {
+    ASSERT( iConnected );
+    TInt err = iDevEncEngine->DiskStatus(aStatus);
+    return err;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncSession::Progress()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C TInt CDevEncSession::Progress( TInt& aProgress ) const
+    {
+    ASSERT( iConnected );
+    // Progress status must be polled, because after the extension has stopped
+    // updating the status there will be no new progress updates --> will wait
+    // indefinitely.
+    TInt err = iDevEncEngine->Progress(aProgress);
+
+    return err;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncSession::Connected()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C TBool CDevEncSession::Connected() const
+    {
+    return iConnected;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncSession::DriveNumber()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C TDriveNumber CDevEncSession::DriveNumber() const
+    {
+    return iDriveNumber;
+    }
+	
+// --------------------------------------------------------------------------
+// CDevEncSession::SetDrive()
+// 
+// --------------------------------------------------------------------------
+EXPORT_C void CDevEncSession::SetDrive( TDriveNumber aNumber )
+    {
+    iDriveNumber = aNumber;
+    }
+
+void CDevEncSession::LoadDevEncEngineL()
+    {
+    FLOG(" CDevEncSession::LoadDevEncEngineL >> ");
+    
+    if (!iDevEncEngine)
+        {
+         TInt err = iLibrary.Load(KEncryptionDll);
+         if (err != KErrNone)
+             {
+             FLOG2("Error in finding the library... %d", err);
+             if (err == KErrNotFound)
+                 err = KErrNotSupported;
+             User::Leave(err);
+             }
+         TLibraryFunction entry = iLibrary.Lookup(1);
+         
+         if (!entry)
+             {
+             FLOG("Error in loading the library...");
+             User::Leave(KErrBadLibraryEntryPoint);
+             }
+         iDevEncEngine = (CDevEncEngineBase *) entry();
+         TInt errconnection = iDevEncEngine->Connect(iDriveNumber);
+         if( errconnection != KErrNone )
+        	 {
+             User::Leave(errconnection);
+        	 }
+         iConnected = ETrue;
+        }
+    FLOG(" CDevEncSession::LoadDevEncEngineL << ");
+    }
+
+void CDevEncSession::UnloadDevEncEngine()
+    {
+    FLOG(" CDevEncSession::UnloadDevEncEngineL >> ");
+    
+    if (iDevEncEngine)
+        {
+        iDevEncEngine->Close();
+        delete iDevEncEngine;
+        iDevEncEngine = NULL;
+        iLibrary.Close();
+        }
+    iConnected = EFalse;
+    
+    FLOG(" CDevEncSession::UnloadDevEncEngineL << ");
+    }
+
+EXPORT_C TInt CDevEncSession::SetDevEncControlL(TInt aValue)
+    {
+    DFLOG2("CDevEncSession SetDevEncControl, value = %d >>", aValue);
+    
+    CRepository* rep = CRepository::NewLC(TUid::Uid(KCRDevEncUiSettings));
+    TInt err = rep->Set(KDevEncUiDmControl, aValue);
+    CleanupStack::PopAndDestroy(rep);
+    
+    DFLOG2("CDevEncSession SetDevEncControl, err = %d <<", err);
+    return err;
+    }
+
+EXPORT_C TInt CDevEncSession::GetDevEncControlL(TInt& aValue)
+    {
+    DFLOG("CDevEncSession GetDevEncControl >>");
+    
+    CRepository* rep = CRepository::NewLC(TUid::Uid(KCRDevEncUiSettings));
+    TInt err = rep->Get(KDevEncUiDmControl, aValue);
+    CleanupStack::PopAndDestroy(rep);
+    
+    DFLOG2("CDevEncSession GetDevEncControl, err = %d <<", err);
+    return err;
+    }
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncRfsPlugin/data/200025B6.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This RFS plugin resets the encryption key of DevEnc
+*
+*
+*/
+
+
+#include <registryinfo.rh>
+#include "DevEncUids.hrh"
+
+// Declares info for two implementations
+RESOURCE REGISTRY_INFO theInfo
+	{
+	// UID for the DLL
+	dll_uid = KDevEncRfsPluginUid;
+	// Declare array of interface info
+	interfaces = 
+		{
+		INTERFACE_INFO
+			{
+			// UID of interface that is implemented
+			interface_uid = 0x102073BB;
+			implementations = 
+				{
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = KDevEncRfsPluginImplUid;
+					version_no = 1;
+					display_name = "DevEnc RFS plugin";
+					default_data = "I"; // N = Normal RFS, D = Deep RFS, I = Init RFS (FirstBoot RFS)
+					opaque_data = "";
+					}
+				};
+			}
+		};
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncRfsPlugin/group/DevEncRfsPlugin.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*
+*/
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+#include    "../../common/DevEncUids.hrh"
+
+TARGET      DevEncRfsPlugin.dll
+
+TARGETTYPE	PLUGIN
+
+CAPABILITY	CAP_ECOM_PLUGIN
+VENDORID	VID_DEFAULT
+
+UID 0x10009D8D KDevEncRfsPluginUid
+
+SOURCEPATH  ../src
+SOURCE      DevEncRfsPlugin.cpp 
+SOURCE      DevEncRfsPluginImp.cpp 
+
+START RESOURCE ..\data\200025B6.rss
+#ifdef SYMBIAN_SECURE_ECOM 
+  TARGET DevEncRfsPlugin.rsc
+#endif 
+END
+
+LANG            SC
+
+USERINCLUDE     ../inc
+USERINCLUDE		../../common
+USERINCLUDE		../../DevEncCommonUtils/inc
+MW_LAYER_SYSTEMINCLUDE
+SYSTEMINCLUDE /epoc32/include/ecom
+
+LIBRARY     euser.lib       // Base library
+LIBRARY     ECom.lib	    // ECom library
+LIBRARY     devenccommonutils.lib
+DEBUGLIBRARY flogger.lib
+
+SOURCEPATH ../../common
+SOURCE DevEncLog.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncRfsPlugin/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*	 This file provides the information required for building RFS Example
+*    	plugin
+*
+*/
+
+
+PRJ_PLATFORMS
+
+PRJ_MMPFILES
+
+DevEncRfsPlugin.mmp
+
+
+PRJ_EXPORTS
+
+
+PRJ_TESTMMPFILES
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncRfsPlugin/inc/DevEncRfsPlugin.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,90 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*  
+*
+*/
+
+
+
+#ifndef RFSEXAMPLEPLUGIN_H
+#define RFSEXAMPLEPLUGIN_H
+
+//  INCLUDES
+#include <e32base.h>
+#include "rfsPlugin.h"
+#include "DevEncKeyUtils.h"
+
+// CLASS DECLARATION
+
+class CDevEncRfsPlugin: public CRFSPlugin
+    {
+public:
+
+    /**
+    * Two-phased constructor.
+	* @param	aInitParams initial parameters
+    */
+    static CDevEncRfsPlugin* NewL(TAny* aInitParams);
+
+    /**
+    * Destructor.
+    */
+    virtual ~CDevEncRfsPlugin();
+
+    /**
+    * 
+	* @param
+    */
+    void RestoreFactorySettingsL( const TRfsReason aType );
+
+    /**
+    * 
+	* @param
+    */
+    void GetScriptL( const TRfsReason aType, TDes& aPath );
+
+    /**
+    * 
+	* @param
+    */
+    void ExecuteCustomCommandL( const TRfsReason aType, TDesC& aCommand );
+private:
+
+    /**
+    * C++ default constructor.
+    */
+    CDevEncRfsPlugin();
+
+    /**
+    * Constructor.
+    * @param	aInitParams initial parameters
+	*/
+	CDevEncRfsPlugin(TAny* aInitParams);
+
+    /**
+    * Constructor
+    */
+    void ConstructL();
+
+    CDevEncKeyUtils*    iKeyUtils;
+
+    };
+
+
+
+
+#endif      // RFSEXAMPLEPLUGIN_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncRfsPlugin/src/DevEncRfsPlugin.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,100 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     
+*
+*/
+
+
+// INCLUDE FILES
+#include "DevEncRfsPlugin.h"
+
+#ifdef _DEBUG
+#define DEBUG( args... ) RDebug::Print( args )
+#define DEBUGRAW( rawdata ) RDebug::RawPrint( rawdata )
+#else
+#define DEBUG( args... )
+#define DEBUGRAW( rawdata )
+#endif
+
+// LOCAL CONSTANTS
+_LIT(KScriptPath, "");
+
+// ================= MEMBER FUNCTIONS =======================
+
+// C++ default constructor can NOT contain any code, that
+// might leave.
+//
+CDevEncRfsPlugin::CDevEncRfsPlugin()
+    {
+    }
+
+CDevEncRfsPlugin::CDevEncRfsPlugin( TAny* /*aInitParams*/ )
+    { 
+    }
+
+// Destructor
+CDevEncRfsPlugin::~CDevEncRfsPlugin()
+    {
+    delete iKeyUtils;
+    }
+
+// ---------------------------------------------------------
+// NewL
+// ---------------------------------------------------------
+//
+CDevEncRfsPlugin* CDevEncRfsPlugin::NewL( TAny* aInitParams )
+    {
+    DEBUG( _L("CDevEncRfsPlugin::NewL()") );
+    CDevEncRfsPlugin* self = new (ELeave) CDevEncRfsPlugin( aInitParams );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+
+// ---------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------
+//
+void CDevEncRfsPlugin::ConstructL()
+    {
+    DEBUG( _L("CDevEncRfsPlugin::ConstructL()") );
+    iKeyUtils  = new (ELeave) CDevEncKeyUtils();
+    }
+
+void CDevEncRfsPlugin::RestoreFactorySettingsL( const TRfsReason aType )
+    {
+    DEBUG(_L("CDevEncRfsPlugin::RestoreFactorySettingsL(%d)"), aType);
+    
+    if( aType != EInitRfs )
+    	  {
+        TRequestStatus status;
+        iKeyUtils->ResetKey( status );
+        User::WaitForRequest( status );
+        }
+    }
+
+void CDevEncRfsPlugin::GetScriptL( const TRfsReason /*aType*/, TDes& aPath )
+    {
+    aPath.Copy( KScriptPath );
+    }
+
+void CDevEncRfsPlugin::ExecuteCustomCommandL( const TRfsReason /*aType*/,
+                                              TDesC& /*aCommand*/ )
+    {
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncRfsPlugin/src/DevEncRfsPluginImp.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     This class export ECom interface implementations.
+*
+*/
+
+
+#include <e32std.h>
+#include <ImplementationProxy.h>
+
+#include "DevEncRfsPlugin.h"
+#include "DevEncUids.hrh"
+
+// Map the interface UIDs to implementation factory functions
+const TImplementationProxy ImplementationTable[] =
+    {
+    	IMPLEMENTATION_PROXY_ENTRY(KDevEncRfsPluginImplUid,	CDevEncRfsPlugin::NewL)
+    };
+
+// Exported proxy for instantiation method resolution
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+    {
+    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
+
+    return ImplementationTable;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/data/DevEncStarter.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource file for the ES System Application
+*
+*/
+
+
+//  RESOURCE IDENTIFIER
+NAME    ESSA // 4 letter ID
+
+//  INCLUDES
+#include <eikon.rh>
+#include <avkon.rsg>
+#include <avkon.rh>
+#include <avkon.mbg>
+
+//  CONSTANTS  
+
+//  MACROS
+
+//  RESOURCE DEFINITIONS 
+
+RESOURCE RSS_SIGNATURE { }
+
+//RESOURCE TBUF { buf = "DevEncStarter"; }
+
+RESOURCE EIK_APP_INFO
+    {
+    status_pane = r_devencstarter_status_pane;
+    }
+
+// ---------------------------------------------------------
+//
+//  r_devencstarter_status_pane
+//  Define status pane of DevEncStarter.
+//
+// ---------------------------------------------------------
+//
+RESOURCE STATUS_PANE_APP_MODEL r_devencstarter_status_pane
+    {
+    layout = R_AVKON_STATUS_PANE_LAYOUT_EMPTY;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/group/DevEncStarter.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,72 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     This is project specification file for the DevEncStarter
+*     
+*
+*/
+
+
+#include <defaultcaps.hrh>
+#include <data_caging_paths.hrh>
+#include <platform_paths.hrh>
+#include "../../common/DevEncUids.hrh"
+
+TARGET      DevEncStarter.exe
+TARGETTYPE  exe
+UID         0x0 KDevEncStarterUid
+
+VENDORID    VID_DEFAULT
+CAPABILITY  CAP_APPLICATION ReadDeviceData WriteDeviceData SwEvent DiskAdmin 
+
+SOURCEPATH ../src
+SOURCE  DevEncStarter.cpp      
+SOURCE  DevEncStarterEngine.cpp
+SOURCE  DevEncStarterUtils.cpp
+SOURCE  DevEncStarterMemoryEntity.cpp
+SOURCE  DevEncStarterMmcObserver.cpp
+SOURCE  DevEncStarterAppStarter.cpp
+SOURCE  DevEncStarterPropertyObserver.cpp
+
+SOURCEPATH      ../../common
+SOURCE          DevEncLog.cpp
+
+USERINCLUDE ../inc
+USERINCLUDE ../../common
+
+MW_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH        ../data
+START RESOURCE DevEncStarter.rss
+HEADER
+TARGETPATH APP_RESOURCE_DIR
+LANGUAGE_IDS
+END 
+
+// TBI: Remove unnecessary libraries
+LIBRARY apgrfx.lib 
+LIBRARY apparc.lib 
+LIBRARY centralrepository.lib
+LIBRARY commonengine.lib
+LIBRARY cone.lib
+LIBRARY devenccommonutils.lib
+LIBRARY efsrv.lib
+LIBRARY euser.lib
+LIBRARY featmgr.lib
+LIBRARY secui.lib // for security settings
+LIBRARY sysutil.lib // for system startup state
+LIBRARY sisregistryclient.lib // for RSisRegistrySession
+DEBUGLIBRARY flogger.lib 
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,24 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     This is project specification file for the DevEncStarter
+*     
+*
+*/
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_MMPFILES
+DevEncStarter.mmp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/inc/DevEncStarterAppStarter.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+
+#ifndef __DEVENCSTARTERSTARTER_H__
+#define __DEVENCSTARTERSTARTER_H__
+
+// INCLUDES
+#include <e32base.h>
+
+// FORWARD DECLARATIONS
+
+class MAppStarterCallback
+    {
+    public:
+        virtual void AppStarted( const TUint32& aUid )=0;
+    };
+
+class CDevEncStarterStarter : public CActive
+    {
+    public:
+        static CDevEncStarterStarter* NewL( MAppStarterCallback* aCallback );
+        static CDevEncStarterStarter* NewLC( MAppStarterCallback* aCallback );
+        ~CDevEncStarterStarter();
+
+        void StartAppL( const TUint32& aUid );
+        TBool CanStartAppL( const TUint32& aUid );
+
+    protected:
+        void RunL();
+        void DoCancel();
+        TInt RunError( TInt aError );
+
+    private:
+    // Functions
+        CDevEncStarterStarter( MAppStarterCallback* aCallback );
+
+        void ConstructL();
+
+    // Data
+        TUint32 iAppUidStarting;
+        MAppStarterCallback* iCallback; // parent
+    };
+
+#endif //__DEVENCSTARTERSTARTER_H__
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/inc/DevEncStarterDebug.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,44 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#ifndef DEVENCSTARTERDEBUG_H
+#define DEVENCSTARTERDEBUG_H
+
+#ifdef _DEBUG
+
+#define DLOG( aText ) \
+    { \
+    _LIT( KText, aText ); \
+    RDebug::Print( KText ); \
+    }
+
+#define DLOG2( aText, aParam ) \
+    { \
+    _LIT( KText, aText ); \
+    RDebug::Print( KText, aParam ); \
+    }
+
+#else   // _DEBUG not defined, no logging code will be included at all!
+
+#define DLOG( a )
+#define DLOG2( a, p )
+
+#endif // _DEBUG
+
+#endif // DEVENCSTARTERDEBUG_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/inc/DevEncStarterDef.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+#ifndef DEVENCSTARTERDEF_H
+#define DEVENCSTARTERDEF_H
+
+#endif // DEVENCSTARTERDEF_H
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/inc/DevEncStarterEngine.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Predefined contacts engine (state machine)
+*
+*/
+
+
+#ifndef DEVENCSTARTERENGINE_H_
+#define DEVENCSTARTERENGINE_H_
+
+#include <e32std.h>						
+#include <e32base.h>
+#include <e32property.h>
+
+class CDevEncStarterUtils;
+class CDevEncStarterMmcObserver;
+
+NONSHARABLE_CLASS( CDevEncStarterEngine ): public CActive
+    {
+    public:
+	/**
+	    * Symbian 1st phase constructor
+	    * @return Self pointer to CPdcEngine pushed to
+	    * the cleanup stack.
+	    */
+	    static CDevEncStarterEngine* NewLC();
+
+	    /**
+	    * Destructor.
+	    */
+	    virtual ~CDevEncStarterEngine();
+	
+    private: // C++ constructor and the Symbian second-phase constructor
+        CDevEncStarterEngine();
+        void ConstructL();
+	    
+    private: // From CActive
+        void DoCancel();
+    	void RunL();
+    	
+    private:
+    	CDevEncStarterUtils* iUtils; // owned
+    	CDevEncStarterMmcObserver* iMmcObserver; // owned
+    	RProperty iProperty;
+    };
+
+#endif /* DEVENCSTARTERENGINE_H_ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/inc/DevEncStarterMemoryEntity.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,170 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     Class for managing different types of memory on a very abstract level.
+*
+*/
+
+
+#ifndef DEVENCSTARTER_MEMORYENTITY_H
+#define DEVENCSTARTER_MEMORYENTITY_H
+
+#include <e32base.h>
+
+#include <DevEncConstants.h>
+#include "DevEncUiMemInfoObserver.h"
+#include <DevEncDiskStatusObserver.h>
+
+class CDevEncSession;
+class CDevEncUiInfoObserver;
+
+class CDevEncStarterMemoryEntity : public CBase,
+                                   public MDiskStatusObserver
+    {
+    public:
+        /**
+         * Constructs the CDevEncStarterMemoryEntity using the NewLC method, popping
+         * the constructed object from the CleanupStack before returning it.
+         *
+         * @return The newly constructed CDevEncStarterMemoryEntity
+         */
+    	static CDevEncStarterMemoryEntity* NewL( TDevEncUiMemoryType aType );
+
+        /**
+         * Constructs the CDevEncStarterMemoryEntity using the constructor and ConstructL
+         * method, leaving the constructed object on the CleanupStack before returning it.
+         *
+         * @return The newly constructed CDevEncStarterMemoryEntity
+         */
+    	static CDevEncStarterMemoryEntity* NewLC( TDevEncUiMemoryType aType );
+
+    	/**
+         * Adds an observer to this object's list of observers.
+         * @param aInfoObserver The observer to add
+         * @leave Symbian error code
+         */
+        void AddObserverL( MDevEncUiMemInfoObserver* aInfoObserver );
+
+        /**
+         * Removes an observer from this object's list of observers.
+         * Any errors are ignored.
+         * @param aInfoObserver The observer to remove
+         */
+        void RemoveObserver( MDevEncUiMemInfoObserver* aInfoObserver );
+
+        /**
+         * Called periodically. Not intended for use by other classes.
+         * @param aPtr Pointer to an instance of this class.
+         */
+        static TInt ProgressTick( TAny* aPtr );
+
+        /**
+         * Called periodically. Not intended for use by other classes.
+         * @param aPtr Pointer to an instance of this class.
+         */
+        static TInt PollTick( TAny* aPtr );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CDevEncStarterMemoryEntity();
+
+        void Cancel();
+
+        /**
+         * Gets the state of this memory entity.
+         * @return the current state
+         */
+        TUint State() const;
+        
+        /**
+         * Sets the internal state and calls UpdateMemoryInfo()
+         * @param aState the new state
+         **/
+        virtual void SetState( TUint aState );
+
+        /**
+         * Sends the current memory state information to all observers.
+         * @return none
+         */
+        virtual void UpdateMemoryInfo();
+        
+        /*
+         * From MDiskStatusObserver
+         */
+        void DiskStatusChangedL( TInt aStatus );
+
+    private:
+    // functions
+
+        /**
+         * C++ Constructor
+         **/
+        CDevEncStarterMemoryEntity( TDevEncUiMemoryType aType );
+
+        /**
+         * Second-phase constructor
+         **/
+        virtual void ConstructL();
+
+        /**
+         * Starts a timer to periodically update the memory state in the UI
+         * @param aInterval the polling interval
+         **/
+        void StartPolling( TTimeIntervalMicroSeconds32 aInterval );
+
+        /**
+         * Starts a timer to periodically update the memory state in the UI
+         * @param aInterval the polling interval
+         **/
+        void DoStartPollingL( TTimeIntervalMicroSeconds32 aInterval );
+
+        /**
+         * Fetches the encryption state and progress. Called periodically.
+         **/
+        virtual void CheckProgress();
+
+        /**
+         * Performs periodical processing of timeouts. Calls CheckProgress().
+         **/
+        virtual void DoProgressTick();
+
+        /**
+         * Performs periodical processing of timeouts.
+         * Checks if the encryption status has changed.
+         **/
+        virtual void DoPollTick();
+
+    // Data
+
+        /** Owned */
+        CPeriodic* iPeriodic;
+
+        /** Owned */
+        RArray<MDevEncUiMemInfoObserver*> iObservers;
+
+        /** Owned */
+        CDevEncSession* iSession;
+        
+        /** Owned */
+        CDiskStatusObserver* iDiskStatusObserver;
+
+        TUint iState;
+        TUint iPrevState;
+        const TDevEncUiMemoryType iType;
+        TInt iPercentDone;
+        TInt iPrevPercentDone;
+    };
+
+#endif	// DEVENCSTARTER_MEMORYENTITY_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/inc/DevEncStarterMmcObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,100 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef DEVENCSTARTERMMCOBSERVER_H_
+#define DEVENCSTARTERMMCOBSERVER_H_
+
+#include "DevEncMmcObserver.h"
+#include "DevEncStarterUtils.h"
+#include "DevEncUiMemInfoObserver.h"
+#include <f32file.h>
+
+// Forward declarations
+class CDevEncSession;
+//class CDevEncStarterUtils;
+class CDevEncStarterMemoryEntity;
+class CRepository;
+class TMmcInfo;
+
+class CDevEncStarterMmcObserver :  public CBase,
+                                   public MMemoryCardObserver,
+                                   public MDevEncUiMemInfoObserver,
+                                   public MUtilsCallback
+                                 
+    {
+    public:
+        static CDevEncStarterMmcObserver* NewL(
+                                              CDevEncStarterUtils*& aUtils );
+        ~CDevEncStarterMmcObserver();
+
+    // From MMemoryCardObserver
+
+        void MMCStatusChangedL();
+        
+        /**
+         * Called periodically. Not intended for use by other classes.
+         * @param aPtr Pointer to an instance of this class.
+         */
+        static TInt PollTick( TAny* aPtr );
+
+        /**
+        * From MDevEncUiMemInfoObserver.
+        */
+        void UpdateInfo( TDevEncUiMemoryType aType,
+                         TUint aState,
+                         TUint aProgress );
+
+        /**
+        * From MUtilsCallback.
+        */
+        void AppStarted( const TUint32& aUid );
+        
+    private:
+    // Functions
+        CDevEncStarterMmcObserver( CDevEncStarterUtils*& aUtils );
+        void ConstructL();   
+        TInt GetInfo( TMmcInfo& aInfo );
+        void LogInfo( const TMmcInfo& aInfo ) const;
+        TInt CheckMMC();
+
+        TBool NeedToStartUi( TDevEncUiMemoryType aType,
+                             TUint aState );
+
+        TBool NeedToBlockPowerKey();
+
+    // Data
+        /** Owned */
+        CMmcObserver* iObserver;
+
+        /** Owned */
+        CRepository* iCrSettings;
+        
+        RFs iFs;
+
+        /** Owned */
+        RArray<CDevEncStarterMemoryEntity*> iMemEntities;
+
+        TUint iMmcEncState;
+        TUint iPhoneEncState;
+        TInt iMmcStatus;
+
+        /** Not owned */
+        CDevEncStarterUtils*& iUtils;
+        
+        TInt32 iPowerKeyHandle;
+    };
+
+#endif /*DEVENCSTARTERMMCOBSERVER_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/inc/DevEncStarterPropertyObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,150 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+#ifndef DEVENCSTARTERPROPERTYOBSERVER_H
+#define DEVENCSTARTERPROPERTYOBSERVER_H
+
+// INCLUDES
+#include <e32base.h>
+#include <e32property.h>
+
+// CLASS DECLARATION
+
+/**
+ * MDevEncStarterPropertyChangeObserver
+ * Abstract interface for handling property change events.
+ **/
+
+class MDevEncStarterPropertyChangeObserver
+    {
+    public:
+        /**
+         * This is a callback function which is called when a property value is changed.
+         * @param aObserver a refference to the observer interface implementer
+         * @param aCategory UID of Publish And Subscribe category
+         * @param aKey subkey to specify the category event; to be used with Publish And Subscribe
+         * @param aValue the new value
+         * Event enumerations and uid:s of Publish And Subscribe can be found from PSVariables.h
+         **/
+        virtual void HandlePropertyChangeL( const TUid& aCategory,
+                                            const TUint aKey,
+                                            const TInt aValue ) = 0;
+
+        /**
+         * This is a callback function which is called when a P&S components returns an error
+         * @param aCategory UID of Publish And Subscribe category
+         * @param aKey subkey to specify the category event
+         * @param aError an error code
+         **/
+        virtual void HandlePropertyChangeErrorL( const TUid& aCategory,
+                                                 const TUint aKey,
+                                                 TInt aError ) = 0;
+    };
+
+// INCLUDES
+
+// CONSTANTS
+
+// CLASS DECLARATION
+
+/**
+ * Observer class that observes changes of Property values and propogates them further.
+ * The class defines a handle to a property, a single data value representing
+ * an item of state information.
+ *
+ **/
+class CDevEncStarterPropertyObserver : public CActive
+	{
+public:  // Constructors and destructor
+
+    /**
+     * Two-phased constructor.
+     * @param aObserver a reference to the observer interface implementer
+     * @param aCategory UID of Publish And Subscribe category
+     * @param aKey subkey to specify the category event; to be used with Publish And Subscribe
+     * Event enumerations and uid:s of Publish And Subscribe can be found from PSVariables.h
+     **/
+    static CDevEncStarterPropertyObserver* NewL( MDevEncStarterPropertyChangeObserver& aObserver,
+                                            const TUid& aCategory,
+                                            const TUint aKey );
+
+    /**
+     * Destructor.
+     **/
+    ~CDevEncStarterPropertyObserver();
+
+    /**
+     * Updates a value reference in correspondence with the current Property value
+     * @param handle to a value which will be updated
+     * @return KErrNone if operation was successful
+     **/
+	void GetValue( TInt& aValue ) const;
+
+ private:
+    /**
+     * C++ default constructor overload.
+     * Two-phased constructor.
+     * @param aObserver a reference to the observer interface implementer
+     * @param aCategory UID of Publish And Subscribe category
+     * @param aKey subkey to specify the category event; to be used with Publish And Subscribe
+     * Event enumerations and uid:s of Publish And Subscribe can be found from PSVariables.h
+     **/
+	CDevEncStarterPropertyObserver( MDevEncStarterPropertyChangeObserver& aObserver,
+	                           const TUid& aCategory,
+	                           const TUint aKey );
+
+    /**
+     * By default Symbian 2nd phase constructor is private.
+     **/
+    void ConstructL();
+
+ protected:  // Functions from base classes
+    /**
+     * From CActive
+     * Handles an active object’s request completion event
+     **/
+    void RunL();
+
+    /**
+     * From CActive,
+     * Cancels and outstanding request
+     **/
+    void DoCancel();
+
+ private:  // Data
+ 	// Value of a subscribed category property
+ 	TInt iValue;
+
+    // handle to Publish And Subscribe component
+    RProperty iProperty;
+
+    // Observer to be notified when particular Property value has changed
+    MDevEncStarterPropertyChangeObserver& iObserver;
+
+    // UID of Publish And Subscribe category
+    TUid iCategory;
+
+    // subkey to be used with Publish And Subscribe
+    TUint iKey;
+
+	};
+
+#endif  // CPROPERTYOBSERVER_H
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/inc/DevEncStarterUids.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,28 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+#ifndef DEVENCSTARTERUIDS_H
+#define DEVENCSTARTERUIDS_H
+
+#define DEVENCSTARTER_APP_UID 0x20002532 // Change to correct uid!
+#define DEVENCSTARTER_CR_UID  0x20002533 // TBI: Needed?
+
+#endif      // DEVENCSTARTERUIDS_H
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/inc/DevEncStarterUtils.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,110 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+
+#ifndef __DEVENCSTARTERUTILS_H__
+#define __DEVENCSTARTERUTILS_H__
+
+// INCLUDES
+#include <e32std.h>
+#include <eikenv.h>
+#include <w32std.h>
+//#include <akncapserverclient.h>	// for RAknUiServer
+
+#include "DevEncStarterdef.h"
+#include "DevEncStarterAppStarter.h"
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+/**
+ * Callback class for CDevEncStarterUtils.
+ */
+class MUtilsCallback
+    {
+    public:
+        /**
+         * Called when an application is started using CDevEncStarterUtils.
+         * @param aUid The UID of the started application.
+         */
+    	virtual void AppStarted( const TUint32& aUid ) = 0;
+    };
+
+/**
+ * Containts various utility functions.
+ */
+class CDevEncStarterUtils : public CBase,
+                            public MAppStarterCallback
+    {
+    public:
+        /**
+         * Symbian two-phased construction.
+         * @param aEikEnv Reference to the Eikon environment.
+         */
+        static CDevEncStarterUtils* NewL();
+
+        /*
+        * Destructor
+        */
+        virtual ~CDevEncStarterUtils();
+
+        /*
+        * Sends a key event to the application that currently has focus.
+        * @param aUid the UID of the application to start
+        * @param aCallback Reference to callback class. If specified, the
+        * class's AppStarted function will be called on completion of the
+        * request.
+        * @leave Symbian error code.
+        */
+        void StartAppL( const TUint32& aUid, MUtilsCallback* aCallback = 0 );
+
+        /*
+        * From MAppStarterCallback. Calls MUtilsCallback::AppStarted if
+        * specified.
+        * @param aUid The UID of the started application
+        */
+        void AppStarted( const TUint32& aUid );
+
+    private:
+    // Functions
+
+        /*
+        * Second-phase constructor.
+        */
+        void ConstructL();
+
+        /*
+        * C++ constructor.
+        */
+        CDevEncStarterUtils();
+
+    // Data
+        /*
+        * Application starter. Owned
+        */
+        CDevEncStarterStarter* iAppStarter;
+
+        /*
+        * Reference to the callback object. Not owned.
+        */
+        MUtilsCallback* iCallback;
+};
+
+#endif //__DEVENCSTARTERUTILS_H__
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/inc/DevEncUiMemInfoObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     Mixin class for passing memory status updates to observers.
+*
+*/
+
+
+#ifndef __DEVENCUI_MEMINFOOBSERVER_H__
+#define __DEVENCUI_MEMINFOOBSERVER_H__
+
+#include <DevEncConstants.h>
+
+class MDevEncUiMemInfoObserver
+    {
+    public:
+        virtual void UpdateInfo( TDevEncUiMemoryType aType,
+                                 TUint aState,
+                                 TUint aProgress = 0 ) = 0;
+    };
+
+#endif // __DEVENCUI_MEMINFOOBSERVER_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/rom/DevEncStarter.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+ *      Contains information about binary files and binary file locations.
+ *
+*/
+
+
+#ifndef __DEVENCSTARTER_IBY__
+#define __DEVENCSTARTER_IBY__
+
+S60_APP_EXE( DevEncStarter )
+//S60_APP_BITMAP( DevEncStarter )
+S60_APP_AIF_ICONS( DevEncStarter )
+S60_APP_AIF_RSC( DevEncStarter )
+data=DATAZ_\private\10003a3f\apps\DevEncStarter_reg.rsc     private\10003a3f\import\apps\DevEncStarter_reg.rsc
+
+
+#endif // __DEVENCSTARTER_IBY__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/src/DevEncStarter.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,84 @@
+/*
+* Copyright (c) 2002-2006 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Entry point for DevEncStarter
+*
+*/
+
+
+#include <c32comm.h>
+#include "DevEncStarterEngine.h"
+#include "DevEncLog.h"
+
+// LITERALS
+_LIT( KDevEncStarterName, "DevEncStarter" );
+
+// LOCAL FUNCTION PROTOTYPES
+static void StartDevEncStarterL();
+
+// ============================= LOCAL FUNCTIONS ==============================
+
+// ----------------------------------------------------------------------------
+// Entry-point for the USB Watcher.
+// ----------------------------------------------------------------------------
+//
+TInt E32Main()
+    {
+    DFLOG( "DevEncStarter => E32Main" );
+    TInt ret;
+    
+    // rename the thread so it is easy to find the panic application
+    ret = User::RenameThread( KDevEncStarterName );
+    
+    if (ret == KErrNone)
+        {
+        __UHEAP_MARK;
+        // create clean-up stack
+        CTrapCleanup* cleanup = CTrapCleanup::New();
+    
+        TRAP( ret, StartDevEncStarterL() );
+    
+        delete cleanup; // destroy clean-up stack
+        __UHEAP_MARKEND;
+        }
+    
+    DFLOG( "DevEncStarter => E32Main ended" );
+    return ret; // and return
+    }
+
+// ----------------------------------------------------------------------------
+// Constructs and installs the active scheduler, constructs USB Watcher's
+// objects.
+// ----------------------------------------------------------------------------
+//
+static void StartDevEncStarterL()
+    {
+    DFLOG( "DevEncStarter => StartDevEncStarterL" );
+    CActiveScheduler* activeScheduler = new (ELeave) CActiveScheduler();
+    CleanupStack::PushL( activeScheduler );
+    CActiveScheduler::Install( activeScheduler );
+
+    // Create the engine
+    CDevEncStarterEngine* engine = CDevEncStarterEngine::NewLC();
+    
+    // Start the active scheduler, the active scheduler is stopped
+   	// by the engine, when the phone is shutting down.
+   	CActiveScheduler::Start();
+    	
+   	// Cleanup.
+   	CleanupStack::PopAndDestroy( engine );	
+   	CleanupStack::PopAndDestroy( activeScheduler );
+   	DFLOG( "DevEncStarter => StartDevEncStarterL ended" );
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/src/DevEncStarterAppStarter.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,207 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Starts applications
+*
+*/
+
+
+#include <apgcli.h> // for RApaLsSession
+#include <apacmdln.h> // for CApaCommandLine
+#include "DevEncStarterAppStarter.h"
+#include "DevEncLog.h"
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CDevEncStarterStarter::NewL
+// Instancies CDevEncStarterStarter object
+// ----------------------------------------------------------
+//
+CDevEncStarterStarter* CDevEncStarterStarter::NewL( MAppStarterCallback* aCallback )
+    {
+    CDevEncStarterStarter* self = CDevEncStarterStarter::NewLC(aCallback);
+    CleanupStack::Pop();
+    return self;
+    }
+
+
+// ----------------------------------------------------------
+// CDevEncStarterStarter::NewL
+// Instancies CDevEncStarterStarter object
+// ----------------------------------------------------------
+//
+CDevEncStarterStarter* CDevEncStarterStarter::NewLC( MAppStarterCallback* aCallback )
+    {
+    CDevEncStarterStarter* self = new ( ELeave ) CDevEncStarterStarter( aCallback );
+    CleanupStack::PushL ( self );
+    self->ConstructL();
+    //CleanupStack::Pop();
+    return self;
+    }
+
+// ----------------------------------------------------------
+// CDevEncStarterStarter::ConstructL()
+// Initializes data objects
+// ----------------------------------------------------------
+//
+void CDevEncStarterStarter::ConstructL()
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// ----------------------------------------------------------
+// CDevEncStarterStarter::CDevEncStarterStarter()
+// Constructor
+// ----------------------------------------------------------
+//
+CDevEncStarterStarter::CDevEncStarterStarter( MAppStarterCallback* aCallback )
+    : CActive( EPriorityStandard ),
+      iCallback( aCallback )
+    {
+    }
+
+// ----------------------------------------------------------
+// CDevEncStarterStarter::CDevEncStarterStarter()
+// Destructor
+// ----------------------------------------------------------
+//
+CDevEncStarterStarter::~CDevEncStarterStarter()
+    {
+    Cancel();
+    }
+
+// ----------------------------------------------------------
+// CDevEncStarterStarter::CanStartAppL()
+//
+// ----------------------------------------------------------
+//
+TBool CDevEncStarterStarter::CanStartAppL( const TUint32& aUid )
+    {
+    DFLOG2( ">>CDevEncStarterStarter::CanStartAppL %x", aUid );
+    TBool result( EFalse );
+    RApaLsSession ls;
+    CleanupClosePushL( ls );
+    User::LeaveIfError( ls.Connect() );
+
+    TApaAppInfo appInfo;
+    TInt err = ls.GetAppInfo( appInfo, TUid::Uid( aUid ) );
+
+    if ( err == KErrNone )
+        {
+        result = ETrue;
+        }
+    CleanupStack::PopAndDestroy(); // ls
+    return result;
+    }
+
+// ----------------------------------------------------------
+// CDevEncStarterStarter::StartAppL()
+//
+// ----------------------------------------------------------
+//
+void CDevEncStarterStarter::StartAppL( const TUint32& aUid )
+    {
+    DFLOG2( ">>CDevEncStarterStarter::StartAppL %x", aUid );
+
+    if ( this->IsActive() )
+        {
+        DFLOG( "Already active" );
+        return;
+        }
+
+    RApaLsSession ls;
+    CleanupClosePushL( ls );
+    User::LeaveIfError( ls.Connect() );
+
+    TApaAppInfo appInfo;
+    TInt err = ls.GetAppInfo( appInfo, TUid::Uid( aUid ) );
+
+    if ( err == KErrNone )
+        {
+        CApaCommandLine* apaCommandLine = CApaCommandLine::NewLC();
+        apaCommandLine->SetExecutableNameL( appInfo.iFullName );
+        apaCommandLine->SetCommandL( EApaCommandRun );
+        TThreadId threadId;
+        DFLOG2( "iStatus = %d", iStatus.Int() );
+        TRequestStatus* status = &iStatus;
+        TInt startErr = ls.StartApp( *apaCommandLine, threadId, status );
+        DFLOG2( "iStatus after StartApp = %d", iStatus.Int() );
+        CleanupStack::PopAndDestroy( apaCommandLine );
+        if ( startErr == KErrNone )
+            {
+            iAppUidStarting = aUid;
+            SetActive();
+            }
+        else
+            {
+            DFLOG2( "Start error %d", startErr );
+            }
+        }
+    else
+        {
+        FLOG2( "GetAppInfo error %d", err );
+        }
+    CleanupStack::PopAndDestroy(); // ls
+    DFLOG( "<<CDevEncStarterStarter::StartAppL" );
+    }
+
+// ----------------------------------------------------------
+// CDevEncStarterStarter::RunError()
+// CActive Object method
+// ----------------------------------------------------------
+//
+TInt CDevEncStarterStarter::RunError( TInt aError )
+    {
+    DFLOG2( "CDevEncStarterStarter::RunError aError = %d", aError );
+    return aError;
+    }
+
+// ----------------------------------------------------------
+// CDevEncStarterStarter::RunL()
+// CActive Object method
+// ----------------------------------------------------------
+//
+void CDevEncStarterStarter::RunL()
+    {
+    DFLOG2( "CDevEncStarterStarter::RunL, status %d", iStatus.Int()  );
+    if ( iStatus.Int() == KErrNone )
+        {
+        if ( iCallback )
+            {
+            DFLOG( "Informing callback object" );
+            iCallback->AppStarted( iAppUidStarting );
+            }
+        else
+            {
+            DFLOG( "No callback object registered" );
+            }
+        }
+    else
+        {
+        DFLOG( "No callback informing because of error" );
+        }
+    iAppUidStarting = 0;
+    }
+
+// ----------------------------------------------------------
+// CDevEncStarterStarter::DoCancel()
+// CActive Object method
+// ----------------------------------------------------------
+//
+void CDevEncStarterStarter::DoCancel()
+    {
+    }
+
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/src/DevEncStarterEngine.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,123 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Predefined contacts engine (state machine)
+*
+*/
+
+
+#include <startupdomainpskeys.h>
+#include "DevEncStarterEngine.h"
+#include "DevEncStarterdef.h"
+#include "DevEncLog.h"
+#include "DevEncStarterMmcObserver.h"
+#include "DevEncUids.hrh"
+#include "DevEncStarterUtils.h"
+#include "DevEncProtectedPSKey.h"
+
+// ---------------------------------------------------------------------------
+// CDevEncStarterEngine::NewLC
+// C++ constructor
+// ---------------------------------------------------------------------------
+//
+CDevEncStarterEngine* CDevEncStarterEngine::NewLC()
+	{
+	DFLOG( "CDevEncStarterAppUi::NewLC" );
+	CDevEncStarterEngine* self = new( ELeave ) CDevEncStarterEngine();
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CDevEncStarterEngine::CDevEncStarterEngine
+// C++ constructor
+// ---------------------------------------------------------------------------
+//
+CDevEncStarterEngine::CDevEncStarterEngine()
+    : CActive( EPriorityNormal )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// CDevEncStarterEngine::ConstructL
+// ---------------------------------------------------------------------------
+//
+void CDevEncStarterEngine::ConstructL()
+    {
+    DFLOG( "CDevEncStarterAppUi::ConstructL" );
+    iUtils = CDevEncStarterUtils::NewL();
+    iMmcObserver = CDevEncStarterMmcObserver::NewL( iUtils );
+        
+    const TSecurityPolicy policy( ECapability_None );
+    RProperty::Define( KDevEncProtectedUid, KDevEncOperationKey, RProperty::EInt, policy, policy );
+    
+    iProperty.Attach( KPSUidStartup, KPSGlobalSystemState );
+    CActiveScheduler::Add( this );
+    
+    iProperty.Subscribe( iStatus );
+    SetActive();
+    }
+
+// ---------------------------------------------------------------------------
+// CDevEncStarterEngine::~CDevEncStarterEngine
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CDevEncStarterEngine::~CDevEncStarterEngine()
+    {
+    DFLOG( "CDevEncStarterAppUi::~CDevEncStarterAppUi" );
+    
+    delete iMmcObserver;
+    delete iUtils;
+    
+    RProperty::Delete( KDevEncProtectedUid, KDevEncOperationKey );
+    
+    Cancel();
+    iProperty.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterEngine::DoCancel
+// -----------------------------------------------------------------------------
+//
+void CDevEncStarterEngine::DoCancel()
+    {
+    DFLOG( "CDevEncStarterEngine::DoCancel()" );
+    iProperty.Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterEngine::RunL
+// -----------------------------------------------------------------------------
+//
+void CDevEncStarterEngine::RunL()
+    {
+    DFLOG( "CDevEncStarterEngine::RunL()" );
+    TInt value( 0 );
+    iProperty.Get( value );
+    
+    if( value == ESwStateShuttingDown )
+        {
+        CActiveScheduler::Stop();
+        }
+    else
+        {
+        iProperty.Subscribe( iStatus );
+        SetActive();
+        }
+	}
+
+// End of file
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/src/DevEncStarterMemoryEntity.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,393 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of CDevEncUiMemoryEntity
+*
+*/
+
+
+#include "DevEncLog.h"
+#include "DevEncStarterMemoryEntity.h"
+#include "DevEncUiMemInfoObserver.h"
+
+#include <DevEncDiskUtils.h>
+#include <DevEncSession.h>
+#include <f32file.h> // for TDriveNumer
+#include <DevEncEngineConstants.h>
+
+// Local definitions
+const TInt KPercent100( 100 );
+const TTimeIntervalMicroSeconds32 KProgressInterval( 500000 ); // ms, 0.5 seconds
+const TTimeIntervalMicroSeconds32 KPollInterval( 2000000 ); // ms, 2 seconds
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::CDevEncStarterMemoryEntity()
+// 
+// --------------------------------------------------------------------------
+CDevEncStarterMemoryEntity::CDevEncStarterMemoryEntity(
+                        TDevEncUiMemoryType aType )
+    : iType( aType )
+    {
+    // TBI: Get the real states from the underlying SW levels
+	iState = EDecrypted;
+    }
+
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::~CDevEncStarterMemoryEntity()
+// 
+// --------------------------------------------------------------------------
+CDevEncStarterMemoryEntity::~CDevEncStarterMemoryEntity()
+    {
+    if ( iPeriodic )
+        {
+        iPeriodic->Cancel();
+        delete iPeriodic;
+        }
+
+    iObservers.Close();
+    delete iSession;
+    delete iDiskStatusObserver;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::NewL()
+// 
+// --------------------------------------------------------------------------
+CDevEncStarterMemoryEntity* CDevEncStarterMemoryEntity::NewL(
+                                TDevEncUiMemoryType aType )
+	{
+	CDevEncStarterMemoryEntity* self =
+	    CDevEncStarterMemoryEntity::NewLC( aType );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::NewLC()
+// 
+// --------------------------------------------------------------------------
+CDevEncStarterMemoryEntity* CDevEncStarterMemoryEntity::NewLC(
+                                TDevEncUiMemoryType aType )
+	{
+	CDevEncStarterMemoryEntity* self =
+	    new ( ELeave ) CDevEncStarterMemoryEntity( aType );
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+	}
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::ConstructL()
+// 
+// --------------------------------------------------------------------------
+void CDevEncStarterMemoryEntity::ConstructL()
+	{
+    DFLOG( ">>CDevEncStarterMemoryEntity::ConstructL" );
+    switch( iType )
+        	{
+        	case EPhoneMemory: iSession = new ( ELeave ) CDevEncSession( /*EDriveC*/EDriveE );
+                               iDiskStatusObserver = CDiskStatusObserver::NewL( this, /*EDriveC*/EDriveE ); 
+        		               break;
+        		               
+        	case EPrimaryPhoneMemory: iSession = new ( ELeave ) CDevEncSession( EDriveC );
+                              iDiskStatusObserver = CDiskStatusObserver::NewL( this, EDriveC );
+        	    		      break;
+        	    		      
+        	case EMemoryCard: iSession = new ( ELeave ) CDevEncSession( /*EDriveE*/EDriveF );
+                              iDiskStatusObserver = CDiskStatusObserver::NewL( this, /*EDriveE*/EDriveF );
+        	    		      break;    	    		               
+            }
+   
+    User::LeaveIfError( iSession->Connect() );
+
+    // Get initial memory state
+    TInt nfeDiskStatus( EUnmounted );
+#ifndef __WINS__
+    TInt err = iSession->DiskStatus( nfeDiskStatus );
+    if ( err )
+        {
+        DFLOG2( "DevEncStarter: Could not get disk status, error %d", err );
+        nfeDiskStatus = EDecrypted;
+        //User::Leave( err );
+        }
+#else
+    nfeDiskStatus = EDecrypted;
+#endif
+    SetState( nfeDiskStatus );
+
+    if ( ( iState == EEncrypting ) ||
+         ( iState == EDecrypting ) )
+        {
+        // If the app was started in the middle of an ongoing operation,
+        // start polling the progress
+        StartPolling( KProgressInterval );
+        }
+    else
+        {
+        // Otherwise poll every once in a while to see if the status changes
+        //StartPolling( KPollInterval );
+        }
+
+    DFLOG( "<<CDevEncStarterMemoryEntity::ConstructL" );
+	}
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::AddObserverL()
+// 
+// --------------------------------------------------------------------------
+void CDevEncStarterMemoryEntity::AddObserverL( MDevEncUiMemInfoObserver* aInfoObserver )
+    {
+    DFLOG( "CDevEncStarterMemoryEntity::AddObserverL" );
+    if ( !aInfoObserver )
+        {
+        User::Leave( KErrArgument );
+        }
+    iObservers.AppendL( aInfoObserver );
+
+    // The new observer probably wants to know the current states
+    UpdateMemoryInfo();
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::RemoveObserver()
+// 
+// --------------------------------------------------------------------------
+void CDevEncStarterMemoryEntity::RemoveObserver( MDevEncUiMemInfoObserver* aInfoObserver )
+    {
+    if ( !aInfoObserver )
+        {
+        return;
+        }
+    TInt index( iObservers.Find( aInfoObserver ) );
+    if ( index != KErrNotFound )
+        {
+        iObservers.Remove( index );
+        }
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::StartPolling()
+// Starts a timer to periodically update the memory state in the UI
+// --------------------------------------------------------------------------
+void CDevEncStarterMemoryEntity::StartPolling(
+                                      TTimeIntervalMicroSeconds32 aInterval )
+    {
+    DFLOG( "CDevEncStarterMemoryEntity::StartPolling" );
+    TInt error( KErrNone );
+    TRAP( error, DoStartPollingL( aInterval ) );
+    DFLOG2( "CDevEncUiMemoryEntity::StartPolling result %d", error );
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::DoStartPollingL()
+// Starts a timer to periodically update the memory state in the UI
+// --------------------------------------------------------------------------
+void CDevEncStarterMemoryEntity::DoStartPollingL(
+                                      TTimeIntervalMicroSeconds32 aInterval )
+    {
+    DFLOG( "CDevEncStarterMemoryEntity::DoStartPollingL" );
+    TCallBack pollCallBack( PollTick, static_cast<TAny*>( this ) );
+    TCallBack progressCallBack( ProgressTick, static_cast<TAny*>( this ) );
+
+    if ( !iPeriodic )
+        {
+        iPeriodic = CPeriodic::NewL( EPriorityNormal );
+        }
+    iPeriodic->Cancel();
+
+    if ( aInterval == KProgressInterval )
+        {
+        iPeriodic->Start( 0, aInterval, progressCallBack );
+        }
+    else
+        {
+        iPeriodic->Start( 0, aInterval, pollCallBack );
+        }
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::ProgressTick()
+// 
+// --------------------------------------------------------------------------
+TInt CDevEncStarterMemoryEntity::ProgressTick( TAny* aPtr )
+    {
+    CDevEncStarterMemoryEntity* self = static_cast<CDevEncStarterMemoryEntity*>( aPtr );
+    self->DoProgressTick();
+    return 0;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::DoProgressTick()
+// 
+// --------------------------------------------------------------------------
+void CDevEncStarterMemoryEntity::DoProgressTick()
+    {
+    CheckProgress();
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::PollTick()
+// 
+// --------------------------------------------------------------------------
+TInt CDevEncStarterMemoryEntity::PollTick( TAny* aPtr )
+    {
+    CDevEncStarterMemoryEntity* self = static_cast<CDevEncStarterMemoryEntity*>( aPtr );
+    self->DoPollTick();
+    return 0;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::DoPollTick()
+// 
+// --------------------------------------------------------------------------
+void CDevEncStarterMemoryEntity::DoPollTick()
+    {
+    TInt nfeDiskStatus( EUnmounted );
+    TInt err = iSession->DiskStatus( nfeDiskStatus );
+    if ( err )
+        {
+        DFLOG2( "DevEncStarter: Could not get disk status, error %d", err );
+        // Ignore error
+        return;
+        }
+    if ( ( nfeDiskStatus == EEncrypting ) ||
+         ( nfeDiskStatus == EDecrypting ) )
+        {
+        // Some other component has started an encryption operation.
+        // Indicate this to the UI and start polling the progress.
+        SetState( nfeDiskStatus );
+        StartPolling( KProgressInterval );
+        }
+    else
+        {
+        if ( iState != nfeDiskStatus )
+            {
+            // The Mmc status has changed, but we are not in the middle of
+            // any operation. Just set the new state.
+            SetState( nfeDiskStatus );
+            }
+        }
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::SetState()
+// 
+// --------------------------------------------------------------------------
+void CDevEncStarterMemoryEntity::SetState( TUint aState )
+    {
+    DFLOG3( "CDevEncStarterMemoryEntity::SetState, prev %d, new %d",
+            iState, aState );
+    iState = aState;
+    UpdateMemoryInfo();
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::CheckProgress()
+// 
+// --------------------------------------------------------------------------
+void CDevEncStarterMemoryEntity::CheckProgress()
+    {
+    ASSERT( iSession );
+    ASSERT( iSession->Connected() );
+
+    TInt err = iSession->Progress( iPercentDone );
+    
+    DFLOG( "CDevEncStarterMemoryEntity::CheckProgress" );
+    
+    if ( err )
+        {
+        DFLOG( "DevEncStarter: Could not get progress" );
+        iPeriodic->Cancel();
+        }
+    else if ( iPercentDone >= KPercent100 )
+        {
+        DFLOG( "DevEncStarter: Operation complete" );
+        iPeriodic->Cancel();
+        iPercentDone = 0;
+      
+        if( iSession->DriveNumber() == EDriveC )
+        	{
+            // Finalize the phone memory
+        	DFLOG( "DevEncStarter: DiskFinalize" );
+            err = CDevEncDiskUtils::DiskFinalize( iSession->DriveNumber() );
+            if ( err )
+                {
+                DFLOG2( "DevEncStarter: Finalization failed, error %d", err );
+                }
+            }
+
+        // Restart the polling at a slower pace
+        // StartPolling( KPollInterval );
+        }
+    else // Not yet finished...
+        {
+        UpdateMemoryInfo();
+        }
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::UpdateMemoryInfo()
+// 
+// --------------------------------------------------------------------------
+void CDevEncStarterMemoryEntity::UpdateMemoryInfo()
+    {
+    DFLOG( "CDevEncStarterMemoryEntity::UpdateMemoryInfo()" );
+    for ( TInt i = 0; i < iObservers.Count(); i++ )
+        {
+        iObservers[i]->UpdateInfo( iType, iState, iPercentDone );
+        }
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::State()
+// 
+// --------------------------------------------------------------------------
+TUint CDevEncStarterMemoryEntity::State() const
+    {
+    return iState;
+    }
+
+// --------------------------------------------------------------------------
+// CDevEncStarterMemoryEntity::DiskStatusChangedL()
+// From MDiskStatusObserver
+// --------------------------------------------------------------------------
+void CDevEncStarterMemoryEntity::DiskStatusChangedL( TInt aNfeStatus )
+    {
+    if ( ( aNfeStatus == EEncrypting ) ||
+         ( aNfeStatus == EDecrypting ) )
+        {
+        // Some other component has started an encryption operation.
+        // Indicate this to the UI and start polling the progress.
+        DFLOG2( "CDevEncStarterMemoryEntity::DiskStatusChangedL => status = %d",
+        		aNfeStatus );
+        SetState( aNfeStatus );
+        StartPolling( KProgressInterval );
+        }
+    else
+        {        
+        DFLOG2( "CDevEncStarterMemoryEntity::DiskStatusChangedL => status = %d",
+            	 aNfeStatus );
+        
+        if( iState != aNfeStatus )
+        	{
+        	DFLOG2( "CDevEncStarterMemoryEntity::DiskStatusChangedL => status changed, iState was %d", iState );
+            SetState( aNfeStatus );
+        	}
+        }
+    }
+
+// End of File
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/src/DevEncStarterMmcObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,491 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of CDevEncStarterMmcObserver
+*
+*  Version    : %version: 9 %, %date_modified: Fri Nov 13 11:16:40 2009 % by %derived_by: e0326969 %
+*/
+
+
+#include <centralrepository.h>
+#include <DevEncExternalCRKeys.h>
+#include <DevEncEngineConstants.h>
+#include "DevEncLog.h"
+#include "DevEncMmcObserver.h"
+#include "DevEncStarterMmcObserver.h"
+#include "DevEncStarterMemoryEntity.h"
+#include "DevEncStarterUtils.h"
+#include "DevEncUids.hrh"
+#include "MmcInfo.h"
+
+const TInt mmcDrive( /*EDriveE*/EDriveF );
+//const TInt KPowerKeyCode( EKeyPowerOff );
+//const TInt KPowerKeyScanCode( EStdKeyPowerOff );
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterMmcObserver::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+CDevEncStarterMmcObserver* CDevEncStarterMmcObserver::NewL(
+                                               CDevEncStarterUtils*& aUtils )
+    {
+    CDevEncStarterMmcObserver* self =
+        new ( ELeave ) CDevEncStarterMmcObserver( aUtils );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterMmcObserver::CDevEncStarterMmcObserver
+// 
+// -----------------------------------------------------------------------------
+CDevEncStarterMmcObserver::CDevEncStarterMmcObserver(
+                                               CDevEncStarterUtils*& aUtils )
+    : iUtils( aUtils )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterMmcObserver::ConstructL
+// 
+// -----------------------------------------------------------------------------
+void CDevEncStarterMmcObserver::ConstructL()
+    {
+    DFLOG( "CDevEncStarterMmcObserver::ConstructL" );
+    // Central repository settings
+    iCrSettings = CRepository::NewL( TUid::Uid( KCRDevEncUiSettings ) );
+
+    DFLOG( "ObsCon 1" );
+    
+    // Create objects representing the different types of memory
+    // The order is important
+    CDevEncStarterMemoryEntity* phoneMemory =
+        CDevEncStarterMemoryEntity::NewLC( EPhoneMemory );
+    iMemEntities.AppendL( phoneMemory );
+    CleanupStack::Pop( phoneMemory );
+
+        DFLOG( "ObsCon 2" );
+
+    CDevEncStarterMemoryEntity* memoryCard =
+        CDevEncStarterMemoryEntity::NewLC( EMemoryCard );
+    iMemEntities.AppendL( memoryCard );
+    CleanupStack::Pop( memoryCard );
+
+        DFLOG( "ObsCon 3" );
+    CDevEncStarterMemoryEntity* massMemory =
+                CDevEncStarterMemoryEntity::NewLC( EPrimaryPhoneMemory );
+    
+    iMemEntities.AppendL( massMemory );
+    CleanupStack::Pop( massMemory );
+
+    // Create an MMC file system observer
+    User::LeaveIfError( iFs.Connect() );
+    iObserver = CMmcObserver::NewL( this, &iFs );
+    iObserver->StartObserver();
+    
+        DFLOG( "ObsCon 4" );
+
+    // Call the MMC callback function once to get the initial card status
+    MMCStatusChangedL();
+
+        DFLOG( "ObsCon 5" );
+
+    // This class needs to observe memory card status changes.
+    // (This call results in a call to UpdateInfo, hence we need to be fully
+    // constructed before this.)
+    iMemEntities[ EMemoryCard ]->AddObserverL( this );
+
+        DFLOG( "ObsCon 6" );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterMmcObserver::~CDevEncStarterMmcObserver
+// 
+// -----------------------------------------------------------------------------
+CDevEncStarterMmcObserver::~CDevEncStarterMmcObserver()
+    {
+    delete iObserver;
+    iFs.Close();
+
+    if ( iMemEntities.Count() > EMemoryCard ) 
+	    {
+        iMemEntities[ EMemoryCard ]->RemoveObserver( this );
+        for ( TInt i = 0; i < iMemEntities.Count(); i++ )
+            {
+            delete iMemEntities[i];
+            }
+        iMemEntities.Close();
+		}
+    delete iCrSettings;
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterMmcObserver::MMCStatusChangedL
+// From MMemoryCardObserver
+// -----------------------------------------------------------------------------
+void CDevEncStarterMmcObserver::MMCStatusChangedL()
+    {
+    DFLOG( "CDevEncStarterMmcObserver::MMCStatusChangedL" );
+    TVolumeInfo volInfo;
+
+    TInt err = iFs.Volume( volInfo, /*EDriveE*/EDriveF );
+    switch ( err )
+        {
+        case KErrNone:
+            {
+            // Readable MMC inserted
+            DFLOG( "MMC inserted" );
+            iMmcStatus = EMmcOk;
+            
+            break;
+            }
+
+        case KErrNotReady:
+            {
+            // MMC ejected
+            DFLOG( "MMC ejected" );
+            iMmcStatus = EMmcNotPresent;
+            //This is because for some reason when the memory card is ejected the Disk status observer is not notified
+            //thus the Ui is started even if the MMC is removed.
+            iMemEntities[ EMemoryCard ]->SetState( EUnmounted );
+            break;
+            }
+
+        case KErrCorrupt:
+            {
+            // Corrupt or unformatted MMC, or wrong key
+            DFLOG( "MMC corrupt, unformatted or encrypted with other key" );
+            iMmcStatus = EMmcNotReadable;
+
+                break;
+            }
+
+        default:
+            {
+            DFLOG2( "RFs::Volume returned error %d", err );
+            break;
+            }
+        } // switch
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterMmcObserver::GetInfo
+// From MMemoryCardObserver
+// -----------------------------------------------------------------------------
+TInt CDevEncStarterMmcObserver::GetInfo( TMmcInfo& aInfo )
+    {
+    TVolumeInfo volInfo;
+    TDriveInfo driveInfo;
+
+    // Check if MMC mounted
+    TInt err = CheckMMC();
+
+    DFLOG2( "CDevEncStarterMmcObserver::GetInfo - CheckMMC returned %d", err );
+    
+    if( !err )
+        {
+        // MMC is mounted, get further information
+        err = iFs.Drive( driveInfo, mmcDrive );
+        
+        DFLOG2( "CDevEncStarterMmcObserver::GetInfo - iFs.Drive returned %d", err );
+        DFLOG3( "CDevEncStarterMmcObserver::GetInfo - driveInfo.iDriveAtt %d, driveInfo.iMediaAtt %d",
+                driveInfo.iDriveAtt,
+                driveInfo.iMediaAtt );
+
+        if ( !err )
+            {
+            aInfo.iIsFormattable = driveInfo.iMediaAtt & KMediaAttFormattable;
+            aInfo.iIsLockable = driveInfo.iMediaAtt & KMediaAttLockable;
+            aInfo.iIsLocked = driveInfo.iMediaAtt & KMediaAttLocked;
+            aInfo.iIsReadOnly = driveInfo.iMediaAtt & KMediaAttWriteProtected;
+            aInfo.iIsPasswordSet = driveInfo.iMediaAtt & KMediaAttHasPassword;
+
+            if ( !aInfo.iIsLocked )
+                {
+                // Then get volume info for name etc.
+                err = iFs.Volume( volInfo, mmcDrive );
+//#if defined _DEBUG
+#if 0
+                TBuf<50> tempDes1; // helpers for showing valid memory amount, which do not fit in 32 bits
+                TBuf<50> tempDes2;
+
+                tempDes1.Num( volInfo.iSize );
+                tempDes2.Num( volInfo.iFree );
+                DFLOG2( "CDevEncStarterMmcObserver::GetInfo - iFs.Volume returned %d", err );
+                DFLOG2( "CDevEncStarterMmcObserver::GetInfo - volInfo iUniqueID %d, iSize, iFree, iName:", 
+                        volInfo.iUniqueID );
+                DFLOGBUF( tempDes1 );
+                DFLOGBUF( tempDes2 );
+                DFLOGBUF( volInfo.iName );
+#endif // _DEBUG
+                }
+            else
+                {
+                err = KErrLocked;
+                }
+            }
+        else
+            {
+            err = KErrNotReady;
+            }
+        }
+
+    DFLOG2( "CDevEncStarterMmcObserver::GetInfo - err %d", err );
+    
+    if( !err )
+        {
+        // MMC ok, get rest of the information
+        aInfo.iIsInserted = ETrue;
+        aInfo.iIsInUse = EFalse;
+        aInfo.iName = volInfo.iName;
+        aInfo.iUid = volInfo.iUniqueID;
+        // Use all 64 bits
+        aInfo.iCapacity = volInfo.iSize;
+        aInfo.iSpaceFree = volInfo.iFree;
+
+        // Check if the volume is formatted
+        aInfo.iIsFormatted = volInfo.iSize > 0;
+
+        // Test if a previous backup exists
+        aInfo.iBackupExists = EFalse; //BaflUtils::FileExists( iFs, aBackupFile );
+        }
+    else
+        {
+        // By default set values as 
+        aInfo.iIsInserted = EFalse;
+        aInfo.iIsInUse = EFalse;
+        aInfo.iIsFormatted = EFalse;
+        aInfo.iBackupExists = EFalse;
+
+        switch( err )
+            {
+            case KErrInUse:
+                {
+                aInfo.iIsInserted = ETrue;
+                aInfo.iIsInUse = ETrue;
+                break;
+                }
+            case KErrNotReady:
+                {
+                // If card is not ready, but media attributes set, it is reserved.
+                if ( driveInfo.iMediaAtt )
+                    {
+                    aInfo.iIsInserted = ETrue;
+                    aInfo.iIsInUse = ETrue;
+                    }
+                break;
+                }
+            case KErrCorrupt:
+                {
+                aInfo.iIsInserted = ETrue;
+                break;
+                }
+            case KErrLocked:
+                {
+                // Could not mount due card locked or volume info query returned card locked.
+                // Hence info-flags possibly set accoring to iMediaAtt are overridden.
+                aInfo.iIsInserted = ETrue;
+                aInfo.iIsFormatted = ETrue;
+                aInfo.iIsLocked = ETrue;
+                aInfo.iIsPasswordSet = ETrue;
+                aInfo.iIsLockable = ETrue;
+                break;
+                }
+            default:
+                {
+                break;
+                }
+            }
+        }
+
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterMmcObserver::CheckMMC
+// 
+// -----------------------------------------------------------------------------
+TInt CDevEncStarterMmcObserver::CheckMMC()
+    {
+    // Check if MMC mounted, mount if required
+    TFullName fsname;
+
+    // If can't use the drive, returns KErrNotFound
+    TInt err = iFs.FileSystemName( fsname, mmcDrive );
+
+    if ( !err )
+        {
+        // MMC found. Checking if it is mounted
+        if ( fsname.Length( ) == 0 )
+            {
+            // MMC not mounted ( file system name is empty ) 
+            DFLOG( "Mmc not mounted" );
+            err = KErrDisMounted;
+            }
+        }
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterMmcObserver::CheckMMC
+// 
+// -----------------------------------------------------------------------------
+void CDevEncStarterMmcObserver::LogInfo( const TMmcInfo& aInfo ) const
+    {
+    DFLOG2( "aInfo.iIsFormattable %d", aInfo.iIsFormattable ? 1 : 0 );
+    DFLOG2( "aInfo.iIsFormatted %d", aInfo.iIsFormatted ? 1 : 0 );
+    DFLOG2( "aInfo.iIsLockable %d", aInfo.iIsLockable ? 1 : 0 );
+    DFLOG2( "aInfo.iIsLocked %d", aInfo.iIsLocked ? 1 : 0 );
+    DFLOG2( "aInfo.iIsReadOnly %d", aInfo.iIsReadOnly ? 1 : 0 );
+    DFLOG2( "aInfo.iIsPasswordSet %d", aInfo.iIsPasswordSet ? 1 : 0 );
+    DFLOG2( "aInfo.iIsInserted %d", aInfo.iIsInserted ? 1 : 0 );
+    DFLOG2( "aInfo.iBackupExists %d", aInfo.iBackupExists ? 1 : 0 );
+    DFLOG2( "aInfo.iIsInUse %d", aInfo.iIsInUse ? 1 : 0 );
+    }
+
+// --------------------------------------------------------------------------
+// Called by memory entity when memory status changes.
+// 
+// --------------------------------------------------------------------------
+void CDevEncStarterMmcObserver::UpdateInfo( TDevEncUiMemoryType aType,
+                                            TUint aState,
+                                            TUint /*aProgress*/ )
+    {
+    DFLOG3( "CDevEncStarterMmcObserver::UpdateInfo, type %d, state %d",
+            aType, aState );
+    DFLOG2( "Phone state %d", iPhoneEncState );
+    DFLOG2( "Mmc state %d", iMmcStatus );
+
+    TBool startUi = NeedToStartUi( aType, aState );
+
+    if ( aType == EPhoneMemory )
+        {
+        iPhoneEncState = aState;
+        }
+    else // EMemoryCard
+        {
+        iMmcEncState = aState;    
+        }
+
+    if ( startUi )
+        {
+        TInt error( KErrNone );
+        TRAP( error, iUtils->StartAppL( KDevEncUiUid,
+                                        this ) );
+        DFLOG2( "App start requested, result %d", error );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterMmcObserver::NeedToStartUi
+// 
+// -----------------------------------------------------------------------------
+TBool CDevEncStarterMmcObserver::NeedToStartUi( TDevEncUiMemoryType aType,
+                                                TUint aState )
+    {
+    TBool startUi( EFalse );
+    
+    DFLOG2( "CDevEncStarterMmcObserver::NeedToStartUi => aState = %d",
+    		aState );
+    DFLOG2( "CDevEncStarterMmcObserver::NeedToStartUi => iMmcStatus = %d",
+    		iMmcStatus );
+    DFLOG2( "CDevEncStarterMmcObserver::NeedToStartUi => iMmcEncState = %d",
+    		iMmcEncState );
+
+    // Check encryption key status
+    TInt mmcKeyInDriver( 0 );
+    TInt error = iCrSettings->Get( KDevEncUserSettingMemoryCard,
+                                   mmcKeyInDriver );
+    if ( error )
+        {
+        DFLOG2( "Cenrep get error %d", error );
+        return startUi;
+        }
+    
+    if ( ( iMmcStatus == EMmcOk ) && 
+         ( iMmcEncState == EUnmounted ) &&
+         ( aState == EDecrypted ) )
+        {
+        // A readable memory card has just been inserted
+    
+        if ( mmcKeyInDriver )
+            {
+            // We have a valid encryption key, but the newly inserted
+            // card is decrypted. Ask if the user wants to encrypt.
+            // (see UI spec 2.13)
+            startUi = ETrue;
+            }
+        }
+
+    if ( ( iMmcStatus == EMmcNotReadable ) && 
+         ( iMmcEncState == EUnmounted ) &&
+         ( aState == ECorrupted ) )
+        {
+        // An unreadable memory card has just been inserted
+        
+        if ( mmcKeyInDriver )
+            {
+            // We seem to have the wrong encryption key in the driver.
+            // Inform the user that the card cannot be used.
+            // (see UI spec 2.16)
+            startUi = ETrue;
+            }
+        else
+            {
+            // We have no encryption key in the driver.
+            // Ask if the user wants to import a key and decrypt.
+            // (see UI spec 2.17)
+            startUi = ETrue;
+            }
+        }
+
+    if ( ( iMmcStatus == EMmcNotReadable ) && 
+         ( iMmcEncState == ECorrupted ) &&
+         ( aState == ECorrupted ) )
+        {
+        // We have an unreadable memory card, and tried to load a new key
+        // but the card is still unreadable. Inform the user and let the user
+        // select some other key. (see UI spec 2.10)
+        startUi = ETrue;
+        }
+
+    if ( ( iMmcStatus == EMmcOk ) && 
+         ( iMmcEncState == ECorrupted ) &&
+         ( aState == EEncrypted ) )
+        {
+        // We have just imported the correct key and the card is now
+        // readable. Show a note to the user.
+        // (see UI spec 2.7)
+        startUi = ETrue;
+        }
+    return startUi;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterMmcObserver::AppStarted
+// 
+// -----------------------------------------------------------------------------
+void CDevEncStarterMmcObserver::AppStarted( const TUint32& aUid )
+    {
+    if ( !iUtils )
+        {
+        DFLOG( "CDevEncStarterMmcObserver::AppStarted error: no utils" );
+        return;
+        }
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/src/DevEncStarterPropertyObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,123 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+// INCLUDE FILES
+#include "DevEncStarterPropertyObserver.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterPropertyObserver::CPropertyObserver
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CDevEncStarterPropertyObserver::CDevEncStarterPropertyObserver(
+                               MDevEncStarterPropertyChangeObserver& aObserver,
+                               const TUid& aCategory,
+                               const TUint aKey )
+    : CActive( CActive::EPriorityStandard ),
+    iObserver( aObserver ),
+    iCategory( aCategory ),
+    iKey( aKey )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterPropertyObserver::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CDevEncStarterPropertyObserver::ConstructL()
+    {
+    User::LeaveIfError( iProperty.Attach( iCategory, iKey ) );
+    CActiveScheduler::Add( this );
+    iProperty.Subscribe( iStatus );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterPropertyObserver::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CDevEncStarterPropertyObserver* CDevEncStarterPropertyObserver::NewL(
+                               MDevEncStarterPropertyChangeObserver& aObserver,
+                               const TUid& aCategory,
+                               const TUint aKey )
+    {
+    CDevEncStarterPropertyObserver* self =
+        new ( ELeave ) CDevEncStarterPropertyObserver( aObserver, aCategory, aKey );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// Destructor
+CDevEncStarterPropertyObserver::~CDevEncStarterPropertyObserver()
+    {
+    Cancel();
+    iProperty.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterPropertyObserver::RunL
+//
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CDevEncStarterPropertyObserver::RunL()
+    {
+    iProperty.Subscribe( iStatus );
+    SetActive();
+    TInt err = iProperty.Get( iValue );
+    if ( err )
+        {
+        iObserver.HandlePropertyChangeErrorL( iCategory, iKey, err );
+        }
+    else
+        {
+        iObserver.HandlePropertyChangeL( iCategory, iKey, iValue );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterPropertyObserver::DoCancel
+// Cancels an outstanding active request
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CDevEncStarterPropertyObserver::DoCancel()
+    {
+    iProperty.Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CDevEncStarterPropertyObserver::GetValue
+// Returns KErrNone if operation was successful
+// Actual value is written to aValue
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CDevEncStarterPropertyObserver::GetValue( TInt& aValue ) const
+    {
+    aValue = iValue;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/DevEncStarter/src/DevEncStarterUtils.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,128 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  DevEncStarter utilities
+*
+*/
+
+
+#include "DevEncStarterUtils.h"
+#include "DevEncLog.h"
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CDevEncStarterUtils::CDevEncStarterUtils()
+// ----------------------------------------------------------
+//
+CDevEncStarterUtils::~CDevEncStarterUtils()
+    {
+    if (iAppStarter)
+        {
+        delete iAppStarter;
+        iAppStarter = NULL;
+        }
+    }
+
+// ----------------------------------------------------------
+// CDevEncStarterUtils::NewL
+// ----------------------------------------------------------
+//
+CDevEncStarterUtils* CDevEncStarterUtils::NewL()
+    {
+    CDevEncStarterUtils* self = new ( ELeave ) CDevEncStarterUtils();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+// ----------------------------------------------------------
+// CDevEncStarterUtils::CDevEncStarterUtils()
+// ----------------------------------------------------------
+//
+CDevEncStarterUtils::CDevEncStarterUtils()
+    {
+    
+    }
+
+// ----------------------------------------------------------
+// CDevEncStarterUtils::ConstructL()
+// ----------------------------------------------------------
+//
+void CDevEncStarterUtils::ConstructL()
+    {
+    
+    }
+
+// ----------------------------------------------------------
+// CDevEncStarterUtils::StartAppL()
+//
+// ----------------------------------------------------------
+//
+void CDevEncStarterUtils::StartAppL( const TUint32& aUid,
+                                     MUtilsCallback* aCallback )
+    {
+    DFLOG( "CDevEncStarterUtils::StartAppL" );
+    if ( aCallback )
+        {
+        // The calling class wants to know when the application is started
+        if ( iCallback )
+            {
+            User::Leave( KErrInUse );
+            }
+        else
+            {
+            // Used in CDevEncStarterUtils::AppStarted()
+            DFLOG( "Callback stored" );
+            iCallback = aCallback;
+            }
+        }
+
+    if ( !iAppStarter )
+        {
+        iAppStarter = CDevEncStarterStarter::NewLC( this );
+        CleanupStack::Pop( iAppStarter ); // member variable, no cleanupstack
+        DFLOG( "Starter created" );
+        }
+
+    if ( !iAppStarter->IsActive() )
+        {
+        iAppStarter->StartAppL( aUid );
+        DFLOG( "StartAppL called" );
+        }
+    else
+        {
+        DFLOG( "CDevEncStarterUtils::StartAppL: App starter already active" );
+        }
+    }
+
+
+// ----------------------------------------------------------
+// CDevEncStarterUtils::AppStarted()
+//
+// ----------------------------------------------------------
+//
+void CDevEncStarterUtils::AppStarted( const TUint32& aUid )
+    {
+    DFLOG( "CDevEncStarterUtils::AppStarted" );
+    if ( iCallback )
+        {
+        DFLOG2( "CDevEncStarterUtils::AppStarted %x", aUid );
+        iCallback->AppStarted( aUid );
+        iCallback = NULL;
+        }
+    }
+
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/Pk5Recognizer/group/2000FD89.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,42 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project specification file of Pk5 Recognizer.
+*
+*/
+
+
+#include <registryinfo.rh>
+
+RESOURCE REGISTRY_INFO r_registry
+{
+    dll_uid = 0x2000FD89;
+    interfaces =
+    {
+        INTERFACE_INFO
+        {
+            interface_uid = 0x101F7D87;  
+            implementations =
+            {
+                IMPLEMENTATION_INFO
+                {
+                    implementation_uid = 0x2000FD89;
+                    version_no = 1;
+                    display_name = "Pk5Recog";
+                    default_data = "";
+                    opaque_data = "";
+                }
+            };
+        }
+    };
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/Pk5Recognizer/group/Pk5Recognizer.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project specification file of Pk5 Recognizer.
+*
+*/
+
+#include <defaultcaps.hrh>
+#include <data_caging_paths.hrh>
+#include <platform_paths.hrh>
+
+TARGETTYPE PLUGIN
+TARGET Pk5Recognizer.dll
+
+UID 0x10009D8D 0x2000FD89
+
+START RESOURCE  2000FD89.rss
+ TARGET          Pk5Recognizer.rsc
+END
+
+CAPABILITY      CAP_RECOGNISER
+VENDORID        VID_DEFAULT
+
+SOURCEPATH ../src
+SOURCE Pk5Recognizer.cpp
+
+USERINCLUDE       ../inc
+
+SYSTEMINCLUDE     /epoc32/include/ecom
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.LIB
+LIBRARY         apmime.LIB
+LIBRARY         bafl.lib
+LIBRARY         efsrv.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/Pk5Recognizer/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,28 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Provides the information required for building Pk5Recognizer
+*
+*/
+
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+// Exported headers
+
+PRJ_MMPFILES
+Pk5Recognizer.mmp
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/Pk5Recognizer/inc/Pk5Recognizer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,81 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef PK5RECOGNIZER_H_
+#define PK5RECOGNIZER_H_
+
+// INCLUDES
+#include <apmrec.h>
+
+// CLASS DECLARATION
+/**
+*  Mime recognizer for "application/pk5".
+*  
+*/
+const TInt KPk5RecognizerImplementationUid = 0x2000FD89;
+class CPk5Recognizer : public CApaDataRecognizerType
+    {
+    public: // Constructor
+
+        /**
+        * Constructor.
+        */
+        CPk5Recognizer();
+
+		~CPk5Recognizer();
+		static CPk5Recognizer* NewL();
+		
+    public:  // Functions from base classes
+
+        /**
+        * From CApaDataRecognizerType.
+        * Preferred byte size of sample content.
+        */
+        TUint PreferredBufSize();
+
+        /**
+        * From CApaDataRecognizerType.
+        * Return mime type which this class supports to recognize.
+        *
+        * @param aIndex index.
+        * @return always text/plain.
+        */
+        TDataType SupportedDataTypeL(TInt aIndex) const;
+        /**
+        ** From CApaDataRecognizerType.
+        */
+        
+    	static CApaDataRecognizerType* CreateRecognizerL();
+    		
+    private:  // Functions from base classes
+
+        /*
+        // Two phase contructor
+        //
+        */
+        void ConstructL();
+        /**
+        * From CApaDataRecognizerType.
+        * This is a main part of recognization.
+        *
+        * @param aName file name.
+        * @param aBuffer sample content.
+        */
+        void DoRecognizeL(const TDesC& aName, const TDesC8& aBuffer);
+
+    };
+
+#endif /*PK5RECOGNIZER_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/Pk5Recognizer/src/Pk5Recognizer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,170 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of application entry point functions.
+*
+*/
+
+
+// INCLUDE FILES
+#include <apmrec.h>
+#include <apmstd.h>
+#include <e32svr.h>
+#include <ImplementationProxy.h>
+
+#include "Pk5Recognizer.h"
+#include <barsread.h>
+#include <EikEnv.h>
+#include <f32file.h>
+
+// CONSTANTS
+const TUid KUidPk5Recognizer={0x2000FD89};
+_LIT8(KPk5MimeType, "application/vnd.nokia.pk5");
+const TInt KMaxBufferSize(512);
+_LIT(KPk5Extension, ".pk5");
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// ---------------------------------------------------------
+// CPk5Recognizer::CPk5Recognizer()
+// ---------------------------------------------------------
+//
+CPk5Recognizer::CPk5Recognizer()
+    :CApaDataRecognizerType(
+    	KUidPk5Recognizer,
+        CApaDataRecognizerType::ENormal )
+    {
+    iCountDataTypes = 1;
+    }
+
+// ---------------------------------------------------------
+// CPk5Recognizer::~CPk5Recognizer()
+// ---------------------------------------------------------
+//
+CPk5Recognizer::~CPk5Recognizer()
+    {
+    
+    }
+
+// ---------------------------------------------------------
+// CPk5Recognizer::NewL()
+// ---------------------------------------------------------
+//
+CPk5Recognizer* CPk5Recognizer::NewL()
+    {
+    CPk5Recognizer* self = new(ELeave) CPk5Recognizer();
+	CleanupStack::PushL( self  );
+	self->ConstructL();
+	CleanupStack::Pop();
+	return self;
+    }
+
+// ---------------------------------------------------------
+// CPk5Recognizer::ConstructL()
+// ---------------------------------------------------------
+//
+void CPk5Recognizer::ConstructL()
+	{
+	
+	}
+
+// ---------------------------------------------------------
+// CPk5Recognizer::PreferredBufSize()
+// ---------------------------------------------------------
+//
+TUint CPk5Recognizer::PreferredBufSize()
+	{
+    return KMaxBufferSize;
+    }
+
+// ---------------------------------------------------------
+// CPk5Recognizer::SupportedDataTypeL()
+// ---------------------------------------------------------
+//
+TDataType CPk5Recognizer::SupportedDataTypeL(TInt /*aIndex*/) const
+	{
+    return TDataType(KPk5MimeType);
+    }
+    		
+// ---------------------------------------------------------
+// CPk5Recognizer::DoRecognizeL()
+// ---------------------------------------------------------
+//
+void CPk5Recognizer::DoRecognizeL(const TDesC& aName, const TDesC8& /*aBuffer*/)
+    {
+    iConfidence = ENotRecognized;
+    
+    if ( aName.Length() > KPk5Extension().Length() )
+        {
+        TPtrC extension = aName.Right( KPk5Extension().Length() );
+        
+        if( extension.Compare( KPk5Extension ) == 0 )
+        	{
+            iDataType = TDataType(KPk5MimeType);
+            iConfidence = ECertain;
+            }
+        }
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// CApaDataRecognizerType* CreateRecognizer
+// The gate function - ordinal 1
+// -----------------------------------------------------------------------------
+//
+#ifdef EKA2
+
+// ---------------------------------------------------------
+// CPk5Recognizer::CreateRecognizerL()
+// ---------------------------------------------------------
+//
+CApaDataRecognizerType* CPk5Recognizer::CreateRecognizerL()
+    {
+    return CPk5Recognizer::NewL();
+    }
+
+const TImplementationProxy ImplementationTable[] =
+    {
+    IMPLEMENTATION_PROXY_ENTRY(KPk5RecognizerImplementationUid, 
+    	CPk5Recognizer::CreateRecognizerL)
+    };
+
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+    {
+    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
+    return ImplementationTable;
+    }
+    
+#else
+EXPORT_C CApaDataRecognizerType* CreateRecognizer()
+    {
+    CApaDataRecognizerType* thing=new CPk5Recognizer();
+    return thing; // NULL if new failed
+    }
+
+#endif
+// -----------------------------------------------------------------------------
+// E32Dll
+// DLL entry point
+// -----------------------------------------------------------------------------
+//
+
+#ifndef EKA2
+GLDEF_C TInt E32Dll(TDllReason /*aReason*/)
+    {
+    return KErrNone;
+    }
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/common/DevEncConfig.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Common build configuration of Device Encryption components
+*
+*/
+
+
+#ifndef __DEVENCUI_CONFIG_H__
+#define __DEVENCUI_CONFIG_H__
+
+// Comment this out to disable logs
+#define DEVENC_LOG
+
+#endif // __DEVENCUI_CONFIG_H__
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/common/DevEncDef.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,31 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     Common definitions for the application.
+*
+*/
+
+
+#ifndef DEVENCDEF_H_
+#define DEVENCDEF_H_
+
+enum
+    {
+    KMinPasswordLength = 4, // Same as for security code
+    KMaxPasswordLength = 50,
+    KMaxKeyNameLength = 50,
+    KMaxFilenameLength = 100,
+    KEncryptionKeyLength = 32
+    };
+#endif /*DEVENCDEF_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/common/DevEncLog.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,40 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of CFileLog
+*
+*/
+
+
+#include "DevEncLog.h"
+#include <flogger.h>
+
+#if defined( _DEBUG ) && defined ( DEVENC_LOG )
+
+_LIT( KDevEncLogDir, "DevEnc");
+_LIT( KDevEncLogFile, "DevEncdiskutils.log");
+
+void CFileLog::Printf( TRefByValue<const TDesC> aFmt, ... )
+	{
+	VA_LIST list;
+	VA_START( list, aFmt );
+	RFileLogger::WriteFormat( KDevEncLogDir,
+                              KDevEncLogFile,
+	                          EFileLoggingModeAppend,
+	                          aFmt,
+	                          list );
+	}
+
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/common/DevEncLog.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,137 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Debug logging functionality
+*
+*/
+
+
+#ifndef __DEVENC_LOG_H__
+#define __DEVENC_LOG_H__
+
+#include "DevEncConfig.hrh"
+
+#if defined( _DEBUG ) && defined ( DEVENC_LOG )
+
+#include <e32base.h>
+#include <e32cmn.h>
+#include <e32debug.h>
+
+class CFileLog : public CBase
+	{
+    public:
+    	static void Printf( TRefByValue<const TDesC> aFmt, ... );
+	};
+
+// Debug trace to stdout
+#define DLOG( aText ) \
+    { \
+    _LIT( KText, aText ); \
+    RDebug::Print( KText ); \
+    }
+
+// Debug trace to stdout
+#define DLOG2( aText, aParam ) \
+    { \
+    _LIT( KText, aText ); \
+    RDebug::Print( KText, aParam ); \
+    }
+
+// Debug trace to stdout
+#define DLOG3( aText, aParam1, aParam2 ) \
+    { \
+    _LIT( KText, aText ); \
+    RDebug::Print( KText, aParam1, aParam2 ); \
+    }
+
+// Debug trace to file
+#define FLOG( aText ) \
+    { \
+    _LIT( KLogText, aText ); \
+    CFileLog::Printf( KLogText ); \
+    }
+
+// Debug trace to file
+#define FLOG2( aText, b ) \
+    { \
+    _LIT( KLogText, aText ); \
+    CFileLog::Printf( KLogText, b ); \
+    }
+
+// Debug trace to file
+#define FLOG3( aText, b, c ) \
+    { \
+    _LIT( KLogText, aText ); \
+    CFileLog::Printf( KLogText, b, c ); \
+    }
+
+// Debug trace to stdout and file
+#define DFLOG( aText ) \
+    { \
+    DLOG( aText ); \
+    FLOG( aText ); \
+    }
+
+// Debug trace to stdout and file
+#define DFLOG2( aText, aParam ) \
+    { \
+    DLOG2( aText, aParam ); \
+    FLOG2( aText, aParam ); \
+    }
+
+// Debug trace to stdout and file
+#define DFLOG3( aText, aParam1, aParam2 ) \
+    { \
+    DLOG3( aText, aParam1, aParam2 ); \
+    FLOG3( aText, aParam1, aParam2 ); \
+    }
+
+// Debug trace a string literal to file
+#define FLOGBUF( aText ) \
+    { \
+    CFileLog::Printf( aText ); \
+    }
+
+// Debug trace a string literal
+#define DLOGBUF( aText ) \
+    { \
+    RDebug::Print( aText ); \
+    }
+
+// Debug trace a string literal to file and stdout
+#define DFLOGBUF( aText ) \
+    { \
+    DLOGBUF( aText ); \
+    FLOGBUF( aText ); \
+    }
+    
+#else   // _DEBUG not defined, no logging code will be included at all
+
+#define DLOG( a )
+#define DLOG2( a, b )
+#define DLOG3( a, b, c )
+#define FLOG( a )
+#define FLOG2( a, b )
+#define FLOG3( a, b, c )
+#define DFLOG( a )
+#define DFLOG2( a, b )
+#define DFLOG3( a, b, c )
+#define FLOGBUF( a )
+#define DFLOGBUF( a )
+    
+#endif // _DEBUG
+
+#endif // __DEVENC_LOG_H__
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/common/DevEncUids.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Uids of components related to Device Encryption
+*
+*/
+
+
+#ifndef DEVENCUIUIDS_HRH
+#define DEVENCUIUIDS_HRH
+
+#define KDevEncUiUid              0x2000259A
+#define KDevEncStarterUid         0x2000259B
+#define KDevEncOmaDmPluginUid     0x200025B5
+#define KDevEncOmaDmPluginImplUid 0x200025BB
+#define KDevEncRfsPluginUid       0x200025B6
+#define KDevEncRfsPluginImplUid   0x200025BC
+#define KDevEncCommonUtilsUid     0x200025B7
+#define KDevEncNotifPluginUid     0x20002672
+#define KDevEncNotifPluginImplUid 0x20002673
+#define KDevEncPasswdDlgUid       0x20002674
+
+#define KDevEncNokiaVID           0x70000001
+
+#endif  // DEVENCUIUIDS_HRH
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Provides the information required for building all
+*               Device Encryption components.
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_EXPORTS
+
+// ROM file
+../rom/DevEncDiskUtils.iby CORE_MW_LAYER_IBY_EXPORT_PATH(DevEncDiskUtils.iby)
+
+#include "../DevEncCommonUtils/group/bld.inf"
+#include "../DevEncRfsPlugin/group/bld.inf"
+#include "../Pk5Recognizer/group/bld.inf"
+#include "../DevEncStarter/group/bld.inf"
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/layers.sysdef.xml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,14 @@
+<?xml version="1.0"?>
+<!DOCTYPE SystemDefinition SYSTEM "sysdef_1_4_0.dtd" [
+  <!ENTITY layer_real_source_path "sf/mw/securitysrv/devencdiskutils" >
+]>
+
+<SystemDefinition name="devencdiskutils" schema="1.4.0">
+  <systemModel>
+    <layer name="mw_layer">
+      <module name="devencdiskutils">
+        <unit unitID="ES.devencdiskutils" mrp="" bldFile="&layer_real_source_path;/group" name="devencdiskutils" />
+      </module>
+    </layer>
+  </systemModel>
+</SystemDefinition>
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/rom/DevEncDiskUtils.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Contains information about binary files and their locations.
+*
+*/
+
+
+#ifndef __DEVENC2_IBY__
+#define __DEVENC2_IBY__
+
+#ifdef FF_DEVICE_ENCRYPTION_FEATURE
+//---------------------------------------------------------------------------
+// Device Encryption Common Utilities.
+//---------------------------------------------------------------------------
+file=ABI_DIR\BUILD_DIR\devenccommonutils.dll SHARED_LIB_DIR\devenccommonutils.dll
+
+//---------------------------------------------------------------------------
+// Device Encryption RFS Plugin
+//---------------------------------------------------------------------------
+ECOM_PLUGIN(DevEncRfsPlugin.dll,DevEncRfsPlugin.rsc)
+
+//---------------------------------------------------------------------------
+// Device Encryption Recognizer.
+//---------------------------------------------------------------------------
+ECOM_PLUGIN(Pk5Recognizer.dll,2000FD89.rsc)
+data=\epoc32\data\z\Resource\Plugins\Pk5Recognizer.RSC 	"Resource\Plugins\Pk5Recognizer.RSC"
+
+//---------------------------------------------------------------------------
+// Device Encryption Starter
+//---------------------------------------------------------------------------
+S60_APP_EXE( DevEncStarter )
+//S60_APP_AIF_RSC( DevEncStarter )
+data=DATAZ_\private\10003a3f\apps\DevEncStarter_reg.rsc private\10003a3f\import\apps\DevEncStarter_reg.rsc
+data=DATAZ_\resource\apps\DevEncStarter.rsc             resource\apps\DevEncStarter.rsc
+
+#endif // FF_DEVICE_ENCRYPTION_FEATURE
+#endif // __DEVENC2_IBY__
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/sis/DevEnc.pkg	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,68 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+; DevEnc.pkg
+;
+;Language - standard language definitions
+&EN
+
+;Standard SIS file header (use UI application UID)
+#{"DevEncUi"},(0x2000259A),1,0,0
+
+;Localised Vendor name
+%{"Nokia"}
+
+;Unique Vendor name
+:"Nokia"
+
+;Supports Series 60 v 3.0
+[0x101F7961], 0, 0, 0, {"Series60ProductID"}
+
+;Files to install
+
+;----------------------------------------------------------------------------
+; Device Encryption UI
+;----------------------------------------------------------------------------
+"\epoc32\release\armv5\urel\DevEncUi.exe"                 -"!:\sys\bin\DevEncUi.exe"
+"\epoc32\data\z\resource\apps\DevEncUi.rsc"               -"!:\resource\apps\DevEncUi.rsc"
+"\epoc32\data\z\private\10003a3f\apps\DevEncUi_reg.rsc"   -"!:\private\10003a3f\import\apps\DevEncUi_reg.rsc"
+;"\epoc32\data\z\private\10202be9\200025A6.txt"            -"!:\private\10202be9\200025A6.txt"
+;"\epoc32\data\z\resource\apps\DevEncUi.mif"              -"!:\resource\apps\DevEncUi.mif"
+
+;----------------------------------------------------------------------------
+; Device Encryption Common Utilities
+;----------------------------------------------------------------------------
+"\epoc32\release\armv5\urel\devenccommonutils.dll"        -"!:\sys\bin\devenccommonutils.dll"
+
+;----------------------------------------------------------------------------
+; Device Encryption Device Management Adapter
+;----------------------------------------------------------------------------
+"\epoc32\release\armv5\urel\DevEncUiDmAdapter.dll"        -"!:\sys\bin\DevEncUiDmAdapter.dll"
+"\epoc32\data\z\resource\plugins\DevEncUiDmAdapter.rsc"   -"!:\resource\plugins\DevEncUiDmAdapter.rsc"
+
+;----------------------------------------------------------------------------
+; Device Encryption Notifier Plugin
+;----------------------------------------------------------------------------
+"\epoc32\release\armv5\urel\DevEncNotifPlugin.dll"        -"!:\sys\bin\DevEncNotifPlugin.dll"
+;"\epoc32\release\armv5\urel\DevEncNotifWrapper.dll"       -"!:\sys\bin\DevEncNotifWrapper.dll"
+"\epoc32\data\z\resource\plugins\DevEncNotifPlugin.rsc"  -"!:\resource\plugins\DevEncNotifPlugin.rsc"
+"\epoc32\data\z\resource\devencnotifplugin.rsc"           -"!:\resource\devencnotifplugin.rsc"
+
+;----------------------------------------------------------------------------
+; Device Encryption PK5 Recognizer Plugin
+;----------------------------------------------------------------------------
+"..\..\..\..\epoc32\release\armv5\urel\Pk5Recognizer.dll"        -"!:\sys\bin\Pk5Recognizer.dll"
+"..\..\..\..\epoc32\data\Z\resource\plugins\Pk5Recognizer.rsc"    -"!:\resource\plugins\Pk5Recognizer.rsc"
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devencdiskutils/sysdef_1_4_0.dtd	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,86 @@
+ <!ELEMENT SystemDefinition (systemModel?, build?)>
+ <!ATTLIST SystemDefinition
+  name CDATA #REQUIRED
+  schema CDATA #REQUIRED>
+ <!ELEMENT systemModel (layer+)>
+ <!ELEMENT layer (logicalset* | module*)*>
+ <!ATTLIST layer
+  name CDATA #REQUIRED
+  levels CDATA #IMPLIED
+  span CDATA #IMPLIED>
+ <!ELEMENT logicalset (logicalsubset* | module* | unit* | package* | prebuilt*)*>
+ <!ATTLIST logicalset name CDATA #REQUIRED>
+ <!ELEMENT logicalsubset (module* | unit* | package* | prebuilt*)*>
+ <!ATTLIST logicalsubset name CDATA #REQUIRED>
+ <!ELEMENT module (component* | unit* | package* | prebuilt*)*>
+ <!ATTLIST module
+  name CDATA #REQUIRED
+  level CDATA #IMPLIED>
+ <!ELEMENT component (unit* | package* | prebuilt*)*>
+ <!ATTLIST component name CDATA #REQUIRED>
+ <!ELEMENT unit EMPTY>
+ <!ATTLIST unit
+  unitID ID #REQUIRED
+  name CDATA #REQUIRED
+  mrp CDATA #REQUIRED
+  filter CDATA #IMPLIED
+  bldFile CDATA #REQUIRED
+  priority CDATA #IMPLIED
+  contract CDATA #IMPLIED>
+ <!ELEMENT package EMPTY>
+ <!ATTLIST package
+  name CDATA #REQUIRED
+  mrp CDATA #REQUIRED
+  filter CDATA #IMPLIED
+  contract CDATA #IMPLIED>
+ <!ELEMENT prebuilt EMPTY>
+ <!ATTLIST prebuilt
+  name CDATA #REQUIRED
+  version CDATA #REQUIRED
+  late (Y|N) #IMPLIED
+  filter CDATA #IMPLIED
+  contract CDATA #IMPLIED>
+ <!ELEMENT build (option* | target+ | targetList+ | unitList+ | configuration+)*>
+ <!ELEMENT unitList (unitRef+)>
+ <!ATTLIST unitList
+  name ID #REQUIRED
+  description CDATA #REQUIRED>
+ <!ELEMENT unitRef EMPTY>
+ <!ATTLIST unitRef unit IDREF #REQUIRED>
+ <!ELEMENT targetList EMPTY>
+ <!ATTLIST targetList
+  name ID #REQUIRED
+  description CDATA #REQUIRED
+  target IDREFS #REQUIRED>
+ <!ELEMENT target EMPTY>
+ <!ATTLIST target
+  name ID #REQUIRED
+  abldTarget CDATA #REQUIRED
+  description CDATA #REQUIRED>
+ <!ELEMENT option EMPTY>
+ <!ATTLIST option
+  name ID #REQUIRED
+  abldOption CDATA #REQUIRED
+  description CDATA #REQUIRED
+  enable (Y | N | y | n) #REQUIRED>
+ <!ELEMENT configuration (unitListRef+ | layerRef+ | task+)*>
+ <!ATTLIST configuration
+  name ID #REQUIRED
+  description CDATA #REQUIRED
+  filter CDATA #REQUIRED>
+ <!ELEMENT task ( unitListRef* , (buildLayer | specialInstructions))>
+ <!ELEMENT unitListRef EMPTY>
+ <!ATTLIST unitListRef unitList IDREF #REQUIRED>
+ <!ELEMENT layerRef EMPTY>
+ <!ATTLIST layerRef layerName CDATA #REQUIRED>
+ <!ELEMENT buildLayer EMPTY>
+ <!ATTLIST buildLayer
+  command CDATA #REQUIRED
+  targetList IDREFS #IMPLIED
+  unitParallel (Y | N | y | n) #REQUIRED
+  targetParallel (Y | N | y | n) #IMPLIED>
+ <!ELEMENT specialInstructions EMPTY>
+ <!ATTLIST specialInstructions
+  name CDATA #REQUIRED
+  cwd CDATA #REQUIRED
+  command CDATA #REQUIRED>  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/common/GBALogger.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,194 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of loggers
+*
+*/
+
+
+#ifdef _DEBUG
+
+#include    "GBALogger.h"
+#include    <flogger.h>
+
+const TInt KDebugBufferSize1024 = 1024;
+const TInt KDebugBufferSize240 = 240;
+const TInt KDebugBufferSize120 = 120;
+
+_LIT(KTimeFormat, "%F%D/%M/%Y %J:%T:%S");
+
+void debuglineL(const char *a, void *arg1, void* arg1b, void *arg2, void *arg3, const char *arg4) 
+    {
+    
+    HBufC8* logbuf = HBufC8::NewLC( KDebugBufferSize1024 );
+    TPtr8 ptrlogbuf = logbuf->Des();
+    
+    TPtrC8 p((const unsigned char *)a);
+    TPtrC8 temp_arg4((TUint8 *)arg4);
+    ptrlogbuf.Format(p, arg1,arg1b, arg2, arg3);
+    ptrlogbuf.Append(temp_arg4);
+    
+    if ( logbuf->Length() <= KDebugBufferSize120 )
+        {
+        RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                  EFileLoggingModeAppend, 
+                                  *logbuf );
+        }
+    else
+        {
+        RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                  EFileLoggingModeAppend, 
+                                  logbuf->Left( KDebugBufferSize120 ) );
+        //max length is 150, print another line 
+        if (logbuf->Mid(KDebugBufferSize120).Length()<= KDebugBufferSize120 )
+            { 
+            RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                      EFileLoggingModeAppend, 
+                                      logbuf->Mid(KDebugBufferSize120) );
+            }
+        else
+            {
+            RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                      EFileLoggingModeAppend, 
+                                      logbuf->Mid(KDebugBufferSize120, KDebugBufferSize120) );
+            RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                      EFileLoggingModeAppend, 
+                                      logbuf->Mid(KDebugBufferSize240) );                           
+            }  
+                                  
+          }     
+    CleanupStack::PopAndDestroy( logbuf );
+    }
+
+
+void debuglineL(const char *a, void *arg1, void* arg1b, void *arg2, void *arg3, const TDesC &arg4) 
+    {
+    
+    HBufC8* logbuf = HBufC8::NewLC( KDebugBufferSize1024 );
+    TPtr8 ptrlogbuf = logbuf->Des();
+    
+    TPtrC8 p((const unsigned char *)a);
+    ptrlogbuf.Format(p, arg1,arg1b, arg2, arg3);
+    ptrlogbuf.Append(arg4);
+    
+    if ( logbuf->Length() <= KDebugBufferSize120 )
+        {
+        RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                  EFileLoggingModeAppend, 
+                                  *logbuf );
+        }
+    else
+        {
+        RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                  EFileLoggingModeAppend, 
+                                  logbuf->Left( KDebugBufferSize120 ) );
+        //max length is 150, print another line 
+        if (logbuf->Mid(KDebugBufferSize120).Length()<= KDebugBufferSize120 )
+            { 
+            RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                      EFileLoggingModeAppend, 
+                                      logbuf->Mid(KDebugBufferSize120) );
+            }
+        else
+            {
+            RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                      EFileLoggingModeAppend, 
+                                      logbuf->Mid(KDebugBufferSize120, KDebugBufferSize120) );
+            RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                      EFileLoggingModeAppend, 
+                                      logbuf->Mid(KDebugBufferSize240) );                          	
+            }  
+                                  
+    	  }     
+    CleanupStack::PopAndDestroy( logbuf );
+    }
+
+void debuglineL(const char *a, void *arg1, void *arg1b, void *arg2, void *arg3, const TDesC8 &arg4) 
+    {
+    HBufC8* logbuf = HBufC8::NewLC( KDebugBufferSize1024 );
+    TPtr8 ptrlogbuf = logbuf->Des();
+    TPtrC8 p((const unsigned char *)a);
+    ptrlogbuf.Format(p, arg1,arg1b, arg2, arg3);
+    ptrlogbuf.Append(arg4);
+    if ( logbuf->Length() <= KDebugBufferSize120 )
+        {
+        RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                  EFileLoggingModeAppend, 
+                                  *logbuf );
+        }
+    else
+        {
+        RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                  EFileLoggingModeAppend, 
+                                  logbuf->Left(KDebugBufferSize120) );
+        //max length is 150, print another line 
+        
+        if (logbuf->Mid(KDebugBufferSize120).Length()<= KDebugBufferSize120 )
+            { 
+            RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                      EFileLoggingModeAppend, 
+                                      logbuf->Mid(KDebugBufferSize120) );
+            }
+        else
+            {
+            RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                      EFileLoggingModeAppend, 
+                                      logbuf->Mid(KDebugBufferSize120, KDebugBufferSize120) );
+            RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                                      EFileLoggingModeAppend, 
+                                      logbuf->Mid(KDebugBufferSize240) );                          	
+            }                               
+    	  }     
+    CleanupStack::PopAndDestroy( logbuf );     
+    }
+
+void debuglineL(const char *a, void *arg1, void *arg1b, void *arg2, void *arg3, const char *arg4, const TInt& aNum ) 
+    {
+    HBufC8* logbuf = HBufC8::NewLC( KDebugBufferSize120 );
+    TPtr8 ptrlogbuf = logbuf->Des();
+    TPtrC8 temp_arg4((TUint8 *)arg4);
+    ptrlogbuf.Format( temp_arg4, aNum );
+     
+    debuglineL(a, arg1, arg1b, arg2, arg3, *logbuf);
+    CleanupStack::PopAndDestroy( logbuf );
+    }
+
+void debuglineL(const char *a, void *arg1, void *arg1b, void *arg2, void *arg3, const TDesC &arg4, const TInt& aNum ) 
+    {
+    HBufC* logbuf = HBufC::NewLC(KDebugBufferSize120);
+    TPtr ptrlogbuf = logbuf->Des();
+    ptrlogbuf.Format( arg4, aNum );
+    
+    debuglineL(a, arg1, arg1b, arg2, arg3, *logbuf);
+    CleanupStack::PopAndDestroy( logbuf );
+    }    
+
+void DebugBinary( const TDesC8 &buf ) 
+    {
+    RFileLogger::HexDump( KGBALogDir, KGBALogFileName,
+        EFileLoggingModeAppend, 
+       NULL, NULL , buf.Ptr(), buf.Length() );
+    } 
+
+void debugTTimeL( TTime& aTime )
+    {
+    TBuf<KDebugBufferSize120> buf;
+    aTime.FormatL( buf, KTimeFormat);
+    RFileLogger::WriteFormat( KGBALogDir, KGBALogFileName,
+                             EFileLoggingModeAppend, 
+                             buf );
+    }
+
+#endif
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/data/gba_license.txt	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,8 @@
+End-User License Agreement: 
+By installing or using this software you are confirming acceptance of this software and agree to be bound by the terms and conditions of this Licence.
+
+Grant of License: 
+Nokia grants you a non-exclusive, non-transferable limited end-user right to use this software for the sole purpose of developing and testing applications or middleware software for the Symbian Platform.
+
+Disclaimer of Warranty: 
+THIS SOFTWARE IS PROVIDED TO YOU "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NOKIA, ITS MEMBERS, SUPPLIERS AND LICENSORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATE, OR PROFITS; OR INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaapi/BWINS/gba2u.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,10 @@
+EXPORTS
+	?Bootstrap@CGbaUtility@@QAEHUTGBABootstrapInputParams@@AAUTGBABootstrapOutputParams@@@Z @ 1 NONAME ; int CGbaUtility::Bootstrap(struct TGBABootstrapInputParams, struct TGBABootstrapOutputParams &)
+	?Bootstrap@CGbaUtility@@QAEXUTGBABootstrapInputParams@@AAUTGBABootstrapOutputParams@@AAVTRequestStatus@@@Z @ 2 NONAME ; void CGbaUtility::Bootstrap(struct TGBABootstrapInputParams, struct TGBABootstrapOutputParams &, class TRequestStatus &)
+	?CancelBootstrap@CGbaUtility@@QAEHXZ @ 3 NONAME ; int CGbaUtility::CancelBootstrap(void)
+	?NewL@CGbaUtility@@SAPAV1@AAVMGbaObserver@@@Z @ 4 NONAME ; class CGbaUtility * CGbaUtility::NewL(class MGbaObserver &)
+	?NewL@CGbaUtility@@SAPAV1@XZ @ 5 NONAME ; class CGbaUtility * CGbaUtility::NewL(void)
+	?NewLC@CGbaUtility@@SAPAV1@AAVMGbaObserver@@@Z @ 6 NONAME ; class CGbaUtility * CGbaUtility::NewLC(class MGbaObserver &)
+	?NewLC@CGbaUtility@@SAPAV1@XZ @ 7 NONAME ; class CGbaUtility * CGbaUtility::NewLC(void)
+	?SetBSFAddress@CGbaUtility@@QAEHABVTDesC8@@@Z @ 8 NONAME ; int CGbaUtility::SetBSFAddress(class TDesC8 const &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaapi/EABI/gba2u.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,14 @@
+EXPORTS
+	_ZN11CGbaUtility13SetBSFAddressERK6TDesC8 @ 1 NONAME
+	_ZN11CGbaUtility15CancelBootstrapEv @ 2 NONAME
+	_ZN11CGbaUtility4NewLER12MGbaObserver @ 3 NONAME
+	_ZN11CGbaUtility4NewLEv @ 4 NONAME
+	_ZN11CGbaUtility5NewLCER12MGbaObserver @ 5 NONAME
+	_ZN11CGbaUtility5NewLCEv @ 6 NONAME
+	_ZN11CGbaUtility9BootstrapE24TGBABootstrapInputParamsR25TGBABootstrapOutputParams @ 7 NONAME
+	_ZN11CGbaUtility9BootstrapE24TGBABootstrapInputParamsR25TGBABootstrapOutputParamsR14TRequestStatus @ 8 NONAME
+	_ZTI11CGbaUtility @ 9 NONAME ; #<TI>#
+	_ZTI24CGbaClientRequestHandler @ 10 NONAME ; #<TI>#
+	_ZTV11CGbaUtility @ 11 NONAME ; #<VT>#
+	_ZTV24CGbaClientRequestHandler @ 12 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaapi/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,23 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: Build info file for GBA API components 
+*
+*/
+
+PRJ_MMPFILES
+
+gba.mmp
+    
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaapi/group/gba.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file for project GBA
+*
+*/
+
+#include <platform_paths.hrh>
+TARGET            gba2.dll
+TARGETTYPE        DLL
+UID               0x1000008d 0x20029F08
+
+VENDORID    VID_DEFAULT
+CAPABILITY  CAP_CLIENT_DLL
+
+SMPSAFE
+
+USERINCLUDE ../inc 
+USERINCLUDE ../../inc
+
+
+MW_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH ../src
+
+SOURCE		  GbaUtility.cpp
+SOURCE        GbaClientRequestHandler.cpp
+SOURCE        GbaServerSession.cpp
+
+
+SOURCEPATH ../../common
+SOURCE GBALogger.cpp
+
+
+LIBRARY euser.lib 
+DEBUGLIBRARY flogger.lib
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaapi/inc/GbaClientrequesthandler.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,196 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface for handling gba bootstrapping
+*
+*/
+
+
+#ifndef GBACLIENTREQUESTHANDLER_H
+#define GBACLIENTREQUESTHANDLER_H
+
+#include <e32base.h>
+#include "gbautility.h"
+
+// CLASS DECLARATION
+class RGbaServerSession;
+
+/**
+ * Interface for handling gba bootstrapping
+ *
+ * @lib gba2.lib
+ * @since S60 3.2
+ *
+*/  
+class CGbaClientRequestHandler : public CActive
+    {
+    public:
+        
+        /**
+        * NewL factory function with an observer. It is used with callback function
+        * which should be implemented by the client. The interface is defined in class
+        * MGbaObserver
+        *
+        * @since S60 3.2
+        * @param aObserver Client implemented observer that will be
+        *                  called when the bootstrap is done
+        * @return
+        */
+        static CGbaClientRequestHandler* NewL(MGbaObserver& aObserver);
+
+        /**
+        * NewLC factory function with an observer. It is used with callback function
+        * which should be implemented by the client. The interface is defined in class
+        * MGbaObserver
+        *
+        * @since S60 3.2
+        * @param aObserver Client implemented observer that will be
+        *                  called when the bootstrap is done
+        * @return
+        */
+        static CGbaClientRequestHandler* NewLC(MGbaObserver& aObserver) ;
+        
+        
+        /**
+        * NewL factory function without observer. User should create its own state 
+        * machine.
+        *
+        * @since S60 3.2
+        * @param 
+        *
+        * @return
+        */
+        static CGbaClientRequestHandler* NewL();
+
+        /**
+        * NewLC factory function without observer. User should create its own state 
+        * machine.
+        *
+        * @since S60 3.2
+        * @param 
+        *
+        * @return
+        */
+        static CGbaClientRequestHandler* NewLC() ;
+
+        
+        /**
+        * destructor
+        */
+        virtual ~CGbaClientRequestHandler();
+
+    public:
+    
+        /**
+        * Bootstrap function. It is a asynchronous function with callback function.
+        * Performs a bootstrap and calls the callback function when bootstrap is done.
+        * This function should be used when the instance of CGbaClientRequestHandler is 
+        * created by factory function with observer.
+        * This function requires ReadDeviceData capability
+        *
+        * @since S60 3.2
+        * @param aInput/aOutput structures to hold input and output parameters, 
+        *        client must ensure that buffer is available when boostrapping is completed
+        *
+        * @return KErrNone factory function and bootstrap match
+        *         KErrGeneral factory fucntion and boostrap function doesnot match
+        */
+        TInt Bootstrap( const TGBABootstrapInputParams aInput, TGBABootstrapOutputParams& aOutput);
+                
+        /**
+        * Asynchronous bootstrap function. Performs asynchronous bootstrap.
+        * This function should be used when the instance of CGbaClientRequestHandler is 
+        * created by factory function without observer.
+        * This function requires ReadDeviceData capability
+        *
+        * @since S60 3.2
+        * @param aInput/aOutput structures to hold input and output parameters, 
+        *                 client must ensure that buffer is available when
+        *                 boostrapping is completed
+        *        aStatus 
+        *
+        * @return KErrNone factory function and bootstrap match
+        *         KErrGeneral factory fucntion and boostrap function doesnot match
+        */
+        //IMPORT_C TInt Bootstrap(TGBABootstrapCredentials& aCredentials, TRequestStatus& aStatus );
+        TInt Bootstrap( const TGBABootstrapInputParams aInput, TGBABootstrapOutputParams& aOutput, TRequestStatus& aStatus);
+                
+        /**
+        * Cancel Bootstrap function
+        *
+        * @since S60 3.2
+        * @param 
+        * @return 
+        */
+       TInt CancelBootstrap();
+          
+      /**
+        * Set the BSF address. 
+        * required WriteDeviceData capability. 
+        * The BSF address set by this function will overwrite
+        * the one calculated from IMPI.
+        *
+        * @since S60 3.2
+        * @param aNewVal contain the address
+        *            
+        * @return KErrPermissionDenied, not enought capability
+        */
+        TInt SetBSFAddress( const TDesC8& aAddress );
+      
+    protected: // from CActive
+        
+        void RunL();
+
+        void DoCancel();
+
+       TInt RunError(TInt aError);
+
+    private:
+
+        void ConstructL();
+
+        CGbaClientRequestHandler(MGbaObserver& aObserver);
+      
+        CGbaClientRequestHandler();
+    
+    private: 
+
+    enum TGbaState
+        {
+        EBootstrapNone = 0,
+        EBootstrapping,
+        EBootstrapCancelling
+        };
+        
+
+    private:
+  
+        // the Gba server session 
+        RGbaServerSession*  iSession;
+        
+        TGBABootstrapOutputParams* iGbaOutputParams;
+        
+        TGBABootstrapInputParams iGbaInputParams;
+        
+        //the observer of this class that is informed of Gba updated
+        MGbaObserver* iObserver;
+        
+        //bootstrap state
+        TGbaState iBootstrapState;
+  
+    };
+
+#endif //GBACLIENTREQUESTHANDLER_H  
+
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaapi/inc/GbaServerSession.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  class RGbaServerSession definition
+*
+*/
+
+
+#ifndef GBASERVERSESSION_H_
+#define GBASERVERSESSION_H_
+
+#include <e32base.h>
+#include <gbautility.h>
+
+class RGbaServerSession : public RSessionBase
+    {
+    public:
+        RGbaServerSession();
+        TInt Connect();
+        TVersion Version() const;
+        TInt CancelBootstrap() const;
+        TInt RequestOption(TUid optionUid, TDes8& aValue) const;
+        TInt WriteOption(TUid optionUid, const TDesC8& aValue) const;
+        TInt IsGBAUSupported( TBool& aIsGBAUSupported );
+        void RequestBootstrap(TGBABootstrapInputParams& aInput, TGBABootstrapOutputParams& aOutput, TRequestStatus& aStatus);
+    private:
+        TPtr8   iGbaInputBuffer;
+        TPtr8   iGbaOutputBuffer;
+    };
+
+#endif // GBASERVERSESSION_H
+
+
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaapi/src/GbaClientRequestHandler.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,293 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of CGbaClientRequestHandler
+*
+*/
+
+#include <e32svr.h>
+#include "GbaClientrequesthandler.h"
+#include "GbaServerSession.h"
+#include "GBALogger.h"
+#include "GbaCommon.h"
+
+
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::NewL()
+// -----------------------------------------------------------------------------
+//
+CGbaClientRequestHandler* CGbaClientRequestHandler::NewL(MGbaObserver& aObserver)
+    {
+    CGbaClientRequestHandler* self = CGbaClientRequestHandler::NewLC(aObserver);
+    CleanupStack::Pop( self );
+    return(self) ;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::NewLC()
+// -----------------------------------------------------------------------------
+//
+CGbaClientRequestHandler* CGbaClientRequestHandler::NewLC(MGbaObserver& aObserver)
+    {
+    CGbaClientRequestHandler* self = new (ELeave) CGbaClientRequestHandler(aObserver);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    return self; 
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::NewL()
+// -----------------------------------------------------------------------------
+//
+CGbaClientRequestHandler* CGbaClientRequestHandler::NewL()
+    {
+    CGbaClientRequestHandler* self = NewLC();
+    CleanupStack::Pop( self );
+    return(self) ;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::NewLC()
+// -----------------------------------------------------------------------------
+//
+CGbaClientRequestHandler* CGbaClientRequestHandler::NewLC()
+    {
+    CGbaClientRequestHandler* self = new (ELeave) CGbaClientRequestHandler();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    return self; 
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::ConstructL()
+// -----------------------------------------------------------------------------
+//
+void CGbaClientRequestHandler::ConstructL()
+    {
+    iSession = new(ELeave) RGbaServerSession();
+    User::LeaveIfError(iSession->Connect());
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::CGbaClientRequestHandler()
+// -----------------------------------------------------------------------------
+//
+CGbaClientRequestHandler::CGbaClientRequestHandler(MGbaObserver& aObserver)
+:   CActive(EPriorityStandard),
+    iObserver(&aObserver),
+    iBootstrapState(EBootstrapNone)
+    {
+    CActiveScheduler::Add(this);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::CGbaClientRequestHandler()
+// -----------------------------------------------------------------------------
+//
+CGbaClientRequestHandler::CGbaClientRequestHandler()
+:   CActive(EPriorityStandard),
+    iBootstrapState(EBootstrapNone)
+    {
+    iObserver = NULL;
+    CActiveScheduler::Add(this);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::~CGbaClientRequestHandler()
+// -----------------------------------------------------------------------------
+//
+CGbaClientRequestHandler::~CGbaClientRequestHandler()
+    {
+    if(IsActive())
+        {
+        Cancel();
+        }
+    if ( iSession )
+        {
+        iSession->Close();
+        }
+    delete iSession;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::RunL()
+// -----------------------------------------------------------------------------
+//
+void CGbaClientRequestHandler::RunL()
+    {
+    GBA_TRACE_DEBUG_NUM(("CGbaClientRequestHandler::RunL iStatus=%d"),iStatus.Int());
+    
+    // only when the observer is in use, the runl function should be called.
+    // if observer in runl is NULL, that means the factory function and bootstrap function
+    // that user used that doesnot match.
+    if( !iObserver )
+        {
+        return;
+        }
+	if( iStatus.Int() == KErrCancel && (iBootstrapState == EBootstrapCancelling))
+		  {
+		  iBootstrapState = EBootstrapNone;
+		  return;
+		  }
+    if( iStatus.Int() < KErrNone )
+        {
+        iObserver->BootstrapComplete( iStatus.Int() );
+        return;
+        }
+    
+    switch (iBootstrapState)
+        {
+        case EBootstrapping:
+            {
+            GBA_TRACE_DEBUG(("BTID"));
+            GBA_TRACE_DEBUG_BINARY(iGbaOutputParams->iBTID);
+            GBA_TRACE_DEBUG(("Ks_NAF"));
+            GBA_TRACE_DEBUG_BINARY(iGbaOutputParams->iKNAF);
+            iBootstrapState = EBootstrapNone;
+            iObserver->BootstrapComplete( KErrNone );
+            GBA_TRACE_DEBUG(("Ks_NAF 2"));
+            }
+            break ;
+
+        default:
+            {
+            GBA_TRACE_DEBUG(("Unexpected state"));
+            iBootstrapState = EBootstrapNone;
+            iObserver->BootstrapComplete( KErrUnknown );
+            }
+            break ;
+        }
+    }
+    
+    
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::RunError()
+// -----------------------------------------------------------------------------
+//
+TInt CGbaClientRequestHandler::RunError(TInt aError)
+    {
+    //when bootstrap fails, the error value from server
+    //will be passed back to client.
+    GBA_TRACE_DEBUG_NUM(("CGbaClientRequestHandler::RunError =%d"),aError );    
+    if (iBootstrapState == EBootstrapping)
+        {
+        GBA_TRACE_DEBUG(("Call HandleUnexpected") );
+        iObserver->BootstrapComplete(aError);
+        GBA_TRACE_DEBUG(("Call HandleUnexpected End") );
+        } 
+    return KErrNone;       
+    }
+   
+
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::DoCancel()
+// -----------------------------------------------------------------------------
+//
+void CGbaClientRequestHandler::DoCancel()
+    {
+    if ( iBootstrapState == EBootstrapping )
+        {      
+        CancelBootstrap();
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::Bootstrap()
+// -----------------------------------------------------------------------------
+//
+TInt CGbaClientRequestHandler::Bootstrap( const TGBABootstrapInputParams aInput, TGBABootstrapOutputParams& aOutput )
+    {
+    if ( !iObserver )
+        {
+        return KErrGeneral;
+        }
+    
+    if ( iBootstrapState == EBootstrapping )
+        {
+        return KErrInUse;
+        }
+    
+    iGbaInputParams.iNAFName.Copy(aInput.iNAFName);
+    iGbaInputParams.iFlags = aInput.iFlags;
+    iGbaInputParams.iAPID = aInput.iAPID;
+    iGbaInputParams.iProtocolIdentifier.Copy(aInput.iProtocolIdentifier);
+    iGbaInputParams.iUICCLabel.Copy(aInput.iUICCLabel);
+        
+    iGbaOutputParams = &aOutput;
+    
+    iBootstrapState = EBootstrapping; 
+     
+    if ( !IsActive() )
+        {
+        iSession->RequestBootstrap( iGbaInputParams, *iGbaOutputParams, iStatus);
+        SetActive();
+        }
+    return KErrNone;    
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::Bootstrap()
+// -----------------------------------------------------------------------------
+//
+TInt CGbaClientRequestHandler::Bootstrap( const TGBABootstrapInputParams aInput, TGBABootstrapOutputParams& aOutput, TRequestStatus& aStatus )
+    {
+    iGbaInputParams.iNAFName.Copy(aInput.iNAFName);
+    iGbaInputParams.iFlags = aInput.iFlags;
+    iGbaInputParams.iAPID = aInput.iAPID;
+    iGbaInputParams.iProtocolIdentifier.Copy(aInput.iProtocolIdentifier);
+    iGbaInputParams.iUICCLabel.Copy(aInput.iUICCLabel);
+    
+    iGbaOutputParams = &aOutput;   
+        
+    iSession->RequestBootstrap(iGbaInputParams, *iGbaOutputParams, aStatus);
+    return KErrNone;
+    }    
+
+
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::CancelBootstrap()
+// -----------------------------------------------------------------------------
+//
+TInt CGbaClientRequestHandler::CancelBootstrap()
+    {
+    GBA_TRACE_DEBUG(("CGbaClientRequestHandler::CancelBootstrap"));
+    if ( iObserver )
+        {
+        iBootstrapState = EBootstrapCancelling;
+        }
+    return iSession->CancelBootstrap() ;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaClientRequestHandler::SetBSFAddress()
+// -----------------------------------------------------------------------------
+//
+TInt CGbaClientRequestHandler::SetBSFAddress(const TDesC8& aNewVal)
+    {
+    GBA_TRACE_DEBUG(("CGbaClientRequestHandler::SetBSFAddress"));
+    TUid optionCode = KGbaBSFConfiguration;
+    return iSession->WriteOption(optionCode,aNewVal);
+    }
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaapi/src/GbaServerSession.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,189 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of RGbaServerSession
+*
+*/
+
+
+#include "GbaCommon.h"
+#include "GbaServerSession.h"
+#include "GBALogger.h"
+
+// Number of message slots to reserve for this client server session.
+// In this example we can have one asynchronous request outstanding 
+// and one synchronous request in progress.
+static const TUint KDefaultMessageSlots = 2;
+static const TUid KServerUid3 = {0x20029F0A};
+
+
+static TInt StartServer();
+static TInt CreateServerProcess();
+
+// -----------------------------------------------------------------------------
+// RGbaServerSession::RGbaServerSession()
+// -----------------------------------------------------------------------------
+//
+RGbaServerSession::RGbaServerSession()
+:   RSessionBase(), iGbaInputBuffer(NULL, 0, 0), iGbaOutputBuffer(NULL, 0, 0)
+    {
+    // No implementation required.
+    }
+
+// -----------------------------------------------------------------------------
+// RGbaServerSession::Connect()
+// -----------------------------------------------------------------------------
+//
+TInt RGbaServerSession::Connect()
+    {
+    TInt error = ::StartServer();
+    GBA_TRACE_DEBUG(("RGbaServerSession::Connect"));
+    if (KErrNone == error)
+        {
+        GBA_TRACE_DEBUG(("RGbaServerSession::Connect 1"));
+        error = CreateSession(KGbaServerName,
+                              Version(),
+                              KDefaultMessageSlots);
+        }
+    
+    return error;
+    }
+
+
+// -----------------------------------------------------------------------------
+// RGbaServerSession::Version()
+// -----------------------------------------------------------------------------
+//
+TVersion RGbaServerSession::Version() const
+    {
+    return(TVersion(KGbaServMajorVersionNumber,
+                    KGbaServMinorVersionNumber,
+                    KGbaServBuildVersionNumber));
+    }
+
+
+// -----------------------------------------------------------------------------
+// RGbaServerSession::RequestBootstrap()
+// -----------------------------------------------------------------------------
+//
+void RGbaServerSession::RequestBootstrap( TGBABootstrapInputParams& aInput, TGBABootstrapOutputParams& aOutput, TRequestStatus& aStatus) 
+    {
+    iGbaInputBuffer.Set(reinterpret_cast <TUint8*>(&aInput), sizeof(TGBABootstrapInputParams), sizeof(TGBABootstrapInputParams));
+    iGbaOutputBuffer.Set(reinterpret_cast <TUint8*>(&aOutput), sizeof(TGBABootstrapOutputParams), sizeof(TGBABootstrapOutputParams));
+    TIpcArgs messageParameters(&iGbaInputBuffer, &iGbaOutputBuffer);
+    SendReceive(EGbaServRequestBootstrap, messageParameters, aStatus);
+    }
+
+
+// -----------------------------------------------------------------------------
+// RGbaServerSession::CancelBootstrap()
+// -----------------------------------------------------------------------------
+//
+TInt RGbaServerSession::CancelBootstrap() const
+    {
+    return SendReceive(EGbaServCancelRequestBootstrap);
+    }
+
+// -----------------------------------------------------------------------------
+// RGbaServerSession::WriteOption()
+// -----------------------------------------------------------------------------
+//
+TInt RGbaServerSession::WriteOption(TUid optionUid, const TDesC8& aValue) const
+    {
+    TIpcArgs messageParameters(optionUid.iUid,&aValue); 
+    return SendReceive(EGbaServWriteOption,messageParameters);
+    }
+
+
+// -----------------------------------------------------------------------------
+// RGbaServerSession::IsGBAUSupported()
+// -----------------------------------------------------------------------------
+//
+TInt RGbaServerSession::IsGBAUSupported( TBool& aIsGBAUSupported )
+    {
+
+    TPckg<TBool> pckg( aIsGBAUSupported );
+    TIpcArgs messageParameters( &pckg ); 
+    TInt err = SendReceive(EGbaServIsGBAUSupported,messageParameters);
+    GBA_TRACE_DEBUG_NUM(("returned error is %d"), err );
+    return err;
+    }
+
+
+// -----------------------------------------------------------------------------
+// StartServer()
+// -----------------------------------------------------------------------------
+//
+static TInt StartServer()
+    {
+    TInt result;
+
+    TFindServer findGbaServer(KGbaServerName);
+    TFullName name;
+
+    result = findGbaServer.Next(name);
+    if ( result == KErrNone )
+        {
+        return KErrNone;
+       }
+
+    result = CreateServerProcess();
+    if ( result != KErrNone )
+        {
+        return  result;
+        }
+
+    return  KErrNone;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CreateServerProcess()
+// -----------------------------------------------------------------------------
+//
+static TInt CreateServerProcess()
+    {
+    TInt result;
+    const TUidType serverUid(KNullUid, KNullUid, KServerUid3);
+    RProcess server;
+    result = server.Create( KGbaServerName, _L(""), serverUid );
+    if ( result != KErrNone )
+        {
+        return  result;
+        }
+
+    TRequestStatus stat;
+    server.Rendezvous(stat);
+    if (stat!=KRequestPending)
+        {
+        // abort startup
+        server.Kill(0);
+        }
+    else
+        {
+        // logon OK - start the server
+        server.Resume();
+        }
+    // wait for start or death
+    User::WaitForRequest(stat);
+    // we can't use the 'exit reason' if the server panicked as this
+    // is the panic 'reason' and may be '0' which cannot be distinguished
+    // from KErrNone
+    TInt r=(server.ExitType()==EExitPanic) ? KErrGeneral : stat.Int();
+    server.Close();
+
+    return  r;
+    }
+    
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaapi/src/GbaUtility.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,155 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of CGbaUtility
+*
+*/
+
+#include <gbautility.h>
+#include "GbaClientrequesthandler.h"
+#include "GBALogger.h"
+
+// -----------------------------------------------------------------------------
+// CGbaUtility::NewL()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CGbaUtility* CGbaUtility::NewL(MGbaObserver& aObserver)
+    {
+    CGbaUtility* self = CGbaUtility::NewLC(aObserver);
+    CleanupStack::Pop( self );
+    return(self) ;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaUtility::NewLC()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CGbaUtility* CGbaUtility::NewLC(MGbaObserver& aObserver)
+    {
+    CGbaUtility* self = new (ELeave) CGbaUtility();
+    CleanupStack::PushL(self);
+    self->ConstructL( aObserver );
+    return self; 
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaUtility::NewL()
+// factory function without observer
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CGbaUtility* CGbaUtility::NewL()
+    {
+    CGbaUtility* self = CGbaUtility::NewLC();
+    CleanupStack::Pop( self );
+    return(self) ;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaUtility::NewLC()
+// factory function without observer
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CGbaUtility* CGbaUtility::NewLC()
+    {
+    CGbaUtility* self = new (ELeave) CGbaUtility();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CGbaUtility::ConstructL()
+// -----------------------------------------------------------------------------
+//
+void CGbaUtility::ConstructL( MGbaObserver& aObserver )
+    {
+    iGbaRequestHandler = CGbaClientRequestHandler::NewL( aObserver );
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CGbaUtility::ConstructL()
+// -----------------------------------------------------------------------------
+//
+void CGbaUtility::ConstructL()
+    {
+    iGbaRequestHandler = CGbaClientRequestHandler::NewL();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaUtility::CGbaUtility()
+// -----------------------------------------------------------------------------
+//
+CGbaUtility::CGbaUtility()
+    {
+    
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaUtility::~CGbaUtility()
+// -----------------------------------------------------------------------------
+//
+CGbaUtility::~CGbaUtility()
+    {
+    delete iGbaRequestHandler;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaUtility::Bootstrap()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CGbaUtility::Bootstrap( const TGBABootstrapInputParams aInput, TGBABootstrapOutputParams& aOutput )
+    {
+    return iGbaRequestHandler->Bootstrap( aInput, aOutput );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaUtility::Bootstrap()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CGbaUtility::Bootstrap( const TGBABootstrapInputParams aInput, TGBABootstrapOutputParams& aOutput, TRequestStatus& aStatus )
+    {
+    iGbaRequestHandler->Bootstrap( aInput, aOutput, aStatus );    
+    }    
+
+
+// -----------------------------------------------------------------------------
+// CGbaUtility::CancelBootstrap()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CGbaUtility::CancelBootstrap()
+    {
+    return iGbaRequestHandler->CancelBootstrap();
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CGbaUtility::SetBSFAddress()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CGbaUtility::SetBSFAddress( const TDesC8& aAddress )
+    {
+    return iGbaRequestHandler->SetBSFAddress(aAddress);
+    }
+
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbafilter/Data/20029F09.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2000 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource file for GBA http filter
+*
+*/
+
+#include "ecom/registryinfov2.rh"
+
+RESOURCE REGISTRY_INFO theInfo
+	{
+	// resource format version for ROM-only filter
+	resource_format_version = RESOURCE_FORMAT_VERSION_2;
+
+	dll_uid = 0x20029F09;
+	interfaces=
+		{
+		INTERFACE_INFO
+			{
+			interface_uid = 0x101F446D;
+			implementations = 
+				{
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x20029F10;
+					version_no = 1;
+                    display_name = "gbafilter2";
+					
+					// For HTTP-TF the default_data must be defined as follows
+					// 1.Protocol identifier
+					//    HTTP-TF uses first part (separated with /-character) to identify
+					//    what protocol this filter will support. It could also be WSP but 
+					//    then HTTP-TF does not load it with any sessions that based on HTTP.
+					// 2.Separator
+					//    /-separator must be always there
+					// 3.Filter category
+					//    + = mandatory (HTTP-TF will panic if installation of this filter fails)
+					//    - = Explicit (Does not install filter)
+					//      = Implicit (Installs filter but traps possible errors and continues)
+
+					default_data = "HTTP/AUTHENTICATION||WSP/AUTHENTICATION";
+					opaque_data = "";
+					}
+				};
+			}
+		};
+	}
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbafilter/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build info file for GBA Filter components
+*
+*/
+
+
+
+PRJ_PLATFORMS
+
+DEFAULT
+
+PRJ_EXPORTS
+
+
+PRJ_MMPFILES
+
+httpfiltergba.mmp
+                            
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbafilter/group/httpfiltergba.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file for project HTTPFilterGBA
+*
+*/
+
+#include <platform_paths.hrh>
+
+TARGET httpfiltergba2.dll
+TARGETTYPE PLUGIN
+
+CAPABILITY CAP_ECOM_PLUGIN
+
+// ECom Recogniction UID followed by Unique 3rd UID
+UID 0x10009D8D 0x20029F09
+VENDORID VID_DEFAULT 
+
+SMPSAFE
+
+SOURCEPATH ../src
+SOURCE HTTPFilterGBAMain.cpp HTTPFilterGBA.cpp 
+
+SOURCEPATH ../../common
+SOURCE GBALogger.cpp
+USERINCLUDE ../inc
+USERINCLUDE ../../inc
+
+
+SYSTEMINCLUDE /epoc32/include/ecom 
+APP_LAYER_SYSTEMINCLUDE
+
+
+SOURCEPATH ../Data
+START RESOURCE 20029F09.rss
+TARGET httpfiltergba2.rsc
+END
+
+LIBRARY 		euser.lib 
+LIBRARY 		ecom.lib 
+LIBRARY 		http.lib 
+LIBRARY 		bafl.lib 
+LIBRARY 		hash.lib 
+LIBRARY 		inetprotutil.lib 
+LIBRARY 		gba2.lib
+LIBRARY 		imut.lib //for base64 en/decoding
+DEBUGLIBRARY 	flogger.lib charconv.lib 
+//EOF
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbafilter/inc/HTTPFilterGBA.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,243 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  GBA Filter definitions
+*
+*/
+
+
+#ifndef __HTTPFILTERGBA_H_
+#define __HTTPFILTERGBA_H_
+
+#include <http/mhttpfilter.h>
+#include <http/rhttpsession.h>
+#include <http/cecomfilter.h>
+#include <http/framework/httplogger.h>
+
+#include <gbautility.h>
+
+class RHTTPResponse;
+class RHTTPTransaction;
+class CMD5;
+
+const TInt KMaxTypeLength = 255;
+const TInt KBsfAddressSize = 128;
+
+
+class CHTTPFilterGBA : public CEComFilter, public MHTTPFilter, public MGbaObserver
+{
+    enum
+        {
+        EAlgUnknown,
+        EAlgMd5,
+        EAlgMd5Sess
+        };
+
+    enum
+        {
+        EQopNone,
+        EQopAuth = 1,
+        EQopAuthInt = 2
+        };
+public:
+
+	static CEComFilter* InstallFilterL(TAny* aSession);
+ 
+	virtual ~CHTTPFilterGBA();
+
+public:	// Methods from MHTTPFilterBase
+
+	/// @see MHTTPFilterBase::MHFRunL
+	virtual void MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent);
+
+	/// @see MHTTPFilterBase::MHFSessionRunL
+	virtual void MHFSessionRunL(const THTTPSessionEvent& aEvent);
+
+	/// @see MHTTPFilterBase::MHFRunError
+	virtual TInt MHFRunError(TInt aError, RHTTPTransaction aTransaction, const THTTPEvent& aEvent);
+
+	/// @see MHTTPFilterBase::MHFSessionRunError
+	virtual TInt MHFSessionRunError(TInt aError, const THTTPSessionEvent& aEvent);
+
+public:	// Methods from MHTTPFilter
+
+	/// @see MHTTPFilter::MHFUnload
+	virtual void MHFUnload(RHTTPSession aSession, THTTPFilterHandle aHandle);
+
+	/// @see MHTTPFilter::MHFLoad
+	virtual void MHFLoad(RHTTPSession aSession, THTTPFilterHandle aHandle);
+	
+	inline void SetProtocolIdentifierL( const TDesC8& aIdentifier){
+	    iProtocolIdentifier = aIdentifier;
+	}
+	
+	inline void SetGBAFlags(const TUint8 aFlags){
+	    iFlags = aFlags;
+	}
+	
+	inline void SetGBALabel(const TDesC8& aLabel){
+	    iUICCLabel =  aLabel ;
+	}
+
+    //Only for testing purpose
+	//To force BSF address for use
+	inline void SetBSFAddress(const TDesC8& aBsfAddress){
+	        iBsfAddress = aBsfAddress;
+	};
+
+ private:
+	
+	CHTTPFilterGBA();
+
+	///ContructL also Installs the filter.
+	void ConstructL( RHTTPSession aSession );
+	
+#if defined (_DEBUG)
+	void DumpResponseHeadersL( RHTTPResponse& aResponse );
+#endif
+
+	void CheckHeadersL( RHTTPTransaction& aTrans );
+	
+	void ProcessBodyPartL( RHTTPTransaction& aTrans );
+	
+	void Cleanup( const RHTTPTransaction& aTrans );
+	
+	void CleanupAll();
+	
+    TInt FindHeaderPartToUseL(RHTTPTransaction aTransaction) const;
+    
+	TBool FindAuth(const TDesC8& aQop) const;
+	
+	void DoSubmitL( RHTTPTransaction aTransaction );
+	
+	void EncodeDigestAuthL( TInt aCred, RHTTPTransaction aTransaction );
+	
+    void DAddCredentialsToListL( 	RString aUsernameStr,
+    								RString aPasswordStr,
+    								RString aRealmStr,
+    								RStringF aUriStr,
+    								RString aOpaque,
+    								RString aNonce,
+    								TInt aQop,
+    								TInt aAuthAlg );
+   /**
+    * Calculate H(A1). See section 3.2.2.2
+    */
+    void HAOneL( int aAlgorithm,
+               const RString& aUsername,
+               const RString& aPW,
+		       const RString& aRealm,
+               const RString& aNonceValue,
+               TDesC8& aCNonce,
+               TDes8& aResult);
+
+    
+    /**
+    * Calculate H(A2). See section 3.2.2.3
+    */
+    void HATwoL(const RStringF& aMethod, const RString& aRequestUri, TDes8& aResult);
+
+    /**
+    * Calculate a hash and in the form of a 32 character hex result.
+    */
+    void Hash(const TDesC8& aMessage, TDes8& aHash);
+
+    /**
+    * Generate a cnonce value
+    */	
+    void GenerateCNonce( TDes8& aNonce );
+
+    /**
+    * Returns the requested uri 
+    * that can be used in uri field or request header
+    *
+    * @param aTransaction current transaction
+    * @return requested URI
+    */
+    RString RequestUriL( RHTTPTransaction& aTransaction);
+                   
+    /**
+    * Check and return QoP from the response header.
+    * @param aHeader authentication header
+    * @param aWwwAuthHeader authentication header name
+    * @param aHeaderPart which authentication header field in the response header
+    * @return one of KQopXXX enum. KQopAuth is prefered.
+    */    
+    TInt CheckQop( RHTTPHeaders& headers,
+                   RStringF& aWwwAuthHeader,
+                   TInt aHeaderPart );
+ 
+ 	void DGetCredentialsFromPropertiesL( RHTTPTransaction& aTransaction );
+ 	
+ 	TInt DFindCredentialsForURI( const TUriC8& aURI );
+ 	
+ 	void DRemoveCredentialsFromList( TInt aCredId );
+ 	
+ 	TInt DFindCredentials( const RString& aRealm, const TUriC8& aURI );
+ 	
+ 	//Inherited from MGbaObserver
+    void BootstrapComplete(TInt error);
+ 	
+     class TDCredentials
+        {
+        public:
+            RStringToken iUser;  //username
+            RStringToken iPassword; //password
+            RStringTokenF iURI;  //uri
+            RStringToken iRealm; //Realm used - there may be multiple for each host
+            RStringToken iOpaque;
+            RStringToken iNonce;
+            TInt iQop;
+            TInt iAlgorithm;
+            TInt iNc;   // nonce-count
+        };
+
+	/// A count to make sure we delete at the right time.
+	TInt        iLoadCount;
+	RStringPool iStringPool;
+    RStringF    iOpaqueStr;
+    RStringF    iNonceStr;
+	RStringF    iQopStr;
+	RStringF 	iStaleStr;
+	RStringF    iAuthInfo;
+	RStringF 	iUsernameStr;
+	RStringF 	iPasswordStr;
+    RStringF    iQopAuthStr;
+    RStringF    iMd5Str;
+    RStringF    iMd5SessStr;
+    RStringF    iRealmStr;
+	RStringF 	iUserAgent;
+    TInt64      iSeed;
+    CMD5*       iMD5Calculator;
+	TInt		iOffset;
+	TUint8      iFlags;
+	TBuf8<5>    iProtocolIdentifier;
+	TInt        iBootstrapCount;
+	TBool       iBootstrapPending;
+	TBool       iHaveGbaBootstrapCredentials;
+	TBool       iGBAU;
+	TBuf8<KMaxTypeLength>     iUICCLabel;
+	CActiveSchedulerWait      iBootstrapWait;
+	CGbaUtility*              iGbaUtility;
+    TGBABootstrapInputParams  iGbaInputParams;
+    TGBABootstrapOutputParams iGbaOutputParams;
+    //Only for testing  purpose
+    TBuf8<KBsfAddressSize>    iBsfAddress;
+    // Internal list of valid credentials
+    RArray<TDCredentials>     iDCredentials;
+
+};
+
+#endif //__HTTPFILTERGBA_H_
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbafilter/src/HTTPFilterGBA.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1505 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of CHTTPFilterGBA
+*
+*/
+
+#include <http/rhttptransaction.h>
+#include <http/rhttpheaders.h>
+#include <http/rhttpresponse.h>
+#include <httperr.h>
+#include <httpstringconstants.h>
+#include <imcvcodc.h>      //for base64 en/decoding
+#include "HTTPFilterGBA.h"
+#include "GbaCommon.h"
+#include <bautils.h>
+#include <e32math.h>
+#include <hash.h>
+#include <e32const.h>
+#include "GBALogger.h"
+
+//Constants
+const TInt KStatusTextLength512 = 512;
+const TInt KB64KeySize = 64;
+const TInt KIntegerConstant8 = 8;
+const TInt KIntegerConstant32 = 32;
+const TInt KIntegerConstant33 = 33;
+// Length of a digest hash when represented in hex
+const TInt KHashLength = 32;
+// Length of a digest hash before converting to hex.
+const TInt KRawHashLength = 16;
+// Length of nonce-count
+const TInt KNonceCountLength = 8;
+
+_LIT8( KUserAgentProductToken,"3gpp-gba");
+_LIT8(K3GPPRealmString,"3GPP-Bootstrapping@");
+_LIT8( KMd5AlgorithmStr, "MD5" );
+_LIT8( KMd5SessAlgorithmStr, "MD5-sess" );
+_LIT8( KQopAuthStr, "auth" );
+_LIT8( KQopAuthIntStr, "auth-int" );
+_LIT8( KAuthenticationInfoStr, "Authentication-Info" );
+_LIT8( KColon, ":" );
+_LIT8( KDefaultProtocolAlg, "\x01\x00\x00\x00\x02");
+_LIT(KGBAHttpFilter, "HTTP FILTER GBA");
+
+// format for output of data/time values
+#if defined (_DEBUG) && defined (_LOGGING)
+_LIT(KDateFormat,"%D%M%Y%/0%1%/1%2%/2%3%/3 %:0%H%:1%T%:2%S.%C%:3");
+#endif
+
+void PanicGBAHttpFilters(TInt aErr = 0)
+{
+    User::Panic(KGBAHttpFilter, aErr);
+}
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CHTTPFilterGBA::CHTTPFilterGBA
+// Constructor
+// -----------------------------------------------------------------------------
+//
+CHTTPFilterGBA::CHTTPFilterGBA()
+		: iBootstrapCount(0),iHaveGbaBootstrapCredentials(EFalse)
+{
+
+}
+
+// -----------------------------------------------------------------------------
+// CHTTPFilterGBA::InstallFilterL
+// Initialize the filter and register it to sesssion's filter collection
+// -----------------------------------------------------------------------------
+//
+CEComFilter* CHTTPFilterGBA::InstallFilterL(TAny* aParams)
+{
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::CHTTPFilterGBA++"));
+	__ASSERT_DEBUG(aParams != NULL, PanicGBAHttpFilters());
+	RHTTPSession* session = REINTERPRET_CAST(RHTTPSession*, aParams);
+	CHTTPFilterGBA* filter = new (ELeave) CHTTPFilterGBA();
+	CleanupStack::PushL(filter);
+	filter->ConstructL(*session);
+	CleanupStack::Pop(filter);
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::CHTTPFilterGBA--"));
+	return filter;
+}
+	
+// -----------------------------------------------------------------------------
+// CHTTPFilterGBA::ConstructL
+// Memory and resource allocation, leaves
+// -----------------------------------------------------------------------------
+//
+void CHTTPFilterGBA::ConstructL(RHTTPSession aSession)
+{
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::ConstructL++"));
+	
+	//......................................................................................
+	
+	//Unload GBA http filter from existing GBA and MBMS server's
+	
+	
+	//This GBA http filter cannot be loaded from old GBA server (GBAServer) and it's 
+	//Required to reject a filter loading request from a GBA server  on existing platforms
+	//where GBA component is already built-in and the GBA server UID3 is 0x2000F868
+	//Note- some s60 3.2 and 5.0 platforms already has GBA component as built in.
+	//Reason: Ub interface should not have the User-Agent string "3gpp-gba"
+    if( RProcess().SecureId() == TSecureId (0x2000F868))
+    {
+    	GBA_TRACE_DEBUG(("Not accessible from GBA Server++"));
+        return;
+    }
+    
+    //This GBA http filter cannot be loaded from MBMS server (MBMSServer) and it's 
+    //Required to reject a filter loading request from a MBMS server
+    //where MBMS component is already build-in[N96 platforms only] and the mbms server UID3 is 0x2001957B
+    //Reason: Ub interface should not have the User-Agent string "3gpp-gba"
+    if( RProcess().SecureId() == TSecureId (0x2001957B))
+    {
+        GBA_TRACE_DEBUG(("Not accessible from MBMS Server++"));
+        return;
+    } 
+    //......................................................................................
+       
+   	iProtocolIdentifier.Copy(KDefaultProtocolAlg);
+
+	iUICCLabel = KUSIM;
+	iStringPool = aSession.StringPool();
+
+	// register the filter
+	RStringF filterName = iStringPool.OpenFStringL( KHTTPFilterGBAName );
+	CleanupClosePushL( filterName );
+
+    iOpaqueStr = iStringPool.StringF( HTTP::EOpaque, RHTTPSession::GetTable() );
+    iNonceStr = iStringPool.StringF( HTTP::ENonce, RHTTPSession::GetTable() );
+    iQopStr = iStringPool.StringF( HTTP::EQop, RHTTPSession::GetTable() );
+    iStaleStr = iStringPool.StringF( HTTP::EStale, RHTTPSession::GetTable() );
+    
+    iMd5Str = iStringPool.OpenFStringL( KMd5AlgorithmStr );
+    iMd5SessStr = iStringPool.OpenFStringL( KMd5SessAlgorithmStr );
+    iQopAuthStr = iStringPool.OpenFStringL( KQopAuthStr );
+    iAuthInfo = iStringPool.OpenFStringL( KAuthenticationInfoStr );
+    
+    iRealmStr = iStringPool.StringF( HTTP::ERealm, RHTTPSession::GetTable() );
+    iUsernameStr = iStringPool.StringF( HTTP::EUsername, RHTTPSession::GetTable() );
+    iPasswordStr = iStringPool.StringF( HTTP::EPassword, RHTTPSession::GetTable() );
+	iUserAgent = iStringPool.OpenFStringL( KUserAgentProductToken );
+    
+    //Regsiter for THTTPEvent::ESubmit http event
+    //The User-Agent string gets appended with "3gpp-gba" string, 
+    //indicating client is gba capable to the application server.
+    aSession.FilterCollection().AddFilterL( *this,
+                                            THTTPEvent::ESubmit,
+                                            RStringF(),
+                                            KAnyStatusCode,
+                                            EStatusCodeHandler,
+                                            filterName);
+   
+    //Regsiter for THTTPEvent::EGotResponseHeaders http event with "Authentication-Info" header 
+    //and HTTPStatus::EOk http status code,just to know if the credentials established are valid.
+    aSession.FilterCollection().AddFilterL( *this,
+                                            THTTPEvent::EGotResponseHeaders,
+                                            iAuthInfo,
+                                            HTTPStatus::EOk,
+                                            EStatusCodeHandler,
+                                            filterName );
+
+    //Regsiter for THTTPEvent::EGotResponseHeaders http event with "WWW-Authenticate" header 
+    //and HTTPStatus::EUnauthorized http status code
+    //The priority for this is set to MHTTPFilter::EStatusCodeHandler - 1,
+    //so the gba filter intercepts the transaction before the default 
+    //http digest authentication filter(which has priority MHTTPFilter::EStatusCodeHandler).
+
+    aSession.FilterCollection().AddFilterL( *this, 
+											THTTPEvent::EGotResponseHeaders,	// Any transaction event
+											iStringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable()),
+											HTTPStatus::EUnauthorized,
+											MHTTPFilter::EStatusCodeHandler - 1,	  // Priority of filter
+											filterName );						      // Name of filter
+
+	CleanupStack::PopAndDestroy( &filterName );
+	
+	//Check if the "user agent" header field in http session headers has "3gpp-gba" string in it.
+	//If it does n't have "3gpp-gba" string,append  it to the existing value.
+    TBool found = EFalse;
+    TPtrC8 rawFieldData;
+    RHTTPHeaders sessionHeaders = aSession.RequestSessionHeadersL();
+    RStringF sessionHeaderfieldname = aSession.StringPool().StringF( HTTP::EUserAgent, RHTTPSession::GetTable());
+    sessionHeaders.GetRawField(sessionHeaderfieldname, rawFieldData);
+    found = rawFieldData.Find(iUserAgent.DesC()) != KErrNotFound;
+
+    if(!found)
+        sessionHeaders.SetFieldL( sessionHeaderfieldname, iUserAgent );	    
+
+    iMD5Calculator = CMD5::NewL();
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::ConstructL--"));
+}
+
+
+//------------------------------------------------------------------------
+// CHTTPFilterGBA::~CHTTPFilterGBA
+// Destructor
+//------------------------------------------------------------------------
+//
+CHTTPFilterGBA::~CHTTPFilterGBA()
+{
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::~CHTTPFilterGBA++"));
+	CleanupAll();															
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::~CHTTPFilterGBA--"));
+}
+
+//------------------------------------------------------------------------
+// CHTTPFilterGBA::MHFLoad
+//------------------------------------------------------------------------
+//
+void CHTTPFilterGBA::MHFLoad(RHTTPSession, THTTPFilterHandle)
+{
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::MHFLoad"));
+	++iLoadCount;
+}
+
+//------------------------------------------------------------------------
+// CHTTPFilterGBA::MHFUnload
+//------------------------------------------------------------------------
+//
+void CHTTPFilterGBA::MHFUnload(RHTTPSession , THTTPFilterHandle)
+{
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::MHFUnload++"));
+	
+    __ASSERT_DEBUG( iLoadCount >= 0, PanicGBAHttpFilters() );
+    
+	if (--iLoadCount)
+	{
+		return;
+	}
+	delete this;
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::MHFUnload--"));
+}
+
+//------------------------------------------------------------------------
+// CHTTPFilterGBA::MHFRunL
+// See MHTTPFilterBase::MHFRunL 
+//------------------------------------------------------------------------
+//
+void CHTTPFilterGBA::MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent)
+{
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::MHFRunL++"));
+	
+	GBA_TRACE_DEBUG_NUM(("MHFRunL Event %d"), aEvent.iStatus );
+	
+	if (aEvent.iUID != KHTTPUid) 
+		return;
+
+	switch(aEvent.iStatus)
+	{
+		case THTTPEvent::ESubmit:
+		{
+			DoSubmitL(aTransaction);
+		}
+		break;
+
+		case THTTPEvent::EGotResponseHeaders:
+		{
+			// Get HTTP status code from header (e.g. 200)
+			RHTTPResponse resp = aTransaction.Response();
+			TInt status = resp.StatusCode();
+			GBA_TRACE_DEBUG_NUM(("MHFRunL staus code %d"), status );
+			// Get status text (e.g. "OK")
+			TBuf<KStatusTextLength512> statusText;
+			statusText.Copy(resp.StatusText().DesC());
+			
+			GBA_TRACE_DEBUG(("status text:"));
+			GBA_TRACE_DEBUG(statusText);
+			CheckHeadersL( aTransaction );
+		}
+		break;
+		case THTTPEvent::EGotResponseBodyData:
+		{
+            GBA_TRACE_DEBUG(("Event: EGotResponseBodyData"));
+		}
+		break;
+		case THTTPEvent::EResponseComplete:
+		{
+            GBA_TRACE_DEBUG(("Event: EResponseComplete"));
+			Cleanup( aTransaction );
+		}
+		break;
+		case THTTPEvent::EFailed:
+		{
+            GBA_TRACE_DEBUG(("Event: EFailed"));			
+			Cleanup( aTransaction );		
+		}
+		default: 
+		{
+            GBA_TRACE_DEBUG_NUM(("Unknow Event: ID - %d" ), aEvent.iStatus );
+		}
+		break;
+	}
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::MHFRunL--"));
+}
+
+
+//------------------------------------------------------------------------
+// CHTTPFilterGBA::MHFRunError
+// See MHTTPFilterBase::MHFRunError
+//------------------------------------------------------------------------
+//
+TInt CHTTPFilterGBA::MHFRunError(TInt /*aError*/, RHTTPTransaction aTransaction, const THTTPEvent& )
+{
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::MHFRunError++"));
+	TInt error = 0;
+	// map aError to global error message
+	// pass the errorcode forward
+	THTTPEvent httpEvent(error);
+	TRAP_IGNORE(aTransaction.SendEventL(httpEvent, THTTPEvent::EIncoming, THTTPFilterHandle::ECurrentFilter ));
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::MHFRunError--"));
+	return KErrNone;
+}
+
+//------------------------------------------------------------------------
+// CHTTPFilterGBA::MHFSessionRunL
+// See MHTTPFilterBase::MHFSessionRunL
+//------------------------------------------------------------------------
+//
+void CHTTPFilterGBA::MHFSessionRunL(const THTTPSessionEvent& )
+{
+	// do nothing
+}
+
+//------------------------------------------------------------------------
+// CHTTPFilterGBA::MHFSessionRunL
+// See MHTTPFilterBase::MHFSessionRunL
+//------------------------------------------------------------------------
+//
+TInt CHTTPFilterGBA::MHFSessionRunError(TInt aError, const THTTPSessionEvent& )
+{
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::MHFSessionRunError"));
+	// session problem, need to close GBA engine
+	return aError;
+}
+
+//------------------------------------------------------------------------
+// CHTTPFilterGBA::DumpResponseHeadersL
+// Dump the response headers to LOG file
+//------------------------------------------------------------------------
+//
+#if defined (_DEBUG)
+void CHTTPFilterGBA::DumpResponseHeadersL( RHTTPResponse& aResponse )
+{
+	GBA_TRACE_DEBUG("Dump the header...");
+
+	RHTTPHeaders headers = aResponse.GetHeaderCollection();
+	THTTPHdrFieldIter it = headers.Fields();
+	
+	while( it.AtEnd() == EFalse )
+	{
+        RStringTokenF fieldName = it();
+        RStringF fieldNameStr = iStringPool.StringF (fieldName );
+        THTTPHdrVal fieldVal;
+        TInt fieldParts = 0; // For the case if next the call fails.
+        TRAP_IGNORE( fieldParts =  headers.FieldPartsL( fieldNameStr ) );
+		// dump the first part of  a  header field
+		for ( TInt ii = 0; ii < fieldParts; ii++ )
+		{	
+			if( headers.GetField( fieldNameStr, ii, fieldVal ) == KErrNone )
+			{
+				const TDesC8& fieldNameDesC = fieldNameStr.DesC();
+				GBA_TRACE_DEBUG(" : ");
+                GBA_TRACE_DEBUG(fieldNameDesC);
+
+				switch( fieldVal.Type() )
+				{
+				case THTTPHdrVal::KTIntVal:
+					{
+						GBA_TRACE_DEBUG_NUM(("%d"), fieldVal.Int() );
+					}
+					break;
+				case THTTPHdrVal::KStrFVal:
+					{
+						RStringF fieldValStr = iStringPool.StringF( fieldVal.StrF() );
+						const TDesC8& fieldValDesC = fieldValStr.DesC();
+                        GBA_TRACE_DEBUG(fieldValDesC);
+					}
+					break;
+				case THTTPHdrVal::KStrVal:
+					{
+						RString fieldValStr = iStringPool.String( fieldVal.Str() );
+						const TDesC8& fieldValDesC = fieldValStr.DesC();
+						GBA_TRACE_DEBUG(fieldValDesC);
+					}
+					break;
+				case THTTPHdrVal::KDateVal:
+					{
+						TDateTime date = fieldVal.DateTime();
+						TBuf<KStatusTextLength512> dateTimeString;
+						TTime t( date );
+						t.FormatL( dateTimeString, KDateFormat );
+						TBuf8<KStatusTextLength512> dtStr;
+						dtStr.Copy( dateTimeString.Left( 128 ) );
+						GBA_TRACE_DEBUG(dtStr);
+					}
+					break;
+				case THTTPHdrVal::KNoType:
+				default:
+					{
+					GBA_TRACE_DEBUG("Unrecognized value type");
+					}
+					break;
+				}
+			}
+		}
+
+		++it;
+	}
+	GBA_TRACE_DEBUG("Header is Dumped already");
+}
+#endif
+
+//------------------------------------------------------------------------
+// CHTTPFilterGBA::CheckHeadersL
+// Check HTTP headers and extract MIME type
+//------------------------------------------------------------------------
+// 
+void CHTTPFilterGBA::CheckHeadersL(  RHTTPTransaction& aTrans )
+{
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::CheckHeadersL++"));
+	// read the header data and check the MIME type here	
+	// check the status and body
+	RHTTPResponse response = aTrans.Response();
+	TInt status = response.StatusCode();
+
+	#if defined (_DEBUG)
+	DumpResponseHeadersL( response );
+	#endif
+
+	THTTPHdrVal fieldVal;
+
+	// check if status == 401 and realm is 3GPP then we need to bootstrap, if we are already bootstrappign this is the second call
+	if(  status == HTTPStatus::EUnauthorized )
+	{
+	    TInt headerPart = FindHeaderPartToUseL(aTrans);
+        if( headerPart == KErrNotFound )
+            return;
+    	
+	    THTTPHdrVal headerVal;
+        TInt cred = KErrNotFound;
+
+	    if( aTrans.PropertySet().Property( iRealmStr, headerVal ) )
+	    	cred = DFindCredentials( headerVal, aTrans.Request().URI() );
+	    RStringF wwwAuthHeader = iStringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable());
+	    RHTTPHeaders headers(aTrans.Response().GetHeaderCollection());
+
+	    RString realm;
+	    THTTPHdrVal hdrVal;
+	    if (!headers.GetParam(wwwAuthHeader, iStringPool.StringF(HTTP::ERealm,RHTTPSession::GetTable()), 
+				  hdrVal, headerPart))
+	    {
+			realm = hdrVal;
+			const TDesC8& val = realm.DesC();
+			if(val.FindF(K3GPPRealmString) == 0)
+			{
+				GBA_TRACE_DEBUG(("3GPP-Bootstrapping realm detected...\n"));
+	            THTTPHdrVal authTypeParam;
+	            if ( headers.GetField( wwwAuthHeader, headerPart, authTypeParam ) == KErrNone )
+	                // we need to store realm, opaque, nonce and qop values to
+	                // use them when resubmitting the request
+	                {
+	                THTTPHdrVal algorithmVal;
+	                THTTPHdrVal nonceVal;
+	                THTTPHdrVal realmVal;
+	                THTTPHdrVal opaqueVal;
+	                THTTPHdrVal staleVal;
+	                TInt algVal( EAlgUnknown );
+	                TInt authVal( EQopNone );
+
+	                aTrans.PropertySet().RemoveProperty( iNonceStr );
+	                aTrans.PropertySet().RemoveProperty( iRealmStr );
+	                aTrans.PropertySet().RemoveProperty( iOpaqueStr );
+	                aTrans.PropertySet().RemoveProperty( iQopStr );
+	                aTrans.PropertySet().RemoveProperty( iStaleStr );
+
+	                if( !headers.GetParam( wwwAuthHeader, 
+	                                      iStringPool.StringF( HTTP::EAlgorithm, 
+	                                                      RHTTPSession::GetTable() ), 
+	                                      algorithmVal, 
+	                                      headerPart ) )
+	                    {
+	                    if( !algorithmVal.Str().DesC().CompareF( iMd5Str.DesC() ) )
+	                        {
+	                        algVal = EAlgMd5;
+	                        }
+	                    else if( !algorithmVal.Str().DesC().CompareF( iMd5SessStr.DesC() ) )
+	                        {
+	                        algVal = EAlgMd5Sess;
+	                        }
+	                    }
+
+	                authVal = CheckQop( headers, wwwAuthHeader, headerPart );
+
+	                headers.GetParam( wwwAuthHeader, iNonceStr, nonceVal, headerPart );
+	                headers.GetParam( wwwAuthHeader, iRealmStr, realmVal, headerPart );
+	                headers.GetParam( wwwAuthHeader, iOpaqueStr, opaqueVal, headerPart );
+	                headers.GetParam( wwwAuthHeader, iStaleStr, staleVal, headerPart );
+
+	                if( ( authVal & EQopAuth || authVal == EQopNone )
+	                    && nonceVal.Type() == THTTPHdrVal::KStrVal
+	                    && realmVal.Type() == THTTPHdrVal::KStrVal )
+	                    {
+	                    aTrans.PropertySet().SetPropertyL( iNonceStr, nonceVal );
+	                    aTrans.PropertySet().SetPropertyL( iRealmStr, realmVal );
+	                    // Opaque
+	                    if( opaqueVal.Type() == THTTPHdrVal::KStrVal )
+	                        {
+	                        aTrans.PropertySet().SetPropertyL( iOpaqueStr, opaqueVal );
+	                        }
+
+	                    // Qop
+	                    aTrans.PropertySet().SetPropertyL( iQopStr, authVal );
+	                    // Algorithm
+	                    aTrans.PropertySet().SetPropertyL( iStringPool.StringF( HTTP::EAlgorithm, 
+	                                                              RHTTPSession::GetTable() ), 
+	                                                              algVal );
+
+	                    _LIT8( KTrue, "TRUE" );
+	                    if( staleVal.Type() == THTTPHdrVal::KStrVal 
+	                        && !staleVal.Str().DesC().CompareF( KTrue ) )
+	                        // stale is true -> nonce expired
+	                        {
+                            GBA_TRACE_DEBUG(("Stale found"));
+	                        // update nonce value
+	                        TDCredentials& creds = iDCredentials[cred];
+	                        iStringPool.String( creds.iNonce ).Close();
+	                        creds.iNonce = nonceVal.Str().Copy();
+
+	                        // indicate to engine that no uname/pwd dialog needed
+	                        staleVal.SetInt( 1 );
+	                        aTrans.PropertySet().SetPropertyL( iStaleStr, staleVal );
+	                        }
+
+	                    }
+	                }
+	 				RHTTPTransactionPropertySet propSet = aTrans.PropertySet();
+	                THTTPHdrVal staleVal;
+
+					// don't show the uname&pwd dialog
+	                staleVal.SetInt( 1 );
+	                propSet.SetPropertyL( iStaleStr, staleVal );
+	                // if we are already bootstrapping results will be retrieved when request is resubmitted
+	                GBA_TRACE_DEBUG(("Do Bootstrap\n"));
+	                // start bootstrap process
+	                if(!iGbaUtility)
+	                    {
+	                    iGbaUtility = CGbaUtility::NewL(*this);
+	                    
+	                    //setbsf address required only for testing purpose
+	                    if(iBsfAddress.Size())
+	                        {
+                            iGbaUtility->SetBSFAddress(iBsfAddress);
+	                        }    
+	                    }
+	                
+	                // obtain NAF FQDN from URI
+	                iGbaInputParams.iNAFName.Copy(aTrans.Request().URI().UriDes());
+	                iGbaInputParams.iUICCLabel.Copy(iUICCLabel);
+	                iGbaInputParams.iProtocolIdentifier.Copy(iProtocolIdentifier);
+	                
+	                //iBootstrapCount == 0  - soft bootstrapp - get cradentials from gba cache
+	                //iBootstrapCount == 1  - force bootstrapp - get cradentials from BSF server
+	                //iBootstrapCount > 1  need to cancel http transaction to break out of the UE-NAF communication loop
+	                if(iBootstrapCount == 0){
+	                iGbaInputParams.iFlags = EGBADefault;
+                        GBA_TRACE_DEBUG(("iCredentials.Flags = EGBADefault"));
+	                }
+	                else if(iBootstrapCount == 1){
+	                iGbaInputParams.iFlags = EGBAForce;
+                        GBA_TRACE_DEBUG(("iCredentials.Flags = EGBAForce"));
+	                }
+	                else{
+                        GBA_TRACE_DEBUG(("iCredentials.Flags"));
+                        iBootstrapCount = 0;
+                        return;
+	                }
+	                
+	                //Default accesspoint will be used - iAPID = -1
+	                iGbaInputParams.iAPID = -1;
+                    
+	                //Cancel the transaction
+	                aTrans.Cancel();
+                    
+	                // fetch credentials from bootstrapper
+	                iGbaUtility->Bootstrap(iGbaInputParams, iGbaOutputParams);
+	                iBootstrapCount++;
+	                iBootstrapPending = ETrue;
+	                if(!iBootstrapWait.IsStarted())
+	                    {
+                        iBootstrapWait.Start();
+	                    }
+	                
+	                if( iHaveGbaBootstrapCredentials )
+	                    {
+                        GBA_TRACE_DEBUG(("Have stored credentials"));
+                        RHTTPTransactionPropertySet propSet = aTrans.PropertySet();
+                        GBA_TRACE_DEBUG(("BTID:"));
+                        GBA_TRACE_DEBUG(iGbaOutputParams.iBTID);
+                        // Encodes the KNAF to generate a password
+                        TImCodecB64 b64coder;
+                        TBuf8<KB64KeySize> keyBase64;
+                        b64coder.Initialise();
+                        b64coder.Encode( iGbaOutputParams.iKNAF, keyBase64 );
+                        RString username = iStringPool.OpenStringL( iGbaOutputParams.iBTID );
+                        CleanupClosePushL<RString>( username );
+                        RString password = iStringPool.OpenStringL( keyBase64 );
+                        CleanupClosePushL<RString>( password );
+                        propSet.SetPropertyL( iUsernameStr, username );
+                        propSet.SetPropertyL( iPasswordStr, password );
+                        CleanupStack::PopAndDestroy(&password);
+                        CleanupStack::PopAndDestroy(&username);
+                        // Re-submit the http request with much needed credentials
+                        aTrans.SubmitL(); 
+                        }
+	                else
+	                    {
+                        //Since bootstrapping failed,Do not have to resubmit the http request ?
+                        return;
+                        }
+			}
+	    }
+		}
+
+	if( status == HTTPStatus::EOk && iGbaUtility){
+		// if we have bootstrapped, it seems that we have succeeded
+		iBootstrapCount = 0;
+	}
+   	GBA_TRACE_DEBUG(("CHTTPFilterGBA::CheckHeadersL--"));
+	
+}
+
+void CHTTPFilterGBA::DoSubmitL( RHTTPTransaction aTransaction )
+{
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::DoSubmitL++"));
+	
+    // always add 3gpp-gba into user-agent field in headers,
+    // THIS CAN BE REMOVED WHEN GBA IS ADDED INTO THE CATALOG OF THE DEVICE
+    // WHICH IS STATIC.
+	
+	RHTTPHeaders hdr = aTransaction.Request().GetHeaderCollection();
+	
+	RStringF fieldname = aTransaction.Session().StringPool().StringF(HTTP::EUserAgent,RHTTPSession::GetTable());
+	
+	TBool found = EFalse;
+	TPtrC8 rawFieldData;
+	
+	hdr.GetRawField(fieldname, rawFieldData);
+	
+	found = rawFieldData.Find(iUserAgent.DesC()) != KErrNotFound;
+	
+	//Append "3gpp-gba" string to the "user agent" transaction header field only when,
+	//http transaction user agent header field has been set already(rawFieldData.Size() > 0) by an application,
+	//which opened the http transaction and also
+	//the transaction user agent header field value does not have "3gpp-gba" string in it.
+	
+	if(!found && rawFieldData.Size())
+	    hdr.SetFieldL(fieldname, iUserAgent);
+	
+    TInt cred = KErrNotFound;
+    
+    //iHaveGbaBootstrapCredentials - ETrue ,when the GBA bootstrapping is completed successfully
+    if( iHaveGbaBootstrapCredentials )
+        {
+        // Get credentials from URI, only for wwwAuthenticate
+        // If there are credentials in the transaction properties, add them to the list
+        DGetCredentialsFromPropertiesL( aTransaction );
+    
+        // just in case we always remove stale value from properties
+        aTransaction.PropertySet().RemoveProperty( iStaleStr );
+    
+        // If we have credentials for this URL, add them
+        cred = DFindCredentialsForURI( aTransaction.Request().URI() );
+    
+        if ( cred != KErrNotFound )
+            {
+            EncodeDigestAuthL( cred, aTransaction );
+            }
+        }
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::DoSubmitL--"));
+}
+
+//-----------------------------------------------------------------------------
+// CHTTPFilterGBA::Cleanup
+// Cleanup the resource related with a transaction
+//-----------------------------------------------------------------------------
+//
+void CHTTPFilterGBA::Cleanup( const RHTTPTransaction& /*aTrans*/ )
+{
+}
+
+//-----------------------------------------------------------------------------
+// CHTTPFilterGBA::CleanupAll
+// Cleanup all the GBA transactions, in case a session error happens or a session
+// is closed.
+//-----------------------------------------------------------------------------
+//
+void CHTTPFilterGBA::CleanupAll()
+{	
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::CleanupAll++"));
+	while(TInt i = iDCredentials.Count())
+	{
+		DRemoveCredentialsFromList(i-1);
+	} 
+
+	iQopAuthStr.Close();
+	iMd5SessStr.Close();
+	iMd5Str.Close();
+	iAuthInfo.Close();
+	iUserAgent.Close();
+    delete iMD5Calculator;
+    iMD5Calculator = NULL;
+    delete 	iGbaUtility;
+    iGbaUtility = NULL;
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::CleanupAll--"));
+}
+
+
+TInt CHTTPFilterGBA::FindHeaderPartToUseL(RHTTPTransaction aTransaction) const
+{
+    // There may be several different authentication fields. We need
+    // to chose the strongest one we understnad. Currently, we only
+    // support 2, Basic and Digest, and Digest is the strongest
+    // assuming there is a qop that we can accept. Therefore, we keep
+    // track of the last good basic one we found, and return the
+    // moment we find an acceptable digest one.
+
+    // While we're here, we check that all desired fields are there.
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::FindHeaderPartToUseL++"));
+    RStringF wwwAuthenticate = iStringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable());
+    RStringF realm = iStringPool.StringF(HTTP::ERealm,RHTTPSession::GetTable());
+    RStringF nonce = iStringPool.StringF(HTTP::ENonce,RHTTPSession::GetTable());
+    RStringF qop   = iStringPool.StringF(HTTP::EQop,RHTTPSession::GetTable());
+    TInt lastGoodBasic = KErrNotFound;
+    RHTTPHeaders headers = aTransaction.Response().GetHeaderCollection();
+    const TInt parts = headers.FieldPartsL(wwwAuthenticate);
+    GBA_TRACE_DEBUG_NUM((" FindHeaderPartToUseL part no:1 = %d"), parts );
+    for (TInt ii = 0; ii < parts; ii++)
+    {
+	THTTPHdrVal fieldVal;// The name of the current field.
+	THTTPHdrVal hdrVal;//A scratch hdrVal
+	headers.GetField(wwwAuthenticate, ii, fieldVal);
+	TInt x = fieldVal.StrF().Index(RHTTPSession::GetTable());
+	GBA_TRACE_DEBUG_NUM((" FindHeaderPartToUseL part no:1 = %d"), x );
+	switch (fieldVal.StrF().Index(RHTTPSession::GetTable()))
+	{
+	    case HTTP::EDigest:
+	    	
+	    	{
+	    	GBA_TRACE_DEBUG_NUM((" FindHeaderPartToUseL realm  = %d"), headers.GetParam(wwwAuthenticate, realm, hdrVal, ii) );
+	    	
+	    	GBA_TRACE_DEBUG_NUM((" FindHeaderPartToUseL nonce  = %d"), headers.GetParam(wwwAuthenticate, nonce, hdrVal, ii) );
+	    
+			if (headers.GetParam(wwwAuthenticate, realm, hdrVal, ii) == 
+			    KErrNone &&
+			    headers.GetParam(wwwAuthenticate, nonce, hdrVal, ii) == 
+			    KErrNone)
+			{
+				GBA_TRACE_DEBUG_NUM((" FindHeaderPartToUseL qop  = %d"), headers.GetParam(wwwAuthenticate, qop, hdrVal, ii) );
+				
+			    // We've got a realm and a nonce. If there's a qop, we
+			    // need to check it's acceptable.
+			    if (headers.GetParam(wwwAuthenticate, qop, hdrVal, ii) != 
+				KErrNone || FindAuth(hdrVal.Str().DesC()))
+			    	{
+			    	GBA_TRACE_DEBUG_NUM((" FindHeaderPartToUseL part no = %d"), ii );
+			    	return ii;
+			    	}
+				
+			}
+	    	}
+		break;
+
+	    default:
+		// We don't understand this, whatever it is. Ignore it.
+		break;
+	}
+    }
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::FindHeaderPartToUseL--"));
+    return lastGoodBasic;
+}
+
+
+TBool CHTTPFilterGBA::FindAuth(const TDesC8& aQop) const
+{
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::FindAuth++"));
+    TPtrC8 tokens = aQop;
+    TPtrC8 token;
+    const TDesC8& auth = iStringPool.StringF(HTTP::EAuth,RHTTPSession::GetTable()).DesC();
+    TInt len;
+    do
+    {
+    	len = tokens.Locate(',');
+    	if(len == -1)
+    		len = tokens.Length();
+    	token.Set(tokens.Ptr(),len);
+		if (token.Compare(auth) == 0)
+		{
+		    return ETrue;
+    	}
+    	tokens.Set(tokens.Ptr()+len);
+    }  while(tokens.Length());
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::FindAuth--"));
+    return EFalse;
+}
+
+
+
+void CHTTPFilterGBA::EncodeDigestAuthL( TInt aCred, RHTTPTransaction aTransaction )
+    {
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::EncodeDigestAuthL++"));
+
+	// For now, only support RFC2069 format. The digest is
+	// MD5(H(A1):nonce:H(A2))
+	TBuf8<KHashLength> hash;
+    TBuf8<KNonceCountLength> nonceCount;
+
+    TDCredentials cred = iDCredentials[aCred];
+    
+
+    THTTPHdrVal nonce( iStringPool.String( cred.iNonce ) );
+    THTTPHdrVal realm( iStringPool.String( cred.iRealm ) );
+    THTTPHdrVal qop;
+    THTTPHdrVal uname( iStringPool.String( cred.iUser ) );
+    THTTPHdrVal password( iStringPool.String( cred.iPassword ) );
+    THTTPHdrVal opaque( iStringPool.String( cred.iOpaque ) );
+
+    if( cred.iQop & EQopAuth )
+        // recent release supports only qop 'auth'.
+        {
+        qop.SetStrF( iQopAuthStr );
+        }
+
+	THTTPHdrVal requestUri;
+    // we get url from request and modify as made in chttpclienthandler.cpp
+    RString uriStr = RequestUriL( aTransaction );
+    CleanupClosePushL<RString>( uriStr );
+
+	requestUri.SetStr( uriStr );
+	
+	HBufC8* stringToHash = NULL;
+	RStringF auth = iStringPool.StringF(HTTP::EAuth,RHTTPSession::GetTable());
+
+	TBuf8<KHashLength> cnonce;
+	if ( cred.iQop != EQopNone )
+		{
+        GenerateCNonce( cnonce );
+
+        // 7 is for colons
+        // 8 for nc-value
+        stringToHash = HBufC8::NewMaxLC( KHashLength +  // H(A1)
+                                         1 +    // ":"
+                                         nonce.Str().DesC().Length() + 
+                                         1 +    // ":"
+                                         KIntegerConstant8 +    // nc value
+                                         1 +    // ":"
+                                         KHashLength +  // cnonce
+                                         1 +    // ":"
+										 qop.StrF().DesC().Length() +
+                                         1 +    // ":"
+										 KHashLength ); // H(A2)
+		TPtr8 stringMod = stringToHash->Des();
+		stringMod.Zero();
+		HAOneL( cred.iAlgorithm, uname, password, realm.Str(), nonce, cnonce, stringMod );
+		stringMod.Append(':');
+		stringMod.Append(nonce.Str().DesC());
+
+        // nc value
+		stringMod.Append(':');
+        ++cred.iNc;
+        // nc value is of 8 chars length and in hexadecimal format
+        nonceCount.NumFixedWidth( cred.iNc, EHex, KIntegerConstant8 );
+		stringMod.Append( nonceCount );
+		stringMod.Append(':');
+
+		stringMod.Append(cnonce);
+		stringMod.Append(':');
+		stringMod.Append(auth.DesC());
+		stringMod.Append(':');
+		HATwoL(aTransaction.Request().Method(), requestUri.Str(), hash);
+		stringMod.Append(hash);
+		}
+	else
+		{
+		// The response is the hash of H(A1):nonce:H(A2).
+		// Crqeate a buffer for the string to convert into MD5. The
+		// length is 32 characters for each of the hashes, 2
+		// characters for the 2 colons, plus the length of the nonce
+		stringToHash = HBufC8::NewMaxLC(nonce.Str().DesC().Length() + 
+												 2 * KHashLength + 2);
+		TPtr8 stringMod = stringToHash->Des();
+		stringMod.Zero();
+		HAOneL( cred.iAlgorithm, uname, password, realm.Str(), nonce, cnonce, stringMod );
+		stringMod.Append(':');
+		stringMod.Append(nonce.Str().DesC());
+		stringMod.Append(':');
+		HATwoL(aTransaction.Request().Method(), requestUri.Str(), hash);
+		stringMod.Append(hash);
+		}
+	
+	Hash(*stringToHash, hash);
+	CleanupStack::PopAndDestroy(stringToHash);
+
+	// OK. hash now contains the digest response. Set up the header.
+	RHTTPHeaders requestHeaders(aTransaction.Request().GetHeaderCollection());
+	
+	requestHeaders.RemoveField(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable())); 
+
+	requestHeaders.SetFieldL(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+							 THTTPHdrVal(iStringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+							 iStringPool.StringF(HTTP::EUsername,RHTTPSession::GetTable()),
+							 uname);
+	requestHeaders.SetFieldL(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+							 THTTPHdrVal(iStringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+							 iStringPool.StringF(HTTP::ERealm,RHTTPSession::GetTable()),
+							 realm);
+	requestHeaders.SetFieldL(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+							 THTTPHdrVal(iStringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+							 iStringPool.StringF(HTTP::ENonce,RHTTPSession::GetTable()),
+							 nonce);
+	RString hashStr = iStringPool.OpenStringL(hash);
+	CleanupClosePushL<RString>(hashStr);
+
+	THTTPHdrVal hdrVal;
+    hdrVal.SetStr(hashStr);
+	requestHeaders.SetFieldL(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+							 THTTPHdrVal(iStringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+							 iStringPool.StringF(HTTP::EResponse,RHTTPSession::GetTable()),
+							 hdrVal);
+
+	requestHeaders.SetFieldL(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+							 THTTPHdrVal(iStringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+							 iStringPool.StringF(HTTP::EUri,RHTTPSession::GetTable()),
+							 requestUri);
+	CleanupStack::PopAndDestroy(&hashStr);
+	if ( cred.iQop != EQopNone )
+		{
+        // QOP
+		hdrVal.SetStrF( auth );
+		requestHeaders.SetFieldL(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+								 THTTPHdrVal(iStringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+								 iStringPool.StringF(HTTP::EQop,RHTTPSession::GetTable()),
+								 hdrVal);
+		RString cnonceString = iStringPool.OpenStringL(cnonce);
+        // CNonce
+		CleanupClosePushL<RString>( cnonceString );
+		hdrVal.SetStr(cnonceString);
+		requestHeaders.SetFieldL(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+								 THTTPHdrVal(iStringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+								 iStringPool.StringF(HTTP::ECnonce,RHTTPSession::GetTable()),
+								 hdrVal);
+		CleanupStack::PopAndDestroy( &cnonceString );
+        // Nonce-count
+        RString nonceStr = iStringPool.OpenStringL( nonceCount );
+        CleanupClosePushL<RString>( nonceStr );
+		hdrVal.SetStr( nonceStr );
+		requestHeaders.SetFieldL(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+								 THTTPHdrVal(iStringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+								 iStringPool.StringF(HTTP::ENc,RHTTPSession::GetTable()),
+								 hdrVal);
+        CleanupStack::PopAndDestroy( &nonceStr );
+		}
+	
+	if(  opaque.Str().DesC().Length() )
+		requestHeaders.SetFieldL(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+								 THTTPHdrVal(iStringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+								 iStringPool.StringF(HTTP::EOpaque,RHTTPSession::GetTable()),
+								 opaque );	
+
+    if( cred.iAlgorithm == EAlgMd5 )
+        {
+		requestHeaders.SetFieldL(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+								 THTTPHdrVal(iStringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+								 iStringPool.StringF(HTTP::EAlgorithm,RHTTPSession::GetTable()),
+								 iMd5Str );
+        }
+    else if( cred.iAlgorithm == EAlgMd5Sess )
+        {
+		requestHeaders.SetFieldL(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+								 THTTPHdrVal(iStringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+								 iStringPool.StringF(HTTP::EAlgorithm,RHTTPSession::GetTable()),
+								 iMd5SessStr );
+        }
+
+    // set it again
+    // this may be needed if auth. fails and stale is true.
+    aTransaction.PropertySet().SetPropertyL( iRealmStr, realm );
+    
+    CleanupStack::PopAndDestroy( &uriStr );
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::EncodeDigestAuthL--"));
+    }
+  
+void CHTTPFilterGBA::DAddCredentialsToListL( RString aUsernameStr,
+        RString aPasswordStr,
+        RString aRealmStr,
+        RStringF aUriStr,
+        RString aOpaque,
+        RString aNonce,
+        TInt aQop,
+        TInt aAuthAlg )
+    {
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::DAddCredentialsToListL++"));
+    GBA_TRACE_DEBUG("uname: ");
+    GBA_TRACE_DEBUG(aUsernameStr.DesC());
+    GBA_TRACE_DEBUG("pwd: ");
+    GBA_TRACE_DEBUG(aPasswordStr.DesC());
+    GBA_TRACE_DEBUG("realm: ");
+    GBA_TRACE_DEBUG(aRealmStr.DesC());
+    GBA_TRACE_DEBUG("uri: ");
+    GBA_TRACE_DEBUG(aUriStr.DesC());
+    GBA_TRACE_DEBUG_NUM(("qop: %d"), aQop );
+    GBA_TRACE_DEBUG_NUM(("alg: %d"), aAuthAlg );
+
+    TDCredentials newCred;
+    newCred.iUser = aUsernameStr;
+    newCred.iPassword = aPasswordStr;
+    newCred.iRealm = aRealmStr;
+    newCred.iURI = aUriStr;
+    newCred.iOpaque = aOpaque;
+    newCred.iNonce = aNonce;
+    newCred.iQop = aQop;
+    newCred.iAlgorithm = aAuthAlg;
+    newCred.iNc = 0;
+    User::LeaveIfError( iDCredentials.Append( newCred ) );
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::DAddCredentialsToListL--"));
+    }
+
+// -----------------------------------------------------------------------------
+// CHTTPFilterGBA::HAOneL
+// Calculates H(A1)
+// -----------------------------------------------------------------------------
+//
+void CHTTPFilterGBA::HAOneL(int aAlgorithm,
+                                           const RString& aUsername,
+                                           const RString& aPW,
+								           const RString& aRealm, 
+                                           const RString& aNonceValue,
+                                           TDesC8& aCNonce,
+                                           TDes8& aResult )
+	{
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::HAOneL++"));
+    TBuf8<KHashLength> hash;
+
+	HBufC8* a1 = HBufC8::NewMaxL(aUsername.DesC().Length() + 
+								 aPW.DesC().Length() + 
+								 aRealm.DesC().Length() + 2 );
+	TPtr8 a1Mod = a1->Des();
+	a1Mod.Zero();
+	a1Mod.Append( aUsername.DesC() );
+	a1Mod.Append( KColon );
+	a1Mod.Append( aRealm.DesC() );
+	a1Mod.Append( KColon );
+	a1Mod.Append( aPW.DesC() );
+
+	GBA_TRACE_DEBUG("a1 first hash material");
+	GBA_TRACE_DEBUG(*a1);
+	
+
+	Hash( *a1, hash );
+	
+	GBA_TRACE_DEBUG("a1 first hash");
+	GBA_TRACE_DEBUG(hash);
+
+    delete a1;
+    a1 = NULL;
+
+    if( aAlgorithm == EAlgMd5Sess )
+        {
+	    a1 = HBufC8::NewMaxL( KHashLength +
+                               1 +  // ":"
+                               aNonceValue.DesC().Length() +
+                               1 +  // ":"
+							   aCNonce.Length() );
+	    TPtr8 a1Mod = a1->Des();
+	    a1Mod.Zero();
+        a1Mod.Append( hash );
+        a1Mod.Append( KColon );
+        a1Mod.Append( aNonceValue.DesC() );
+        a1Mod.Append( KColon );
+        a1Mod.Append( aCNonce );
+
+        GBA_TRACE_DEBUG("a1 final hash material");
+        GBA_TRACE_DEBUG(*a1);
+
+	    Hash(*a1, aResult);
+	    
+        GBA_TRACE_DEBUG("a1 final hash");
+        GBA_TRACE_DEBUG(hash);
+	    delete a1;
+        a1 = NULL;
+        }
+    else
+        {
+        aResult.Copy( hash );
+        }
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::HAOneL--"));
+	}
+
+
+// -----------------------------------------------------------------------------
+// CHTTPFilterGBA::HAtwoL
+// Calculates H(A2)
+// -----------------------------------------------------------------------------
+//
+void CHTTPFilterGBA::HATwoL(const RStringF& aMethod, 
+								           const RString& aRequestUri,
+								           TDes8& aResult)
+	{
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::HAtwoL++"));
+	// In the auth qop, a2 is Method:digest-uri-value
+	// Digest-uri-value. We don't support auth-int qop
+	// Allocate enough space for the method, the URI and the colon.
+	TPtrC8 requestUri = aRequestUri.DesC();
+	TPtrC8 method = aMethod.DesC();
+	HBufC8* a2 = HBufC8::NewMaxLC(requestUri.Length() + method.Length() + 1);
+	TPtr8 a2Mod = a2->Des();
+	a2Mod.Zero();
+	a2Mod.Append(method);
+	a2Mod.Append(':');
+	a2Mod.Append(requestUri);
+
+    GBA_TRACE_DEBUG("a2 final hash material");
+    GBA_TRACE_DEBUG(*a2);
+
+	Hash(*a2, aResult);
+
+    GBA_TRACE_DEBUG("a2 final hash");
+    GBA_TRACE_DEBUG(aResult);
+
+	CleanupStack::PopAndDestroy(a2);
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::HAtwoL--"));
+	}
+
+// -----------------------------------------------------------------------------
+// CHTTPFilterGBA::Hash
+// Calculates hash value
+// -----------------------------------------------------------------------------
+//
+void CHTTPFilterGBA::Hash(const TDesC8& aMessage, TDes8& aHash)
+	{
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::Hash++"));
+	// Calculate the 128 bit (16 byte) hash
+	iMD5Calculator->Reset();
+	TPtrC8 hash = iMD5Calculator->Hash( aMessage );
+	// Now print it as a 32 byte hex number
+	aHash.Zero();
+	_LIT8(formatStr, "%02x");
+	for (TInt ii = 0; ii < KRawHashLength; ii++)
+		{
+		TBuf8<2> scratch;
+		scratch.Zero();
+		scratch.Format( formatStr, hash[ii] );
+		aHash.Append( scratch );
+		}
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::Hash--"));
+	}
+
+// -----------------------------------------------------------------------------
+// CHTTPFilterGBA::GenerateCNonce
+// Generate unique cnonce value.
+// -----------------------------------------------------------------------------
+//
+void CHTTPFilterGBA::GenerateCNonce(TDes8& aNonce)
+	{
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::GenerateCNonce++"));
+	// 'Inspired by' CObexAuthenticator
+
+	// The purpose of the client nonce is to protect against 'chosen
+	// plaintext' attacks where a hostile server tricks the client
+	// into supplying a password using a specific server nonce that
+	// allows an (as yet undiscovered) flaw in MD5 to recover the
+	// password. As such the only important thing about client nonces
+	// is that they change and aren't predictable. See section 4.9 of
+	// RFC2616
+
+	TTime time;
+	time.UniversalTime();
+	TInt64 randomNumber = Math::Rand(iSeed);
+	randomNumber <<= KIntegerConstant32;
+	randomNumber += Math::Rand(iSeed);
+	TBuf8<KIntegerConstant33> key;
+	key.Zero();
+	key.AppendNum(time.Int64(), EHex);
+	key.Append(_L8(":"));
+	key.AppendNum(randomNumber, EHex);
+	
+	Hash(key, aNonce);
+	GBA_TRACE_DEBUG(("CHTTPFilterGBA::GenerateCNonce--"));
+	}
+
+// -----------------------------------------------------------------------------
+// CHTTPFilterGBA::RequestUriLC
+// Returns requested URI in form that can be used in uri field.
+// This code comes from 
+// Application-protocols/http/httpclient/chttpclienthandler.cpp.
+// -----------------------------------------------------------------------------
+//
+RString CHTTPFilterGBA::RequestUriL( RHTTPTransaction& aTransaction )
+    {
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::RequestUriL++"));
+    TBool useProxy( EFalse );
+    THTTPHdrVal useProxyHdr;
+    RStringF proxyUsage = iStringPool.StringF( HTTP::EProxyUsage, RHTTPSession::GetTable() );
+    RHTTPRequest request = aTransaction.Request();
+    const TUriC8& uri = request.URI();
+    RStringF scheme = iStringPool.OpenFStringL( uri.Extract( EUriScheme ) );
+    CleanupClosePushL<RStringF>( scheme );
+    CUri8* uriToUse = CUri8::NewLC( uri );
+
+    if( aTransaction.Session().ConnectionInfo().Property( proxyUsage, useProxyHdr ) )
+        {
+	    // Is a proxy being used?
+        useProxy = ( useProxyHdr.StrF().Index(RHTTPSession::GetTable()) == HTTP::EUseProxy );
+        }
+
+	if( !useProxy || (useProxy && scheme.Index(RHTTPSession::GetTable()) == HTTP::EHTTPS ))
+		{
+		// Not going via a proxy - need to remove the scheme and authority parts
+		uriToUse->RemoveComponentL( EUriScheme );
+		uriToUse->RemoveComponentL( EUriHost );	// this also removes the userinfo + port
+		}
+
+    RString uriStr = iStringPool.OpenStringL( uriToUse->Uri().UriDes()  );
+
+    CleanupStack::PopAndDestroy( uriToUse );
+    CleanupStack::PopAndDestroy( &scheme );
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::RequestUriL--"));
+    return uriStr;    
+    }
+
+// -----------------------------------------------------------------------------
+// CHTTPFilterGBA::CheckQop
+//
+// -----------------------------------------------------------------------------
+//
+TInt CHTTPFilterGBA::CheckQop( RHTTPHeaders& aHeaders,
+                                                RStringF& aWwwAuthHeader,
+                                                TInt aHeaderPart )
+    {
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::CheckQop++"));
+    THTTPHdrVal qopVal;
+    TInt retVal( EQopNone );
+    
+    if( !aHeaders.GetParam( aWwwAuthHeader, iQopStr, qopVal, aHeaderPart ) )
+        {
+        TPtrC8 qopBuf( qopVal.Str().DesC() );
+        TPtrC8 qopValue;
+        TInt comma;
+
+        do
+            {
+            comma = qopBuf.Locate( ',' );
+            
+            if( comma != KErrNotFound )
+                {
+                qopValue.Set( qopBuf.Left(comma) );
+                }
+            else
+                {
+                qopValue.Set( qopBuf );
+                }
+
+            if( !qopValue.CompareF(iQopAuthStr.DesC()) )
+                {
+                retVal |= EQopAuth;
+                }
+            else if( !qopValue.CompareF(KQopAuthIntStr) )
+                {
+                retVal |= EQopAuthInt;
+                }
+            
+            qopBuf.Set( qopBuf.Right(qopBuf.Length()-comma-1));
+            }while( comma != KErrNotFound );
+        }
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::CheckQop--"));    
+    return retVal;
+    }
+
+void CHTTPFilterGBA::DGetCredentialsFromPropertiesL( RHTTPTransaction& aTransaction )
+    {
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::DGetCredentialsFromPropertiesL++"));
+    THTTPHdrVal usernameVal;
+    THTTPHdrVal passwordVal;
+    THTTPHdrVal realmVal;
+    THTTPHdrVal nonceVal;
+    THTTPHdrVal staleVal;
+    const TUriC8& uri = aTransaction.Request().URI();
+    RHTTPTransactionPropertySet propSet = aTransaction.PropertySet();
+    TBool staleAvail = propSet.Property( iStaleStr, staleVal );
+    
+    
+    if ( propSet.Property( iUsernameStr, usernameVal ) &&
+         propSet.Property( iPasswordStr, passwordVal ) &&
+         propSet.Property( iRealmStr, realmVal ) && 
+         propSet.Property( iNonceStr, nonceVal )
+          )
+        // if stale is TRUE we don't need to update credential
+        {
+        
+
+        TInt pushCounter( 0 );
+        TInt cred = DFindCredentialsForURI( uri );
+        if ( cred != KErrNotFound )
+            {
+            // Remove old credentials from the list
+            DRemoveCredentialsFromList( cred );
+            }
+
+        TPtrC8 uriPathPtr( uri.UriDes() );
+
+        if ( uriPathPtr.LocateReverse( '/' ) > 0 )
+            {
+            uriPathPtr.Set( uriPathPtr.Left( uriPathPtr.LocateReverse( '/' ) ) );
+            }
+
+        RStringF uriStr = iStringPool.OpenFStringL( uriPathPtr );
+        CleanupClosePushL( uriStr );
+        ++pushCounter;
+
+        THTTPHdrVal opaqueVal;
+
+        RString opaqueStr;
+        
+        if( !propSet.Property( iOpaqueStr, opaqueVal ) )
+            // this isn't a error case
+            {    
+            opaqueStr = iStringPool.OpenStringL( KNullDesC8 );
+            CleanupClosePushL<RString>( opaqueStr );
+            ++pushCounter;
+            }
+        else
+            {
+            opaqueStr = opaqueVal;
+            }
+       
+        THTTPHdrVal qopVal;
+
+        if( !propSet.Property( iQopStr, qopVal ) )
+            // this isn't a error case
+            {
+            qopVal.SetInt( EQopNone );
+            }
+
+      
+        THTTPHdrVal algVal;
+        if( !propSet.Property( iStringPool.StringF( HTTP::EAlgorithm, 
+                                           RHTTPSession::GetTable() ), algVal) )
+            {
+            algVal.SetInt( EAlgUnknown );
+            }
+        // Add credentials to the list from the transaction's properties
+       DAddCredentialsToListL( usernameVal.Str().Copy(), 
+                                passwordVal.Str().Copy(),
+                                realmVal.Str().Copy(), 
+                                uriStr.Copy(), 
+                                opaqueStr.Copy(), 
+                                nonceVal.Str().Copy(),
+                                qopVal.Int(),
+                                algVal.Int()
+                                );
+        // this is not the traditional way to pop and destroy elements
+        // but in this case this is the simplest one.
+        CleanupStack::PopAndDestroy( pushCounter ); // [opaqueVal,]uriStr
+        }
+  
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::DGetCredentialsFromPropertiesL--"));
+    }
+
+
+TInt CHTTPFilterGBA::DFindCredentialsForURI( const TUriC8& aURI )
+    {
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::DFindCredentialsForURI++"));
+    // Check if any of the stored URIs are the beginning of the URI
+    // we're trying now. If they are, we can immediately attempt to
+    // re-use the existing credentials.
+    _LIT8 ( KSchemeEnd, "://" );
+    TInt count = iDCredentials.Count();
+
+    for ( TInt cred = 0; cred < count; ++cred )
+        {
+        const TPtrC8& transDes = aURI.UriDes();
+        const TPtrC8& credDes =
+            iStringPool.StringF( iDCredentials[ cred ].iURI ).DesC();
+        TPtrC8 transNoSchemePtr( transDes );
+        TPtrC8 credNoSchemePtr( credDes );
+
+        if ( transNoSchemePtr.Find( KSchemeEnd() ) > 0 )
+            {
+            transNoSchemePtr.Set( transNoSchemePtr.Mid( transNoSchemePtr.Find( KSchemeEnd ) ) );
+            }
+
+        if ( credNoSchemePtr.Find( KSchemeEnd() ) > 0 )
+            {
+            credNoSchemePtr.Set( credNoSchemePtr.Mid( credNoSchemePtr.Find( KSchemeEnd ) ) );
+            }
+
+        if ( transNoSchemePtr.Length() >= credNoSchemePtr.Length() )
+            {
+            // The URI is long enough, which is a good start.
+
+            if ( transNoSchemePtr.Left( credNoSchemePtr.Length() ).Compare( credNoSchemePtr ) == 0 )
+                {
+                // The descriptors match. Things are looking good. In
+                // the interests of paranoia, if we haven't matched
+                // the entire URI, check that the character after the
+                // match is '/'.
+                if ( transNoSchemePtr.Length() == credNoSchemePtr.Length() )
+                    {
+                    GBA_TRACE_DEBUG_NUM("Found cred(1): %d", cred ); 
+                    GBA_TRACE_DEBUG("uri: ");
+                    GBA_TRACE_DEBUG(aURI.UriDes());
+                    return cred;
+                    }
+
+                else if ( transNoSchemePtr[ credNoSchemePtr.Length() ] == '/' )
+                    {
+                    GBA_TRACE_DEBUG_NUM("Found cred(2): %d", cred ); 
+                    GBA_TRACE_DEBUG("uri: ");
+                    GBA_TRACE_DEBUG(aURI.UriDes());
+                    return cred;
+                    }
+                }
+            }
+        }
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::DFindCredentialsForURI--"));
+    return KErrNotFound;
+    }
+
+
+void CHTTPFilterGBA::DRemoveCredentialsFromList( TInt aCredId )
+    {
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::DRemoveCredentialsFromList++"));
+    GBA_TRACE_DEBUG_NUM("DRemoveCredentialsFromList: %d", aCredId );
+
+    TDCredentials& creds = iDCredentials[ aCredId ];
+    iStringPool.String( creds.iUser ).Close();
+    iStringPool.String( creds.iPassword ).Close();
+    iStringPool.StringF( creds.iURI ).Close();
+    iStringPool.String( creds.iRealm ).Close();
+    iStringPool.String( creds.iOpaque ).Close();
+    iStringPool.String( creds.iNonce ).Close();
+    iDCredentials.Remove( aCredId );
+    iDCredentials.Close();
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::DRemoveCredentialsFromList--"));
+    }
+
+TInt CHTTPFilterGBA::DFindCredentials( const RString& aRealm,
+        const TUriC8& aURI )
+    {
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::DFindCredentials++"));
+    TInt count = iDCredentials.Count();
+
+    for ( TInt cred = 0; cred < count; ++cred )
+        {
+        if ( iDCredentials[ cred ].iRealm == aRealm )
+            {
+            TUriParser8 parser;
+            parser.Parse( iStringPool.StringF( iDCredentials[ cred ].iURI ).DesC() );
+
+            if ( !parser.Compare( aURI, EUriHost ) &&
+                 ( ( !parser.Compare( aURI, EUriPort ) )
+                   || ( !parser.IsPresent( EUriPort ) &&
+                        !aURI.IsPresent( EUriPort ) ) ) )
+                {                
+                GBA_TRACE_DEBUG_NUM("Found cred(3): %d", cred );
+                return cred;
+                }
+            }
+        }
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::DFindCredentials--"));
+    return KErrNotFound;
+    }
+
+
+void CHTTPFilterGBA::BootstrapComplete( TInt aError )
+{
+    GBA_TRACE_DEBUG(("CHTTPFilterGBA::BootstrapComplete--"));
+    if( aError == KErrNone)
+        {
+        iBootstrapPending = EFalse;
+        iHaveGbaBootstrapCredentials = ETrue;
+        }
+    else
+        {
+        iBootstrapPending = EFalse;
+        iHaveGbaBootstrapCredentials = EFalse;
+        }
+    iBootstrapWait.AsyncStop();
+}
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbafilter/src/HTTPFilterGBAMain.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of TImplementationProxy
+*
+*/
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include "HTTPFilterGBA.h"
+
+const TImplementationProxy KImplementationTable[] = 
+	{	
+	IMPLEMENTATION_PROXY_ENTRY(0x20029F10,CHTTPFilterGBA::InstallFilterL) 
+	};
+
+
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+	{
+	aTableCount = sizeof(KImplementationTable) / sizeof(TImplementationProxy);
+	return KImplementationTable;
+	}
+                                             
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaserver/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,24 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: Build info file for GBA Server components 
+*
+*/
+
+
+PRJ_MMPFILES
+
+gbaserver.mmp
+    
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaserver/group/gbaserver.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,66 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file for project gba server
+*
+*/
+
+#include <platform_paths.hrh>
+TARGET            gbaserver2.exe
+TARGETTYPE        exe
+
+UID               0x1000008d 0x20029F0A
+
+VENDORID    VID_DEFAULT
+CAPABILITY  CAP_SERVER NetworkControl
+
+SMPSAFE
+
+USERINCLUDE       ../inc
+USERINCLUDE      ../../inc
+
+APP_LAYER_SYSTEMINCLUDE 
+SYSTEMINCLUDE /epoc32/include/ecom
+
+SOURCEPATH      ../src
+SOURCE          GbaSession.cpp
+SOURCE          GbaServer.cpp
+SOURCE 			bootstrap.cpp 
+SOURCE 			dataretriever.cpp
+
+SOURCEPATH     ../../common
+SOURCE         GBALogger.cpp
+
+LIBRARY         euser.lib
+LIBRARY         efsrv.lib 
+LIBRARY         estor.lib
+LIBRARY 		ecom.lib 
+LIBRARY 		bafl.lib
+LIBRARY 		commdb.lib
+LIBRARY 		http.lib 
+LIBRARY 		hash.lib
+LIBRARY 		inetprotutil.lib 
+LIBRARY 		esock.lib 
+LIBRARY 		centralrepository.lib
+LIBRARY 		imut.lib //for base64 en/decoding
+LIBRARY 		cmmanager.lib
+DEBUGLIBRARY    flogger.lib
+
+
+
+
+
+
+
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaserver/inc/GbaServer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,74 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  GBA Server definitions
+*
+*/
+
+
+#ifndef   GBASERVER_H
+#define   GBASERVER_H
+
+#include <e32base.h>
+#include <f32file.h>
+#include "GbaServerPolicy.h"
+
+void PanicClient( const RMessage2& aMessage, TInt aPanic );
+void PanicServer( TInt aPanic );
+
+class CShutdown : public CTimer
+    {
+    enum { EGbaServerShutdownDelay = 0x200000 }; // approx 2s
+    public:
+        inline CShutdown();
+        inline void ConstructL();
+        inline void Start();
+    private:
+        void RunL();
+    };
+
+
+
+class CGbaServer : public CPolicyServer
+    {
+    public : 
+        static CGbaServer* NewL();
+        static CGbaServer* NewLC();
+        ~CGbaServer();
+        //Increment the count of the active sessions for this server
+        void IncrementSessions();
+
+        //Decrement the count of the active sessions for this server. 
+        //If no more sessions are in use the server terminates.
+        void DecrementSessions();
+       //Reads specified option from server.
+       TBool ReadOptionL(const TUid& aOptionID, TDes8& aValue) const;
+       //write specified option 
+       void WriteOptionL(const TUid& aOptionID, const TDesC8& aValue) const;
+
+    private:
+        CGbaServer() ;
+        void ConstructL() ;
+        CSession2* NewSessionL(const TVersion& aVersion, const RMessage2& aMessage) const;
+        void MakePrivateFilenameL(RFs& aFs, const TDesC& aLeafName, TDes& aNameOut) const;
+        void  EnsurePathL( RFs& aFs, const TDesC& aFile ) const;
+
+    private:
+        TInt        iSessionCount;
+        CShutdown   iShutdown;    
+    };
+
+
+#endif //GBASERVER_H
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaserver/inc/GbaServerPolicy.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,76 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  GBA Server Policy definitions
+*
+*/
+
+
+#ifndef   GBASERVERPOLICY_H
+#define   GBASERVERPOLICY_H
+
+#include <e32base.h>
+#include "GbaCommon.h"
+
+// Panic Category 
+_LIT(KGbaServer, "gbaserver2");
+
+
+// Total number of policy ranges
+const TUint KGBARangeCount = 5;
+
+const TInt GBARanges[KGBARangeCount] =
+    {
+    EGbaServRequestBootstrap,             // Range 0  
+    EGbaServCancelRequestBootstrap,       // Range 1
+    EGbaServWriteOption,                  // Range 2
+    EGbaServIsGBAUSupported,              // Range 3 
+    EGbaServIsGBAUSupported+1             // Range 4
+    };                                    
+
+// Policy to implement for each of the ranges in range table.
+const TUint8 GBAElementsIndex[KGBARangeCount] =
+    {
+    1,                                    // ReadDeviceData is required for bootstrap 
+    CPolicyServer::EAlwaysPass,           // No cap required for cancel bootstrap
+    0,                                    // WriteDeviceData is required for write options
+    1,                                    // ReadDeviceData is required for checking gba-u 
+    CPolicyServer::ENotSupported          // applies to 5th range (out of range IPC)
+    };
+
+// Specific capability checks.
+const CPolicyServer::TPolicyElement GBAElements[] =
+    {
+        // policy "0"; 
+        {
+        _INIT_SECURITY_POLICY_C1( ECapabilityWriteDeviceData ),
+        CPolicyServer::EFailClient
+        },
+        // policy "1"; 
+        {
+        _INIT_SECURITY_POLICY_C1( ECapabilityReadDeviceData ),
+        CPolicyServer::EFailClient
+        }
+    };
+
+// Packs all the security definitions into a policy.
+const CPolicyServer::TPolicy GBAPolicy =
+    {
+    CPolicyServer::EAlwaysPass, // all connect attempts should pass
+    KGBARangeCount,             // number of ranges
+    GBARanges,                  // ranges array
+    GBAElementsIndex,           // elements<->ranges index
+    GBAElements,                // array of elements
+    };
+
+#endif //GBASERVERPOLICY_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaserver/inc/GbaSession.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  class CGbaServerSession definition
+*
+*/
+
+
+#ifndef GBASESSION_H
+#define GBASESSION_H
+
+#include <e32base.h>
+#include "GbaServer.h"
+#include "bootstrap.h" 
+#include "GbaCommon.h"
+
+class CBootstrapStateMachine;
+
+class CGbaServerSession : public CSession2
+    {
+    public: 
+        static CGbaServerSession* NewL();
+        virtual ~CGbaServerSession();
+        //Server reference
+        CGbaServer* Server();
+       
+    private:
+        void ConstructL();
+        CGbaServerSession();
+        //Handle the event cause when Bootstrapping is completed.
+        void StateMachineCallBack( TInt aError ) ;
+        void ServiceL(const RMessage2& aMessage);
+        void CreateL() ;
+        void RequestBootstrapL(const RMessage2& aMessage);
+
+    private: 
+        RMessage2  iMessage;
+        C3GPPBootstrap* i3GPPBootstrap;
+        TGBABootstrapInputParams    iGbaInputParams;
+        TGBABootstrapOutputParams   iGbaOutputParams;
+    
+    friend class C3GPPBootstrap;
+    };
+
+#endif //GBASESSION_H
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaserver/inc/M3GPPAuthenticationCallback.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,78 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  class M3GPPAuthenticationCallback definition
+*
+*/
+
+
+#ifndef	__M3GPPAUTHENTICATIONCALLBACK_H__
+#define	__M3GPPAUTHENTICATIONCALLBACK_H__ 
+
+// System includes
+#include <uri8.h>
+#include <stringpool.h>
+#include <http/rhttpsession.h>
+
+/** 
+	@public
+	@class			M3GPPAuthenticationCallback
+
+	The mixin that needs to be implemented if 3gpp digest AKA authentication is to be
+	supported. This supplies the username and password and nonce when they are
+	needed for authentication.
+	To use, subclass off this class and implement GetCredentialsL. To install
+	the class into a session, call InstallAuthenticationL.
+ */
+
+class M3GPPAuthenticationCallback
+	{
+ public:
+	/** Gets some credentials. Note that the first 3 parameters are
+		informational and many clients may not have a use for
+		them. Clients may want to display some or all of these
+		parameters to the user, so that the user knows who they are
+		giving their credentials to, and how securely they will be
+		transmitted.
+		@param aURI The URI being requested
+		@param aRealm The realm being requested
+		@param aNonce The value of the nonce field: used to transport RAND/AUTN vectors
+		@param aAuthenticationType The type of authentication (basic or digest)
+		@param aAlgorithm The algorithm used in the Digest procedure eg MD5
+		@param aUsername The username is returned in this parameter. 
+		The caller will close the returned string.
+		@param aPassword The password is returned in this parameter
+		The caller will close the returned string.
+		@param aResync The AUTS - authentication resyncronization value is returned in this parameter
+		The caller will close the returned string. If aResyncRequired is false this variable will not be initialized.
+		@param aResyncRequired will be set to true, if call caused the uicc to request resynchronization
+		@return True if credentials have been obtained. 
+		@exception Anything. If this function leaves the transaction will be 
+		failed. 
+	*/
+	//##ModelId=3B1E52A5015D
+	virtual TBool GetCredentialsL(const TUriC8& aURI, RString aRealm, RString aNonce, 
+								  RString aAlgorithm,
+								  RString& aUsername, 
+								  RString& aPassword,
+								  RString& aResync,
+								  TBool& aResyncRequired) = 0;
+
+	};
+
+
+
+#endif //	__M3GPPAUTHENTICATIONCALLBACK_H__
+                                                                 
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaserver/inc/bootstrap.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,157 @@
+/*
+ * Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+ * All rights reserved.
+ * This component and the accompanying materials are made available
+ * under the terms of "Eclipse Public License v1.0"
+ * which accompanies this distribution, and is available
+ * at the URL "http://www.eclipse.org/legal/epl-v10.html".
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:  Bootstrap classes definitions
+ *
+ */
+
+#ifndef BOOTSTRAPIMPL_H
+#define BOOTSTRAPIMPL_H
+
+#include <e32base.h>
+#include <stringpool.h>
+#include <http.h>
+#include <gbautility.h>
+#include "M3GPPAuthenticationCallback.h"
+#include "gbauicc.h"
+
+void ResetAndDestroyArray(TAny* aArray);
+
+class CGbaServerSession;
+class CDataRetriever;
+// format for output of data/time values
+_LIT(KDateFormat,"%D%M%Y%/0%1%/1%2%/2%3%/3 %:0%H%:1%T%:2%S.%C%:3");
+
+class MBootstrapCallBack : public M3GPPAuthenticationCallback
+    {
+public:
+    
+    virtual void CompleteBootStrappingL(TInt aError) = 0;
+    
+    virtual TBool InterfaceIs2G() = 0;
+    
+    };
+
+class C3GPPBootstrap : public CActive, public MBootstrapCallBack
+    {
+public:
+    
+    static C3GPPBootstrap* NewL(CGbaServerSession* aSession);
+    
+    static C3GPPBootstrap* NewLC(CGbaServerSession* aSession);
+    
+    void InitializeL();
+    
+    void GetBootstrappingMaterialL(const TDesC8& aBSFAddress,
+            const TDesC8& aNAFURL, const TDesC8& aUICC_LABEL,
+            const TUint8& aFlags, const TDesC8& aKeyUsage, TDes8 &aKsNAF,
+            TDes8 &aBTID, TTime &aLifetime, EGBARunType& aGBARunType,
+            const TInt& aIAPID);
+    
+    void CancelBootstrap();
+    
+    TInt GetState() const;
+    
+    void Cleanup();
+    
+    TBool GBAUAvailabilityL();
+
+    // from M3GPPAuthenticationCallback  
+    TBool GetCredentialsL(const TUriC8& aURI, RString aRealm, RString aNonce,
+            RString aAlgorithm, RString& aUsername, RString& aPassword,
+            RString& aResync, TBool& aResyncRequired);
+
+    virtual ~C3GPPBootstrap();
+
+    //from MBootstrapCallBack
+    void CompleteBootStrappingL(TInt aError);
+    
+    TBool InterfaceIs2G();
+
+private:
+
+    void DoBootstrapL();
+    
+    TBool GenerateKeyMaterialL();
+    
+    void ConstructL();
+    
+    C3GPPBootstrap(CGbaServerSession* aSession);
+    
+    TBool LoadCredentialsL();
+    
+    void StoreCredentialsL();
+    
+    TBool ConvertStringToTTime(TDesC8& aLifetimeBuf, TTime* aLifetime);
+    
+    TBool IsStillValid(TTime* aLifetime);
+    
+    TInt LoadGBAUAvailabililtyFromStoreL(TBool& aIsfromGBAClient, TBool& aGBAUAvail);
+    
+    void SaveGBAUAvailabilityToStoreL(TBool& aGBAUAvail);
+    
+    TBool CheckGBAUAvailabilityL(TBool aIsfromGBAClient);
+    
+    MUICCInterface* RequestUICCInterfaceL();
+    
+    TBool IsPluginExistL();
+    
+    void MakePrivateFilenameL(RFs& aFs, const TDesC& aLeafName, TDes& aNameOut);
+    
+    void EnsurePathL(RFs& aFs, const TDesC& aFile);
+
+    //From CActive
+    void RunL();
+    
+    TInt RunError(TInt aError);
+    
+    void DoCancel();
+
+public:
+
+    enum TBootstrapperState
+        {
+        EIdle, EInitialize, EBusy, ECancel
+        };
+private:
+    enum TSecurityAlgorithm
+        {
+        ESecAlgUnknown, EAKAv1, EAKAv2, ESIMv2
+        };
+
+private:
+
+    MUICCInterface* iSmartCardInterface;
+    TDes8*          iCallerBTIDBuf;     //not owned,  pointer to return buffer
+    TDes8*          iCallerKsNAFBuf;    //not owned,  pointer to return buffer
+    TTime*          iCallerLifetime;    //not owned, pointer to return object
+    EGBARunType*    iCallerGBARunType;  //not owned, pointer to return object
+    HBufC8*         iKsNAF;             //owned
+    HBufC8*         iBTID;              //owned
+    TTime           iLifetime;          //onwed
+    HBufC8*         iIdentity;          //buffer for impi
+    HBufC8*         iNAFID;             //buffer for nafid
+    HBufC8*         iRand;              //buffer for rand
+    HBufC8*         iMasterKey;         //buffer for Ks
+    EGBARunType     iGBARunType;
+    CDataRetriever* iDataRetriever;     //owned
+    TInt            iAuthFailed;
+    TBootstrapperState iBSState;
+    TBool           iGBAUAvailable;
+    TUid            iImplementationUID;
+    TUid            iDtorIDKey;
+    CGbaServerSession* iSession;        //Not owned
+    };
+
+#endif
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaserver/inc/dataretriever.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,157 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This file contains class CDataRetriever. It encapsulates
+*                http connection to the bsf  
+*
+*/
+
+
+#ifndef DATARETRIEVER_H
+#define DATARETRIEVER_H
+
+#include <e32base.h>
+
+#include <stringpool.h>
+#include <http.h>
+#include <es_sock.h> 
+#include <commdbconnpref.h>
+#include <cmmanagerext.h>
+#include <hash.h>
+#include "M3GPPAuthenticationCallback.h"
+
+
+// HTTPHeader data lenghts
+const TInt KMaxHeaderNameLen = 32;
+const TInt KMaxHeaderValueLen = 128;
+const TInt KMaxBootstrapRespLen = 1024;
+
+
+// forward declarations
+class MBootstrapCallBack;
+
+class MHttpRequestEvents
+    {
+    public:
+        virtual void EventRequestCompletedL(TInt aErrorCode) = 0;
+    };
+
+
+/** 
+ * Handles all events for the active transaction.
+ */
+class C3GPPBootstrapHttpHandler : public CBase, public MHTTPTransactionCallback
+    {
+    public:
+            
+        static C3GPPBootstrapHttpHandler* NewLC(    MHttpRequestEvents* aEventSink,
+                                                    M3GPPAuthenticationCallback* aDataRetrieverCallBack );
+        static C3GPPBootstrapHttpHandler* NewL( MHttpRequestEvents* aEventSink,
+                                                M3GPPAuthenticationCallback* aDataRetrieverCallBack );
+        virtual ~C3GPPBootstrapHttpHandler();
+        //methods from MHTTPTransactionCallback
+        virtual void MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent);
+        virtual TInt MHFRunError(TInt aError, RHTTPTransaction aTransaction, const THTTPEvent& aEvent);
+        HBufC8* GetResponse();  // intended to contain the TID!
+           
+        void Reset();
+    private:
+        C3GPPBootstrapHttpHandler(  MHttpRequestEvents* aEventSink,
+                                    M3GPPAuthenticationCallback* aDataRetrieverCallBack );
+        void ConstructL();
+        // handles HTTP 401 Authorization required
+        TInt HandleAuthorizationChallengeL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent);
+        // HTTP DIGEST authentication stuff
+        TInt FindHeaderPartToUseL(RHTTPTransaction aTransaction) const;
+        void EncodeDigestAuthL( const RString& aUsername, const RString& aPW,
+                                RHTTPTransaction& aTransaction, TInt headerPart, const THTTPHdrVal& aRequestUri);
+        TBool FindAuth(const TDesC8& aQop) const;
+        void GenerateCNonce(TDes8& aNonce);
+        void Hash(const TDesC8& aMessage, TDes8& aHash);
+        void HATwoL(const RStringF& aMethod, const RString& aRequestUri, const TDesC8& aHentity, TDes8& aResult);
+        void HAOneL(const RString& aUsername,const RString& aPW, const RString& aRealm, TDes8& aResult);
+        void DigestCalcL( const TDesC8& aHentity,TDes8& result );
+        TInt CheckRspAuthL( RHTTPTransaction aTransaction );
+
+    private:
+        // The digest calculator
+        CMD5*               iMD5Calculator;
+        // A seed for random numbers, used for client nonces.
+        TInt64              iSeed;
+        MHttpRequestEvents* iEventSink;
+        MHTTPDataSupplier*  iRespBody;
+        HBufC8*             iResponse;
+        TBool               iSucceeded;
+        RString             iUsername;
+        RString             iPassword;
+        RString             iNonce;
+        RString             iCnonce;
+        RString             iUri; 
+        RString             iRealm;
+        RStringF            iMethod;
+        M3GPPAuthenticationCallback* iDataRetrieverCallBack;
+    };
+
+
+
+class CDataRetriever : public CBase, public MHttpRequestEvents
+    {
+    public:
+        static CDataRetriever* NewLC( MBootstrapCallBack* aBootstrapCallBack );
+        static CDataRetriever* NewL( MBootstrapCallBack* aBootstrapCallBack );
+        ~CDataRetriever();
+        void MakeRequestL( TRequestStatus* aRequestStatus,
+                           const TDesC8& aIdentity,
+                           const TDesC8& aRealm,
+                           const TDesC8& aBsfUri,
+                           const TDesC8& aReferrerNAFUri,
+                           const TInt& aIAPID ); 
+                           
+        void CancelRequest();
+        HBufC8 * QueryResponseValueL();
+        // event from httphandler when request has been completed, 
+        //aErrorCode is standard symbian error codes
+        void EventRequestCompletedL(TInt aErrorCode);
+  
+    private:
+        void SetHeaderL(RHTTPHeaders aHeaders, TInt aHdrField, const TDesC8& aHdrValue);
+        void SetupSessionL( const TInt& aIAPID );
+        TUint32 GetInternetDestIDL();
+        CDataRetriever( MBootstrapCallBack* aBootstrapCallBack );
+        void ConstructL();
+        TBool ValidateGivenIAPIDL( const TInt& aIAPID );
+    
+    private:
+        enum TInternalState
+            {
+            EReadyForRequest,   //  Ready and waiting for MakeRequest call
+            EMakeRequestCalled, //  Request function was called, now waiting for http request to complete
+            };
+            
+    private:
+          TInternalState            iInternalState;
+          TRequestStatus*           iCallerRequestStatus;   // status of the caller
+          RHTTPSession              iHTTPSession;
+          RHTTPTransaction          iHTTPTransaction;
+          RConnection               iConnection;
+          RSocketServ               iSockServ;
+          C3GPPBootstrapHttpHandler* iHttpHandler;          // we own this    
+          MBootstrapCallBack*       iBootstrapCallBack;     // don't own this
+          RCmManagerExt             iCmManagerExt;
+    };
+
+
+
+#endif // DATARETRIEVER_H
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaserver/src/GbaServer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,377 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of CGbaServer
+*
+*/
+
+
+#include <e32svr.h>
+#include <e32math.h>
+#include <s32file.h>
+#include "GbaServer.h"
+#include "GbaSession.h"
+#include "GBALogger.h"
+
+_LIT(KGBAStoreStandardDrive, "C:");
+_LIT(KGbaIniFileName, "GbaConf.ini");
+
+const TInt KPrivateFilepathLength = 20; 
+
+// -----------------------------------------------------------------------------
+// CGbaServer::CGbaServer()
+// -----------------------------------------------------------------------------
+//
+CGbaServer::CGbaServer():CPolicyServer( EPriorityStandard, GBAPolicy, ESharableSessions )
+    {
+    // Implementation not required
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaServer::~CGbaServer()
+// -----------------------------------------------------------------------------
+//
+CGbaServer::~CGbaServer()
+    {
+    GBA_TRACE_DEBUG(("CGbaServer::~CGbaServer"));
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaServer::NewL()
+// -----------------------------------------------------------------------------
+//
+CGbaServer* CGbaServer::NewL()
+    {
+    CGbaServer* self = CGbaServer::NewLC();
+    CleanupStack::Pop( self ) ;
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaServer::NewLC()
+// -----------------------------------------------------------------------------
+//
+CGbaServer* CGbaServer::NewLC()
+    {
+    CGbaServer* self = new (ELeave) CGbaServer();
+    CleanupStack::PushL( self ) ;
+    self->ConstructL() ;
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaServer::ConstructL()
+// -----------------------------------------------------------------------------
+//
+void CGbaServer::ConstructL()
+    { 
+    StartL( KGbaServerName ) ;
+    iShutdown.ConstructL();
+    if(!iShutdown.IsActive())
+        {
+        iShutdown.Start();
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaServer::ConstructL()
+// -----------------------------------------------------------------------------
+//
+CSession2* CGbaServer::NewSessionL(const TVersion& aVersion, const RMessage2& /*aMessage*/) const
+    {
+    GBA_TRACE_DEBUG(("Creating NewSessionL"));
+    // check we're the right version
+    if (!User::QueryVersionSupported(TVersion(KGbaServMajorVersionNumber,
+                                              KGbaServMinorVersionNumber,
+                                              KGbaServBuildVersionNumber),
+                                              aVersion))
+        {
+        GBA_TRACE_DEBUG(("Version isn't supported"));
+        User::Leave(KErrNotSupported);
+        }
+    CGbaServerSession* session = CGbaServerSession::NewL();
+    return session;
+    
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaServer::IncrementSessions()
+// -----------------------------------------------------------------------------
+//
+void CGbaServer::IncrementSessions()
+    {
+    GBA_TRACE_DEBUG(("CGbaServer::IncrementSessions"));
+    iSessionCount++;
+    iShutdown.Cancel();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaServer::DecrementSessions()
+// -----------------------------------------------------------------------------
+//
+void CGbaServer::DecrementSessions()
+    {
+    GBA_TRACE_DEBUG(("CGbaServer::DecrementSessions"));
+    if ( --iSessionCount == 0 )
+        {
+        if(!iShutdown.IsActive())
+            {
+            iShutdown.Start();
+            }
+        }
+    GBA_TRACE_DEBUG(("CGbaServer::DecrementSessions END"));
+    }
+
+
+// -----------------------------------------------------------------------------
+// CGbaServer::ReadOptionL()
+// -----------------------------------------------------------------------------
+//
+TBool CGbaServer::ReadOptionL(const TUid& aOptionID, TDes8& aValue) const
+    {
+    GBA_TRACE_DEBUG(("ReadOptionL"));
+    TInt pushCount = 0;
+    TInt result = EFalse;
+    RFs fs;
+       
+    User::LeaveIfError( fs.Connect() );
+    CleanupClosePushL( fs );
+    pushCount++; 
+    TFindFile folder( fs );
+  
+    TFileName fullPath;
+    MakePrivateFilenameL(fs, KGbaIniFileName, fullPath);
+  
+    TInt err = folder.FindByDir( fullPath, KNullDesC);
+  
+    if (  err != KErrNone )
+        {
+        CleanupStack::PopAndDestroy( pushCount );
+        return result;
+        }
+    else
+       {
+       CDictionaryFileStore* pStore = CDictionaryFileStore::OpenLC( fs, fullPath , KGbaIniUid );   
+       pushCount++;
+
+       if ( pStore->IsPresentL( aOptionID ) )
+          {          
+          RDictionaryReadStream drs;
+          CleanupClosePushL( drs );
+          drs.OpenL(*pStore,aOptionID); 
+
+          TInt length = drs.ReadInt32L();
+          drs.ReadL(aValue,length); 
+          CleanupStack::PopAndDestroy( &drs );
+          result = ETrue;
+          }
+       }
+
+     CleanupStack::PopAndDestroy( pushCount );
+     return result;
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CGbaServer::WriteOptionL()
+// -----------------------------------------------------------------------------
+//
+void CGbaServer::WriteOptionL(const TUid& aOptionID, const TDesC8& aValue) const
+    {
+    GBA_TRACE_DEBUG(("WriteOptionL"));
+    TInt pushCount = 0;
+    RFs fs;
+    User::LeaveIfError(fs.Connect());
+    CleanupClosePushL( fs );
+    pushCount++;
+    TFindFile folder( fs );
+     
+    TFileName fullPath;
+    MakePrivateFilenameL(fs, KGbaIniFileName, fullPath);
+    EnsurePathL(fs, fullPath );
+    
+    GBA_TRACE_DEBUG(fullPath); 
+     
+    TInt err = folder.FindByDir( fullPath, KNullDesC);
+  
+    if (  err == KErrNotFound || err == KErrNone )  
+       {
+       CDictionaryFileStore* pStore = CDictionaryFileStore::OpenLC( fs, fullPath, KGbaIniUid );   
+       pushCount++;       
+
+       RDictionaryWriteStream wrs;
+       CleanupClosePushL( wrs );
+       wrs.AssignL(*pStore,aOptionID);
+       
+       wrs.WriteInt32L(aValue.Length());
+       wrs.WriteL(aValue);
+       wrs.CommitL();
+       
+       pStore->CommitL();  
+       CleanupStack::PopAndDestroy( &wrs );
+       CleanupStack::PopAndDestroy( pushCount );     
+       GBA_TRACE_DEBUG(aValue);
+       }
+    else
+        {
+        CleanupStack::PopAndDestroy( pushCount );    
+        User::LeaveIfError( err );
+        }
+    }
+
+
+
+// ---------------------------------------------------------------------------
+// CGbaServer::MakePrivateFilenameL()
+// ---------------------------------------------------------------------------
+//
+void CGbaServer::MakePrivateFilenameL(RFs& aFs, const TDesC& aLeafName, 
+                                     TDes& aNameOut) const
+    {
+    aNameOut.Copy(KGBAStoreStandardDrive);
+    // Get private path
+    TBuf<KPrivateFilepathLength> privatePath;
+    aFs.PrivatePath(privatePath);
+    aNameOut.Append(privatePath);
+    aNameOut.Append(aLeafName);
+    }
+    
+      
+// ---------------------------------------------------------------------------
+// CGbaServer::EnsurePathL()
+// ---------------------------------------------------------------------------
+//      
+void CGbaServer::EnsurePathL( RFs& aFs, const TDesC& aFile ) const
+    {
+    TInt err = aFs.MkDirAll(aFile);
+    if (err != KErrNone && err != KErrAlreadyExists)
+        {
+        User::Leave(err);
+        }
+    } 
+    
+    
+// -----------------------------------------------------------------------------
+// CShutdown::CShutdown
+// -----------------------------------------------------------------------------
+//
+inline CShutdown::CShutdown()
+  :CTimer(-1)
+    {
+    CActiveScheduler::Add(this);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CShutdown::ConstructL
+// -----------------------------------------------------------------------------  
+//
+inline void CShutdown::ConstructL()
+    {
+    CTimer::ConstructL();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CShutdown::Start
+// -----------------------------------------------------------------------------  
+//
+inline void CShutdown::Start()
+    {
+    GBA_TRACE_DEBUG(("GbaServer: starting shutdown timeout"));
+    After( EGbaServerShutdownDelay );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CShutdown::RunL
+// -----------------------------------------------------------------------------  
+//
+void CShutdown::RunL()
+    {
+    GBA_TRACE_DEBUG(("GbaServer: server timeout ... closing"));
+    CActiveScheduler::Stop();
+    }
+
+// ======== LOCAL FUNCTIONS ========
+
+// --------------------------------------------
+// PanicClient()
+// -------------------------------------------- 
+//
+void PanicClient( const RMessage2& aMessage, TInt aPanic )
+    {
+    aMessage.Panic( KGbaServer, aPanic );
+    }
+
+
+// --------------------------------------------
+// PanicServer()
+// -------------------------------------------- 
+//
+void PanicServer( TInt aPanic )
+    {
+    User::Panic( KGbaServer, aPanic );
+    }
+
+
+// --------------------------------------------
+// RunServerL()
+// -------------------------------------------- 
+//
+static void RunServerL()
+    {
+    // Construct active scheduler
+    CActiveScheduler* activeScheduler = new (ELeave) CActiveScheduler;
+    CleanupStack::PushL(activeScheduler) ;
+    CActiveScheduler::Install(activeScheduler);
+    // Construct our server
+    CGbaServer* server = CGbaServer::NewLC();    
+    RProcess::Rendezvous(KErrNone);
+    // Start handling requests
+    CActiveScheduler::Start();
+    CleanupStack::PopAndDestroy( server );
+    CleanupStack::PopAndDestroy( activeScheduler );
+    }
+
+
+// --------------------------------------------
+// E32Main:()
+// -------------------------------------------- 
+//
+TInt E32Main()
+    {
+ __UHEAP_MARK;
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+    
+    TInt err = KErrNoMemory;
+    
+    if ( cleanup )
+        { 
+        TRAP(err, RunServerL());
+        delete cleanup;
+        }
+__UHEAP_MARKEND;
+    return err;
+    }
+    
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaserver/src/GbaSession.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,261 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of CGbaServerSession
+*
+*/
+
+
+#include <e32svr.h>
+#include "GbaSession.h"
+#include "bootstrap.h"
+#include "GBALogger.h"      
+//Constants
+const TInt KMessageIndex0 = 0;
+const TInt KMessageIndex1 = 1;
+
+// ---------------------------------------------------------------------------
+// CGbaServerSession* CGbaServerSession::NewL()
+// ---------------------------------------------------------------------------
+//
+CGbaServerSession* CGbaServerSession::NewL()
+    {
+    CGbaServerSession* self=new(ELeave) CGbaServerSession;
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGbaServerSession::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CGbaServerSession::ConstructL()
+    {
+    i3GPPBootstrap = C3GPPBootstrap::NewL( this );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGbaServerSession::CGbaServerSession()
+// ---------------------------------------------------------------------------
+//
+CGbaServerSession::CGbaServerSession()
+    {
+    // Implementation not required
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGbaServerSession::~CGbaServerSession()
+// ---------------------------------------------------------------------------
+//
+CGbaServerSession::~CGbaServerSession()
+    {
+    GBA_TRACE_DEBUG(("CGbaServerSession destructor"));
+    Server()->DecrementSessions();
+    GBA_TRACE_DEBUG((" delete state machine"));
+    delete i3GPPBootstrap;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGbaServerSession::ServiceL()
+// ---------------------------------------------------------------------------
+//
+void CGbaServerSession::ServiceL(const RMessage2& aMessage)
+    {
+    GBA_TRACE_DEBUG(("CGbaServerSession::ServiceL"));   
+    switch (aMessage.Function())
+        {
+        case EGbaServRequestBootstrap:
+            {
+            GBA_TRACE_DEBUG(("Request bootstrap")); 
+            RequestBootstrapL(aMessage);
+            }
+            break ;
+        
+        case EGbaServIsGBAUSupported:
+            {
+            GBA_TRACE_DEBUG(("Check is GBA-U supported"));    
+            TBool isGBAUSupported = i3GPPBootstrap->GBAUAvailabilityL();
+            
+            if ( isGBAUSupported )
+                {
+                GBA_TRACE_DEBUG(("GBA-U is available"));    
+                }
+            else
+                {
+                GBA_TRACE_DEBUG(("GBA-U is not available"));
+                }
+            
+            const TPckgC<TBool> pckg( isGBAUSupported );
+            aMessage.Write( KMessageIndex0, pckg ); 
+            aMessage.Complete( KErrNone ); 
+            }
+            break;
+            
+        case EGbaServCancelRequestBootstrap :
+            {
+            GBA_TRACE_DEBUG(("Cancelling bootstrapping"));
+            if ( i3GPPBootstrap->GetState() != C3GPPBootstrap::EIdle )
+                {
+                i3GPPBootstrap->CancelBootstrap();
+                // complete original bootstrapping
+                iMessage.Complete(KErrCancel); 
+                // complete the message for canceling
+                aMessage.Complete(KErrNone);
+                }
+            else
+                {
+                aMessage.Complete(KErrNone);
+                } 
+            } 
+            break ;
+
+        case EGbaServWriteOption :
+            {
+            GBA_TRACE_DEBUG(("CGbaServerSession::ServiceL EGbaServWriteOption"));   
+
+            //Get the dictionary store UID           
+            TUid uid = TUid::Uid(aMessage.Int0());
+            
+            //First get the length of descriptor
+            TInt length = aMessage.GetDesLength(1);
+            
+            // If bigger than 256,
+            // we think it is an attack. 
+            if ( length <= 0 || length > KMaxURLLength )
+                {
+                aMessage.Complete( KErrBadDescriptor );
+                break;
+                }
+            
+            //read the content
+            HBufC8 *buf = HBufC8::NewLC( length );
+            TPtr8 ptrbuf = buf->Des();
+            aMessage.Read(KMessageIndex1,ptrbuf,0);
+                       
+            Server()->WriteOptionL( uid,*buf );
+            aMessage.Complete( KErrNone );
+            CleanupStack::PopAndDestroy( buf );
+            }
+            break;
+                   
+        default :
+            {
+            GBA_TRACE_DEBUG(("Unexpected request"));
+            aMessage.Complete(KErrArgument);
+            }
+            
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGbaServerSession::RequestBootstrapL()
+// ---------------------------------------------------------------------------
+//
+void CGbaServerSession::RequestBootstrapL(const RMessage2& aMessage)
+    {
+    if ( i3GPPBootstrap->GetState() != C3GPPBootstrap::EIdle )
+        {
+        // We're already busy
+        aMessage.Complete(KErrInUse);
+        return;
+        }
+    else
+        {
+        // Keep a copy of message - for use later
+        iMessage = aMessage ;
+        
+        TPtr8 inputPtr(reinterpret_cast <TUint8*>(&iGbaInputParams), sizeof(TGBABootstrapInputParams), sizeof(TGBABootstrapInputParams));
+        
+        //Sanity checking
+        //First get the length of descriptor
+        TInt inputDesLength = aMessage.GetDesLength(0);
+                   
+        // if the length is not eqaul to the size of gba credentails
+        // return bad descriptor
+       if ( inputDesLength != sizeof(TGBABootstrapInputParams))
+           {
+           aMessage.Complete( KErrBadDescriptor );
+           return;
+           }
+        
+        aMessage.Read(KMessageIndex0,inputPtr,0);
+        
+        //Initialize bootstrap process using the state machine
+        i3GPPBootstrap->InitializeL();
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGbaServerSession::StateMachineCallBack()
+// bootstrap state machine call back function
+// Copy the credentail back to client and complete the RMessage
+// If something wrong, complete RMessage with error value
+// ---------------------------------------------------------------------------
+//
+void CGbaServerSession::StateMachineCallBack( TInt aError )
+    {
+    if ( i3GPPBootstrap->GetState() != C3GPPBootstrap::EIdle )
+        {
+        if ( aError == KErrNone )
+            {
+            GBA_TRACE_DEBUG(("B-TID to be sent"));
+            GBA_TRACE_DEBUG(iGbaOutputParams.iBTID);
+            GBA_TRACE_DEBUG(("KsNAF to be sent"));
+            GBA_TRACE_DEBUG_BINARY(iGbaOutputParams.iKNAF);
+            // Write the obtained Gba Bootstrap Creds data back to the client
+            TPtr8 gbaBuffer(NULL,0,0);
+            gbaBuffer.Set(reinterpret_cast <TUint8*>(&iGbaOutputParams), sizeof(TGBABootstrapOutputParams), sizeof(TGBABootstrapOutputParams));
+            TInt res = iMessage.Write(KMessageIndex1, gbaBuffer,0);
+            GBA_TRACE_DEBUG_NUM(("writing message to client with return value = %d."),res);
+            iMessage.Complete( res );
+            } 
+        else 
+            {
+            GBA_TRACE_DEBUG((" Didn't get bootstrap credentails, pass error back"));     
+            // send error message to client     
+            iMessage.Complete( aError );
+            }
+        
+        }
+    }
+    
+
+
+// ---------------------------------------------------------------------------
+// CGbaServerSession::CreateL()
+// ---------------------------------------------------------------------------
+//
+void CGbaServerSession::CreateL()
+    {
+    Server()->IncrementSessions();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGbaServerSession::Server()
+// ---------------------------------------------------------------------------
+//
+CGbaServer* CGbaServerSession::Server()
+      {
+      return static_cast<CGbaServer*>(const_cast<CServer2*>(CSession2::Server()));
+      }
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaserver/src/bootstrap.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1644 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of bootstrap functions
+*
+*/
+
+
+// This component has the following responsibilities 
+// 1. Allow configuration of the BSF URL   
+// 2. Open http connection to bsf    
+// 3. On digest auth req get nonce  
+// 4. Use this to find RAND AUTN 
+// 5. Execute SIM auth, get back SRES, IK,CK 
+// 6. return SRES 
+// 7. Store keymaterial  to a token   
+
+#include <imcvcodc.h>                   //for base64 en/decoding
+#include <ecom.h>
+#include "dataretriever.h"
+#include "bootstrap.h" 
+#include "GbaCommon.h"
+#include "GBALogger.h"
+#include "GbaSession.h"
+
+const TInt KKsNAFMaxLength = 128;
+const TInt KStringLength = 80;
+const TInt KMaxLengthIMPI = 255;
+const TInt KMaxLengthNAFID = 255; 
+const TInt KMaxLengthBTID = 255;
+const TInt KMaxLengthKs = 32;
+const TInt KMaxLengthRES = 16;          //16 bytes for RES
+const TInt KMaxLengthAUTS = 16;         //16 bytes for AUTS
+const TInt KMaxLengthEnAUTS = 20;
+const TInt KMaxLengthRAND = 16;         //16 bytes for RAND
+const TInt KMaxLengthTimeString = 30 ;
+const TInt KHTTPTagLength = 7;
+const TInt KAlgorithmTybeBufferLength = 32;
+const TInt KBufferSize255 = 255;
+const TInt KVariableIndex0 = 0;
+const TInt KVariableIndex1 = 1;
+const TInt KVariableIndex2 = 2;
+const TInt KVariableIndex3 = 3;
+const TInt KVariableIndex4 = 4;
+const TInt KVariableIndex5 = 5;
+const TInt KVariableIndex6 = 6;
+
+#define GBA_UICC_INTERFACE_IMPLE        0x20029F0F
+#define GBA_SOFTISIM_INTERFACE_IMPLE    0x20029F0E
+
+// XML tags
+_LIT8(KBTIDFlag,"<btid>");
+_LIT8(KBTIDEndFlag,"</btid>");
+_LIT8(KLifetimeFlag,"<lifetime>");
+_LIT8(KLifetimeEndFlag,"</lifetime>");
+_LIT(KGbaCredentialsFileName, "GbaCredentials.dat");
+_LIT(KGBAStoreStandardDrive, "C:");
+_LIT(KTimeFormat, "time %d,%d,%d,%d,%d,%d");
+_LIT(KErrorMessage, "FAILED error = %d");
+_LIT(Kakav1, "akav1");
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::NewL()
+// -----------------------------------------------------------------------------
+//
+C3GPPBootstrap* C3GPPBootstrap::NewL( CGbaServerSession* aSession )
+    {
+    C3GPPBootstrap* self = NewLC( aSession );
+    CleanupStack::Pop(self);
+    return(self) ;
+    }
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::NewLC()
+// -----------------------------------------------------------------------------
+//
+C3GPPBootstrap* C3GPPBootstrap::NewLC( CGbaServerSession* aSession )
+    {
+    C3GPPBootstrap* self = new (ELeave) C3GPPBootstrap( aSession );
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::~C3GPPBootstrap()
+// -----------------------------------------------------------------------------
+//
+C3GPPBootstrap::~C3GPPBootstrap()
+    {
+    REComSession::DestroyedImplementation(iDtorIDKey);  
+    if(IsActive())
+        Cancel();
+    if( iSmartCardInterface )
+        {
+        iSmartCardInterface->Release();
+        REComSession::FinalClose();
+        }
+    delete iKsNAF;
+    delete iNAFID;
+    delete iRand;
+    delete iBTID;
+    delete iIdentity;
+    delete iMasterKey;
+    delete iDataRetriever;
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::ConstructL()
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrap::ConstructL()
+    {
+    GBA_TRACE_BEGIN();
+
+    GBA_TRACE_DEBUG(("initializing buffers"));
+    iKsNAF = HBufC8::NewL(KKsNAFMaxLength);
+    iBTID = HBufC8::NewL(KMaxLengthBTID);
+    iNAFID = HBufC8::NewL(KMaxLengthNAFID);
+    iIdentity = HBufC8::NewL(KMaxLengthIMPI);
+    iMasterKey = HBufC8::NewL(KMaxLengthKs);
+    iRand = HBufC8::NewL(KMaxLengthRAND);
+
+    GBA_TRACE_DEBUG(("initializing http handler"));
+    iDataRetriever  = CDataRetriever::NewL( this );
+    
+    iImplementationUID.iUid = GBA_UICC_INTERFACE_IMPLE;
+    //if want softisim for testing
+    //iImplementationUID.iUid = GBA_SOFTISIM_INTERFACE_IMPLE;
+    
+    //Interface is initialized based on the plug in
+    if ( !IsPluginExistL() )
+        {
+        GBA_TRACE_DEBUG(("There aren't plug-in existing"));
+        User::LeaveIfError( KErrGeneral );
+        }
+     
+    GBA_TRACE_DEBUG(("requesting uicc handler"));
+    iSmartCardInterface = RequestUICCInterfaceL();
+    GBA_TRACE_DEBUG(("request made"));
+    
+    if ( !iSmartCardInterface )
+        {
+        GBA_TRACE_DEBUG(("Get interface failed"));
+        User::LeaveIfError( KErrGeneral );
+        }
+    
+    CActiveScheduler::Add( this );
+
+    GBA_TRACE_END();
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::C3GPPBootstrap()
+// -----------------------------------------------------------------------------
+//
+C3GPPBootstrap::C3GPPBootstrap( CGbaServerSession* aSession ): CActive( EPriorityStandard ),
+        iSmartCardInterface( NULL ), iLifetime ( 0 ),iGBARunType( ENoType ), iBSState(EIdle), iSession ( aSession )
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CBootstrapStateMachine::InitializeL()
+// ---------------------------------------------------------------------------
+//
+void C3GPPBootstrap::InitializeL()
+    {
+    if ( IsActive() )
+        {
+        User::LeaveIfError( KErrInUse );
+        }
+    
+    iBSState = EInitialize;
+    GBA_TRACE_DEBUG(("Bootstrapping State machine startL()"));
+    iStatus = KRequestPending;
+    SetActive();
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    }
+
+
+// ---------------------------------------------------------------------------
+// C3GPPBootstrap::RunL()
+// ---------------------------------------------------------------------------
+//
+void C3GPPBootstrap::RunL()
+    {
+    GBA_TRACE_DEBUG(("C3GPPBootstrap::RunL() -enter"));
+    
+    GBA_TRACE_DEBUG_NUM(("C3GPPBootstrap::RunL iStatus=%d"), iStatus.Int() );
+    GBA_TRACE_DEBUG_NUM(("C3GPPBootstrap::RunL iBSState=%d"), iBSState );
+    
+    if((iBSState == ECancel) & iStatus.Int() == KErrCancel)
+        {
+        iBSState = EIdle;
+        return;
+        }
+    
+    User::LeaveIfError( iStatus.Int() );
+    
+    switch(iBSState)
+        {
+        case EInitialize:
+            {
+            GBA_TRACE_DEBUG(("C3GPPBootstrap::RunL() - EInitialize"));
+            DoBootstrapL();
+            GBA_TRACE_DEBUG(("C3GPPBootstrap::RunL() - EInitialize end"));
+            break;  
+            }
+           
+        case EBusy:
+            {
+            GBA_TRACE_DEBUG(("C3GPPBootstrap::RunL() - EBusy"));
+            iSession->StateMachineCallBack( iStatus.Int() );
+            Cleanup();
+            GBA_TRACE_DEBUG(("C3GPPBootstrap::RunL() - EBusy end"));
+            break;
+            }
+  
+       default:
+           GBA_TRACE_DEBUG(("C3GPPBootstrap::RunL() - default"));
+           break;
+       }
+    GBA_TRACE_DEBUG(("C3GPPBootstrap::RunL() -exit"));
+    }
+
+
+TInt C3GPPBootstrap::RunError(TInt aError)
+    {
+    GBA_TRACE_DEBUG_NUM(("Failed with error = %d"), aError );
+    iSession->StateMachineCallBack( aError );
+    //Back to EBootstrapIdle
+    iBSState = EIdle;
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// C3GPPBootstrap::DoCancel()
+// ---------------------------------------------------------------------------
+//
+void C3GPPBootstrap::DoCancel()
+    {
+    GBA_TRACE_DEBUG(("C3GPPBootstrap::DoCancel()"));
+    switch(iBSState)
+        {
+         case EInitialize:
+         case EBusy:
+             {
+             GBA_TRACE_DEBUG(("C3GPPBootstrap::DoCancel() EBootstrapDone"));
+             CancelBootstrap();
+             break;
+             }
+        default:
+            break;
+        };
+    Cleanup();
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::CancelBootstrap()
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrap::CancelBootstrap()
+    {
+    GBA_TRACE_BEGIN();
+    iBSState = ECancel;
+    iDataRetriever->CancelRequest();
+    GBA_TRACE_END();
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::DoBootstrapL()
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrap::DoBootstrapL( )
+    {
+
+    HBufC8 *BsfUrl = HBufC8::NewLC(KMaxURLLength);
+    TPtr8 PtrBSFUrl( BsfUrl->Des() );
+    
+    // fetch bsf address override if available
+    if ( !iSession->Server()->ReadOptionL( KGbaBSFConfiguration, PtrBSFUrl ) )
+        {
+        //If no preset bsf, empty the buffer
+        //We will calculate the address ourselves
+        PtrBSFUrl.Zero();
+        }
+    
+    GBA_TRACE_DEBUG((" BSF server address:"));
+    GBA_TRACE_DEBUG( PtrBSFUrl );
+    
+    GetBootstrappingMaterialL(
+                                   PtrBSFUrl,
+                                   iSession->iGbaInputParams.iNAFName,
+                                   iSession->iGbaInputParams.iUICCLabel,
+                                   iSession->iGbaInputParams.iFlags,
+                                   iSession->iGbaInputParams.iProtocolIdentifier,
+                                   iSession->iGbaOutputParams.iKNAF, 
+                                   iSession->iGbaOutputParams.iBTID, 
+                                   iSession->iGbaOutputParams.iLifetime,
+                                   iSession->iGbaOutputParams.iGbaRunType,
+                                   iSession->iGbaInputParams.iAPID );
+    
+    GBA_TRACE_DEBUG(("Bootstrap Request is sent out, let us wait for callback "));
+    
+    CleanupStack::PopAndDestroy( BsfUrl );
+    }
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::GetBootstrappingMaterialL()
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrap::GetBootstrappingMaterialL(
+                                    const TDesC8& aBSFAddress, 
+                                    const TDesC8& aNAFURL,
+                                    const TDesC8& aUICC_LABEL,
+                                    const TUint8& aFlags,
+                                    const TDesC8& aKeyUsage,
+                                    TDes8 &aKsNAF, 
+                                    TDes8 &aBTID,
+                                    TTime &aLifetime,
+                                    EGBARunType& aGBARunType, 
+                                    const TInt& aIAPID )
+    { 
+    GBA_TRACE_BEGIN();
+    //save the return buffer's pointer. Copy the databack when bootstrapping is done
+    iCallerKsNAFBuf = &aKsNAF;
+    iCallerLifetime = &aLifetime;
+    iCallerBTIDBuf  = &aBTID;
+    iCallerGBARunType = &aGBARunType;
+
+    TUriParser8 uriparser;
+    
+
+    GBA_TRACE_DEBUG(("the given naf url is:"));    
+    GBA_TRACE_DEBUG(aNAFURL);
+    
+    //this implementation is used to solve symbian API's problem
+    // when parsing pure ip address
+    if ( (aNAFURL.FindF(KHTTPTag) != KErrNotFound) || (aNAFURL.FindF(KHTTPSTag) != KErrNotFound) )
+        {
+        //the naf url has http tag
+        User::LeaveIfError( uriparser.Parse(aNAFURL) );
+        } 
+    else
+        {
+        GBA_TRACE_DEBUG(("the naf url has no http tag, add one for parser"));
+        HBufC8* temp = HBufC8::NewL( aNAFURL.Length() +  KHTTPTagLength );
+        CleanupStack::PushL(temp);
+        TPtr8 ptrtemp = temp->Des();
+        ptrtemp.Copy( KHTTPTag );
+        ptrtemp.Append(aNAFURL);
+        GBA_TRACE_DEBUG( *temp );
+        User::LeaveIfError( uriparser.Parse( *temp ) );
+        CleanupStack::PopAndDestroy(temp);
+        }
+    
+  
+    //Calculate the NAFID, NAFID= NAF_FQDN + keyusage
+    
+    TPtr8 ptrNAFID = iNAFID->Des();
+    //parse the FQDN out from NAFaddress
+    ptrNAFID.Copy( uriparser.Extract(EUriHost) );
+    ptrNAFID.Append( aKeyUsage );
+    
+    GBA_TRACE_DEBUG(("NAF ID ="));
+    GBA_TRACE_DEBUG(*iNAFID);
+    
+    
+    GBA_TRACE_DEBUG(("UICC label is:"));
+    GBA_TRACE_DEBUG(aUICC_LABEL);
+  
+    // Get IMPI   
+    TPtr8 ptrIdentity = iIdentity->Des();
+    //Clean the buffer and Set Length to 0
+    ptrIdentity.Zero();
+  
+    //get the IMPI from smart card
+    iSmartCardInterface->QueryIdentityL(ptrIdentity);
+  
+    GBA_TRACE_DEBUG(("IMPI is:"));
+    GBA_TRACE_DEBUG( *iIdentity );
+  
+    // Get GBA_U availability 
+    // EFalse means the call is not from gba client directly.
+    iGBAUAvailable = CheckGBAUAvailabilityL( EFalse );
+
+  
+    if ( iGBAUAvailable )
+        {
+        GBA_TRACE_DEBUG(("GBA-U is available"));    
+        }
+    else
+        {
+        GBA_TRACE_DEBUG(("GBA-U is not available"));
+        }   
+  
+    // Load Credentails from store.
+    // First compare the IMPI and key lifetime
+    // If IMPI is different or key expires, then return EFalse to 
+    // start a new bootstrapping.
+  
+    // If IMPI & key lifetime checking both ok,
+    // GBA_U will load B-TID and key lifetime and ask smart card to 
+    // calculate the Ks_NAF
+    // GBA_ME will load Ks, Rand, B-TId and key lifetime and calculate it
+    // by ourselves.
+    
+    // The GBA run type is also taken from cached store
+    
+    if( !(aFlags & EGBAForce) && LoadCredentialsL() ) 
+        {
+        GBA_TRACE_DEBUG(("Still ok ???"));
+        iStatus = KRequestPending;
+        SetActive();
+        iBSState = EBusy;
+        TRequestStatus* callerStatus = &iStatus;
+        User::RequestComplete(callerStatus, KErrNone);
+        return;
+        }
+  
+    // check if the BSF URL was overriden
+    TBuf8<KMaxURLLength> BsfUrl;
+    
+    if ( aBSFAddress.Length() == 0 )
+        {
+        GBA_TRACE_DEBUG(("No preset BSF URL, calcuate from IMPI"));
+        iSmartCardInterface->QueryHomeNetworkDnL(BsfUrl);
+        }
+    else
+        {
+        if ( iSmartCardInterface->InterfaceIs2G() )
+            { 
+            BsfUrl.Copy( KHTTPSTag );
+            }
+        else
+            {
+            BsfUrl.Copy( KHTTPTag ); 
+            }    
+       BsfUrl.Append( aBSFAddress );
+       }
+  
+    GBA_TRACE_DEBUG(("The bsf url is:"));
+    GBA_TRACE_DEBUG(BsfUrl);
+    
+    // dataretriever makes the actual http connection to the bsf
+    // when it completes values can be retrieved 
+    TUriParser8 uriparser1;
+    User::LeaveIfError( uriparser1.Parse(BsfUrl) );
+    
+    iStatus = KRequestPending;
+    SetActive(); // event should come from bootstrapper 
+    iBSState = EBusy;
+
+    
+    //set reaml as FQDN of bsf
+    iDataRetriever->MakeRequestL( &iStatus, *iIdentity, uriparser1.Extract( EUriHost ), BsfUrl, aNAFURL, aIAPID );
+    GBA_TRACE_END();
+    }
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::GBAUAvailabilityL()
+// -----------------------------------------------------------------------------
+//
+TBool C3GPPBootstrap::GBAUAvailabilityL()
+    {
+    //the call is from gba client directly
+    return CheckGBAUAvailabilityL( ETrue );
+    }
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::GetState()
+// -----------------------------------------------------------------------------
+//
+TInt C3GPPBootstrap::GetState() const 
+    {   
+    return iBSState;  
+    };    
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::CompleteBootStrappingL()
+// This is the callback function called by datareceiver
+// when B-TID and key lifetime is received from BSF
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrap::CompleteBootStrappingL( TInt aError )
+    {
+    // check that we have handler to receive data  
+    GBA_TRACE_DEBUG(("C3GPPBootstrapImpl::CompleteBootStrappingL"));
+
+    // Check if triplet auth failed.
+    if ( aError != KErrNone ) 
+        {
+        GBA_TRACE_DEBUG(("Bootstrap failed"));
+        return;
+        }
+  
+    HBufC8* rspbody = iDataRetriever->QueryResponseValueL();
+    if (!rspbody)
+        {
+        GBA_TRACE_DEBUG(("Error no response body"));
+        User::LeaveIfError( KErrGeneral );
+        }
+    CleanupStack::PushL( rspbody );
+    GBA_TRACE_DEBUG(("response body is received. Loaded response:"));
+    GBA_TRACE_DEBUG(*rspbody);
+
+    // make sure it contains a B-TID
+    TInt p = rspbody->FindC(KBTIDFlag);
+    TInt e = rspbody->FindC(KBTIDEndFlag);
+    if ( p != KErrNotFound && e != KErrNotFound)
+        {
+        p += TPtrC8(KBTIDFlag).Length();
+        TInt length = e-p;
+        
+        //Copy the B-TID value to caller's buffer
+        //Continue getting Ks_(ext)_NAF
+        iCallerBTIDBuf->Copy(rspbody->Mid(p,length)); 
+        
+        //The B-TID needs to be stored in smart card.
+        //Must save here for later use.
+        TPtr8 ptrBTID = iBTID->Des();
+        ptrBTID.Copy(*iCallerBTIDBuf);
+        } 
+    else 
+        {  
+        GBA_TRACE_DEBUG(("Error didn't contain BTID"));
+        CleanupStack::PopAndDestroy(rspbody);
+        User::LeaveIfError( KErrGeneral );
+        }
+  
+    GBA_TRACE_DEBUG(("Extracted B-TID:"));
+    GBA_TRACE_DEBUG(*iBTID);
+
+    TBuf8<KMaxLengthTimeString> LifetimeBuf;
+    p = rspbody->FindC(KLifetimeFlag);
+    e = rspbody->FindC(KLifetimeEndFlag);
+    if ( p != KErrNotFound && e != KErrNotFound )
+        {
+        p += TPtrC8(KLifetimeFlag).Length();
+        TInt length = e-p;
+        LifetimeBuf.Copy( rspbody->Mid(p,length) );
+        } 
+
+    CleanupStack::PopAndDestroy(rspbody);
+
+    GBA_TRACE_DEBUG(("Lifetime in string:"));
+    GBA_TRACE_DEBUG(LifetimeBuf);
+    
+    //Convert the string to TTime object
+    //
+    if ( !ConvertStringToTTime( LifetimeBuf, &iLifetime ) )
+        {
+        GBA_TRACE_DEBUG(("Couldn't convert lifetime"));
+        User::LeaveIfError( KErrGeneral );
+        }
+
+    // Set the lifetime to caller's buffer
+    *iCallerLifetime = iLifetime;
+    
+    //After bootstrap is succesful, the B-TID and keylifetime
+    //should be sent back to smart card to store in GBA_U.
+    if ( iGBAUAvailable )
+        {
+        HBufC8* lifetime = HBufC8::NewLC( LifetimeBuf.Length() );
+        TPtr8 lifetimePtr = lifetime->Des();
+        lifetimePtr.Copy( LifetimeBuf );
+        TInt err = iSmartCardInterface->UpdateGBADataL( *iBTID, *lifetime );
+        CleanupStack::PopAndDestroy( lifetime );
+        User::LeaveIfError( err );
+        iGBARunType = EGBAU;
+        }
+    else
+        {
+        if ( iSmartCardInterface->InterfaceIs2G() )
+            {
+            iGBARunType = E2GGBA;
+            }
+        else
+            {
+            iGBARunType = E3GGBAME;
+            }    
+        }
+
+    // Set the GBA run type back to caller   
+    *iCallerGBARunType = iGBARunType;  
+    // cache the new fangled credentials
+    StoreCredentialsL();
+  
+    // Generate Key material and copy it to parameter being returned 
+    if ( GenerateKeyMaterialL() )
+        {
+    
+        if ( iGBAUAvailable )
+            {
+            GBA_TRACE_DEBUG(("It is GBA_U mode,The ks_ext_naf is calculated by smart card"));
+            GBA_TRACE_DEBUG_BINARY( *iKsNAF); 
+            }
+        else
+            {
+            GBA_TRACE_DEBUG(("It is GBA_ME mode,The ks_naf is calculated by gbamodule"));
+            GBA_TRACE_DEBUG_BINARY( *iKsNAF );  
+            GBA_TRACE_DEBUG(("It is GBA_ME mode,The ks_naf is calculated by gbamodule 1"));
+            }
+        //Set KsNAF back to caller's buffer
+        iCallerKsNAFBuf->Copy(*iKsNAF);     
+        }
+    else
+        {
+        GBA_TRACE_DEBUG(("Error no keys"));
+        User::LeaveIfError( KErrGeneral );
+        }
+    GBA_TRACE_END();
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::GetCredentialsL()
+// function GetCredentialsL
+// discussion:  Gets URI, Realm, Nonce and AuthenticationType, and gives back Username and Password.
+// param: :aURI : the address of the bsf.
+// param: :aRealm : the realm of the bsf.
+// param: :aNonce : the nonce sent by the bsf.
+// param: :aAuthenticationType : the authentication type sent by the bsf.
+// param: :aUsername : Generated Username by underlying algorithm (AKA or SIM).
+// param: :aPassword : Generated Password by underlying algorithm (AKA or SIM).
+// result:  The result of the operation: true for success and false for failure!
+// ----------------------------------------------------------------------------- 
+TBool C3GPPBootstrap::GetCredentialsL(const TUriC8& /*aURI*/, RString aRealm, RString aNonce, 
+                      RString aAlgorithm,
+                      RString& aUsername, 
+                      RString& aPassword,
+                      RString& aResync,
+                      TBool& aResyncRequired)
+    {
+    GBA_TRACE_BEGIN();    
+    
+    // smartcard interface returns true if credentials are received
+    TBool GotKeys = EFalse;
+    TInt pushCount = 0;
+  
+    HBufC *algType=HBufC::NewLC( KAlgorithmTybeBufferLength );
+    pushCount++;
+    
+    TPtr pAlgType(algType->Des());
+    pAlgType.Copy(aAlgorithm.DesC());
+    pAlgType.LowerCase();
+  
+    TInt SecurityAlgorithm;
+    
+    //AuthenticationType MUST be AKAV1-MD5
+    //Find() function returns the offset of the data sequence from the beginning of 
+    //this descriptor's data. KErrNotFound, if the data sequence cannot be found.
+    if ( pAlgType.Find(Kakav1) != KErrNotFound ) 
+        {
+        GBA_TRACE_DEBUG((" algorithm is akav1")); 
+        SecurityAlgorithm = EAKAv1;
+        }
+    else 
+        {
+        GBA_TRACE_DEBUG((" algorithm is unknown")); 
+        SecurityAlgorithm = ESecAlgUnknown;
+        }   
+  
+    HBufC8 *nonce = HBufC8::NewLC(KStringLength);
+    pushCount++;
+
+    TPtr8 ptrNonce = nonce->Des();
+    ptrNonce.Copy(aNonce.DesC());
+    
+    GBA_TRACE_DEBUG((" The base64 encoded nonce value from BSF server (RAND + AUTN)"));
+    GBA_TRACE_DEBUG(aNonce.DesC());
+    GBA_TRACE_DEBUG((" The base64 encoded nonce value after copying into buffer:"));
+    GBA_TRACE_DEBUG(*nonce);
+  
+    //buffer used to store decoded nonce value
+    HBufC8 *decodedNonce = HBufC8::NewLC(KStringLength);
+    pushCount++;
+
+    TPtr8 ptrDecNonce = decodedNonce->Des();
+    
+    //fill the buffer with zeros.
+    ptrDecNonce.FillZ();
+    
+    // decodes the base64 nonce
+    TImCodecB64 b64coder;
+    b64coder.Initialise();
+    b64coder.Decode( *nonce, ptrDecNonce );
+    
+    GBA_TRACE_DEBUG((" The decoded nonce value in binary"));
+    GBA_TRACE_DEBUG_BINARY( *decodedNonce );
+  
+    //Allocate buffer RES, password for http digest
+    HBufC8* RES = HBufC8::NewLC( KMaxLengthRES );
+    pushCount++;
+    TPtr8 ptrRES = RES->Des();
+    
+    //Allocate buffer AUTS, if the out of sync happens        
+    HBufC8* AUTS = HBufC8::NewLC( KMaxLengthAUTS );
+    pushCount++;
+    TPtr8 ptrAUTS = AUTS->Des();
+    
+    GBA_TRACE_DEBUG((" check algorithm value"));
+    switch (SecurityAlgorithm) 
+        {
+    case EAKAv1: 
+        {  
+        GBA_TRACE_DEBUG((" EAKAv1"));  
+        aResyncRequired = EFalse;
+        //Set the RAND AUTN to smart card
+        GotKeys = iSmartCardInterface->QueryAuthenticationL( *decodedNonce, ptrRES, ptrAUTS );
+        
+        TBool AUTSBufEmpty = EFalse;
+
+        // No out of sync detected
+        if ( GotKeys || AUTS->Length() == 0 )
+            {
+            GBA_TRACE_DEBUG(("AUTS is not returned. No out of sync detected"));
+            AUTSBufEmpty = ETrue;
+            }
+          
+        if ( !GotKeys && !AUTSBufEmpty && AUTS->Length()>0 )
+            {
+            aResyncRequired = ETrue;
+            GBA_TRACE_DEBUG(("AUTS is returned. Resync is required"));
+            GBA_TRACE_DEBUG_BINARY(*AUTS);
+            }
+            
+      // keep rand
+      // as the first 16 bytes in Nonce as RAND
+      TPtr8 ptrRand = iRand->Des();
+      ptrRand.Copy( ptrDecNonce.Left(KMaxLengthRAND) );
+      
+      GBA_TRACE_DEBUG(("RAND is:"));
+      GBA_TRACE_DEBUG_BINARY(*iRand);
+      
+      //if GBA_U is available, we donot need to save the 
+      //Ks. It is stored on smart card
+      
+      if( GotKeys && !iGBAUAvailable ) 
+          {
+          // keep master key
+          TPtr8 ptrMasterKey = iMasterKey->Des();
+          if ( !iSmartCardInterface->QueryKs( ptrMasterKey ) )
+              {
+              User::LeaveIfError( KErrGeneral );
+              }   
+          }
+      }
+        break;
+    
+      case ESecAlgUnknown:
+          {
+          User::LeaveIfError( KErrArgument );
+          }
+          break;
+        
+      default:
+           {
+           User::LeaveIfError( KErrArgument );    
+           } 
+        break;
+        }
+  
+
+    GBA_TRACE_DEBUG(("AKA password RES for BSF"));
+    GBA_TRACE_DEBUG_BINARY( *RES );
+  
+    // if received keys or auts then we can attempt to authenticate towards the BSF 
+    // is this code setting the password? Password should be the RES or empty
+        
+    if ( aResyncRequired )
+    //AUTS returned
+        {
+        _LIT8(KEmptyPwd,"");
+        aPassword = aRealm.Pool().OpenStringL(KEmptyPwd);
+        }
+
+    if(GotKeys)
+        {
+        //Set RES as password
+        TRAPD( err,aPassword = aRealm.Pool().OpenStringL(*RES) );
+        err = err;
+        GBA_TRACE_DEBUG_NUM((" Set RES as password error %d"), err );
+        }
+    
+    //Set IMPI as username
+    aUsername = aRealm.Pool().OpenStringL(iIdentity->Des());
+    
+    // convert received auts into a string
+    if ( aResyncRequired )
+        {
+        GBA_TRACE_DEBUG(("adding auts to the headers"));      
+        HBufC8 *encodedAUTS = HBufC8::NewLC( KMaxLengthEnAUTS );
+        pushCount++;
+        TPtr8 ptrEncAUTS = encodedAUTS->Des();
+        ptrEncAUTS.FillZ();
+
+        b64coder.Encode( *AUTS, ptrEncAUTS );
+                
+        GBA_TRACE_DEBUG(*encodedAUTS);
+      
+        aResync = aRealm.Pool().OpenStringL(*encodedAUTS);
+        }
+      
+    CleanupStack::PopAndDestroy(pushCount);
+    GBA_TRACE_END();
+    return GotKeys;
+    }
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::GenerateKeyMaterialL()
+// ----------------------------------------------------------------------------- 
+TBool C3GPPBootstrap::GenerateKeyMaterialL() 
+    {
+    TPtr8 derivedKey(iKsNAF->Des());
+    
+    if ( iGBAUAvailable )
+        {
+        iSmartCardInterface->QueryKeyMaterialL(
+              KNullDesC8,
+              KNullDesC8,
+              iIdentity->Des(),
+              *iNAFID,
+              derivedKey
+              );
+        return ETrue; 
+        }
+    else
+        {
+        iSmartCardInterface->QueryKeyMaterialL(
+                                  iMasterKey->Des(),
+                                  iRand->Des(),
+                                  iIdentity->Des(),
+                                  *iNAFID,
+                                  derivedKey
+                                  );
+        return ETrue; 
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::Cleanup()
+// ----------------------------------------------------------------------------- 
+void C3GPPBootstrap::Cleanup()
+    {
+    GBA_TRACE_DEBUG(("Enter "));
+    iBSState = EIdle;
+    iGBAUAvailable = EFalse;
+    iGBARunType = ENoType;
+    
+    iKsNAF->Des().Zero(); 
+    iBTID->Des().Zero();   
+    iLifetime = 0; 
+
+    iIdentity->Des().Zero(); //buffer for impi
+    iNAFID->Des().Zero();    //buffer for nafid
+    iRand->Des().Zero();     //buffer for rand
+    iMasterKey->Des().Zero(); //buffer for Ks
+    GBA_TRACE_DEBUG(("Exit "));
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::LoadCredentials()
+// GBA_ME, load the cached credentails to calculate ks_naf 
+// ----------------------------------------------------------------------------- 
+TBool C3GPPBootstrap::LoadCredentialsL()
+    {
+    GBA_TRACE_DEBUG(("Enter "));
+    TBool result = EFalse;
+  
+    // check if the values are in memory
+    // IsStillValid needs to be implemented
+    //if( iMasterKey && IsStillValid( &iLifetime ))
+      //{
+      //GBA_TRACE_DEBUG(("using the Ks in memory"));
+      //return ETrue;
+      //}
+    
+    GBA_TRACE_DEBUG(("Checking if the credtials are stored"));
+    
+    RFs fs;
+    User::LeaveIfError( fs.Connect() ); 
+    CleanupClosePushL(fs);
+    TFindFile folder( fs );
+    
+    TFileName fullPath;
+    
+    MakePrivateFilenameL(fs, KGbaCredentialsFileName, fullPath);
+    GBA_TRACE_DEBUG(fullPath);
+    
+    TInt err = folder.FindByDir( fullPath, KNullDesC);
+  
+    if (  err != KErrNone )
+        {
+        GBA_TRACE_DEBUG(("No credentials store available"));
+        CleanupStack::PopAndDestroy(&fs);
+        return result;
+        }
+    else
+        {
+        GBA_TRACE_DEBUG(("Found credentials store "));
+        CDictionaryFileStore* pStore = CDictionaryFileStore::OpenLC(fs,fullPath,KUidGBACredRoot);    
+        
+        TInt length = 0;
+        HBufC8* tmpIdentity = NULL;
+
+        //Read IMPI
+        if ( pStore->IsPresentL( KUidIMPI ) )
+            {
+            GBA_TRACE_DEBUG(("IMPI is present "));
+            RDictionaryReadStream reader;
+            CleanupClosePushL(reader);
+            reader.OpenL(*pStore,KUidIMPI); 
+            length = reader.ReadInt32L();
+            tmpIdentity = HBufC8::NewL(length);
+            TPtr8 ptrtmpIdentity = tmpIdentity->Des();
+      
+            reader.ReadL(ptrtmpIdentity,length);
+            GBA_TRACE_DEBUG(("IMPI = ")); 
+            GBA_TRACE_DEBUG(ptrtmpIdentity);
+            CleanupStack::PopAndDestroy( &reader );
+            }
+        
+        //Read ks
+        if ( pStore->IsPresentL( KUidKs ) )
+            {
+            GBA_TRACE_DEBUG(("Ks is present, the cached credentials are from GBA_ME "));
+            GBA_TRACE_DEBUG(("Ks is present "));
+            RDictionaryReadStream reader1;
+            CleanupClosePushL(reader1);
+            reader1.OpenL(*pStore,KUidKs); 
+            length = reader1.ReadInt32L();
+            
+            TPtr8 ptrmk = iMasterKey->Des();
+            ptrmk.Zero();
+            reader1.ReadL(ptrmk,length);
+            ptrmk.SetLength(length);
+            GBA_TRACE_DEBUG(("Ks = ")); 
+            GBA_TRACE_DEBUG_BINARY(ptrmk);
+            CleanupStack::PopAndDestroy( &reader1 );
+            }
+      
+      
+      //Read rand
+        if ( pStore->IsPresentL( KUidRand ) )
+            {
+            GBA_TRACE_DEBUG(("Rand is present "));
+            RDictionaryReadStream reader2;
+            CleanupClosePushL(reader2);
+            reader2.OpenL(*pStore,KUidRand); 
+            length = reader2.ReadInt32L();
+
+            TPtr8 ptrRand = iRand->Des();
+            ptrRand.Zero();
+            reader2.ReadL(ptrRand,length);
+            ptrRand.SetLength(length);
+            GBA_TRACE_DEBUG(("Rand = ")); 
+            GBA_TRACE_DEBUG_BINARY(ptrRand);  
+            CleanupStack::PopAndDestroy( &reader2 );
+            }  
+        
+        //Read BTID
+        if ( pStore->IsPresentL( KUidBTID ) )
+            {
+            GBA_TRACE_DEBUG(("B-TID is present "));
+            RDictionaryReadStream reader3;
+            CleanupClosePushL(reader3);
+            reader3.OpenL(*pStore,KUidBTID); 
+            length = reader3.ReadInt32L();
+
+            TPtr8 ptrBTID = iBTID->Des();
+            ptrBTID.Zero();
+            reader3.ReadL(ptrBTID,length);
+            ptrBTID.SetLength(length);
+            GBA_TRACE_DEBUG(("BTID = ")); 
+            GBA_TRACE_DEBUG(ptrBTID); 
+            CleanupStack::PopAndDestroy( &reader3 );
+            }
+      
+        //Read key lifetime
+        if ( pStore->IsPresentL( KUidkeylifetime ) )
+            {
+            GBA_TRACE_DEBUG(("key lifetime is present "));
+            RDictionaryReadStream reader4;
+            CleanupClosePushL(reader4);
+            reader4.OpenL(*pStore,KUidkeylifetime); 
+            iLifetime = NULL;
+            TPtr8 ptrkeylifetime((TUint8*)&iLifetime,sizeof(TTime));
+          
+            reader4.ReadL(ptrkeylifetime,sizeof(TTime));
+            GBA_TRACE_DEBUG(("keylifetime = "));
+            GBA_TRACE_TIME( iLifetime );
+            CleanupStack::PopAndDestroy( &reader4 );
+            }  
+      
+        //Read GBA run type
+        if ( pStore->IsPresentL( KUidGBARunType ) )
+            {
+            GBA_TRACE_DEBUG(("GBARunType is present "));
+            RDictionaryReadStream reader5;
+            CleanupClosePushL(reader5);
+            reader5.OpenL(*pStore,KUidGBARunType); 
+            iGBARunType = (EGBARunType)reader5.ReadInt8L();  
+            CleanupStack::PopAndDestroy( &reader5 );
+            }
+      
+      
+        //done with store
+        CleanupStack::PopAndDestroy( pStore );
+	    CleanupStack::PopAndDestroy(&fs);
+                                           
+        result = IsStillValid( &iLifetime ) && *tmpIdentity == *iIdentity;
+        
+        //smart card has been changed
+        if ( *tmpIdentity != *iIdentity )
+            {
+        	iSmartCardInterface->NotifyCardChangeL();
+            }
+        
+        GBA_TRACE_DEBUG(("Cached IMPI = ")); 
+        GBA_TRACE_DEBUG(*tmpIdentity);
+        GBA_TRACE_DEBUG(("IMPI from smart card = ")); 
+        GBA_TRACE_DEBUG(*iIdentity);
+        
+        // this has served its purpose
+        delete tmpIdentity;
+
+        // if the credentials aren't valid delete the old key
+        if ( !result )
+            {
+            GBA_TRACE_DEBUG(("clean buffers since the key wasn't valid anymore or the card had been changed"));
+            // clean up the created buffers;
+            iMasterKey->Des().Zero();
+            iRand->Des().Zero();
+            iBTID->Des().Zero();
+            iLifetime = NULL;
+            }
+        else
+            {
+            GBA_TRACE_DEBUG(("cached keys were still valid"));
+            GBA_TRACE_DEBUG(("Cached B-TID is:"));
+            GBA_TRACE_DEBUG(*iBTID );
+            
+            iCallerBTIDBuf->Copy( *iBTID );
+            
+            // Set the run type
+            *iCallerGBARunType = iGBARunType;
+            
+            //Set key life time
+            *iCallerLifetime = iLifetime;
+            
+            // generate material based on the stored credentials
+            if ( GenerateKeyMaterialL() )
+                {
+                if ( iGBAUAvailable )
+                    {
+                    GBA_TRACE_DEBUG(("Calu from Cached Ks: It is GBA_U mode,The ks_ext_naf is calculated by smart card"));
+                    GBA_TRACE_DEBUG_BINARY( *iKsNAF ); 
+                    GBA_TRACE_DEBUG(("Calu test11"));
+
+                    }
+                else
+                    {
+                    GBA_TRACE_DEBUG(("Calu from Cached Ks. It is GBA_ME mode,The ks_naf is calculated by gbamodule"));
+                    GBA_TRACE_DEBUG_BINARY( *iKsNAF ); 
+                    }
+                    //Set KsNAF back to caller's buffer
+                iCallerKsNAFBuf->Copy(*iKsNAF);       
+                }
+            else
+                {
+                GBA_TRACE_DEBUG(("Error no keys"));
+                result = EFalse;
+                }
+            }
+         GBA_TRACE_DEBUG(("Calu test11"));   
+        }
+    return result;
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::StoreCredentialsL()
+// Store bootstrapping credentails into the store
+// GBA_ME: IMPI, Ks, Rand, B-TID, key lifetime
+// GBA_U:  IMPI, B-TID, key lifetime
+// ----------------------------------------------------------------------------- 
+void C3GPPBootstrap::StoreCredentialsL()
+    {
+    GBA_TRACE_DEBUG(("Save credentials into dictionary store"));
+  
+    RFs fs;    
+    User::LeaveIfError(fs.Connect());
+    CleanupClosePushL(fs);
+    TFindFile folder( fs );
+    
+    TFileName fullPath;
+    
+    MakePrivateFilenameL(fs, KGbaCredentialsFileName, fullPath);
+    EnsurePathL(fs, fullPath );
+
+    GBA_TRACE_DEBUG(fullPath);
+    TInt err = folder.FindByDir( fullPath, KNullDesC );
+  
+    if (  err == KErrNotFound || err == KErrNone || err == KErrPathNotFound )  
+        {
+    
+        CDictionaryFileStore* pStore = CDictionaryFileStore::OpenLC(fs,fullPath,KUidGBACredRoot);   
+        
+        //Save IMPI
+        RDictionaryWriteStream writer;
+        CleanupClosePushL(writer);
+        writer.AssignL(*pStore, KUidIMPI);
+        writer.WriteInt32L(iIdentity->Size());
+        writer.WriteL(*iIdentity);
+        writer.CommitL();
+        CleanupStack::PopAndDestroy( &writer );
+       
+        //GBA_U doesn't need to save ks and rand.
+        if ( !iGBAUAvailable )
+            {
+            GBA_TRACE_DEBUG(("It is GBA_ME, save Ks and Rand"));
+            //Save ks
+            RDictionaryWriteStream writer1;
+            CleanupClosePushL(writer1);
+            writer1.AssignL( *pStore, KUidKs );
+            writer1.WriteInt32L(iMasterKey->Size());
+            writer1.WriteL(*iMasterKey);
+            writer1.CommitL();
+            CleanupStack::PopAndDestroy( &writer1 );
+          
+            //Save Rand
+            RDictionaryWriteStream writer2;
+            CleanupClosePushL(writer2);
+            writer2.AssignL(*pStore,KUidRand );
+            writer2.WriteInt32L(iRand->Size());
+            writer2.WriteL(*iRand);
+            writer2.CommitL();
+            CleanupStack::PopAndDestroy( &writer2 );
+            }
+        else
+            {
+            GBA_TRACE_DEBUG(("It is GBA_U, remove Ks and Rand if there are"));    
+            pStore->RemoveL(KUidKs);
+            pStore->RemoveL(KUidRand);
+            }    
+        //Save B-TID
+        RDictionaryWriteStream writer3;
+        CleanupClosePushL(writer3);
+        writer3.AssignL(*pStore,KUidBTID );
+        writer3.WriteInt32L(iBTID->Size());
+        writer3.WriteL(*iBTID);
+        writer3.CommitL();
+        CleanupStack::PopAndDestroy( &writer3 );
+      
+        //Save key lifetime
+        RDictionaryWriteStream writer4;
+        CleanupClosePushL(writer4);
+        writer4.AssignL(*pStore,KUidkeylifetime );
+        TPtrC8 ptrkeylifetime((TUint8*)&iLifetime,sizeof(TTime));
+        writer4.WriteL(ptrkeylifetime); 
+        writer4.CommitL();
+        CleanupStack::PopAndDestroy( &writer4 );
+      
+        //Save gba run type
+        RDictionaryWriteStream writer5;
+        CleanupClosePushL(writer5);
+        writer5.AssignL(*pStore,KUidGBARunType);
+        writer5.WriteInt8L(iGBARunType);
+        writer5.CommitL();
+        CleanupStack::PopAndDestroy( &writer5 );
+      
+        pStore->CommitL();
+        CleanupStack::PopAndDestroy( pStore );
+        CleanupStack::PopAndDestroy( &fs );     
+        }
+    else
+        {
+        CleanupStack::PopAndDestroy( &fs );
+        User::LeaveIfError( err );    
+        } 
+    }
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::CheckGBAUAvailability()
+// Check the GBA availability from store, if no record there, check from 
+// smart card directly.
+// -----------------------------------------------------------------------------
+TBool C3GPPBootstrap::CheckGBAUAvailabilityL( TBool aIsfromGBAClient )
+    {       
+    TBool GBAUAvailability = EFalse;
+    //Read the record from store
+    TInt result = LoadGBAUAvailabililtyFromStoreL( aIsfromGBAClient, GBAUAvailability );
+    
+    //The store GBA type is GBA_U or GBA_ME
+    if ( result != KErrNotFound && result != KErrGeneral )
+        {
+        //return the cached GBAU availabilty, since smart card is not changed
+        return GBAUAvailability;
+        }
+    else if ( result == KErrGeneral )
+        {
+        //impi is different
+        //delete the whole store
+        RFs fs;
+        User::LeaveIfError( fs.Connect() );
+        CleanupClosePushL(fs);
+        TFileName fullPath;
+        MakePrivateFilenameL(fs, KGbaCredentialsFileName, fullPath);
+        fs.Delete( fullPath );
+        CleanupStack::PopAndDestroy( &fs );
+        }
+    else
+        {
+        //The first time query    
+        } 
+    // There is no record on GBA_U availability or impis are different   
+    // It only happens on the first time when GBA server starts
+    // or after smart card is removed.
+    
+    //retrieve the GBA availability from smart card
+    iSmartCardInterface->QueryGBAUAvailabilityL( GBAUAvailability );
+    
+    SaveGBAUAvailabilityToStoreL( GBAUAvailability );
+    return GBAUAvailability;   
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::LoadGBAUAvailabililtyFromStoreL()
+// -----------------------------------------------------------------------------
+TInt C3GPPBootstrap::LoadGBAUAvailabililtyFromStoreL( TBool& aIsfromGBAClient, TBool& aGBAUAvail )
+    { 
+    GBA_TRACE_DEBUG(("Loading the GBA-U avail from store"));
+    TInt cleanupstack = 0;
+    RFs fs;
+    User::LeaveIfError( fs.Connect() );
+    CleanupClosePushL(fs);
+    cleanupstack++;
+    TFindFile folder( fs );
+    
+    
+    TFileName fullPath;
+    MakePrivateFilenameL(fs, KGbaCredentialsFileName, fullPath);
+    GBA_TRACE_DEBUG(fullPath);
+    TInt err = folder.FindByDir( fullPath, KNullDesC );
+  
+    // the store file is not available  
+    if (  err != KErrNone )
+        {
+        GBA_TRACE_DEBUG(("No store available"));
+        CleanupStack::PopAndDestroy(cleanupstack); 
+        
+        //get impi here, save to store later
+        if ( aIsfromGBAClient )
+            {
+            //retrieve the impi from smart card
+            TPtr8 idPtr = iIdentity->Des();
+            idPtr.Zero();
+            TRAPD(error,iSmartCardInterface->QueryIdentityL(idPtr)); 
+    
+            if( error != KErrNone )
+                {
+                GBA_TRACE_DEBUG((" Can't get IMPI from smart card"));
+                User::LeaveIfError( error );
+                }
+        
+            GBA_TRACE_DEBUG((" got IMPI"));    
+            }
+        return KErrNotFound;
+      }
+    else
+       {
+       GBA_TRACE_DEBUG(("Found store "));
+       CDictionaryFileStore* pStore = CDictionaryFileStore::OpenLC(fs,KGbaCredentialsFileName,KUidGBACredRoot);    
+       cleanupstack++;
+       TInt impiLength = 0;
+       HBufC8* cachedimpi = NULL;
+       TInt8 GBAUAvail = 0;
+       
+       //Read GBA-U avail
+       if ( pStore->IsPresentL( KUidGBAUAvail ) )
+           {
+           GBA_TRACE_DEBUG(("GBAU Avail is present "));
+           RDictionaryReadStream reader;
+           CleanupClosePushL(reader);
+           reader.OpenL(*pStore,KUidGBAUAvail); 
+           GBAUAvail = reader.ReadInt8L();
+           CleanupStack::PopAndDestroy( &reader );
+           }
+            
+       //Read IMPI
+       if ( pStore->IsPresentL( KUidIMPI ) )
+          {
+          GBA_TRACE_DEBUG(("IMPI is present "));
+          RDictionaryReadStream reader1;
+          CleanupClosePushL(reader1);
+          cleanupstack++; 
+          reader1.OpenL(*pStore,KUidIMPI);
+          impiLength = reader1.ReadInt32L();
+        
+          cachedimpi = HBufC8::NewLC(impiLength);
+          cleanupstack++;
+          TPtr8 ptrcachedimpi = cachedimpi->Des();
+      
+          reader1.ReadL(ptrcachedimpi,impiLength);
+          ptrcachedimpi.SetLength(impiLength);
+          GBA_TRACE_DEBUG(("IMPI = ")); 
+          GBA_TRACE_DEBUG(ptrcachedimpi);
+
+          if ( aIsfromGBAClient )
+              {
+              //retrieve the impi from smart card
+              TPtr8 idPtr = iIdentity->Des();
+              idPtr.Zero();
+              TRAPD(error,iSmartCardInterface->QueryIdentityL(idPtr)); 
+    
+              if( error != KErrNone )
+                  {
+                  GBA_TRACE_DEBUG((" Can't get IMPI from smart card"));
+                  User::LeaveIfError( error );
+                  }
+        
+              GBA_TRACE_DEBUG((" got IMPI"));    
+              }
+
+        
+          if( *iIdentity == *cachedimpi )
+              {
+              GBA_TRACE_DEBUG(("IMPI are the same"));    
+              //the impi are the same, return the cached gbau availability
+              CleanupStack::PopAndDestroy(cleanupstack);
+              aGBAUAvail = (TBool)GBAUAvail;
+              return KErrNone;
+              }
+          else
+              {
+              GBA_TRACE_DEBUG(("IMPIs are different"));    
+              //the impi are different, return KErrGeneral
+              iSmartCardInterface->NotifyCardChangeL();
+              CleanupStack::PopAndDestroy(cleanupstack); 
+              return KErrGeneral;    
+              }
+           }
+        else
+           {
+           GBA_TRACE_DEBUG(("no impi present"));    
+           return KErrGeneral;   
+           }  
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::SaveGBAUAvailabilityToStoreL()
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrap::SaveGBAUAvailabilityToStoreL( TBool& aGBAUAvail )
+    {
+    GBA_TRACE_DEBUG(("Save GBA-U avail into dictionary store"));
+  
+    RFs fs;
+    User::LeaveIfError(fs.Connect());
+    CleanupClosePushL(fs);
+    TFindFile folder( fs );
+    
+    TFileName fullPath;
+    MakePrivateFilenameL(fs, KGbaCredentialsFileName, fullPath);
+    EnsurePathL(fs, fullPath );
+    GBA_TRACE_DEBUG(fullPath);
+    TInt err = folder.FindByDir( fullPath, KNullDesC );
+  
+    if (  err == KErrNotFound || err == KErrNone || err == KErrPathNotFound )  
+        {
+    
+        CDictionaryFileStore* pStore = CDictionaryFileStore::OpenLC(fs,fullPath,KUidGBACredRoot);   
+      
+        //Save IMPI
+        RDictionaryWriteStream writer;
+        CleanupClosePushL(writer);
+        writer.AssignL(*pStore, KUidIMPI);
+        writer.WriteInt32L(iIdentity->Size());
+        writer.WriteL(*iIdentity);
+        writer.CommitL();
+        CleanupStack::PopAndDestroy( &writer );    
+        //Save GBA-U avail
+        RDictionaryWriteStream writer1;
+        CleanupClosePushL(writer1);
+        writer1.AssignL(*pStore,KUidGBAUAvail );
+        writer1.WriteInt8L((TInt8)aGBAUAvail);
+        writer1.CommitL();
+        CleanupStack::PopAndDestroy( &writer1 );
+      
+        pStore->CommitL();
+        CleanupStack::PopAndDestroy(pStore);
+        CleanupStack::PopAndDestroy(&fs);
+        GBA_TRACE_DEBUG(("Save GBA-U avail successfully"));    
+        }
+    else
+        {
+        GBA_TRACE_DEBUG(("Save GBA-U avail failed"));
+        CleanupStack::PopAndDestroy(&fs);
+        User::LeaveIfError( err );    
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::IsStillValid()
+// -----------------------------------------------------------------------------
+//
+TBool C3GPPBootstrap::IsStillValid( TTime* aLifetime )
+    {
+    TTime nowTime;
+    nowTime.UniversalTime();
+    GBA_TRACE_DEBUG(("Current Time:"));
+    GBA_TRACE_TIME( nowTime );
+    
+    GBA_TRACE_DEBUG(("Expiry Time:"));
+    GBA_TRACE_TIME( *aLifetime );
+    
+    if( *aLifetime > nowTime )
+        {
+        GBA_TRACE_DEBUG(("key still valid"));
+        return ETrue;
+        }
+    else
+        {
+        GBA_TRACE_DEBUG(("key expired"));
+        return EFalse;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrap::ConvertStringToTTime()
+// -----------------------------------------------------------------------------
+//
+TBool C3GPPBootstrap::ConvertStringToTTime(TDesC8& aLifetimeBuf, TTime* aLifetime)
+{
+  GBA_TRACE_BEGIN();
+  TInt aTimeVariable[KVariableIndex6] = 
+  {
+          0,0,0,0,0,0
+  }; // { year,month,day,hour,minute,second }
+  
+  // assuming the lifetime is given in ISO 8601 format
+  // YYYY-MM-DD or YYYYMMDD (we don't allow YYYYMM or YYYY format, although this isn't specified in the standard)
+  // (year could have a + before it if key is valid beyond year 9999, but we hope that someone will rewrite this within next 8000 years)
+  // there might be a T between date and time we just ignore it
+  // hours 
+  // hh:mm:ss or hhmmss
+  // hh:mm or hhmm
+  // hh
+
+  TInt pos = 0;
+  TInt len = KVariableIndex4;
+  for(TInt variableIndex = 0; variableIndex < KVariableIndex6; variableIndex++)
+  {
+    // if next value isn't a digit we're done
+    if(!TChar(aLifetimeBuf[pos]).IsDigit())
+      break;
+        
+    if(pos + len < aLifetimeBuf.Length())
+    {
+    
+      TLex8 lex(aLifetimeBuf.Mid(pos,len));
+      if(KErrNone  != lex.Val(aTimeVariable[variableIndex]))
+      {
+        GBA_TRACE_DEBUG(("failed"));
+        GBA_TRACE_DEBUG(aLifetimeBuf.Mid(pos,len));
+        return EFalse;
+      }
+      pos += len;
+      
+
+      // remove possible separators
+      if(aLifetimeBuf[pos] == '-' || aLifetimeBuf[pos] == ':')
+        pos += 1;
+      // there can be spaces after month
+      if( variableIndex == KVariableIndex2 )
+        while(pos < aLifetimeBuf.Length() && 
+        (TChar(aLifetimeBuf[pos]).IsSpace() || aLifetimeBuf[pos] == 'T'))
+            pos++;
+      
+    }
+    else
+    { 
+      // if we don't get second it doesn't matter
+      if(variableIndex >= KVariableIndex5)
+        break; 
+      return EFalse;
+    }
+    len = KVariableIndex2; // year is the exception 
+  }
+  // Symbian months and days start from 0, UTC months from 1
+  aTimeVariable[1] = aTimeVariable[1] - 1;
+  aTimeVariable[2] = aTimeVariable[2] - 1;
+
+  TBuf<KBufferSize255> aDBBuf;
+  aDBBuf.Format(KTimeFormat, aTimeVariable[KVariableIndex0],aTimeVariable[KVariableIndex1],aTimeVariable[KVariableIndex2],
+                          aTimeVariable[KVariableIndex3],aTimeVariable[KVariableIndex4],aTimeVariable[KVariableIndex5]);
+  GBA_TRACE_DEBUG(aDBBuf);
+
+  // time should always be in UTC so no need to check the timezone
+  TDateTime dt;
+
+  TRAPD(error,dt.Set(
+    aTimeVariable[KVariableIndex0],
+    (TMonth)(aTimeVariable[KVariableIndex1]), 
+    aTimeVariable[KVariableIndex2],
+    aTimeVariable[KVariableIndex3],
+    aTimeVariable[KVariableIndex4],
+    aTimeVariable[KVariableIndex5],
+    0
+    ));
+
+  if(error != KErrNone)
+  {
+    aDBBuf.Format(KErrorMessage,error);
+    GBA_TRACE_DEBUG(aDBBuf);
+    return EFalse;
+  }
+
+  *aLifetime = dt;
+  
+  GBA_TRACE_END();
+  return ETrue;
+}
+
+
+// ---------------------------------------------------------------------------
+// C3GPPBootstrap::CreateImplementationL()
+// ---------------------------------------------------------------------------
+//
+MUICCInterface* C3GPPBootstrap::RequestUICCInterfaceL()
+    {
+    GBA_TRACE_BEGIN();
+    TAny* ptr = REComSession::CreateImplementationL(iImplementationUID, iDtorIDKey);
+    MUICCInterface* ptyped = static_cast<MUICCInterface*>(ptr);
+    GBA_TRACE_END();
+    return ptyped;
+    }
+
+
+// ---------------------------------------------------------------------------
+// C3GPPBootstrap::IsPluginExistL()
+// ---------------------------------------------------------------------------
+//
+TBool C3GPPBootstrap::IsPluginExistL()
+    {
+    GBA_TRACE_BEGIN();
+    RImplInfoPtrArray array; 
+    // Note that a special cleanup function is required to reset and destroy
+    // all items in the array, and then close it.
+    TCleanupItem cleanup(ResetAndDestroyArray, &array);
+    CleanupStack::PushL(cleanup);  
+
+    REComSession::ListImplementationsL( KGBAUICCInterfaceUID, array );
+    
+    if( array.Count())
+        {
+        CleanupStack::PopAndDestroy(&array); //array, results in a call to ResetAndDestroyArray
+        GBA_TRACE_END();
+        return ETrue;
+        }
+    else
+        {
+        GBA_TRACE_END();
+        CleanupStack::PopAndDestroy(&array); //array, results in a call to ResetAndDestroyArray
+        return EFalse;
+        }
+    }
+
+
+// CleanupEComArray function is used for cleanup support of locally declared arrays
+void ResetAndDestroyArray(TAny* aArray)
+    {
+    GBA_TRACE_BEGIN();
+    (static_cast<RImplInfoPtrArray*> (aArray))->ResetAndDestroy();
+    (static_cast<RImplInfoPtrArray*> (aArray))->Close();
+    GBA_TRACE_END();
+    }
+
+
+// ---------------------------------------------------------------------------
+// C3GPPBootstrap::InterfaceIs2G()
+// ---------------------------------------------------------------------------
+//
+TBool C3GPPBootstrap::InterfaceIs2G() 
+    {
+    return iSmartCardInterface->InterfaceIs2G();
+    }
+    
+    
+// ---------------------------------------------------------------------------
+// C3GPPBootstrap::MakePrivateFilenameL()
+// ---------------------------------------------------------------------------
+//
+void C3GPPBootstrap::MakePrivateFilenameL(RFs& aFs, const TDesC& aLeafName, 
+                                     TDes& aNameOut)
+    {
+    aNameOut.Copy(KGBAStoreStandardDrive);
+    // Get private path
+    TBuf<KStringLength> privatePath;
+    aFs.PrivatePath(privatePath);
+    aNameOut.Append(privatePath);
+    aNameOut.Append(aLeafName);
+    }
+    
+      
+// ---------------------------------------------------------------------------
+// C3GPPBootstrap::EnsurePathL()
+// ---------------------------------------------------------------------------
+//      
+void C3GPPBootstrap::EnsurePathL( RFs& aFs, const TDesC& aFile )
+    {
+    TInt err = aFs.MkDirAll(aFile);
+    if (err != KErrNone && err != KErrAlreadyExists)
+        {
+        User::Leave(err);
+        }
+    }   
+   
+//EOF
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/gbaserver/src/dataretriever.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1358 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of bootstrap and data retriever
+*
+*/
+
+
+#include <e32math.h> 
+#include <hash.h>
+#include <commdb.h>
+#include <es_enum.h>
+#include <centralrepository.h>
+#include <cmconnectionmethodext.h>
+#include <cmconnectionmethoddef.h>
+#include <cmpluginpacketdatadef.h>
+#include <cmdestinationext.h>
+#include <http/thttpevent.h>
+#include "dataretriever.h"
+#include "GbaCommon.h"
+#include "GBALogger.h"
+#include "bootstrap.h"	 
+
+_LIT8(KUserAgent,"S60 GBA 1.0");
+_LIT8(KAccept,"*/*");
+_LIT8(KNCVal_2, ":00000001:");
+_LIT8(Kfopaque,"");
+_LIT8(Kfalgo,"AKAv1-MD5");
+_LIT8(Kalgorithm,"algorithm");
+_LIT8(formatStr, "%02x");
+_LIT8(KAuthInt,"auth-int");
+_LIT8(KAuts,"auts");
+_LIT8(KHTTPAuthInfo,"Authentication-Info");
+_LIT8(KMD5HashofEmpty,"d41d8cd98f00b204e9800998ecf8427e");
+_LIT8(KClose, "Close");
+_LIT(KColon, ":");
+
+
+//Constants
+const TInt KNumber3 = 3;
+const TInt KNumber5 = 5;
+const TInt KNumber8 = 8;
+const TInt KNumber32 = 32;
+const TInt KNumber33 = 33;
+const TInt KNumber34 = 34;
+// Length of a digest hash when represented in hex
+const TInt KHashLength = 32;
+// Length of a digest hash before converting to hex.
+const TInt KRawHashLength = 16;
+const TInt KMaxRequestBuffer = 255;
+const TInt KAlgLength = 40;
+
+// ---------------------------------------------------------------------------
+// CDataRetriever::NewL()
+// ---------------------------------------------------------------------------
+//
+CDataRetriever* CDataRetriever::NewL( MBootstrapCallBack* aBootstrapCallBack )
+    {
+    CDataRetriever* self = NewLC( aBootstrapCallBack );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDataRetriever::NewLC()
+// ---------------------------------------------------------------------------
+//
+CDataRetriever* CDataRetriever::NewLC( MBootstrapCallBack* aBootstrapCallBack )
+    {
+    CDataRetriever* self = new (ELeave) CDataRetriever( aBootstrapCallBack ) ;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDataRetriever::CDataRetriever()
+// ---------------------------------------------------------------------------
+//
+CDataRetriever::CDataRetriever( MBootstrapCallBack* aBootstrapCallBack ) 
+    : iBootstrapCallBack( aBootstrapCallBack ) 
+    { 
+    }
+    
+    
+// ---------------------------------------------------------------------------
+// CDataRetriever::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CDataRetriever::ConstructL()
+    {
+    iHttpHandler = C3GPPBootstrapHttpHandler::NewL( this, iBootstrapCallBack );
+    iInternalState = EReadyForRequest;
+    iCmManagerExt.OpenL();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDataRetriever::~CDataRetriever()
+// ---------------------------------------------------------------------------
+//
+CDataRetriever::~CDataRetriever()
+    {
+    GBA_TRACE_DEBUG(("CDataRetriever::~CDataRetriever"));
+    
+    delete iHttpHandler;
+    iHTTPTransaction.Close();
+    iHTTPSession.Close();
+    iConnection.Close();
+    iSockServ.Close();
+    iCmManagerExt.Close();
+    
+    if ( iInternalState == EMakeRequestCalled )
+        {
+        GBA_TRACE_DEBUG(("CDataRetriever::~CDataRetriever EMakeRequestCalled"));
+        User::RequestComplete(iCallerRequestStatus, KErrCancel);
+        }
+    
+    GBA_TRACE_DEBUG(("CDataRetriever::~CDataRetriever End"));
+    }
+
+// ---------------------------------------------------------------------------
+// CDataRetriever::EventRequestCompletedL()
+// ---------------------------------------------------------------------------
+//
+void CDataRetriever::EventRequestCompletedL(TInt aErrorCode)
+    {
+    GBA_TRACE_DEBUG(("CDataRetriever::EventRequestCompletedL enter"));
+    
+    if ( iInternalState == EMakeRequestCalled )
+        {
+        GBA_TRACE_DEBUG(("CDataRetriever::EventRequestCompletedL EMakeRequestCalled"));
+
+        TRAPD( err, iBootstrapCallBack->CompleteBootStrappingL( aErrorCode ) );
+        if( err == KErrNone )
+            User::RequestComplete(iCallerRequestStatus,aErrorCode);
+        else
+            User::RequestComplete(iCallerRequestStatus, err);
+        // Get Ready for new request
+        iHttpHandler->Reset();
+        iHTTPTransaction.Close();
+        iHTTPSession.Close();
+        iConnection.Close();
+        iSockServ.Close();
+        iInternalState = EReadyForRequest;
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDataRetriever::CancelRequest()
+// ---------------------------------------------------------------------------
+//
+void CDataRetriever::CancelRequest()
+    {
+    GBA_TRACE_DEBUG(("CDataRetriever::CancelRequest"));
+    if ( iInternalState == EMakeRequestCalled )
+        {        
+        iInternalState = EReadyForRequest;
+        iHttpHandler->Reset();
+        iHTTPTransaction.Close();
+        iHTTPSession.Close();
+        iConnection.Close();
+        iSockServ.Close();
+        User::RequestComplete( iCallerRequestStatus, KErrCancel );
+        }
+    }
+    
+    
+// ---------------------------------------------------------------------------
+// CDataRetriever::MakeRequestL()
+// ---------------------------------------------------------------------------
+//
+void CDataRetriever::MakeRequestL(
+                 TRequestStatus* aRequestStatus,
+                 const TDesC8& aIdentity,
+                 const TDesC8& aRealm,
+                 const TDesC8& aBsfUri,
+                 const TDesC8& aReferrerNAFUri,
+                 const TInt& aIAPID )
+    {
+    GBA_TRACE_BEGIN(); 
+    
+    if ( iInternalState != EReadyForRequest )
+        {        
+        User::LeaveIfError( KErrInUse );
+        }
+    
+    iCallerRequestStatus = aRequestStatus;
+  
+    SetupSessionL( aIAPID );
+
+    // Add headers appropriate to all methods
+    TUriParser8 URIParse; 
+
+    User::LeaveIfError( URIParse.Parse( aBsfUri ) );
+
+    iHTTPTransaction = iHTTPSession.OpenTransactionL( URIParse, *iHttpHandler );
+    RHTTPHeaders hdr = iHTTPTransaction.Request().GetHeaderCollection();
+    
+    GBA_TRACE_DEBUG(URIParse.Extract(EUriHost) );
+         
+    SetHeaderL(hdr,HTTP::EHost, URIParse.Extract(EUriHost) );     
+    SetHeaderL(hdr,HTTP::EUserAgent, KUserAgent);
+    SetHeaderL(hdr,HTTP::EAccept, KAccept);     
+    SetHeaderL(hdr,HTTP::EReferer, aReferrerNAFUri);
+    
+    SetHeaderL(hdr, HTTP::EConnection, KClose);
+  
+    TBuf8<KMaxRequestBuffer> bufAuth;
+    bufAuth.Copy(_L8("Digest username=\""));
+    bufAuth.Append(aIdentity);
+    bufAuth.Append(_L8("\", realm=\""));
+    
+    bufAuth.Append(aRealm);
+    bufAuth.Append(_L8("\", nonce=\"\", uri=\"/\", response=\"\""));
+
+    GBA_TRACE_DEBUG(bufAuth);
+    SetHeaderL(hdr,HTTP::EAuthorization,bufAuth);
+    
+    iHTTPTransaction.SubmitL();    
+    iInternalState = EMakeRequestCalled;
+    GBA_TRACE_END();
+    }
+
+// ---------------------------------------------------------------------------
+// CDataRetriever::SetHeaderL()
+// ---------------------------------------------------------------------------
+//
+void CDataRetriever::SetHeaderL(RHTTPHeaders aHeaders, TInt aHdrField, const TDesC8& aHdrValue)
+    {
+    RStringF valStr = iHTTPSession.StringPool().OpenFStringL(aHdrValue);
+    THTTPHdrVal val(valStr);
+    aHeaders.SetFieldL(iHTTPSession.StringPool().StringF(aHdrField,RHTTPSession::GetTable()), val);
+    valStr.Close();
+    }
+
+// ---------------------------------------------------------------------------
+// CDataRetriever::SetupSessionL()
+// Establish a connection for bootstrapping
+// ---------------------------------------------------------------------------
+//
+void CDataRetriever::SetupSessionL( const TInt& aIAPID )
+    {
+    GBA_TRACE_DEBUG(("CDataRetriever::SetupSession"));
+    // check that sockserver is available
+
+    User::LeaveIfError(iSockServ.Connect() );
+    GBA_TRACE_DEBUG(("Socket server connected")); 
+
+    // check that connection is possible
+    User::LeaveIfError(iConnection.Open(iSockServ) );
+    GBA_TRACE_DEBUG(("Connection opened")); 
+    
+    if ( !ValidateGivenIAPIDL( aIAPID ) )
+        {	
+        GBA_TRACE_DEBUG(("No valid iapid from user")); 
+        TConnSnapPref snapPref;
+        TUint32 snapid = GetInternetDestIDL();
+        GBA_TRACE_DEBUG_NUM(("the chosen snap id is %d"), snapid ); 
+        snapPref.SetSnap( snapid );
+        TInt err = iConnection.Start( snapPref );
+        
+        if ( err != KErrNone )
+            {
+            GBA_TRACE_DEBUG_NUM(("internet nap error is %d"), err ); 
+            TCommDbConnPref connPref;
+            connPref.SetDialogPreference( ECommDbDialogPrefPrompt );
+            User::LeaveIfError( iConnection.Start( connPref ) );
+            }    
+       }
+    else
+        {
+        GBA_TRACE_DEBUG(("User gives valid iapid go with it"));
+        //given iapid is valid, go with it
+        TCommDbConnPref connPref;
+        connPref.SetDirection( ECommDbConnectionDirectionOutgoing );
+        
+        //No dialog present
+        connPref.SetDialogPreference( ECommDbDialogPrefDoNotPrompt );
+        connPref.SetIapId( aIAPID );	
+         
+        User::LeaveIfError( iConnection.Start( connPref ) );
+        }
+    
+    GBA_TRACE_DEBUG(("Access point selection done!"));       
+
+    GBA_TRACE_DEBUG(("CDataRetriever::SetupSession, connect choosen is done "));
+    
+    iHTTPSession.OpenL();
+	    
+    //GBA Http  filter gets loaded into to http session when session is opened
+	//Remove GBA http filter from http session iHTTPSession
+    //Reason: Ub interface should not have the User-Agent string "3gpp-gba"
+	RStringF filterName = iHTTPSession.StringPool().OpenFStringL( KHTTPFilterGBAName );
+    CleanupClosePushL<RStringF>( filterName );
+    iHTTPSession.FilterCollection().RemoveFilter( filterName );
+    CleanupStack::PopAndDestroy( &filterName );
+	
+    GBA_TRACE_DEBUG(("Session opened"));  
+    
+    //Set selected access point.
+    RStringPool strPool = iHTTPSession.StringPool();
+    RHTTPConnectionInfo httpconnInfo = iHTTPSession.ConnectionInfo();
+    
+    httpconnInfo.SetPropertyL ( strPool.StringF(HTTP::EHttpSocketServ,
+            RHTTPSession::GetTable() ), THTTPHdrVal (iSockServ.Handle()) );
+    
+    TInt connPtr = REINTERPRET_CAST(TInt, &iConnection);
+
+    httpconnInfo.SetPropertyL ( strPool.StringF(HTTP::EHttpSocketConnection,
+              RHTTPSession::GetTable() ), THTTPHdrVal (connPtr) );
+    
+    //if 2G interface and cert is untrusted, surpress the warning dialog
+    if ( iBootstrapCallBack->InterfaceIs2G() )
+        {
+        //surpress the warning dialog
+        httpconnInfo.SetPropertyL ( strPool.StringF(HTTP::ESecureDialog,
+              RHTTPSession::GetTable() ),strPool.StringF(HTTP::EDialogNoPrompt,
+              RHTTPSession::GetTable() )  );
+        }
+  
+    GBA_TRACE_DEBUG(("SetupSession done")); 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDataRetriever::ValidateGivenIAPIDL()
+// ---------------------------------------------------------------------------
+//
+TBool CDataRetriever::ValidateGivenIAPIDL( const TInt& aIAPID )
+    {
+    using namespace CMManager;
+    GBA_TRACE_DEBUG((" start valid iapid given by user"));
+    //aIAPID == -1 selected default accesspoint
+    if ( aIAPID == -1 )
+        {
+        return EFalse;
+        }
+    else
+        {
+        TInt CleanupCounter = 0;
+   
+        RArray<TUint32> destIdArray;
+        CleanupClosePushL( destIdArray );
+        CleanupCounter++;
+        iCmManagerExt.AllDestinationsL( destIdArray );
+
+        for ( TInt i = 0; i< destIdArray.Count(); i++ )
+           {
+           RCmDestinationExt dest = iCmManagerExt.DestinationL( destIdArray[i] );
+           CleanupClosePushL( dest );
+           CleanupCounter++;
+         
+           for ( TInt j=0; j < dest.ConnectionMethodCount(); j++ )
+              {
+           
+              TUint32 iapId = dest. ConnectionMethodL(j).GetIntAttributeL( ECmIapId );
+              
+              if ( iapId == aIAPID )
+                  {
+                  GBA_TRACE_DEBUG((" IAPID matches !!"));
+                  CleanupStack::PopAndDestroy( CleanupCounter );
+                  return ETrue;
+                  }
+              }
+             
+           CleanupStack::PopAndDestroy( &dest ); //dest
+           CleanupCounter--; // dest
+           }
+        GBA_TRACE_DEBUG((" search is over no matching IAPID!!"));
+        CleanupStack::PopAndDestroy( CleanupCounter );
+        return EFalse;    
+        }    
+    }
+
+// ---------------------------------------------------------------------------
+// CDataRetriever::QueryResponseValueL()
+// ---------------------------------------------------------------------------
+//
+HBufC8* CDataRetriever::QueryResponseValueL() 
+    {
+    return iHttpHandler->GetResponse();
+    } 
+
+// ---------------------------------------------------------------------------
+// CDataRetriever::GetInternetDestIDL()
+// ---------------------------------------------------------------------------
+//
+TUint32 CDataRetriever::GetInternetDestIDL()
+    {
+    using namespace CMManager;
+    GBA_TRACE_DEBUG((" Get the Dest ID of Internet"));
+
+    TInt CleanupCounter = 0;
+   
+    RArray<TUint32> destIdArray;
+    CleanupClosePushL( destIdArray );
+    CleanupCounter++;
+    iCmManagerExt.AllDestinationsL( destIdArray );
+
+    for ( TInt i = 0; i< destIdArray.Count(); i++ )
+         {
+         RCmDestinationExt dest = iCmManagerExt.DestinationL( destIdArray[i] );
+         CleanupClosePushL( dest );
+         CleanupCounter++;
+         
+         if ( dest.MetadataL( ESnapMetadataInternet ) )
+             {
+             GBA_TRACE_DEBUG_NUM((" found the internet dest id = %d"), destIdArray[i] );
+             
+             TUint32 desID = destIdArray[i];
+             CleanupStack::PopAndDestroy( CleanupCounter );
+             return desID; 
+             }
+             
+         CleanupStack::PopAndDestroy( &dest );
+         CleanupCounter--; // dest
+         }
+    GBA_TRACE_DEBUG(("not found the internet dest id") );
+    CleanupStack::PopAndDestroy( CleanupCounter );
+    return NULL;
+	}
+    
+
+// C3GPPBootstrapHttpHandler 
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::ConstructL()
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrapHttpHandler::ConstructL()
+    {
+    iResponse=HBufC8::NewL(KMaxBootstrapRespLen);
+    iMD5Calculator =  CMD5::NewL(); 
+    iSucceeded=EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::C3GPPBootstrapHttpHandler()
+// -----------------------------------------------------------------------------
+//
+C3GPPBootstrapHttpHandler::C3GPPBootstrapHttpHandler( MHttpRequestEvents* aEventSink, M3GPPAuthenticationCallback* aDataRetrieverCallBack )
+        : iEventSink ( aEventSink ), iDataRetrieverCallBack ( aDataRetrieverCallBack )
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::~C3GPPBootstrapHttpHandler()
+// -----------------------------------------------------------------------------
+//
+C3GPPBootstrapHttpHandler::~C3GPPBootstrapHttpHandler()
+    {
+    GBA_TRACE_DEBUG(("C3GPPBootstrapHttpHandler::~C3GPPBootstrapHttpHandler()"));
+    Reset();
+	delete iResponse;
+	delete iMD5Calculator;
+    GBA_TRACE_DEBUG(("C3GPPBootstrapHttpHandler::~C3GPPBootstrapHttpHandler() end"));
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::Reset()
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrapHttpHandler::Reset()
+    {
+    // close strings in string pool if they were opened 
+    iUsername.Close();
+    iPassword.Close();
+    iNonce.Close();
+    iCnonce.Close();
+    iUri.Close();
+    iRealm.Close();
+    iMethod.Close();
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::NewLC()
+// -----------------------------------------------------------------------------
+//
+C3GPPBootstrapHttpHandler* C3GPPBootstrapHttpHandler::NewLC( MHttpRequestEvents* aEventSink, 
+                                                             M3GPPAuthenticationCallback* aDataRetrieverCallBack )
+    {
+    C3GPPBootstrapHttpHandler* me = new(ELeave)C3GPPBootstrapHttpHandler( aEventSink, aDataRetrieverCallBack );
+    CleanupStack::PushL(me);
+    me->ConstructL();
+    return me;
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::NewL()
+// -----------------------------------------------------------------------------
+//
+C3GPPBootstrapHttpHandler* C3GPPBootstrapHttpHandler::NewL( MHttpRequestEvents* aEventSink ,
+                                                            M3GPPAuthenticationCallback* aDataRetrieverCallBack )
+    {
+    C3GPPBootstrapHttpHandler* me = NewLC(aEventSink, aDataRetrieverCallBack );
+    CleanupStack::Pop(me);
+    return me;
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::MHFRunL()
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrapHttpHandler::MHFRunL( RHTTPTransaction aTransaction, const THTTPEvent& aEvent )
+    {
+    GBA_TRACE_DEBUG_NUM(("MHFRunL received event %d"), aEvent.iStatus );
+    
+    switch (aEvent.iStatus)
+       {
+       case THTTPEvent::EGotResponseHeaders:
+          {
+          // HTTP response headers have been received. 
+          // We can determine now if there is going to be a response body to save.
+          GBA_TRACE_DEBUG(("THTTPEvent::EGotResponseHeaders"));
+          RHTTPResponse resp = aTransaction.Response();
+          TInt status = resp.StatusCode();
+          
+          RStringF statusStr = resp.StatusText();
+      
+          // 401 = we received a authorization challenge
+          if ( status == HTTPStatus::EUnauthorized )
+             {
+             // resubmit the transaction and hope for the best
+             TInt result = HandleAuthorizationChallengeL(aTransaction, aEvent);
+             if( result == KErrNone )
+                 {
+                 aTransaction.Cancel();
+                 aTransaction.SubmitL();
+                 }
+             else
+                 {
+                 aTransaction.Cancel();
+                 iEventSink->EventRequestCompletedL( result );
+                 }
+             //a new request with password is sent.
+             return;
+             }
+          TInt responseBodySize = 0;
+      
+          // 200 received, succeeded with body
+          if ( resp.HasBody() && ( status == HTTPStatus::EOk ) )
+              {
+              MHTTPDataSupplier *respbody = resp.Body();
+              if ( respbody )
+                  {
+                  responseBodySize = respbody->OverallDataSize();
+                  GBA_TRACE_DEBUG_NUM(("Response body size is %d"), responseBodySize );
+                  iSucceeded = ETrue;
+                  }
+              }
+          //Reallocate iResponse buffer size if the response size is greater than KMaxBootstrapRespLen
+          if( responseBodySize > KMaxBootstrapRespLen )
+              iResponse = iResponse->ReAllocL( responseBodySize );
+          // we take this opportunity to reset our own buffers
+          TPtr8 ptrResp(iResponse->Des());
+          
+          ptrResp.Zero();
+          } 
+          break;
+      
+      case THTTPEvent::EGotResponseBodyData:
+          {
+          GBA_TRACE_DEBUG(("THTTPEvent::EGotResponseBodyData"));
+          // Get the body data supplier
+          iRespBody = aTransaction.Response().Body();
+      
+          // Some (more) body data has been received (in the HTTP response)
+          // Append to the output file if we're saving responses
+          TPtr8 ptrResp(iResponse->Des());
+          
+          TPtrC8 bodyData;
+          TBool lastChunk = EFalse;
+                    
+          while ( !lastChunk ) 
+              {
+              GBA_TRACE_DEBUG(("THTTPEvent::EGotResponseBodyData in loop"));
+              lastChunk = iRespBody->GetNextDataPart( bodyData );
+              
+              //Issue with formatting string with a special character
+              //GBA_TRACE_DEBUG( bodyData );
+              if ( bodyData.Length() <= ( ptrResp.MaxLength() - ptrResp.Length() ) )
+                  { 
+                  ptrResp.Append( bodyData );  
+                  }
+              else
+                  {
+                  break;  
+                  }
+              } 
+      
+          GBA_TRACE_DEBUG_NUM(("Response body received size is %d"), iResponse->Length() );
+          // Done with that bit of body data
+          iRespBody->ReleaseData();
+          } 
+          break;
+          
+      case THTTPEvent::EResponseComplete:
+          {
+          GBA_TRACE_DEBUG(("THTTPEvent::EResponseComplete"));
+          // The transaction's response is complete
+          } 
+          break;
+          
+      case THTTPEvent::ESucceeded:
+         {
+         GBA_TRACE_DEBUG(("THTTPEvent::ESucceeded || KErrDisconnected"));
+         if ( iSucceeded )
+             {
+              // verify authrsp
+              User::LeaveIfError(CheckRspAuthL(aTransaction));
+              
+              //Set it back
+              iSucceeded=EFalse;
+              
+              GBA_TRACE_DEBUG(("THTTPEvent::ESucceeded || KErrDisconnected 1"));
+              iEventSink->EventRequestCompletedL(KErrNone); 
+             }
+         else
+            {
+            iEventSink->EventRequestCompletedL( KErrDisconnected );        
+            GBA_TRACE_DEBUG(("Connection was closed"));
+            }
+        } 
+        break;
+        
+     case THTTPEvent::EFailed:
+        {
+        GBA_TRACE_DEBUG(("THTTPEvent::EFailed"));
+        RHTTPResponse resp = aTransaction.Response();
+        TInt status = resp.StatusCode();
+        GBA_TRACE_DEBUG_NUM( ("http StatusCode : %d "), status );
+        iEventSink->EventRequestCompletedL( KErrUnknown );
+        } 
+        break;
+     
+     //The transaction is being cancelled. An outgoing event. 
+     case THTTPEvent::ECancel:
+        {
+        GBA_TRACE_DEBUG(("THTTPEvent::ECancel"));
+        aTransaction.Cancel();
+        } 
+        break;
+
+     // this warning can come when going through proxies
+     case THTTPEvent::ERedirectedTemporarily:
+        break;
+        
+     default:
+         {
+         GBA_TRACE_DEBUG_NUM(("Failed with HTTP event event: %d "),aEvent.iStatus );
+         if( aEvent.iStatus < 0 )
+             {
+             // close off the transaction if it's an error
+             aTransaction.Cancel();
+             iEventSink->EventRequestCompletedL( aEvent.iStatus );
+             }
+         } 
+         break;
+       }
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::MHFRunError()
+// -----------------------------------------------------------------------------
+// 
+TInt C3GPPBootstrapHttpHandler::MHFRunError(TInt aError, RHTTPTransaction /*aTransaction*/, const THTTPEvent& aEvent)
+    {
+    GBA_TRACE_DEBUG_NUM(("MHFRunError called with error code = %d"), aError);    
+    GBA_TRACE_DEBUG_NUM(("MHFRunError called with http event = %d"),aEvent.iStatus );
+    // tell caller that there was an error
+    TRAPD(err, iEventSink->EventRequestCompletedL(aError));
+    return err;
+    }
+  
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::HandleAuthorizationChallengeL()
+// -----------------------------------------------------------------------------
+// 
+TInt C3GPPBootstrapHttpHandler::HandleAuthorizationChallengeL( RHTTPTransaction aTransaction, const THTTPEvent& /*aEvent*/ )
+    {
+    GBA_TRACE_BEGIN();
+    TInt pushCount = 0;
+    RStringPool stringPool = aTransaction.Session().StringPool(); 
+    RStringF wwwAuthHeader = stringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable());
+    RHTTPHeaders headers(aTransaction.Response().GetHeaderCollection());
+    
+    //find header which has digest algorithm and qop is auth-int
+    TInt headerPart = FindHeaderPartToUseL( aTransaction );
+
+    if ( headerPart == KErrNotFound )
+        {
+        return KErrArgument;
+        }
+
+    THTTPHdrVal authTypeParam;
+    TInt error = headers.GetField( wwwAuthHeader, headerPart, authTypeParam );
+  
+    // If anything goes wrong, just stop. This will have the effect of
+    // returning the error response from the server to the client.
+    if ( error != KErrNone )
+        {
+        return error;     
+        }
+        
+    TBool    haveUserPW = EFalse;
+    RString  realm;
+    RString  username;
+    RString  password;
+    RString  nonce;
+    RString  algorithm;
+    RString  resync;                  
+  
+    // Get realm value from response header
+    THTTPHdrVal realmVal;
+    error  = headers.GetParam( wwwAuthHeader, 
+                           stringPool.StringF( HTTP::ERealm, RHTTPSession::GetTable() ), realmVal, headerPart ) ;
+    if ( error != KErrNone )
+        {
+        return error;
+        }
+    
+    realm = realmVal.Str();
+    GBA_TRACE_DEBUG(("Realm:"));
+    GBA_TRACE_DEBUG(realm.DesC());
+    
+    THTTPHdrVal nonceVal;
+    //Get nonce value from response header
+    // contain the RAND and AUTH
+    error = headers.GetParam( stringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable()), 
+                              stringPool.StringF(HTTP::ENonce,RHTTPSession::GetTable()),
+                              nonceVal,
+                              headerPart);
+    if ( error != KErrNone )
+        {
+        return error;
+        }
+    
+    nonce=nonceVal.Str();
+    GBA_TRACE_DEBUG(("Nonce:"));
+    GBA_TRACE_DEBUG(nonce.DesC());
+  
+    //Fetch algorithm type
+    THTTPHdrVal algVal;  
+    error = headers.GetParam( stringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable()), 
+                              stringPool.StringF(HTTP::EAlgorithm,RHTTPSession::GetTable()),
+                              algVal,
+                              headerPart);
+    if ( error != KErrNone )
+        {
+        return error;
+        }
+    
+    algorithm=algVal.Str();
+    GBA_TRACE_DEBUG(("Algorithm:"));
+    GBA_TRACE_DEBUG(algorithm.DesC());
+    
+    // If the SQN is out of range, Resync is required
+    TBool resyncrequired = EFalse;
+    
+    //Get password from smart card
+    //The smart card will first authenticate the nonce value 
+    RStringF authType = authTypeParam.StrF(); 
+    
+    TRAP( error, haveUserPW = iDataRetrieverCallBack->GetCredentialsL( aTransaction.Request().URI(),
+              realm, nonce, algorithm, username, password, resync, resyncrequired ) ) ;
+    
+    if ( error != KErrNone )
+        {
+        GBA_TRACE_DEBUG_NUM(("Get Gredentails failed with error %d"), error );
+        return error;
+        }
+    
+    if ( haveUserPW || resyncrequired )
+        {
+        CleanupClosePushL(username);
+        pushCount++;
+        CleanupClosePushL(password);
+        pushCount++;       
+        //Resync required
+        if( resyncrequired )
+            {
+            CleanupClosePushL(resync);
+            pushCount++;     
+            }
+        
+        GBA_TRACE_DEBUG(("HandleAuthorizationChallengeL: received following credentials"));
+        GBA_TRACE_DEBUG(("Realm:"));
+        GBA_TRACE_DEBUG(realm.DesC());
+        GBA_TRACE_DEBUG(("Username:"));
+        GBA_TRACE_DEBUG(username.DesC());
+        GBA_TRACE_DEBUG(("Password:"));
+        GBA_TRACE_DEBUG_BINARY(password.DesC());
+        GBA_TRACE_DEBUG(("Resync:"));
+        GBA_TRACE_DEBUG_BINARY(resync.DesC());
+        
+        }
+    else //No password and no resync required
+        {
+        CleanupStack::PopAndDestroy( pushCount ); 
+        return KErrNotFound;  
+        }
+
+    // Encode the Username/Password
+    switch ( authType.Index( RHTTPSession::GetTable() ) )
+        {
+        case HTTP::EDigest:
+           {
+           THTTPHdrVal requestUri;
+           RHTTPTransactionPropertySet propSet = aTransaction.PropertySet();
+           propSet.Property( stringPool.StringF(HTTP::EUri,RHTTPSession::GetTable()), requestUri );
+           //save rsp auth calcuation
+           //Save the string handle for rsp auth checking
+           //Close the previous handle, then set new one
+           iUsername.Close();
+           iUsername = username.Copy();
+           iPassword.Close();
+           iPassword = password.Copy();
+           iRealm.Close();
+           iRealm = realm.Copy();
+           iNonce.Close();
+           iNonce = nonce.Copy();
+           iUri.Close();
+           iUri = requestUri.Str().Copy();
+           
+           TRAP ( error, EncodeDigestAuthL( username, password, aTransaction, headerPart, requestUri ) );
+           GBA_TRACE_DEBUG(("After Encode Digest AuthL"));
+           if ( error != KErrNone )
+               {
+               GBA_TRACE_DEBUG_NUM(("After Encode Digest AuthL error %d"), error );
+               CleanupStack::PopAndDestroy( pushCount );
+               return error;
+               }
+           }
+           break;
+        default:
+           {
+           CleanupStack::PopAndDestroy( pushCount );
+           return KErrArgument;
+           }
+           
+        }
+     GBA_TRACE_DEBUG(("After Encode Digest AuthL 1"));
+    // Resubmit the request to the server
+    // add resyncronization header to the request if it is available
+    if ( resyncrequired )
+        {
+        THTTPHdrVal hdrVal;
+        RStringF unStr = stringPool.OpenFStringL(KAuts);
+        CleanupClosePushL(unStr);
+        pushCount++;
+        hdrVal.SetStr(resync);
+        RHTTPHeaders requestHeaders(aTransaction.Request().GetHeaderCollection());
+        requestHeaders.SetFieldL( stringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+                                 THTTPHdrVal(stringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+                                 unStr,
+                                 hdrVal );
+       }
+    GBA_TRACE_DEBUG(("After Encode Digest AuthL 2"));   
+    CleanupStack::PopAndDestroy( pushCount ); 
+    GBA_TRACE_DEBUG(("After Encode Digest AuthL 3"));
+    return KErrNone;
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::FindHeaderPartToUseL()
+// -----------------------------------------------------------------------------
+//
+TInt C3GPPBootstrapHttpHandler::FindHeaderPartToUseL( RHTTPTransaction aTransaction ) const
+    {
+    //We only pick up the first digest authentication fields:
+    
+    RStringPool stringPool = aTransaction.Session().StringPool(); 
+
+    RStringF wwwAuthenticate = stringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable());
+    RStringF realm = stringPool.StringF(HTTP::ERealm,RHTTPSession::GetTable());
+    RStringF nonce = stringPool.StringF(HTTP::ENonce,RHTTPSession::GetTable());
+    RStringF qop   = stringPool.StringF(HTTP::EQop,RHTTPSession::GetTable());
+    
+    RHTTPHeaders headers = aTransaction.Response().GetHeaderCollection();
+    const TInt parts = headers.FieldPartsL( wwwAuthenticate );
+    
+    for ( TInt i = 0; i < parts; i++ )
+    {
+    THTTPHdrVal fieldVal;// The name of the current field.
+    THTTPHdrVal hdrVal;//A scratch hdrVal
+    headers.GetField(wwwAuthenticate, i, fieldVal);
+    switch ( fieldVal.StrF().Index(RHTTPSession::GetTable() ) )
+        {
+        case HTTP::EDigest:
+            {
+            // It is Digest, let us check realm, nonce, qop then
+            if ( headers.GetParam(wwwAuthenticate, realm, hdrVal, i ) == KErrNone 
+                 &&
+                 headers.GetParam(wwwAuthenticate, nonce, hdrVal, i ) == KErrNone)
+                {
+                // We've got a realm and a nonce. If there's a qop, we
+                // need to check it's acceptable.
+               if ( headers.GetParam(wwwAuthenticate, qop, hdrVal, i ) == KErrNone 
+                    && 
+                    FindAuth( hdrVal.Str().DesC() ) )
+                     {
+                     // the header has qop and it is auth-int.
+                     // we found it
+                     return i;
+                     }
+
+                }
+            }
+            break;
+
+        default:
+            //Ingore if it is not Digest
+            break;
+        }
+    }
+    return KErrNotFound;
+}
+
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::EncodeDigestAuthL()
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrapHttpHandler::EncodeDigestAuthL( const RString& aUsername, 
+            const RString& aPW, 
+            RHTTPTransaction& aTransaction,
+            TInt aHeaderPart,
+            const THTTPHdrVal& aRequestUri )
+    {
+    GBA_TRACE_BEGIN();
+    TInt pushCount = 0; 
+    
+    RStringPool stringPool = aTransaction.Session().StringPool(); 
+
+    GBA_TRACE_DEBUG(("Username:"));
+    GBA_TRACE_DEBUG(aUsername.DesC());
+
+    GBA_TRACE_DEBUG(("Passwd:"));
+    GBA_TRACE_DEBUG_BINARY(aPW.DesC());
+  
+    TBuf8<KHashLength> hash;
+    TBuf8<KHashLength> cnonce;
+    //Nonce
+    THTTPHdrVal nonce;
+    RHTTPHeaders headers = aTransaction.Response().GetHeaderCollection();
+    TInt error = headers.GetParam(stringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable()), 
+          stringPool.StringF(HTTP::ENonce,RHTTPSession::GetTable()), nonce,
+          aHeaderPart);
+    
+    if ( error != KErrNone )
+        {
+        User::LeaveIfError( error );
+        }
+    
+    //realm
+    THTTPHdrVal realm;
+    error = headers.GetParam(stringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable()),
+           stringPool.StringF(HTTP::ERealm,RHTTPSession::GetTable()), realm,
+           aHeaderPart);
+    
+    if ( error != KErrNone )
+        {
+        User::LeaveIfError( error );
+        }
+    
+    //qop       
+    THTTPHdrVal qop;
+    error = headers.GetParam(stringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable()),
+           stringPool.StringF(HTTP::EQop,RHTTPSession::GetTable()), qop,
+           aHeaderPart);
+    
+   if ( error != KErrNone )
+        {
+        User::LeaveIfError( error );
+        }
+    
+    GenerateCNonce( cnonce );
+    
+    GBA_TRACE_DEBUG(("cnonce:"));
+    GBA_TRACE_DEBUG_BINARY( cnonce );
+    
+    RString cnonceString = stringPool.OpenStringL(cnonce); 
+    CleanupClosePushL(cnonceString);
+    pushCount++;
+    
+    // stored for auth calculations
+    iCnonce.Close();
+    iCnonce = cnonceString.Copy();
+    
+    // stored for auth calculations
+    iMethod.Close();
+    iMethod = aTransaction.Request().Method().Copy();
+    
+    DigestCalcL( KMD5HashofEmpty, hash );
+    
+    GBA_TRACE_DEBUG(("hash:"));
+    GBA_TRACE_DEBUG_BINARY( hash );
+    
+    // OK. hash now contains the digest response. Set up the header.
+    RHTTPHeaders requestHeaders(aTransaction.Request().GetHeaderCollection());
+    RHTTPHeaders responseHeaders(aTransaction.Response().GetHeaderCollection());
+  
+    requestHeaders.RemoveField(stringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable())); 
+    
+    //Copy useranme
+    THTTPHdrVal hdrVal;
+    hdrVal.SetStr(aUsername);
+    
+    //Set the username to request header
+    requestHeaders.SetFieldL(stringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+           THTTPHdrVal(stringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+           stringPool.StringF(HTTP::EUsername,RHTTPSession::GetTable()),
+           hdrVal);
+        
+    // copy Realm from response headers
+    responseHeaders.GetParam(stringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable()), 
+           stringPool.StringF(HTTP::ERealm,RHTTPSession::GetTable()),
+           hdrVal, 
+           aHeaderPart);
+    
+    // Set the Realm to request header
+    requestHeaders.SetFieldL(stringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+           THTTPHdrVal(stringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+           stringPool.StringF(HTTP::ERealm,RHTTPSession::GetTable()),
+           hdrVal);
+    
+    // copy nonce from response headers
+    responseHeaders.GetParam(stringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable()), 
+           stringPool.StringF(HTTP::ENonce,RHTTPSession::GetTable()), 
+           hdrVal,
+           aHeaderPart);
+    
+    // set nonce to request header
+    requestHeaders.SetFieldL(stringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+           THTTPHdrVal(stringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+           stringPool.StringF(HTTP::ENonce,RHTTPSession::GetTable()),
+           hdrVal);
+    
+    // Set uri to request header.
+    // the uri has already been fetched from http property setting
+    requestHeaders.SetFieldL(stringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+           THTTPHdrVal(stringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+           stringPool.StringF(HTTP::EUri,RHTTPSession::GetTable()),
+           aRequestUri);
+    
+    // Qop with quotation marks   
+    // copy qop from response headers
+     responseHeaders.GetParam(stringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable()), 
+           stringPool.StringF(HTTP::EQop,RHTTPSession::GetTable()), 
+           hdrVal,
+           aHeaderPart);
+    
+    // Set Qop to request header
+     requestHeaders.SetFieldL(stringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+           THTTPHdrVal(stringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+           stringPool.StringF(HTTP::EQop,RHTTPSession::GetTable()),
+           hdrVal);
+     
+    //Set Nc
+    hdrVal.SetStrF(stringPool.StringF(HTTP::E00000001,RHTTPSession::GetTable()));
+    requestHeaders.SetFieldL(stringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+                  THTTPHdrVal(stringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+                  stringPool.StringF(HTTP::ENc,RHTTPSession::GetTable()),
+                  hdrVal);
+     
+    // Set Cnonce to request header.
+    hdrVal.SetStr(cnonceString);
+    requestHeaders.SetFieldL(stringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+           THTTPHdrVal(stringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+           stringPool.StringF(HTTP::ECnonce,RHTTPSession::GetTable()),
+           hdrVal);
+   
+    // Set response to request header.
+    RString hashStr = stringPool.OpenStringL(hash);
+    CleanupClosePushL(hashStr);
+    hdrVal.SetStr(hashStr);
+    requestHeaders.SetFieldL(stringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+           THTTPHdrVal(stringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+           stringPool.StringF(HTTP::EResponse,RHTTPSession::GetTable()),
+           hdrVal);
+    CleanupStack::PopAndDestroy(&hashStr);
+
+    // Get Opaque from response header.
+    error = responseHeaders.GetParam(stringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable()), 
+             stringPool.StringF(HTTP::EOpaque,RHTTPSession::GetTable()), 
+             hdrVal, aHeaderPart);
+    
+    // Set Opaque 
+    if ( error != KErrNotFound )
+        {
+        GBA_TRACE_DEBUG((" found the opaque value and copy it"));
+        requestHeaders.SetFieldL(stringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+                       THTTPHdrVal(stringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+                       stringPool.StringF(HTTP::EOpaque,RHTTPSession::GetTable()),
+                       hdrVal);
+        } 
+    else
+        {
+        GBA_TRACE_DEBUG((" No opaque value send empty one"));
+        RString opaque =  stringPool.OpenStringL(Kfopaque);
+        GBA_TRACE_DEBUG((" No opaque value send empty one 1"));
+        CleanupClosePushL(opaque);
+        pushCount++;
+        hdrVal.SetStr(opaque);
+       GBA_TRACE_DEBUG((" No opaque value send empty one 2"));
+        requestHeaders.SetFieldL(stringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
+             THTTPHdrVal(stringPool.StringF(HTTP::EDigest,RHTTPSession::GetTable())),
+             stringPool.StringF(HTTP::EOpaque,RHTTPSession::GetTable()),
+             hdrVal);
+       }
+    GBA_TRACE_DEBUG((" No opaque value send empty one 3"));
+    // Set algorithm.   
+    TBuf8<KAlgLength> algbuf;
+    algbuf.Copy(_L8(", "));
+    algbuf.Append(Kalgorithm);
+    algbuf.Append(_L8("="));
+    algbuf.Append(Kfalgo);
+   
+    GBA_TRACE_DEBUG((" No opaque value send empty one 5"));
+   
+    RStringF valStr = stringPool.OpenFStringL(algbuf);
+    THTTPHdrVal val(valStr);
+    requestHeaders.SetFieldL(stringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), val);
+    valStr.Close();
+    
+    GBA_TRACE_DEBUG((" No opaque value send empty one 4"));
+
+    CleanupStack::PopAndDestroy(pushCount);
+    GBA_TRACE_DEBUG((" No opaque value send empty one 6"));
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::FindAuth()
+// -----------------------------------------------------------------------------
+//
+TBool C3GPPBootstrapHttpHandler::FindAuth(const TDesC8& aQop) const
+    {
+    GBA_TRACE_BEGIN();
+    if ( aQop == KAuthInt )
+        {
+        GBA_TRACE_DEBUG((" qop is equal to auth-int"));
+        return ETrue;
+        }
+    else
+        {
+        GBA_TRACE_DEBUG((" qop is NOT equal to auth-int"));
+        GBA_TRACE_DEBUG((""));
+        return EFalse;    
+        }    
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::HA1L()
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrapHttpHandler::HAOneL(const RString& aUsername,const RString& aPW,
+           const RString& aRealm, TDes8& aResult)
+    {
+    HBufC8* a1 = HBufC8::NewMaxLC(aUsername.DesC().Length() 
+           + aPW.DesC().Length()  
+           + 1
+           + aRealm.DesC().Length() + 1
+           );
+    TPtr8 a1Mod = a1->Des();
+    a1Mod.Zero();
+    
+    a1Mod.Append(aUsername.DesC());
+    a1Mod.Append(':');
+    a1Mod.Append(aRealm.DesC());
+    a1Mod.Append(':');
+    a1Mod.Append(aPW.DesC().Ptr(),aPW.DesC().Length());
+
+    GBA_TRACE_DEBUG(a1Mod);
+    Hash(*a1, aResult);
+    GBA_TRACE_DEBUG(("after hash"));
+    CleanupStack::PopAndDestroy(a1);
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::HAtwoL()
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrapHttpHandler::HATwoL(const RStringF& aMethod, 
+           const RString& aRequestUri,
+           const TDesC8& aHentity,
+           TDes8& aResult)
+    {
+    // In the auth qop, a2 is Method:digest-uri-value:empty body hash
+    // Allocate enough space for the method, the URI and the colon, empty content-hash and colon.
+    TPtrC8 requestUri = aRequestUri.DesC();
+    TPtrC8 method = aMethod.DesC();
+    HBufC8* a2 = HBufC8::NewMaxLC( requestUri.Length() + method.Length() + KNumber34 );
+    TPtr8 a2Mod = a2->Des();
+    a2Mod.Zero();
+    a2Mod.Append(method);
+    a2Mod.Append(':');
+    
+    a2Mod.Append( requestUri );
+    GBA_TRACE_DEBUG( requestUri );
+    // since for this method is always auth-int we always add hentity
+    a2Mod.Append(':');
+    a2Mod.Append(aHentity);
+    GBA_TRACE_DEBUG(a2Mod);
+
+    Hash(*a2, aResult);
+
+    GBA_TRACE_DEBUG_BINARY(aResult);
+    CleanupStack::PopAndDestroy(a2);
+    
+    GBA_TRACE_DEBUG(("Exit HATwoL"));
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::Hash()
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrapHttpHandler::Hash(const TDesC8& aMessage, TDes8& aHash)
+    {
+    GBA_TRACE_DEBUG(("hash"));
+    // Calculate the 128 bit (16 byte) hash
+    iMD5Calculator->Reset();
+    TPtrC8 hash = iMD5Calculator->Hash(aMessage);
+    GBA_TRACE_DEBUG(("after hash"));
+    // Now print it as a 32 byte hex number
+    aHash.Zero();
+    for ( TInt ii = 0; ii < KRawHashLength; ii++ )
+        {
+        TBuf8<2> scratch;
+        scratch.Zero();
+        scratch.Format(formatStr, hash[ii]);
+        aHash.Append(scratch);
+      }
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::GenerateCNonce()
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrapHttpHandler::GenerateCNonce(TDes8& aNonce)
+    {
+    // The purpose of the client nonce is to protect aextst 'chosen
+    // plaintext' attacks where a hostile server tricks the client
+    // into supplying a password using a specific server nonce that
+    // allows an (as yet undiscovered) flaw in MD5 to recover the
+    // password. As such the only important thing about client nonces
+    // is that they change and aren't predictable. See section 4.9 of
+    // RFC2616
+
+    TTime time;
+    time.UniversalTime();
+    TInt64 randomNumber = Math::Rand(iSeed);
+    randomNumber <<= KNumber32;
+    randomNumber += Math::Rand(iSeed);
+    TBuf8<KNumber33> key;
+    key.Zero();
+    key.AppendNum(time.Int64(), EHex);
+    key.Append(KColon);
+    key.AppendNum(randomNumber, EHex);
+  
+    Hash(key, aNonce);
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::CheckRspAuthL()
+// -----------------------------------------------------------------------------
+//
+TInt C3GPPBootstrapHttpHandler::CheckRspAuthL(RHTTPTransaction aTransaction)
+    {
+    RStringF wwwAuthInfoHeader = aTransaction.Session().StringPool().OpenFStringL(KHTTPAuthInfo);
+    RHTTPHeaders headers(aTransaction.Response().GetHeaderCollection());
+
+    THTTPHdrVal rspAuthVal;
+    
+    TInt retVal = headers.FieldPartsL(wwwAuthInfoHeader);
+
+    TInt error = headers.GetField(wwwAuthInfoHeader, 0, rspAuthVal);
+
+    if(error != KErrNone)
+    {
+    	wwwAuthInfoHeader.Close();
+    	return error;
+    } 
+    wwwAuthInfoHeader.Close();
+    return KErrNone;      
+    }
+
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::DigestCalcL()
+// -----------------------------------------------------------------------------
+//
+void C3GPPBootstrapHttpHandler::DigestCalcL(
+    const TDesC8& aHentity,
+    TDes8& aResult )
+    {
+    TInt stringToHashLength = iNonce.DesC().Length() + 
+          KNumber8 + // auth-int length 
+          KNumber3 * KHashLength + KNumber8 + iPassword.DesC().Length() + KNumber5;
+    HBufC8* stringToHash = HBufC8::NewMaxLC(stringToHashLength);
+    TPtr8 stringMod = stringToHash->Des();
+    stringMod.Zero();
+    HAOneL(iUsername, iPassword, iRealm, stringMod);
+    stringMod.Append(':');
+    stringMod.Append(iNonce.DesC());
+    stringMod.Append(KNCVal_2);
+    stringMod.Append(iCnonce.DesC());
+    stringMod.Append(':');
+    stringMod.Append(KAuthInt);
+    stringMod.Append(':');
+    TBuf8<KHashLength> hash;
+    HATwoL(iMethod, iUri, aHentity,hash);
+    GBA_TRACE_DEBUG_BINARY(stringMod);
+    stringMod.Append(hash);   
+    GBA_TRACE_DEBUG(stringMod);
+    Hash(*stringToHash, aResult);
+    CleanupStack::PopAndDestroy(stringToHash);
+    };
+
+// -----------------------------------------------------------------------------
+// C3GPPBootstrapHttpHandler::GetResponse()
+// -----------------------------------------------------------------------------
+//
+ HBufC8* C3GPPBootstrapHttpHandler::GetResponse()
+    {
+    return iResponse->Alloc();
+    };
+    
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build info file for GBA components
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_EXPORTS
+
+// export iby files
+../rom/gba.iby  CORE_MW_LAYER_IBY_EXPORT_PATH( gba.iby )
+../sis/gba_stub.sis   /epoc32/data/z/system/install/gba_stub.sis
+
+PRJ_MMPFILES
+
+
+//../uicc/group/gbauicc.mmp
+//../gbaserver/group/gbaserver.mmp
+//../gbaapi/group/gba.mmp
+//../gbafilter/group/httpfiltergba.mmp
+
+
+#include "../uicc/group/bld.inf"
+#include "../gbaserver/group/bld.inf"
+#include "../gbaapi/group/bld.inf"
+#include "../gbafilter/group/bld.inf"
+        
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/inc/GBALogger.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,70 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  logger declarations
+*
+*/
+
+#ifndef __GBALOGGER_H_
+#define __GBALOGGER_H_
+
+#include <e32base.h>
+
+_LIT( KGBALogDir, "GBA" );
+_LIT( KGBALogFileName, "GBALog.txt" );
+_LIT( KEnter, "Enter ---->");
+_LIT( KEnd, "Exit <----");
+
+#ifdef _DEBUG
+
+    void debuglineL(const char *a, void *arg1, void* f, void *arg2, void *arg3, const TDesC &arg4);
+    void debuglineL(const char *a, void *arg1, void* f, void *arg2, void *arg3, const TDesC8 &arg4);
+    void debuglineL(const char *a, void *arg1, void* f, void *arg2, void *arg3, const char *arg4, const TInt &aNum);
+    void debuglineL(const char *a, void *arg1, void* f, void *arg2, void *arg3, const TDesC8 &arg4, const TInt &aNum);
+    void DebugBinary(const TDesC8 &buf);
+    void debugTTimeL( TTime& aTime );
+    void debuglineL(const char *a, void *arg1, void* f, void *arg2, void *arg3, const char *arg4);
+
+    #define GBA_DEBUG
+    #define GBA_TRACE_DEBUG_DESC(a) debuglineL("%s:%s %d: %d",(void *) __FILE__, (void *) __func__, (void *)__LINE__, (void *)User::TickCount(),(a))
+    #define GBA_TRACE_DEBUG_NUM( a,b ) debuglineL("%s:%s %d: %d",(void *) __FILE__, (void *) __func__, (void *)__LINE__, (void *)User::TickCount(),(a),b)
+    
+#ifdef LOG_GBA_KEYS
+    #define GBA_TRACE_DEBUG_BINARY(a) DebugBinary((a));
+#else
+    #define GBA_TRACE_DEBUG_BINARY(a)
+#endif 
+    
+    #define GBA_TRACE_BEGIN() debuglineL("%s:%s %d: %d",(void *) __FILE__, (void *) __func__, (void *)__LINE__, (void *)User::TickCount(),(KEnter))
+    #define GBA_TRACE_END() debuglineL("%s:%s %d: %d",(void *) __FILE__, (void *) __func__, (void *)__LINE__, (void *)User::TickCount(),(KEnd))
+    #define GBA_TRACE_TIME( a ) debugTTimeL( (a) );
+    #define GBA_TRACE_DEBUG(a) debuglineL("%s:%s %d: %d",(void *) __FILE__, (void *) __func__, (void *)__LINE__, (void *)User::TickCount(),(a))
+
+#else
+
+    #define GBA_TRACE_DEBUG_DESC(a)
+    #define GBA_TRACE_DEBUG(a) 
+    #define GBA_TRACE_DEBUG_NUM(a,b)
+    #define GBA_TRACE_DEBUG_BINARY(a)
+    #define GBA_TRACE_BEGIN()
+    #define GBA_TRACE_END()
+    #define GBA_TRACE_TIME( a )
+
+#endif
+
+
+#endif //__GBALOGGER_H_
+                                                                        
+//EOF
+    
+    
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/inc/GbaCommon.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  GBA Common definitions
+*
+*/
+
+
+#ifndef GBACOMMON_H
+#define GBACOMMON_H
+
+#include <e32base.h>
+
+_LIT8( KHTTPFilterGBAName, "GBA2");
+_LIT(KGbaServerName,"gbaserver2");
+_LIT8(KHTTPTag,"http://");
+_LIT8(KHTTPSTag,"https://");
+
+//the server version. A version must be specified when 
+//creating a session with the server
+const TUint KGbaServMajorVersionNumber=0;
+const TUint KGbaServMinorVersionNumber=1;
+const TUint KGbaServBuildVersionNumber=1;
+
+// Dictionary store UID for GBA ini
+const TUid KGbaIniUid = { 0x00001 };
+const TUid KGbaBSFConfiguration = { 0x00002 };
+
+// Dictionary store UID for GBA credentials
+// IMPI, Ks, Rand, B-TID, key lifetime
+const TUid KUidGBACredRoot = { 0x00001 };
+const TUid KUidIMPI = { 0x00002 };
+const TUid KUidKs = { 0x00003 };
+const TUid KUidRand = { 0x00004 };
+const TUid KUidBTID = { 0x00005 };
+const TUid KUidkeylifetime = { 0x00006 };
+const TUid KUidGBARunType = { 0x00007 };
+const TUid KUidGBAUAvail = { 0x00008 };
+
+//opcodes used in message passing between client and server
+enum TGbaServRqst
+    { 
+    EGbaServRequestBootstrap,
+    EGbaServCancelRequestBootstrap,
+    EGbaServQueryOption,
+    EGbaServWriteOption,
+    EGbaServIsGBAUSupported,
+    };
+
+#endif // GBACOMMON_H
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/inc/gbauicc.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,113 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Functionality for accessing uicc
+*
+*/
+
+
+#ifndef _GBAUICC_H_
+#define _GBAUICC_H_
+
+#include <e32base.h>
+
+_LIT8(KAKAV1, "USIM");
+_LIT8(KSIMV1, "SIM");
+_LIT8(KISIMV1, "ISIM");
+_LIT8(KUICC_DEFAULT, "");
+
+#define GBAUICC_INTERFACE  0x2000F86B
+
+const TUid KGBAUICCInterfaceUID = { GBAUICC_INTERFACE };
+
+/**
+* An abstract interface for accessing applications on UICC. Use this interface to query identity and authentication parameters from UICC.
+*/
+class MUICCInterface
+    {
+    public:
+
+        /**
+         * Fetches identity stored on the UICC
+         * param stores
+         * exception if UICC is not accessible call will leave
+         * result is returned 3GPP TS 23.003: "3rd Generation Partnership Project; Technical Specification Group Core Network; Numbering, addressing and identification".
+         */
+        virtual void QueryIdentityL(TDes8& aIdentity) = 0;
+   
+        /**
+         * Fetches Home network domain name
+         * exception if UICC is not accessible call will leave
+         * result is returned 
+         * see 3GPP TS 23.003: "3rd Generation Partnership Project; Technical Specification Group Core Network; Numbering, addressing and identification".
+         */
+        virtual void QueryHomeNetworkDnL(TDes8& aHNDN) = 0;
+
+        /**
+         * Queries authentication vector from UICC application
+         * param challenge in
+         * param calculated response
+         * return true on success false on failure
+         * exception if UICC is not accessible call will leave
+         */
+        virtual TBool QueryAuthenticationL(const TDesC8& aNonce, TDes8& aResponse, TDes8& aResync ) = 0; 
+  
+        /**
+         * Fetches key material from UICC
+         * param resulting key material
+         */
+        virtual void QueryKeyMaterialL  (   const TDesC8& aKeyMaterial,
+                                            const TDesC8& aRand,
+                                            const TDesC8& aIMPI,
+                                            const TDesC8& aUTF8_NAF_ID,
+                                            TDes8& aDerivedKey )  = 0; 
+  
+       /**
+        * Fetches the master keys in what ever format they exist
+        */
+       virtual TBool QueryKs(TDes8& aKS) =0;
+
+
+       /**
+        * Check if the 2G interface
+        * Return ETrue when only 2G interface available 
+        */
+       virtual TBool InterfaceIs2G() = 0;
+
+
+        /**
+         * The API used to update B-TID and key lifetime
+         */
+        virtual TInt UpdateGBADataL( const TDesC8& aBTID, const TDesC8& aLifetime ) = 0;
+
+        /**
+         * API to get the GBA_U availability
+         * Set aGBAAvail to ETrue if smart card is GBA_U card
+         */
+        virtual void QueryGBAUAvailabilityL( TBool& aGBAAvail ) = 0;
+    
+        /**
+         * delete the objects
+         */
+        virtual void Release() = 0;
+        
+        /*
+         * Notify the smart card is changed
+         */
+         virtual void NotifyCardChangeL() = 0; 
+    }; 
+
+#endif // _GBAUICC_H_
+//EOF
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/rom/gba.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Image description file for GBA
+*
+*/
+
+
+#ifndef __GBA_IBY__
+#define __GBA_IBY__
+
+#include <Bldvariant.hrh>
+
+
+FILE=ABI_DIR\BUILD_DIR\gba2.dll	        SHARED_LIB_DIR\gba2.dll
+FILE=ABI_DIR\BUILD_DIR\gbaserver2.exe	PROGRAMS_DIR\gbaserver2.exe
+
+data=ZSYSTEM\install\gba_stub.sis    	System\Install\gba_stub.sis
+
+ECOM_PLUGIN( gbauicc2.dll, gbauicc2.rsc )
+
+ECOM_PLUGIN( httpfiltergba2.dll, httpfiltergba2.rsc )
+
+#endif //__GBA_IBY__
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/sis/gba.pkg	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,44 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description: Package file for urel GBA
+;
+; Language
+&EN
+
+; Header
+#{"GBA (Beta)"},(0x2000F867), 0, 3, 0, TYPE=SA,RU
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+"..\data\gba_license.txt"-"", FT, TA
+
+; Product dependency for Series 60 v5.1
+  [0x10283160], 0, 0, 0, {"Series60ProductID"}   
+
+; Files to install
+
+"\epoc32\release\armv5\urel\gbaserver2.exe"			-"c:\sys\bin\gbaserver2.exe"
+"\epoc32\release\armv5\urel\gbauicc2.dll"			-"c:\sys\bin\gbauicc2.dll"
+"\epoc32\data\z\resource\plugins\gbauicc2.rsc"			-"c:\resource\plugins\gbauicc2.rsc"
+"\epoc32\release\armv5\urel\gba2.dll"				-"c:\sys\bin\gba2.dll"
+"\epoc32\release\armv5\urel\httpfiltergba2.dll"			-"c:\sys\bin\httpfiltergba2.dll"
+"\epoc32\data\z\resource\plugins\httpfiltergba2.rsc"		-"c:\resource\plugins\httpfiltergba2.rsc"
+
+
+
+
Binary file gba/sis/gba.sis has changed
Binary file gba/sis/gba.sisx has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/sis/gba_stub.pkg	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,39 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description: Package file for GBA Stub
+;
+; Language
+&EN
+
+; Header
+#{"GBA"}, (0x2000F867), 1, 0, 0, TYPE=SA
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Files to install
+
+""-"z:\sys\bin\gbaserver2.exe"
+""-"z:\sys\bin\gbauicc2.dll"
+""-"z:\resource\plugins\gbauicc2.rsc"
+""-"z:\sys\bin\gba2.dll"
+""-"z:\sys\bin\httpfiltergba2.dll"
+""-"z:\resource\plugins\httpfiltergba2.rsc"
+
+
+
+
Binary file gba/sis/gba_stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/uicc/data/20029F0B.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,40 @@
+/*
+* Copyright (c) 2000 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECom Registrition File for KeyEncryptor Plugin
+*
+*/
+
+
+#include <registryinfo.rh>
+
+RESOURCE REGISTRY_INFO theInfo
+    {
+    dll_uid = 0x20029F0B;
+    interfaces = 
+        {
+        INTERFACE_INFO
+            {
+            interface_uid = 0x2000F86B;
+            implementations = 
+                {
+                BINARY_IMPLEMENTATION_INFO
+                    {
+                    implementation_uid = 0x20029F0F;
+                    version_no = 1;
+                    display_name = "gba uicc plugin 2";
+                    }
+                };
+            }
+        };
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/uicc/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,24 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build info file for GBA uicc components
+*
+*/
+
+
+PRJ_MMPFILES
+
+gbauicc.mmp
+    
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/uicc/group/gbauicc.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file for project GBA uicc
+*
+*/
+
+
+#include <platform_paths.hrh>
+TARGET            gbauicc2.dll
+TARGETTYPE        PLUGIN
+UID               0x10009d8d 0x20029F0B
+
+VENDORID VID_DEFAULT
+
+CAPABILITY CAP_ECOM_PLUGIN 
+
+SMPSAFE
+
+USERINCLUDE   ../inc
+USERINCLUDE   ../../inc
+
+START RESOURCE ../data/20029F0B.rss
+TARGET gbauicc2.rsc
+END
+
+
+MW_LAYER_SYSTEMINCLUDE
+SYSTEMINCLUDE /epoc32/include/libc
+SYSTEMINCLUDE /epoc32/include/ecom
+
+SOURCEPATH ../src
+SOURCE GbaAkaIsa.cpp 
+
+
+SOURCEPATH ../../common
+SOURCE GBALogger.cpp
+
+
+LIBRARY 		euser.lib
+LIBRARY 		etel.lib 
+LIBRARY 		etelmm.lib
+LIBRARY 		hash.lib
+LIBRARY 		customapi.lib
+DEBUGLIBRARY 	flogger.lib
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/uicc/inc/GBAAkaIsa.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,93 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   class CAkaIsaInterface definition
+*
+*/
+
+
+#ifndef _AKAISAINTERFACE_H_
+#define _AKAISAINTERFACE_H_
+
+#include "gbauicc.h"
+
+// INCLUDES
+#include <e32base.h>
+#include <rmmcustomapi.h>
+
+//Constants
+const TUint8 KAKA_RES_LENGTH =  16;
+const TUint8 KAKA_IK_LENGTH  = 16;
+const TUint8 KAKA_CK_LENGTH  = 16;
+const TUint8 KAKA_KEY_LENGTH = 16;
+const TUint8 KAKA_RAND_LENGTH = 16;
+const TUint8 KRESPONSE_2G_LENGTH = 16;
+
+#define GBA_UICC_INTERFACE_IMPLE 0x20029F0F
+const TUid KGBAUICCImpleUID = { GBA_UICC_INTERFACE_IMPLE };
+
+// CLASS DECLARATION
+class CAkaIsaInterface : public CBase, public MUICCInterface 
+    {
+    public:
+        static MUICCInterface* NewL(); 
+        virtual ~CAkaIsaInterface();
+        // Inherited from CUICCInterface  
+        void QueryIdentityL(TDes8& aIdentity);
+        void QueryHomeNetworkDnL(TDes8& aHNDN);
+        TBool QueryAuthenticationL(const TDesC8& aNonce, TDes8& aResponse, TDes8& aResync );
+        void QueryKeyMaterialL(const TDesC8& aKeyMaterial, const TDesC8& aRand, const TDesC8& aIMPI, const TDesC8& aUTF8_NAF_ID, TDes8& aDerivedKey ); 
+        TBool QueryKs(TDes8& aKS);
+        // Check the GBA_U availability from smart card apps
+        void QueryGBAUAvailabilityL( TBool& aGBAAvail );
+        // Save B-TID and key lifttime from BSF to smart card 
+        TInt UpdateGBADataL( const TDesC8& aBTID, const TDesC8& aLifetime );  
+        TBool InterfaceIs2G(); 
+        void Release(); 
+        void NotifyCardChangeL();
+        void QueryCardInterfaceL();
+    
+    private:
+    
+        CAkaIsaInterface();
+        void ConstructL();
+		//run aka
+        TBool QueryAuthenticationGBAUL(const TDesC8& aNonce, TDes8& aResponse, TDes8& aResync );
+        //run aka
+        TBool QueryAuthentication3GL(const TDesC8& aNonce, TDes8& aResponse, TDes8& aResync );
+        //run simulated aka for 2G
+        void QueryAuthentication2GL( const TDesC8& aNonce, TDes8& aResponse ); 
+    
+    private:
+        enum TCardInterface
+           {
+           ENoInterface = 0,
+           E2GInterface,	
+           E3GInterface,	// UICC with USIM not supporting Ks_NAF derivation
+           EGBAUInterface	// UICC with USIM application supporting Ks_NAF derivation.
+           };
+        
+    private:
+        TBuf8<KAKA_RES_LENGTH>  iResBuf;
+        TBuf8<KAKA_IK_LENGTH>   iIKBuf;
+        TBuf8<KAKA_CK_LENGTH>   iCKBuf;
+        TCardInterface          iCardInterface;
+        RTelServer              iEtelServer;
+        RMobilePhone            iPhone;
+        RMmCustomAPI            iCustomAPI;
+        
+        }; 
+
+#endif // _AKAISAINTERFACE_H_
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gba/uicc/src/GbaAkaIsa.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,846 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of class CAkaIsaInterface
+*
+*/
+
+
+// INCLUDE FILES
+
+#include <e32math.h>
+#include <etelmmerr.h>
+#include <mmtsy_names.h>            //TSY and Phone name
+#include <hash.h>
+#include <implementationproxy.h>    //for ecom
+#include "GBAAkaIsa.h"
+#include "GBALogger.h"
+#include "GbaCommon.h"
+
+//Constants
+const TInt KMaxBufferSize = 256;
+const TInt KNetworkIdLength2 = 2;
+const TInt KNetworkIdLength3 = 3;
+const TInt KIntegerConstant4 = 4;
+const TInt KIntegerConstant16 = 16;
+const TInt KIntegerConstant32 = 32;
+
+_LIT8( KAT, "@" );
+_LIT8( KIMSMNC, "ims.mnc" );
+_LIT8( KIMSMNC0, "ims.mnc0" );
+_LIT8( KBSFMNC, "bsf.mnc" ); 
+_LIT8( KBSFMNC0, "bsf.mnc0" );     
+_LIT8( KMCC,".mcc");        
+_LIT8( KPUB3GPPORG, ".pub.3gppnetwork.org");
+_LIT8( K3GPPORG, ".3gppnetwork.org");
+_LIT8( K3GPPGBARES, "3gpp-gba-res");
+_LIT8( K3GPPGBAKS, "3gpp-gba-ks");
+_LIT8( KGBAME, "gba-me");
+
+#ifdef __WINS__
+_LIT8( KWINTESTID, "test@pub.3gpp.org");
+#endif
+
+static MUICCInterface* NewFunctionL();
+
+
+// ======== LOCAL FUNCTIONS ========
+// ---------------------------------------------------------------------------
+// MUICCInterface* NewFunctionL()
+// ---------------------------------------------------------------------------
+//
+MUICCInterface* NewFunctionL()
+    {
+    GBA_TRACE_DEBUG(("MUICCInterface* NewFunctionL"));
+    MUICCInterface* UICCInterface = NULL;
+    UICCInterface = CAkaIsaInterface::NewL();
+    return UICCInterface;
+    }
+
+
+// -----------------------------------------------------------------------------
+// TImplementationProxy ImplementationTable[] 
+// -----------------------------------------------------------------------------
+//
+const TImplementationProxy ImplementationTable[] =
+    {
+    IMPLEMENTATION_PROXY_ENTRY(GBA_UICC_INTERFACE_IMPLE, NewFunctionL)
+    };
+
+
+// -----------------------------------------------------------------------------
+// TImplementationProxy* ImplementationGroupProxy()
+// This function is needed by ECom and is the only one exported function
+// -----------------------------------------------------------------------------
+//
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+    {
+    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
+    return (ImplementationTable);
+    }
+
+
+// ================= MEMBER FUNCTIONS =======================
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::CAkaIsaInterface()
+// -----------------------------------------------------------------------------
+//
+CAkaIsaInterface::CAkaIsaInterface():iCardInterface( ENoInterface )   
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::NewL()
+// -----------------------------------------------------------------------------
+//
+MUICCInterface* CAkaIsaInterface::NewL()
+    {
+    GBA_TRACE_DEBUG(("Constructing: CAkaIsaInterface"));
+    CAkaIsaInterface* self = new(ELeave) CAkaIsaInterface();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+    GBA_TRACE_DEBUG(("Construction complete: CAkaIsaInterface"));
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::NewL()
+// -----------------------------------------------------------------------------
+//
+void CAkaIsaInterface::ConstructL()
+    {
+    GBA_TRACE_BEGIN();
+    //Connect to ETel server
+    User::LeaveIfError( iEtelServer.Connect() );
+    //Load phone module
+    User::LeaveIfError( iEtelServer.LoadPhoneModule( KMmTsyModuleName ) );
+    //open phone
+    User::LeaveIfError( iPhone.Open( iEtelServer, KMmTsyPhoneName ) );
+    //open custom api
+    User::LeaveIfError( iCustomAPI.Open(iPhone) );
+    // check card interface, initialize iCardInterface
+    QueryCardInterfaceL();
+    GBA_TRACE_END();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::~CAkaIsaInterface()
+// -----------------------------------------------------------------------------
+//
+CAkaIsaInterface::~CAkaIsaInterface()
+    {
+    GBA_TRACE_BEGIN();
+    //Close all created resources 
+    iCustomAPI.Close(); 
+    iPhone.Close();
+    iEtelServer.Close();
+    GBA_TRACE_END();
+    }
+
+
+void CAkaIsaInterface::QueryIdentityL( TDes8& aIdentity ) 
+    {
+    #ifdef __WINS__
+    aIdentity.Copy(KWINTESTID);
+    return;
+    #endif
+
+    GBA_TRACE_BEGIN();
+    GBA_TRACE_DEBUG(("QueryIdentity is starting..."));
+    
+    TUint32 caps = 0;
+    GBA_TRACE_DEBUG(("Phone is open now doing the actual query..."));
+
+    // Get capability
+    User::LeaveIfError( iPhone.GetIdentityCaps( caps ) );
+
+    if ( caps & (RMobilePhone::KCapsGetSubscriberId))
+        {
+        RMobilePhone::TMobilePhoneSubscriberId id;
+        
+        TRequestStatus status;
+        
+        status =  KRequestPending;
+        RMobilePhone::TMobilePhoneSubscriberId iccID;
+        iPhone.GetSubscriberId( status, iccID );
+        User::WaitForRequest( status );
+        
+        GBA_TRACE_DEBUG_NUM(("Can't get IMSI, error = %d"), status.Int() );
+        User::LeaveIfError( status.Int() );
+        
+        GBA_TRACE_DEBUG(("id="));
+        GBA_TRACE_DEBUG_DESC(iccID);
+
+        aIdentity.Zero();
+        aIdentity.Copy(iccID);
+        
+        // derive the ending part
+        // get the mobile network name MNC and country code MCC
+        
+        //Make IMPI 
+        RMobilePhone::TMobilePhoneNetworkInfoV1 info;
+        TPckg<RMobilePhone::TMobilePhoneNetworkInfoV1> netInfoPckg(info);
+        status =  KRequestPending;
+        iPhone.GetHomeNetwork(status, netInfoPckg);
+        
+        User::WaitForRequest( status );
+        GBA_TRACE_DEBUG_NUM(("Can't get network name, error = %d"), status.Int() );
+        User::LeaveIfError( status.Int() );
+        
+        // append the "<IMSI>@ims.mnc<MNC>.mcc<MCC>.3gppnetwork.org"
+        
+        aIdentity.Append( KAT );
+
+        if ( info.iNetworkId.Length() == KNetworkIdLength2 )
+            {
+            //add one more zero if only 2 digits
+            aIdentity.Append( KIMSMNC0 );
+            }
+    
+        if ( info.iNetworkId.Length() == KNetworkIdLength3 )
+            {
+            aIdentity.Append( KIMSMNC ); 
+            }
+
+        aIdentity.Append( info.iNetworkId );
+
+        aIdentity.Append( KMCC );        
+        aIdentity.Append( info.iCountryCode );
+        aIdentity.Append( K3GPPORG );
+      
+
+        GBA_TRACE_DEBUG(("aIdentity="));
+        GBA_TRACE_DEBUG_DESC(aIdentity);
+        }
+    else
+        {
+        aIdentity.Copy(_L8(""));
+        }
+    
+    GBA_TRACE_END();
+    }
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::QueryAuthenticationGBAUL
+// If the GBA_U available, pass RAND and AUTN to smart card via custom API
+// otherwise use RMobilePhone instead
+// -----------------------------------------------------------------------------
+TBool CAkaIsaInterface::QueryAuthenticationGBAUL(   const TDesC8& aNonce,
+                                                    TDes8& aResponse,
+                                                    TDes8& aResync ) 
+    {
+    GBA_TRACE_BEGIN();
+    TBool keys_available = ETrue;
+    //creat buffer to carry the input and output value
+    RMmCustomAPI::TSimAuthenticationGbaBootstrap gbadata;
+    
+    RMmCustomAPI::TGbaBootstrapDataPckg gbabuf( gbadata ); 
+    
+    //Copy input data, RAND and AUTN
+    gbadata.iRandomParameters.Copy(aNonce.Ptr(),KAKA_RAND_LENGTH);
+    gbadata.iAUTN.Copy(aNonce.Ptr()+KAKA_RAND_LENGTH,KAKA_RAND_LENGTH);
+    
+    //call the API to get the RES 
+    TRequestStatus status;
+    
+    status =  KRequestPending;
+    
+    GBA_TRACE_DEBUG(("Send Authentication request to card"));
+    iCustomAPI.GetWlanSimAuthenticationData( status, gbabuf );
+    GBA_TRACE_DEBUG(("Wait for result..."));
+    User::WaitForRequest( status );
+    
+    GBA_TRACE_DEBUG_NUM(("Authentication is Done, err = %d"),status.Int() );
+
+    if(status == KErrNone)
+        {
+        aResponse.Copy(gbadata.iRES);
+        GBA_TRACE_DEBUG_BINARY(gbadata.iRES);
+        }
+    else
+        {
+        keys_available = EFalse;
+        
+        if (status != KErrMMEtelSqnVerificationFailed )
+            {
+            User::LeaveIfError( status.Int() );
+            }
+        }
+
+    if ( status == KErrMMEtelSqnVerificationFailed )
+        {
+        GBA_TRACE_DEBUG_NUM(("AUTS len is Done !!!, len = %d"), gbadata.iAUTS.Length() );
+        GBA_TRACE_DEBUG_BINARY(gbadata.iAUTS);
+      
+        if(gbadata.iAUTS.Length() == 0)
+            {
+            GBA_TRACE_DEBUG(("Auts is Still zero !!!!!"));
+            }
+       else
+            {
+            GBA_TRACE_DEBUG((" before copy"));
+            aResync.Copy(gbadata.iAUTS); 
+            GBA_TRACE_DEBUG(("after copy auts"));
+            }
+        }
+    GBA_TRACE_DEBUG((" Done!"));
+    GBA_TRACE_END(); 
+    return keys_available;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::QueryAuthentication2GL
+// If the GBA_U available, pass RAND and AUTN to smart card via custom API
+// otherwise use RMobilePhone instead
+// run simulated aka
+// -----------------------------------------------------------------------------
+
+void CAkaIsaInterface::QueryAuthentication2GL(  const TDesC8& aNonce, TDes8& aResponse )
+    {
+    GBA_TRACE_BEGIN();
+    RMmCustomAPI::TSimAuthenticationEapSim authSIMdata;
+    RMmCustomAPI::TSimDataPckg authSIMBuf(authSIMdata);
+    
+    TRequestStatus status;
+    status =  KRequestPending;
+    
+    authSIMdata.iRandomParameters.Copy(aNonce.Ptr(),KAKA_RAND_LENGTH);
+    GBA_TRACE_DEBUG(("SIM authentication"));
+    iCustomAPI.GetWlanSimAuthenticationData(status,authSIMBuf);
+    
+    User::WaitForRequest( status );
+    GBA_TRACE_DEBUG_NUM(("GetWlanSimAuthenticationData return, status = %d"), status.Int() );
+    User::LeaveIfError( status.Int() );
+    
+    GBA_TRACE_DEBUG(("Creating 2G authentication vector KDF(key,\"3gpp-gba-res\",sres)"));
+    GBA_TRACE_DEBUG_BINARY(authSIMdata.iSRES);
+    GBA_TRACE_DEBUG_BINARY(authSIMdata.iKC);
+    
+    TBuf8<KMaxBufferSize> lastSRESKC;
+    TBuf8<2*RMmCustomAPI::KMaxKCLength+KAKA_RAND_LENGTH> kc2;
+    
+    // COPYING Kc twice
+    GBA_TRACE_DEBUG(("Copying iKC"));
+    for( TInt  i=0; i<(RMmCustomAPI::KMaxKCLength) ; i++ )
+        {
+        kc2.Append(  (TUint8)(authSIMdata.iKC[i]) );
+        }
+    GBA_TRACE_DEBUG(("Copying iKC"));
+    for( TInt  i=0;i<(RMmCustomAPI::KMaxKCLength);i++ )
+        {
+        kc2.Append(  (TUint8)(authSIMdata.iKC[i]) );
+        }
+    GBA_TRACE_DEBUG(("appending RAND"));
+    kc2.Append(aNonce.Ptr(),KAKA_RAND_LENGTH);
+    
+    GBA_TRACE_DEBUG(("K part"));
+    GBA_TRACE_DEBUG_BINARY(kc2);
+    
+    // appending RAND
+    lastSRESKC.Append( 0x01);
+    lastSRESKC.Append(K3GPPGBARES);
+    lastSRESKC.Append( 0x00);
+    lastSRESKC.Append( 0x0C);
+    GBA_TRACE_DEBUG(("Copying SRES"));
+    
+    for( TInt i=0; i<KIntegerConstant4; i++ )
+        {
+        lastSRESKC.Append( (TUint8)(authSIMdata.iSRES[i]) );
+        }
+    lastSRESKC.Append( 0x00);
+    lastSRESKC.Append( 0x04);
+    GBA_TRACE_DEBUG(("S part"));
+    GBA_TRACE_DEBUG_BINARY(lastSRESKC);
+    
+    // derive response
+    CMessageDigest* digest = CMessageDigestFactory::NewDigestL( CMessageDigest::ESHA256);
+    CleanupStack::PushL( digest );
+    CHMAC* sha256 = CHMAC::NewL(kc2, digest);
+    CleanupStack::Pop( digest );
+    CleanupStack::PushL( sha256 );
+    TPtrC8 hash(sha256->Hash(lastSRESKC));
+    GBA_TRACE_DEBUG(("resulting hash: "));
+    GBA_TRACE_DEBUG_BINARY(hash);
+    
+    aResponse.Append(hash.Ptr(),KRESPONSE_2G_LENGTH);
+    
+    // KEY MATERIAL NEEDS TO BE STORED
+    // CHECK 3GPP TS 3.3220 V7.5.0 (2006-09) page 54 item 7
+    // The BSF shall generate key material Ks by computing Ks = KDF (key, Ks-input, "3gpp-gba-ks", SRES).
+    // The B-TID value shall be also generated in format of NAI by taking the base64 encoded [12] RAND value
+    // from step 3, and the BSF server name, i.e. base64encoded(RAND)@BSF_servers_domain_name.
+    GBA_TRACE_DEBUG(("DERIVING THE MASTER KEY Ks"));
+    
+    TBuf8<KMaxBufferSize> hashMaterial;
+    hashMaterial.Append(0x01);
+    hashMaterial.Append(aNonce.Mid(KIntegerConstant32,KIntegerConstant16));
+    hashMaterial.Append(0x00);
+    hashMaterial.Append(0x10);
+    hashMaterial.Append(K3GPPGBAKS);
+    hashMaterial.Append(0x00);
+    hashMaterial.Append(0x0b);
+    hashMaterial.Append(authSIMdata.iSRES.Left(RMmCustomAPI::KMaxRESLength));
+    hashMaterial.Append(0x00);
+    hashMaterial.Append(0x04);
+    
+    GBA_TRACE_DEBUG(("key for creating the key"));
+    GBA_TRACE_DEBUG_BINARY(kc2);
+    
+    GBA_TRACE_DEBUG(("hashing material for creating the key"));
+    GBA_TRACE_DEBUG_BINARY(hashMaterial);
+    
+    TPtrC8 keymaterial( sha256->Hash( hashMaterial) );
+    
+    GBA_TRACE_DEBUG(("Master key Ks, !!! Remove from LOG"));
+    GBA_TRACE_DEBUG_BINARY(keymaterial);
+    
+    iCKBuf.Copy(keymaterial.Left(KIntegerConstant16));
+    iIKBuf.Copy(keymaterial.Mid(KIntegerConstant16,KIntegerConstant16));
+    
+    CleanupStack::PopAndDestroy( sha256 );
+    
+    GBA_TRACE_DEBUG(("Done!"));
+    GBA_TRACE_END();
+    }
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::QueryAuthentication3GL
+// If the GBA_U available, pass RAND and AUTN to smart card via custom API
+// otherwise use RMobilePhone instead
+// run aka
+// -----------------------------------------------------------------------------
+TBool CAkaIsaInterface::QueryAuthentication3GL(   const TDesC8& aNonce,
+                                                    TDes8& aResponse,
+                                                    TDes8& aResync )
+    {
+    GBA_TRACE_BEGIN();
+    TBool keys_available = ETrue;
+    
+    RMmCustomAPI::TSimAuthenticationEapAka authAkadata;
+    RMmCustomAPI::TAkaDataPckg authAkaBuf(authAkadata);
+    TRequestStatus status;
+    status =  KRequestPending;
+    authAkadata.iRandomParameters.Copy(aNonce.Ptr(),KAKA_RAND_LENGTH);
+    authAkadata.iAUTN.Copy(aNonce.Ptr()+KAKA_RAND_LENGTH,KAKA_RAND_LENGTH);
+    GBA_TRACE_DEBUG(("AKA authentication"));
+    
+    iCustomAPI.GetWlanSimAuthenticationData(status,authAkaBuf);
+    User::WaitForRequest( status );
+    
+    GBA_TRACE_DEBUG_NUM(("GBA_ME:QueryAuthentication3GL: Authentication error = %d"),status.Int()  );
+    
+    if( status.Int() == KErrNone )
+        {
+        GBA_TRACE_DEBUG(("AKA, appending result"));
+        aResponse.Copy(authAkadata.iRES);
+        GBA_TRACE_DEBUG_BINARY(authAkadata.iRES);
+        
+        GBA_TRACE_DEBUG(("storing keys"));
+        
+        // store results
+        iCKBuf.Copy(authAkadata.iCK);
+        iIKBuf.Copy(authAkadata.iIK);
+        }
+    else
+        {
+        keys_available = EFalse;
+        
+        if (status != KErrMMEtelSqnVerificationFailed )
+            {
+            User::LeaveIfError( status.Int() );
+            }
+        }
+    
+    if ( status == KErrMMEtelSqnVerificationFailed )
+        {
+        GBA_TRACE_DEBUG_NUM(("GBA_ME:QueryAuthentication3GL: AUTS len is Done !!!, len = %d"), authAkadata.iAUTS.Length() );
+        GBA_TRACE_DEBUG_BINARY( authAkadata.iAUTS );
+        
+        if(authAkadata.iAUTS.Length() == 0)
+            {
+            GBA_TRACE_DEBUG(("GBA_U:QueryAuthentication3GL: Auts is Still zero !!!!!"));
+            }
+        else
+            {
+            GBA_TRACE_DEBUG(("QueryAuthentication3GL before copy"));
+            aResync.Copy(authAkadata.iAUTS);
+            GBA_TRACE_DEBUG(("QueryAuthentication3GL after copy auts"));
+            }
+        }
+    GBA_TRACE_END();
+    return keys_available;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::QueryAuthenticationL
+// If the GBA_U available, pass RAND and AUTN to smart card via custom API
+// otherwise use RMobilePhone instead
+// -----------------------------------------------------------------------------
+TBool CAkaIsaInterface::QueryAuthenticationL(
+     const TDesC8& aNonce, 
+     TDes8& aResponse, 
+     TDes8& aResync ) 
+    {
+    GBA_TRACE_BEGIN();
+    GBA_TRACE_DEBUG(("aka nonce="));
+    GBA_TRACE_DEBUG_BINARY(aNonce);
+    // GBA_U not availiable
+    if ( iCardInterface != EGBAUInterface )
+        {
+        GBA_TRACE_DEBUG(("QueryAuthenticationL is starting..."));
+        
+        //run aka
+        if ( iCardInterface == E3GInterface )
+            {
+            return QueryAuthentication3GL( aNonce, aResponse, aResync );
+            }
+        
+        // run simulated aka
+        if ( iCardInterface == E2GInterface )
+            {
+            QueryAuthentication2GL( aNonce, aResponse );
+            return ETrue;
+            }
+        return EFalse;
+        }
+    else
+        {
+        GBA_TRACE_DEBUG(("GBA_U authentication"));
+        return QueryAuthenticationGBAUL( aNonce, aResponse, aResync );   
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::QueryKeyMaterialL()
+// If GBA_U, send the request to smart card.
+// -----------------------------------------------------------------------------
+//
+void CAkaIsaInterface::QueryKeyMaterialL(const TDesC8& aKey, const TDesC8& aRand, const TDesC8& aIMPI, const TDesC8& aUTF8_NAF_ID, TDes8& aDerivedKey ) 
+    {
+    if ( iCardInterface == EGBAUInterface )
+        { 
+        GBA_TRACE_DEBUG_BINARY(aUTF8_NAF_ID);
+
+        GBA_TRACE_DEBUG(("GBA_U:QueryKeyMaterialL: Enter the function"));
+        
+        TRequestStatus status;
+        status =  KRequestPending;
+
+        RMmCustomAPI::TSimAuthenticationGbaNafDerivation nafdata;
+    
+        RMmCustomAPI::TGbaNafDerivationDataPckg nafbuf( nafdata );
+  
+        nafdata.iNafId.Copy( aUTF8_NAF_ID );
+        
+        
+        GBA_TRACE_DEBUG(("GBA_U:QueryKeyMaterialL: copy nafid, no truncate"));
+        GBA_TRACE_DEBUG_BINARY(aUTF8_NAF_ID);
+        
+        nafdata.iImpi.Copy( aIMPI );
+        
+         GBA_TRACE_DEBUG(("GBA_U:QueryKeyMaterialL: copy impi, no truncate"));
+        iCustomAPI.GetWlanSimAuthenticationData( status, nafbuf ); 
+       
+        User::WaitForRequest( status ); 
+        
+        GBA_TRACE_DEBUG_NUM(("GBA_U:QueryKeyMaterialL: QueryKeyMaterial is Done, err = %d"), status.Int());
+          
+        User::LeaveIfError( status.Int() );
+
+        aDerivedKey.Copy( nafdata.iKsExtNaf ); //return the ks_ext_naf
+        }
+    else //GBA_ME
+        {
+        GBA_TRACE_DEBUG(("QueryKeyMaterial"));
+        GBA_TRACE_DEBUG(("derive key as specified in 33.22 V7.5.0 page 35"));
+        // derive key as specified in 33.22 V7.5.0 page 35
+        // S = FC || P0 || L0 || P1 || L1 || P2 || L2 || P3 || L3 ||... || Pn || Ln
+        // derived key = HMAC-SHA-256 ( Key , S )
+        // -  FC = 0x01,
+        // -  P1 = RAND,
+        // -  L1 = length of RAND is 16 octets (i.e. 0x00 0x10),
+        // -  P2 = IMPI encoded to an octet string using UTF-8 encoding (see clause B.2.1),
+        // -  L2 = length of IMPI is variable (not greater that 65535),
+        // -  P3 = NAF_ID with the FQDN part of the NAF_ID encoded to an octet string using UTF-8 encoding (see clause B.2.1), and
+        // -  L3 = length of NAF_ID is variable (not greater that 65535).
+        // In the key derivation of Ks_NAF as specified in clause 4 and Ks_ext_NAF as specified in clause 5,
+        // -  P0 = "gba-me" (i.e. 0x67 0x62 0x61 0x2d 0x6d 0x65), and
+        // -  L0 = length of P0 is 6 octets (i.e., 0x00 0x06).
+        // In the key derivation of Ks_int_NAF as specified in clause 5,
+        // -  P0 = "gba-u" (i.e. 0x67 0x62 0x61 0x2d 0x75), and
+        // -  L0 = length of P0 is 5 octets (i.e., 0x00 0x05).
+        TBuf8<KMaxBufferSize> ks_NAF_material;
+        // FC
+        ks_NAF_material.Append(0x01);
+        // P0
+        ks_NAF_material.Append(KGBAME);
+        // L0
+        ks_NAF_material.Append(0x00);
+        ks_NAF_material.Append(0x06);
+        // P1
+        ks_NAF_material.Append(aRand);
+        // L1 - length of rand in two bytes
+        ks_NAF_material.Append(0x00);
+        ks_NAF_material.Append((TUint8)aRand.Length());
+        // P2
+        ks_NAF_material.Append(aIMPI);
+        // L2 - length of impi in two bytes
+        ks_NAF_material.Append(0x00);
+        ks_NAF_material.Append((TUint8)aIMPI.Length());
+        // P2
+        ks_NAF_material.Append(aUTF8_NAF_ID);
+        // L2 - length of FQDN (NAF_ID) in two bytes
+        ks_NAF_material.Append(0x00);
+        ks_NAF_material.Append((TUint8)aUTF8_NAF_ID.Length());
+        GBA_TRACE_DEBUG(("NAF_ID"));
+        GBA_TRACE_DEBUG_DESC(aUTF8_NAF_ID);    
+        GBA_TRACE_DEBUG(("Value of K"));
+        GBA_TRACE_DEBUG_BINARY(aKey);
+        GBA_TRACE_DEBUG(("Value of S"));
+        GBA_TRACE_DEBUG_BINARY(ks_NAF_material);
+        
+        CMessageDigest* digest = CMessageDigestFactory::NewDigestL( CMessageDigest::ESHA256);
+        CleanupStack::PushL( digest );
+        CHMAC* sha256 = CHMAC::NewL(aKey, digest); //sha256 will take the ownership of digest pointer
+        CleanupStack::Pop( digest );
+        CleanupStack::PushL( sha256 );
+        TPtrC8 hash(sha256->Hash(ks_NAF_material));
+        aDerivedKey.Copy(hash);
+        CleanupStack::PopAndDestroy( sha256 ); //sha256
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::QueryKs()
+// -----------------------------------------------------------------------------
+//
+TBool CAkaIsaInterface::QueryKs( TDes8& aKS )
+    {
+    GBA_TRACE_DEBUG(("CAkaIsaInterface::QueryKs"));
+    if( iIKBuf.Length()> 0 && iCKBuf.Length() > 0 )
+        {
+        GBA_TRACE_DEBUG(("got Ks to copy"));
+        aKS.Append(iCKBuf);
+        aKS.Append(iIKBuf);
+        GBA_TRACE_DEBUG(("Copy done!"));
+        return ETrue;
+        }
+    GBA_TRACE_DEBUG(("No Ks to copy, something wrong in Authentication"));
+    return EFalse;
+    }
+    
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::QueryHomeNetworkDnL()
+// -----------------------------------------------------------------------------
+//
+void CAkaIsaInterface::QueryHomeNetworkDnL( TDes8& aHNDN )
+    {
+    RMobilePhone::TMobilePhoneNetworkInfoV1 info;
+    TPckg<RMobilePhone::TMobilePhoneNetworkInfoV1> netInfoPckg(info);
+    TRequestStatus status;
+
+    status =  KRequestPending;
+    iPhone.GetHomeNetwork(status, netInfoPckg);
+    User::WaitForRequest( status );
+    
+    GBA_TRACE_DEBUG_NUM(("phone status = %d"), status.Int() );
+    User::LeaveIfError( status.Int() );
+    
+    // append the bsf.mnc0<MNC>.mcc<MCC>.pub.3gppnetwork.org or bsf.mnc.<MNC>.mcc<MCC>.pub.3gppnetwork.org
+  
+    if ( InterfaceIs2G() )
+        {
+        aHNDN.Copy( KHTTPSTag );  
+        }
+    else
+        {
+        aHNDN.Copy( KHTTPTag ); 
+        } 
+
+    if ( info.iNetworkId.Length() == KNetworkIdLength2 )
+        {
+        //Append KBSFMNC0 to aHNDN
+        aHNDN.Append( KBSFMNC0 );
+        }
+    
+    if ( info.iNetworkId.Length() == KNetworkIdLength3 )
+        {
+		//Append KBSFMNC to aHNDN
+        aHNDN.Append( KBSFMNC ); 
+        }
+       
+    aHNDN.Append( info.iNetworkId );
+    aHNDN.Append( KMCC );        
+    aHNDN.Append( info.iCountryCode );
+    aHNDN.Append( KPUB3GPPORG );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::InterfaceIs2G()
+// -----------------------------------------------------------------------------
+//
+TBool CAkaIsaInterface::InterfaceIs2G() 
+    {
+    GBA_TRACE_DEBUG(("CAkaIsaInterface: Enter the function "));
+    GBA_TRACE_DEBUG_NUM(("CAkaIsaInterface: iCardInterface is %d "), iCardInterface );
+    return iCardInterface == E2GInterface;
+    };
+
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::QueryGBAUAvailability()
+// Get the GBA_U availability from smart card via custom API
+// -----------------------------------------------------------------------------
+void CAkaIsaInterface::QueryGBAUAvailabilityL( TBool& aGBAAvail )
+    {
+    GBA_TRACE_DEBUG(("QueryGBAUAvailability: Enter the function "));
+    GBA_TRACE_DEBUG_NUM(("QueryGBAUAvailability: iCardInterface is %d "), iCardInterface );
+    aGBAAvail = ( iCardInterface == EGBAUInterface );
+    }
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::UpdateGBADataL()
+// Save the B-TID and keylifetime to smart card
+// -----------------------------------------------------------------------------
+
+TInt CAkaIsaInterface::UpdateGBADataL( const TDesC8& aBTID, const TDesC8& aLifetime )
+    {
+    
+    GBA_TRACE_DEBUG(("GBA_U:UpdateGBADataL: Enter the function"));
+    
+    TRequestStatus status;
+    status =  KRequestPending;
+
+    RMmCustomAPI::TSimAuthenticationGbaBootstrapUpdate updatedata;
+
+    updatedata.iBTid.Copy( aBTID );
+    updatedata.iKeyLifeTime.Copy( aLifetime );
+
+    RMmCustomAPI::TGbaBootstrapUpdateDataPckg updatebuf( updatedata );
+        
+    iCustomAPI.GetWlanSimAuthenticationData( status, updatebuf ); 
+     
+    User::WaitForRequest( status );
+    
+    GBA_TRACE_DEBUG_NUM(("GBA_U:UpdateGBADataL: Update GBA is Done, err = %d"), status.Int());
+    
+    return status.Int();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::Release()
+// -----------------------------------------------------------------------------
+void CAkaIsaInterface::Release()
+     {
+     delete this; 
+     }
+
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::NotifyCardChangeL()
+// -----------------------------------------------------------------------------
+void CAkaIsaInterface::NotifyCardChangeL()
+    {
+    // the card is changed, we need to re-initialize the interface 
+	QueryCardInterfaceL();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CAkaIsaInterface::QueryCardInterfaceL()
+// ----------------------------------------------------------------------------- 
+//   
+void CAkaIsaInterface::QueryCardInterfaceL()
+    {
+    GBA_TRACE_BEGIN();
+
+    GBA_TRACE_DEBUG(("QueryCardInterfaceL is starting..."));
+
+    TUint32 caps = 0;
+      
+    GBA_TRACE_DEBUG(("Found! Phone open! Checking what kind of ICC access we have...known types : {SIM,RUSIM,USIM}"));    
+    User::LeaveIfError( iPhone.GetIccAccessCaps( caps ) );
+
+    if ( caps & RMobilePhone::KCapsUSimAccessSupported )
+        {
+        GBA_TRACE_DEBUG(("This device  offers USIM access")); 
+             
+        //check if the card support GBA-U interface
+        GBA_TRACE_DEBUG(("Check is GBA-U supported")); 
+        TRequestStatus status;
+        status =  KRequestPending;
+
+        RMmCustomAPI::TAppSupport appSupport;
+    
+        //GBA-U 0, MGV-U 1
+        appSupport.iAppNum = 0; 
+     
+        iCustomAPI.GetUSIMServiceSupport( status, appSupport);
+
+        User::WaitForRequest( status );
+
+        GBA_TRACE_DEBUG_NUM(("QueryCardInterfaceL: GBA_U avail checking is Done, err = %d"), status.Int());
+    
+        if ( status.Int() == KErrNotFound )
+            {
+            //Not gba-u service available
+            GBA_TRACE_DEBUG(("QueryCardInterfaceL: it returns KErrNotFound, No GBA-U "));
+            // set interface as 3g then
+            iCardInterface = E3GInterface;
+            }
+        else if ( status.Int() == KErrNone )
+            {
+            //pass the value back
+            GBA_TRACE_DEBUG(("QueryCardInterfaceL: it returns KErrNone"));
+            if ( appSupport.iSupported )
+                {
+            	GBA_TRACE_DEBUG(("QueryCardInterfaceL: GBA-U support "));
+                iCardInterface = EGBAUInterface;
+                }
+            else
+                {
+                GBA_TRACE_DEBUG(("QueryCardInterfaceL: GBA-U NOT support "));
+                iCardInterface = E3GInterface;	
+                }    
+            }
+        else
+            {
+            //leave , unexpected situation
+            User::LeaveIfError(status.Int());    
+            }    
+        }
+    else if( caps & RMobilePhone::KCapsSimAccessSupported )
+        {
+    	GBA_TRACE_DEBUG(("This device  offers SIM access only"));        
+        iCardInterface = E2GInterface;
+        //The card only support 2G interface
+        }
+    else
+        {
+        //nothing	
+        }
+    }
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+#include "../cms/group/bld.inf"            
+
+#include "../pkiutilities/group/bld.inf"
+#include "../wim/Group/bld.inf"
+#include "../remotelock/Group/bld.inf"
+#include "../secsrv_plat/group/bld.inf"
+#include "../securitydialogs/group/bld.inf"
+#include "../boottimeintegritycheck/group/bld.inf"
+#include "../gba/group/bld.inf"
+#include "../devencdiskutils/group/bld.inf"
+
+
+
+PRJ_TESTMMPFILES
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/layers.sysdef.xml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<!DOCTYPE SystemDefinition SYSTEM "sysdef_1_4_0.dtd" [
+  <!ENTITY layer_real_source_path "sf/mw/securitysrv" >
+]>
+
+<SystemDefinition name="securitysrv" schema="1.4.0">
+  <systemModel>
+    <layer name="mw_layer">
+      <module name="securitysrv">
+        <unit name="securitysrv" unitID="sedo.securitysrv" bldFile="&layer_real_source_path;/group" mrp="" />
+      </module>
+      <module name="">
+        <unit unitID="sedo.securitysrv.pkiutilities.Certificates" bldFile="&layer_real_source_path;/pkiutilities/Certificates/group" mrp="" filter="sf_build" name="sedo_securitysrv_pkiutilities_Certificates" />
+      </module>
+      <module name="">
+        <unit unitID="sedo.securitysrv.pkiutilities.Certificates_OEM" bldFile="&layer_real_source_path;/pkiutilities/Certificates_OEM/group" mrp="" filter="oem_build" name="sedo_securitysrv_pkiutilities_Certificates_OEM" />
+      </module> 
+    </layer>
+    <layer name="api_test_layer">
+      <module name="securitysrv_test">
+        <unit unitID="sedo.securitysrv_test" mrp="" bldFile="&layer_real_source_path;/tsrc/group" name="securitysrv_test" />
+      </module>
+    </layer>
+  </systemModel>
+</SystemDefinition>
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/package_definition.xml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,116 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<SystemDefinition schema="3.0.0">
+  <package id="securitysrv" name="Security Services" levels="plugin framework server generic specific">
+    <collection id="gba" name="Generic Bootstrapping Architecture" level="server">
+      <component id="uicc" filter="s60" name="UICC" class="plugin" introduced="^2">
+        <unit bldFile="gba/uicc/group"/>
+      </component>
+      <component id="bootstrap" filter="s60" name="Bootstrap" introduced="^2">
+        <unit bldFile="gba/bootstrap/group"/>
+      </component>
+      <component id="gbaserver" filter="s60" name="GBA Server" introduced="^2">
+        <unit bldFile="gba/gbaserver/group"/>
+      </component>
+      <component id="gbaapi" filter="s60" name="GBA API" introduced="^2">
+        <unit bldFile="gba/gbaapi/group"/>
+      </component>
+      <component id="gbafilter" filter="s60" name="GBA HTTP Filter" class="plugin" introduced="^2">
+        <unit bldFile="gba/gbafilter/group"/>
+      </component>
+      <component id="gba_build" filter="s60" name="Generic Boot Architecture Build" introduced="^2">
+        <unit bldFile="gba/group"/>
+      </component>
+    </collection>
+    <collection id="wim" name="Wireless Identity Module " level="framework">
+      <component id="swimreader" filter="s60" name="SWIM Reader"/>
+      <component id="scard" filter="s60" name="Smart Card"/>
+      <component id="wimutil" filter="s60" name="WIM Utils"/>
+      <component id="wimserver" filter="s60" name="WIM Server"/>
+      <component id="wimclient" filter="s60" name="WIM Client"/>
+      <component id="wimplugin" filter="s60" name="WIM Plugin" class="plugin"/>
+      <component id="wim_build" filter="s60" name="WIM Build">
+           <!-- need to distribute bld.inf to empty components or collapse into a single component -->
+        <unit bldFile="wim/group"/>
+      </component>
+    </collection>
+    <collection id="pkiutilities" name="PKI Utilities" level="plugin">
+      <component id="x509certnameparser" filter="s60" name="X.509 Certificate Name Parser">
+        <unit bldFile="pkiutilities/x509certnameparser/group"/>
+      </component>
+      <component id="pkcs12" filter="s60" name="PKCS #12">
+        <unit bldFile="pkiutilities/pkcs12/group"/>
+      </component>
+      <component id="certmanui" filter="s60" name="Certificate Management UI">
+        <unit bldFile="pkiutilities/certmanui/group"/>
+      </component>
+      <component id="ctsecuritydialogs" filter="s60" name="Crypto Token Security Dialogs">
+        <unit bldFile="pkiutilities/ctsecuritydialogs/group"/>
+      </component>
+      <component id="certsaver" filter="s60" name="Certificate Saver">
+        <unit bldFile="pkiutilities/certsaver/group"/>
+      </component>
+      <component id="secmodui" filter="s60" name="Security Module UI">
+        <unit bldFile="pkiutilities/secmodui/group"/>
+      </component>
+      <component id="devicetoken" filter="s60" name="Device Token">
+        <unit bldFile="pkiutilities/devicetoken/group"/>
+      </component>
+      <component id="certificates" filter="s60" name="Certificates">
+        <unit bldFile="pkiutilities/certificates/group"/>
+      </component>
+      <component id="pkiutilities_build" filter="s60" name="PKI Utilities Build">
+        <unit bldFile="pkiutilities/group"/>
+      </component>
+     <component id="ocsp" name="Online Certificate Status Protocol" introduced="^2" purpose="optional">
+       <unit bldFile="pkiutilities/ocsp/group" mrp="pkiutilities/ocsp/group/securitysrv_ocsp.mrp"/>
+      </component>
+    </collection>
+    <collection id="remotelock" name="Remote Lock" level="generic">
+      <component id="remotelocksettings" filter="s60" name="Remote Lock Settings"/>
+      <component id="remotelockengine" filter="s60" name="Remote Lock Engine"/>
+      <component id="remotelock_build" filter="s60" name="Remote Lock Build">
+           <!-- need to distribute bld.inf to empty components or collapse into a single component -->
+        <unit bldFile="remotelock/group"/>
+      </component>
+    </collection>
+    <collection id="boottimeintegritycheck" name="Boot Time Integrity Check" level="plugin">
+      <component id="trkdummy" filter="s60" name="Trk Dummy">
+        <!-- <unit bldFile="boottimeintegritycheck/trkdummy/group"/> -->
+      </component>
+      <component id="boottimeintegritycheck_build" filter="s60" name="Boot Time Integrity Check Build">
+        <unit bldFile="boottimeintegritycheck/group"/>
+      </component>
+    </collection>
+    <collection id="securitydialogs" name="Security Dialogs" level="specific">
+      <component id="keylockpolicyapi" filter="s60" name="Keylock Policy API">
+        <unit bldFile="securitydialogs/keylockpolicyapi/group"/>
+      </component>
+      <component id="autolock" name="Autolock" filter="s60">
+        <unit bldFile="securitydialogs/autolock/group"/>
+      </component>
+      <component id="secui" filter="s60" name="Security UI">
+        <unit bldFile="securitydialogs/secui/group"/>
+      </component>
+      <component id="securitynotifier" filter="s60" name="Security Notifier">
+        <unit bldFile="securitydialogs/securitynotifier/group"/>
+      </component>
+      <component id="securityobserver" filter="s60" name="Security Observer">
+        <unit bldFile="securitydialogs/securityobserver/group"/>
+      </component>
+    </collection>
+    <collection id="securitysrv_info" name="Security Services Info" level="specific">
+      <component id="secsrv_plat" name="Security Services Platform Interfaces" filter="s60" class="api">
+        <unit bldFile="secsrv_plat/group"/>
+        <!-- <unit bldFile="secsrv_plat/devicelock_access_api/group"/> -->
+        <!-- <unit bldFile="secsrv_plat/keyguard_access_api/group"/> -->
+        <!-- <unit bldFile="secsrv_plat/lockapp_server_api/group"/> -->
+      </component>
+      <component id="securitysrv_test" filter="s60" purpose="development" name="Security Services Test">
+        <!-- <unit bldFile="tsrc/group"/> -->
+      </component>
+      <component id="securitysrv_metadata" name="Security Services Metadata" class="config" introduced="^2" purpose="development" target="desktop">
+        <unit mrp="securitysrv_info/securitysrv_metadata/securitysrv_metadata.mrp"/>
+      </component>
+    </collection>
+  </package>
+</SystemDefinition>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/BWINSCW/CTSecDilogImplU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?NotifierArray@@YAPAV?$CArrayPtr@VMEikSrvNotifierBase2@@@@XZ @ 1 NONAME ; class CArrayPtr<class MEikSrvNotifierBase2> * NotifierArray(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/BWINSCW/CTSecDlgsU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?CreateNoteL@PKIDialogFactory@@SAPAVMPKIDialog@@XZ @ 1 NONAME ; class MPKIDialog * PKIDialogFactory::CreateNoteL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/ClientInc/CDigSigningNote.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,104 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Header file of the CDigSigningNote
+*
+*/
+
+
+#ifndef CDIGSIGNINGNOTE_H
+#define CDIGSIGNINGNOTE_H
+
+//  INCLUDES
+#include "SecurityDialogBase.h"
+#include <DigSigningNote.h>  // MDigSigningNote
+#include <e32std.h>
+
+// CLASS DECLARATION
+
+/**
+*  This class implements MDigSigningNote interface.
+*  
+*
+*  @lib CTSecDlgs.lib
+*  @since Series60_2.6
+*/
+class CDigSigningNote : public CSecurityDialogBase, public MDigSigningNote
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CDigSigningNote* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CDigSigningNote();
+    
+    public: // Functions from MDigSigningNote
+
+        /**
+        * Informs the user during digital signing.
+        * @param aNoteType Identifies the note type.
+        * @param aStatus OUT: KErrNone or KErrNotSupported
+        * @return void
+        */
+        void ShowNote(MDigSigningNote::TNoteType aNoteType, TRequestStatus& aStatus);
+        
+        /**
+        * Saves receipt to Notepad if receipt saving is on in .ini-file and
+        * informs user about this.
+        * @since ?Series60_version
+        * @param aSignedText Signed text in readable form.
+		* @param aStatus OUT: KErrNone or KErrNotSupported
+        * @return void
+        */
+        void SaveSignedText(const TDesC& aSignedText, TRequestStatus& aStatus);
+        
+        /**
+        * Shows instructions how to unblock PIN.
+        * @since ?Series60_version
+        * @param aLabel Label of the PIN.
+        * @param aStatus KErrNone or KErrNotSupported
+        * @return void
+        */
+        void ShowPINBlockedInfo(const TPINLabel& aLabel, TRequestStatus& aStatus);
+
+        /**
+    	*	Release is called to free resources of the MSecurityDialog class
+	    */
+	    void Release();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CDigSigningNote();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    private:    // Data
+        
+	    CBufFlat*	iSenderBuffer;	// Stream buffer for outgoing streams.
+    	HBufC8*     iBufferData;    // iSenderBuffer help buffer
+    };
+
+#endif      // CDIGSIGNINGNOTE_H  
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/ClientInc/CPKIDlg.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,246 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Header file of the CPKIDialog
+*
+*/
+
+
+#ifndef CPKIDLG_H
+#define CPKIDLG_H
+
+//  INCLUDES
+#include "SecurityDialogBase.h"
+#include <PKIDlg.h>  // MPKIDialog
+#include <e32std.h>
+#include <secdlgimpldefs.h>
+
+// FORWARD DECLARATIONS
+class CCTSecurityDialogRequestor;
+
+// CLASS DECLARATION
+
+/**
+*  This class implements MPKIDialog interface.
+*  
+*
+*  @lib CTSecDlgs.lib
+*  @since Series60_3:0
+*/
+NONSHARABLE_CLASS( CPKIDialog ): 
+    public CBase, public MSecurityDialogResponse, public MPKIDialog
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CPKIDialog* NewL();
+        
+    
+    public: // Functions from MPKIDialog
+    
+       /**
+    	* User authentication dialogs
+    	* @param aCertHandleList	A selection of certificates to display to the user.
+    	*							All certificates are displayed if this is empty.
+    	* @param aCertHandle		On return, an identifier for the certificate the user selected.
+    	* 							aStatus - this will be set to KErrNotFound if no certificates
+    	*							could be presented to the user.
+    	* @param aStatus			This will be set to KErrNotFound if no certificates could
+    	* 							be presented to the user.
+    	*/
+    	void UserAuthentication(
+	            const RArray<TCTTokenObjectHandle>& aCertHandleList, 
+	            TCTTokenObjectHandle& aCertHandle,
+	            TRequestStatus& aStatus );
+        
+        /**
+    	* User authentication dialogs with text
+    	* 
+    	* @param aTextToSign		The text to be signed.
+    	* @param aCertHandleList	A selection of certificates to display to the user.
+    	*							All certificates are displayed if this is empty.
+    	* @param aCertHandle		On return, an identifier for the certificate the user selected.
+    	* 							aStatus - this will be set to KErrNotFound if no certificates
+    	*							could be presented to the user.
+    	* @param aStatus			This will be set to KErrNotFound if no certificates could
+    	* 							be presented to the user.
+    	*/
+    	void UserAuthenticationText(
+                const TDesC& aTextToSign,
+	            const RArray<TCTTokenObjectHandle>& aCertHandleList, 
+	            TCTTokenObjectHandle& aCertHandle,
+	            TRequestStatus& aStatus );
+    						   
+    	/**
+    	* Certificate signing request dialog
+    	* 
+    	* @param aSubject		    Subject of the certificate
+    	* @param aKeyHandle      	An identifier of the private used in the CSR.                           
+    	* @param aStatus			This will be set to KErrNotFound if no certificates could
+    	* 							be presented to the user.
+    	*/
+    	void CreateCSR( 
+    	        const TDesC& aSubject,
+                const TCTTokenObjectHandle& aKeyHandle,
+                TRequestStatus& aStatus );					  
+
+            
+        /**
+        * Shows details of the certificate
+        * @param aCertHandle	    An identifier of the certificate
+        * @param aStatus            KErrNone or KErrNotSupported
+        *                           KErrNotFound if no certificates could
+    	* 							be presented to the user.  
+        * @return void
+        */
+        void CertificateDetails( 
+                const TCTTokenObjectHandle& aCertHandle,
+                TRequestStatus& aStatus  );
+        /**
+        * Asks user's approval for certificate saving.
+        * @param aFormat		   The format of the certificate.
+        * @param aCertificateOwnerType	The owner type.
+        * @param aCert					The certificate to be added.
+        * @param aStatus            KErrNone, KErrCancel or KErrNotSupported,
+        *                           KErrArgument if error in certificate parsing
+        * @return void
+        */
+        void SaveCertificate( 
+                TCertificateFormat aFormat,
+                TCertificateOwnerType aCertificateOwnerType, 
+                const TDesC8& aCert, 
+                TRequestStatus& aStatus);
+        
+        /**
+        * Asks user's approval for certificate deleting.
+        * @param aCertHandle	    An identifier of the certificate
+        * @param aStatus            KErrNone, KErrCancel or KErrNotSupported,
+        *                           KErrNotFound if no certificates could
+    	* 							be presented to the user.    
+        * @return void
+        */
+        void DeleteCertificate( 
+                const TCTTokenObjectHandle& aCertHandle,
+                TRequestStatus& aStatus  );
+        
+        /**
+        * Informs the user during digital signing.
+        * @param aNoteType Identifies the note type.
+        * @param aStatus KErrNone or KErrNotSupported
+        * @return void
+        */
+        void Note( MPKIDialog::TNoteType aNoteType,
+                   TRequestStatus& aStatus );
+        
+        /**
+        * Saves receipt to Notepad if receipt saving is on.
+        * @param aSignedText Signed text in readable form.
+        * @param aStatus KErrNone or KErrNotSupported
+        * @return void
+        */
+        void SaveSignedText( const TDesC& aSignedText,
+                             TRequestStatus& aStatus );
+        
+        /**
+        * Shows instructions how to unblock PIN.
+        * @param aLabel Label of the PIN.
+        * @param aStatus KErrNone or KErrNotSupported
+        * @return void
+        */
+        void PINBlockedInfo( const TPINLabel& aLabel,
+                             TRequestStatus& aStatus );       
+        /**
+        * Release is called to free resources of the MDigSigningNote class
+        */
+        void Release();
+        
+    public: // Functions from MSecurityDialogResponse
+    
+        void HandleResponse(TInt aResult);
+        
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CPKIDialog();
+        
+        /**
+        * Destructor.
+        */
+        ~CPKIDialog();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+        
+         /**
+        *
+        * @param aStatus
+        */
+        void InitClientStatus(TRequestStatus& aStatus);
+     
+        /**
+	    * ShowNoteL shows a dialog/note using Notifier API.
+	    *
+	    * @param aStatus	Signaled value for async operation. KErrNone if successful, otherwise system error.
+	    * @param aDlgType	Dialog type
+	    * @param aReturnValue	Return value of a dialog. If aStatus == KErrNone, then the user's response
+	    *						is located here. ETrue means positive response (OK, continue etc.),
+	    *						EFalse means negative response.
+	    * @param aDynamic	Dynamic text for dialog. Effective only if %U is in the localisation resource.
+	    *
+	    * Leaves on: System error before showing the actual dialog
+	    *
+	    * Asserts on: If aDlgType is a PIN/PUK code query.
+	    */
+	    void ShowNoteL(TRequestStatus& aStatus, 
+                       TInt aNoteTypeaDlgType, 
+                       const TDesC& aDynamic = KNullDesC);
+           
+        void RequestWithTokenHandleL( 
+            const TDesC& aText,
+            const TCTTokenObjectHandle& aTokenHandle,
+            TRequestStatus& aStatus );   
+            
+        void DoSaveCertificateL( 
+            TCertificateFormat aFormat,
+            TCertificateOwnerType aCertificateOwnerType, 
+            const TDesC8& aCert, 
+            TRequestStatus& aStatus);
+                       
+    private:    // Data
+        CCTSecurityDialogRequestor* iRequester;	  // Owned
+        TRequestStatus* iClientStatus;  // Pointer to client's request status
+									    // We must signal it when dialogrequestor
+									    // RunL is called to signal the completion of a dialog!
+        
+	    CBufFlat*	iSenderBuffer;	// Stream buffer for outgoing streams.
+    	HBufC8*     iBufferData;    // iSenderBuffer help buffer
+    	
+	    TDialogType iCurrentOperation;
+	
+	    TSignInputBuf iSignInputBuf;
+	    TPtrC8 iVariableDataPtr;
+	    TCTTokenObjectHandle* iClientCertInfoHandlePtr;
+	    TCTTokenObjectHandleBuf iCertInfoHandleBuf;
+	    TBuf8<10> iDlgResponseBuf;
+    };
+
+#endif      // CPKIDLG_H
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/ClientInc/CTSecurityDialogDefs.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,176 @@
+/*
+* Copyright (c) 2002-2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Resource mapper for CT Security Dialogs.
+*
+*/
+
+
+#ifndef __CTSECURITYDIALOGDEFS_H
+#define __CTSECURITYDIALOGDEFS_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <CTSecDlgs.rsg>
+#include <avkon.rsg>
+#include <secdlg.h>
+#include <data_caging_path_literals.hrh>
+#include <secdlgimpldefs.h>
+
+const TUid KUidCTSecDlgAppServer = { 0x10207445 };
+
+/**
+ * Input data for the ESaveCert operation.
+ */
+class TSaveCertInput
+  {
+public:
+  TSecurityDialogNotification iOperation;
+  TCertificateFormat iCertFormat;
+  TCertificateOwnerType iCertOwnerType;
+  TInt iDataSize;
+  };
+
+/** */
+typedef TPckgBuf<TSaveCertInput> TSaveCertInputBuf;
+
+
+// Selection types
+enum
+    {
+    EServerCertNotAccepted,
+    EServerCertAcceptedTemporarily,
+    EServerCertAcceptedPermanently
+    };
+
+// Dialog types for Security dialogs and notes.
+enum TDialogType
+    {
+    EEnterPinNR,
+    EEnterNewPinNR,
+    EEnterPukNR,
+    EVerifyPinNR,
+    EEnterPw,
+    EEnterKeyStorePw,
+    EEnterNewKeyStorePw,
+    EVerifyKeyStorePw,
+
+    EImportKeyPw,
+    EExportKeyPw,
+    //ESignText,
+                       // something wrong with the server certificate)
+    EInfoSignTextRequested,
+    EInfoSignTextCancelled,
+    EInfoSignTextDone,
+    EInfoPinCodeUnblocked,
+    EInfoPwCreating,
+
+    EErrorPinCodeIncorrect,
+    EErrorPinCodeBlocked,
+    EErrorPukCodeIncorrect,
+    EErrorPukCodeBlocked,
+    EErrorCodesDoNotMatch,
+    EErrorWimNotAvailable,
+
+    EPinCodeBlockedInfo,
+    ENoMatchingPersonalCert,
+    EErrorInternal,
+    ESaveReceipt,
+
+    EUserAuthentication,
+    EUserAuthenticationText,
+    ECreateCSR,
+    ECertDetails,
+    ESaveCert,
+    EDeleteCert,
+    };
+
+// Layout types for Dialogs/Notes
+enum TNoteType
+    {
+    EInfoNote,      // Meaning 'information', with green ! sign
+    EErrorNote,     // Meaning 'error', with red ! sign
+    EConfirmationNote,  // Meaning 'confirmed', with green V sign
+
+    EInfoDialog,    // Information dlg,
+    EWarningDialog,   //
+    EErrorDialog,   //
+    EConfirmationDialog,// Confirmation dlg, with blue
+    EOkDialog,      //
+
+    EEnterPinGCodeDialog, //
+    EVerifyPinGCodeDialog,  //
+    EEnterPinNRCodeDialog,  //
+    EVerifyPinNRCodeDialog, //
+    EEnterPinPinCodeDialog,
+    EEnterPwDialog,
+    EEnterPwPwDialog,
+
+    ESecurityAlertDialog
+    };
+
+// KDialogTypeToResourceMapper item definition
+struct TDialogTypeItem
+    {
+    TInt      iDialogType;      // Dialog type
+    TInt    iResourceIdentifier;  // Main resource id
+    TInt    iDynamicResourceIdentifier; // dynamic resource for main resource
+    TNoteType iNoteType;        // Type of dialog/note that we are going to use.
+    TInt    iSoftKeyResource;   // Softkey Resource to use for dlg (does not have effect on notes)                    // if 0 -> The dialog uses its defaults.
+    };
+
+// Dialog type to resource mapper array. Items are TDialogTypeItems.
+const TDialogTypeItem KDialogTypeToResourceMapper[] =
+    {
+    { EEnterPinNR, R_QTN_WIM_PRMT_GEN_WIM_PIN, 0, EEnterPinNRCodeDialog, 0 },
+    { EEnterNewPinNR, R_QTN_WIM_NEW_PIN, 0, EEnterPinPinCodeDialog, 0 },
+    { EEnterPukNR, R_QTN_WIM_PIN_UNBLOCK_QUERY, 0, EEnterPinNRCodeDialog, 0 },
+    { EVerifyPinNR, R_QTN_WIM_VERIFY_PIN, 0, EVerifyPinNRCodeDialog, 0 },
+    { EEnterPw, R_QTN_CM_TITLE_P12_PASSWORD, 0, EEnterPwDialog, 0 },
+    //{ EEnterKeyStorePw, R_QTN_CM_TITLE_KEYSTORE_PASSWORD, 0, EEnterPwDialog, 0 },
+    { EEnterKeyStorePw, R_QTN_SN_ENTER_PHONE_KEYSTORE, 0, EEnterPwDialog, 0 },
+    //{ EEnterNewKeyStorePw, R_QTN_CM_TITLE_NEW_KEYSTORE_PASSWORD, 0, EEnterPwPwDialog, 0 },
+    { EEnterNewKeyStorePw, R_QTN_SN_NEW_PHONE_KEYSTORE, 0, EEnterPwPwDialog, 0 },
+    //{ EVerifyKeyStorePw, R_QTN_CM_TITLE_VERIFY_PASSWORD, 0, EEnterPwPwDialog, 0 },
+    { EVerifyKeyStorePw, R_QTN_WIM_VERIFY_PIN, 0, EEnterPwPwDialog, 0 },
+    { EImportKeyPw, R_QTN_SN_PROMPT_IMPORT_KEY, 0, EEnterPwDialog, 0 },
+    { EExportKeyPw, R_QTN_SN_PROMPT1_CREATE_CODE, 0, EEnterPwPwDialog, 0 },
+
+
+//  { ESignText, 0, 0, EErrorNote, 0 }, // just a dummy
+
+    { EInfoSignTextRequested, R_QTN_WIM_INFO_DIGIT_SIGN_REQ, 0, EInfoNote, 0 },
+    { EInfoSignTextCancelled, R_QTN_WIM_SIGN_CANCELLED, 0, EInfoNote, 0 },
+    { EInfoSignTextDone, R_QTN_WIM_INFO_SIGNATURE_MADE, 0, EConfirmationNote, 0 },
+    { EInfoPinCodeUnblocked, R_QTN_WIM_INFO_PIN_UNBLOCKED, 0, EConfirmationNote, 0 },
+    { EInfoPwCreating, R_QTN_CM_CREATING_KEYSTORE, 0, EInfoNote, 0 },
+
+    { EErrorPinCodeIncorrect, R_QTN_WIM_ERR_WRONG_PIN, 0, EErrorNote, 0 },
+    { EErrorPinCodeBlocked, R_QTN_WIM_ERR_PIN_BLOCKED, 0, EErrorNote, 0 },
+    { EErrorPukCodeIncorrect, R_QTN_WIM_WRONG_UNBLOCK_CODE, 0, EErrorNote, 0 },
+    { EErrorPukCodeBlocked, R_QTN_WIM_PIN_TOTALBLOCKED, 0, EErrorNote, 0 },
+    { EErrorCodesDoNotMatch, R_QTN_WIM_ERR_CODES_DO_NOT_MATCH, 0, EErrorNote, 0 },
+
+    { EPinCodeBlockedInfo, R_QTN_WIM_UNBLOCK_INFO, 0, EInfoNote, 0 },
+    { ENoMatchingPersonalCert, R_QTN_WIM_NO_MATCHING_CERTIFICATE, 0, EInfoDialog, 0 },
+    { EErrorInternal, R_QTN_WIM_ERR_IO_ERROR, 0, EErrorNote, 0 },
+    { EErrorWimNotAvailable, R_QTN_WIM_NOT_AVAILABLE, 0, EErrorNote, 0 },
+    { ESaveReceipt, R_QTN_WIM_RECEIPT_SAVED, 0, EConfirmationDialog, 0 },
+    { EUserAuthentication, R_QTN_SN_AUTHENTICATION_NOTE, 0, EInfoNote, 0 }
+    };
+
+const TInt KCTSecDialSendBufLen = 128;
+
+#endif
+
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/ClientInc/CTSecurityDialogRequestor.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,130 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Dialog Requestor for RNotifier
+*
+*/
+
+
+#ifndef __CTSECURITYDIALOGREQUESTOR_H
+#define __CTSECURITYDIALOGREQUESTOR_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <ct.h>
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+/**
+* This class should be derived by every class
+* which uses CCTSecurityDialogRequestor.
+*
+*  @lib CTSecDlgs.lib
+*  @since Series60_2.6
+*/
+
+class MSecurityDialogResponse
+    {
+    public:
+        /**
+	    *   CWimSecurityDialogRequestor calls this function
+        *   when it gets response from the notifier.
+	    *	@param aResult      Result of the notifier	
+	    */
+        virtual void HandleResponse(TInt aResult) = 0;
+    };
+
+/**
+*  Active object that sends requests to notifier. 
+*
+*  @lib 
+*  @since 
+*/
+
+NONSHARABLE_CLASS( CCTSecurityDialogRequestor ): public CActive
+    {
+    private:
+    	enum TState { EFillingVariableInputBuffer, EMakingRequest };
+
+    public:
+        
+        /**
+        * Two-phased constructor.
+        */
+	    static CCTSecurityDialogRequestor* NewL(MSecurityDialogResponse& aSecurityDialogs);
+        
+        /**
+        * Destructor.
+        */
+	    ~CCTSecurityDialogRequestor();
+
+    public: // New functions
+        
+	    /**
+	    *	RequestDialog Requests a dialog through RNotifier API
+	    *	@param aData	Stream to be sent through RNotifier
+	    *	@param aResponse	Reference to memory where the response from Notifier is to be saved to
+	    */
+	    void RequestDialog(const TDesC8& aData, TDes8& aResponse);
+	    
+	    void RequestVariableBufferDialog( const TDesC8& aOperationData,
+										const TDesC8& aVariableData,
+										const RArray<TCTTokenObjectHandle>& aCertHandleList,
+										TDes8& aResponse );
+
+
+    private:
+        
+        /**
+        * C++ default constructor.
+        */
+	    CCTSecurityDialogRequestor(MSecurityDialogResponse& aSecurityDialogs);
+        
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+	    void ConstructL();
+
+    private:  // Functions from CActive
+        /**
+        *
+        */
+	    void DoCancel();
+        /**
+        *
+        */
+	    void RunL();
+        /**
+        *
+        * @param aError
+        */
+        TInt RunError(TInt aError);
+
+    private:    // Data
+        
+	    MSecurityDialogResponse&	iSecurityDialogs;
+	    RNotifier	iNotifier;
+	    
+	    TState iState;
+	    const TDesC8* iOperationDataPtr;
+	    const TDesC8* iVariableDataPtr;
+	    const RArray<TCTTokenObjectHandle>* iCertHandleListPtr;
+	    HBufC8* iInputBuffer;
+	    TDes8* iResponsePtr;
+    };
+
+#endif  // __CTSECURITYDIALOGREQUESTOR_H
+
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/ClientInc/SecurityDialogBase.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,136 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Class CSecurityDialogBase that implements common functionality 
+*                for CTSecurityDialogs.
+*
+*/
+
+
+#ifndef CSECURITYDIALOGBASE
+#define CSECURITYDIALOGBASE
+
+//  INCLUDES
+#include "CTSecurityDialogRequestor.h"
+#include "CTSecurityDialogDefs.h"
+
+// CONSTANTS
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+/**
+*  Base class of the CTSecurityDialogs  
+*
+*  @lib CTSecDlgs.lib
+*  @since Series60_2.6
+*/
+NONSHARABLE_CLASS( CSecurityDialogBase ): 
+    public CBase, public MSecurityDialogResponse
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * C++ default constructor.
+        */
+        CSecurityDialogBase();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CSecurityDialogBase();
+
+    public: // For Dialog Requester responses.
+
+        /**
+        *
+        * @param aResult
+        */
+	    virtual void HandleResponse(TInt aResult);
+        
+    protected:  // New functions
+        
+        /**
+        *
+        * @param aStatus
+        */
+        void InitClientStatus(TRequestStatus& aStatus);
+
+        /**
+	    * ShowNoteL shows a dialog/note using Notifier API.
+	    *
+	    * @param aStatus	Signaled value for async operation. KErrNone if successful, otherwise system error.
+	    * @param aDlgType	Dialog type
+	    * @param aReturnValue	Return value of a dialog. If aStatus == KErrNone, then the user's response
+	    *						is located here. ETrue means positive response (OK, continue etc.),
+	    *						EFalse means negative response.
+	    * @param aDynamic	Dynamic text for dialog. Effective only if %U is in the localisation resource.
+	    *
+	    * Leaves on: System error before showing the actual dialog
+	    *
+	    * Asserts on: If aDlgType is a PIN/PUK code query.
+	    */
+	    void ShowNoteL(TRequestStatus& aStatus, 
+                       TInt aNoteTypeaDlgType, 
+                       const TDesC& aDynamic = KNullDesC);
+        
+        /**
+	    * Sends dialog request to CCTSecurityDialogRequestor
+	    *
+	    * @param aData	Data needed to display dialog.
+	    */
+        void RequestDialog(const TDesC8& aData);
+
+        /**
+	    * Checks error and if aError != KErrNone completes iClientStatus
+        * with aError.
+        *
+        * @param aError Error to check
+	    *
+	    * @param aData	Data needed to display dialog.
+	    */
+        void CheckError(TInt aError);
+       
+        CCTSecurityDialogRequestor& Requester();
+
+
+    private:    // Data
+        TRequestStatus* iClientStatus;  // Pointer to client's request status
+									    // We must signal it when dialogrequestor
+									    // RunL is called to signal the completion of a dialog!
+
+        CBufFlat*	iSenderBuffer;	// Stream buffer for outgoing streams.
+    	HBufC8*     iBufferData;    // iSenderBuffer help buffer
+
+        CCTSecurityDialogRequestor* iRequester;	  // Owned
+
+        TBuf8<10> iDlgResponseBuf;
+
+        TAny* iReserved;
+    };
+
+#endif      // CSECURITYDIALOGBASE   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/ClientSrc/CDigSigningNote.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,177 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CDigSigningNote class
+*
+*/
+
+
+// INCLUDE FILES
+#include "CDigSigningNote.h"
+#include "CTSecurityDialogRequestor.h"
+#include "CTSecurityDialogDefs.h"
+#include <s32mem.h>
+
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+EXPORT_C MDigSigningNote* DigSigningNoteFactory::CreateNoteL()
+    {
+    return CDigSigningNote::NewL();
+    }
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CDigSigningNote::CDigSigningNote
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CDigSigningNote::CDigSigningNote(): CSecurityDialogBase()
+    {
+    }
+// -----------------------------------------------------------------------------
+// CDigSigningNote::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CDigSigningNote::ConstructL()
+    {
+    iSenderBuffer = CBufFlat::NewL( KCTSecDialSendBufLen );
+    CSecurityDialogBase::ConstructL();
+    }
+// -----------------------------------------------------------------------------
+// CDigSigningNote::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CDigSigningNote* CDigSigningNote::NewL()
+    {
+    CDigSigningNote* self = new( ELeave ) CDigSigningNote;
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CDigSigningNote::~CDigSigningNote()
+    {
+	delete iSenderBuffer;
+	delete iBufferData;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDigSigningNote::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CDigSigningNote::SaveSignedText( 
+    const TDesC& aSignedText, 
+    TRequestStatus& aStatus )
+    {
+    InitClientStatus(aStatus);
+
+    iSenderBuffer->Reset();
+	RBufWriteStream stream;
+	CleanupClosePushL( stream );
+	stream.Open( *iSenderBuffer );
+
+	stream.WriteInt32L( ESaveReceipt );
+    stream.WriteInt32L( aSignedText.Length() );
+	stream << aSignedText;
+
+    // new stuff begin
+	delete iBufferData;
+	iBufferData = NULL;
+	iBufferData = HBufC8::NewL( iSenderBuffer->Ptr(0).Size() );
+	iBufferData->Des() = iSenderBuffer->Ptr(0);
+    // new stuff end
+	CleanupStack::PopAndDestroy(); // stream.close;
+	RequestDialog(*iBufferData);
+    }
+// -----------------------------------------------------------------------------
+// CDigSigningNote::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CDigSigningNote::ShowPINBlockedInfo( 
+    const TPINLabel& aLabel, 
+    TRequestStatus& aStatus )
+    {
+    InitClientStatus(aStatus);
+
+    iSenderBuffer->Reset();
+	RBufWriteStream stream;
+	CleanupClosePushL( stream );
+	stream.Open( *iSenderBuffer );
+
+	stream.WriteInt32L( EPinCodeBlockedInfo );
+	stream << aLabel;
+    // new stuff begin
+	delete iBufferData;
+	iBufferData = NULL;
+	iBufferData = HBufC8::NewL( iSenderBuffer->Ptr(0).Size() );
+	iBufferData->Des() = iSenderBuffer->Ptr(0);
+    // new stuff end
+	CleanupStack::PopAndDestroy(); // stream.close;
+	RequestDialog(*iBufferData);
+    }
+
+// -----------------------------------------------------------------------------
+// CDigSigningNote::ShowNote
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CDigSigningNote::ShowNote( 
+    MDigSigningNote::TNoteType aNoteType, 
+    TRequestStatus& aStatus )
+    {
+    ShowNoteL( aStatus, aNoteType );
+    }
+// -----------------------------------------------------------------------------
+// CDigSigningNote::Release
+//
+// -----------------------------------------------------------------------------
+//
+void CDigSigningNote::Release()
+    {
+    delete this;
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/ClientSrc/CPKIDlg.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,450 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CPKIDialog class
+*
+*/
+
+
+// INCLUDE FILES
+#include "CPKIDlg.h"
+#include "CTSecurityDialogRequestor.h"
+#include "CTSecurityDialogDefs.h"
+#include <s32mem.h>
+
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+EXPORT_C MPKIDialog* PKIDialogFactory::CreateNoteL()
+    {
+    return CPKIDialog::NewL();
+    }
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CPKIDialog::CPKIDialog
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CPKIDialog::CPKIDialog()
+    {
+    }
+// -----------------------------------------------------------------------------
+// CPKIDialog::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CPKIDialog::ConstructL()
+    {
+    iRequester = CCTSecurityDialogRequestor::NewL( *this );
+    iSenderBuffer = CBufFlat::NewL( KCTSecDialSendBufLen );
+    }
+// -----------------------------------------------------------------------------
+// CPKIDialog::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CPKIDialog* CPKIDialog::NewL()
+    {
+    CPKIDialog* self = new( ELeave ) CPKIDialog;
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CPKIDialog::~CPKIDialog()
+    {
+    if ( iRequester )
+        {
+		iRequester->Cancel();
+        }
+	delete iRequester;
+	delete iSenderBuffer;
+	delete iBufferData;
+    }
+
+// -----------------------------------------------------------------------------
+// CPKIDialog::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CPKIDialog::UserAuthentication(
+    const RArray<TCTTokenObjectHandle>& aCertHandleList, 
+    TCTTokenObjectHandle& aCertHandle,
+    TRequestStatus& aStatus )
+    {
+	iCurrentOperation = EUserAuthentication;
+	InitClientStatus( aStatus );
+
+	TSignInput signInput;
+	signInput.iOperation = EUserAuthentication;
+	signInput.iCertHandleArrayTotal = aCertHandleList.Count();
+	TPckgC<TSignInput> signInputBufPtr( signInput );
+	// iSignInputBuf is persistent because further input processing occurs in the AO before
+	// calling the notifier.
+	iSignInputBuf.Copy( signInputBufPtr );
+	iVariableDataPtr.Set( NULL, 0 );
+	iClientCertInfoHandlePtr = &aCertHandle;
+
+	iRequester->RequestVariableBufferDialog( iSignInputBuf, iVariableDataPtr,
+											aCertHandleList, iCertInfoHandleBuf );
+    }
+    
+// -----------------------------------------------------------------------------
+// CPKIDialog::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//    
+void CPKIDialog::UserAuthenticationText( 
+    const TDesC& aTextToSign,
+    const RArray<TCTTokenObjectHandle>& aCertHandleList, 
+    TCTTokenObjectHandle& aCertHandle,
+    TRequestStatus& aStatus )
+    {
+    iCurrentOperation = EUserAuthenticationText;
+	InitClientStatus( aStatus );
+
+	TInt textSize = aTextToSign.Size();
+	TSignInput signInput;
+	signInput.iOperation = EUserAuthenticationText;
+	signInput.iVariableDataSize = textSize;
+	signInput.iCertHandleArrayTotal = aCertHandleList.Count();
+	TPckgC<TSignInput> signInputBufPtr( signInput );
+	// iSignInputBuf is persistent because further input processing occurs in the AO before
+	// calling the notifier.
+	iSignInputBuf.Copy( signInputBufPtr );
+	const TUint8* textToSignPtr = reinterpret_cast<const TUint8*>( aTextToSign.Ptr() );
+	iVariableDataPtr.Set( textToSignPtr, textSize );
+
+	iClientCertInfoHandlePtr = &aCertHandle;
+
+	iRequester->RequestVariableBufferDialog( iSignInputBuf, iVariableDataPtr,
+											aCertHandleList, iCertInfoHandleBuf );
+    }
+
+// -----------------------------------------------------------------------------
+// CPKIDialog::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CPKIDialog::RequestWithTokenHandleL( 
+    const TDesC& aText,
+    const TCTTokenObjectHandle& aTokenHandle,
+    TRequestStatus& aStatus )    
+    {
+    InitClientStatus(aStatus);
+
+    iSenderBuffer->Reset();
+	RBufWriteStream stream;
+	CleanupClosePushL( stream );
+	stream.Open( *iSenderBuffer );
+
+	stream.WriteInt32L( iCurrentOperation );
+	if (0 < aText.Length())
+	    {
+	    stream.WriteInt32L( aText.Length() );
+	    stream << aText;    
+	    }
+    // new stuff begin
+	delete iBufferData;
+	TInt inputBufferSize = 
+	    iSenderBuffer->Ptr(0).Size() + sizeof(TCTTokenObjectHandle);
+	
+	iBufferData = HBufC8::NewL( inputBufferSize );
+	TPtr8 inputBufferPtr( iBufferData->Des() );
+	inputBufferPtr = iSenderBuffer->Ptr(0);
+	
+	TPckgC<TCTTokenObjectHandle> handleBuf( aTokenHandle );
+	inputBufferPtr.Append( handleBuf );
+	
+    // new stuff end
+	CleanupStack::PopAndDestroy(); // stream.close;
+	iRequester->RequestDialog(*iBufferData, iDlgResponseBuf);
+    }
+    
+// -----------------------------------------------------------------------------
+// CPKIDialog::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//        
+void CPKIDialog::CreateCSR( 
+    const TDesC& aSubject,
+    const TCTTokenObjectHandle& aKeyHandle,
+    TRequestStatus& aStatus )
+    {
+    iCurrentOperation = ECreateCSR;
+    TRAPD(ret, RequestWithTokenHandleL(aSubject, aKeyHandle, aStatus));
+    if (ret!=KErrNone)
+        {
+        User::RequestComplete(iClientStatus, ret);
+        }
+        
+    }
+
+// -----------------------------------------------------------------------------
+// CPKIDialog::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CPKIDialog::CertificateDetails( 
+    const TCTTokenObjectHandle& aCertHandle,
+    TRequestStatus& aStatus  )
+    {
+    iCurrentOperation = ECertDetails;
+    TRAPD(ret, RequestWithTokenHandleL(KNullDesC, aCertHandle, aStatus));
+    if (ret!=KErrNone)
+        {
+        User::RequestComplete(iClientStatus, ret);
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CPKIDialog::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CPKIDialog::SaveCertificate( 
+    TCertificateFormat aFormat,
+    TCertificateOwnerType aCertificateOwnerType, 
+    const TDesC8& aCert, TRequestStatus& aStatus)
+    {
+    TRAPD(ret, DoSaveCertificateL(aFormat, aCertificateOwnerType, aCert, aStatus));
+    if (ret!=KErrNone)
+        {
+        User::RequestComplete(iClientStatus, ret);
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CPKIDialog::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CPKIDialog::DoSaveCertificateL( 
+    TCertificateFormat aFormat,
+    TCertificateOwnerType aCertificateOwnerType, 
+    const TDesC8& aCert, TRequestStatus& aStatus)
+    {
+    iCurrentOperation = ESaveCert;
+	InitClientStatus( aStatus );
+	
+	TSaveCertInput saveCertInput;
+	saveCertInput.iOperation = ESaveCert;
+	saveCertInput.iCertFormat = aFormat;
+	saveCertInput.iCertOwnerType = aCertificateOwnerType;
+	saveCertInput.iDataSize = aCert.Size();
+	
+	TPckgC<TSaveCertInput> saveCertInputBuf( saveCertInput );
+	
+	//const TUint8* textToSignPtr = reinterpret_cast<const TUint8*>( aCert.Ptr() );
+    	    
+    // new stuff begin
+	delete iBufferData;
+	TInt inputBufferSize = aCert.Size() + sizeof(TSaveCertInput);
+	
+	iBufferData = HBufC8::NewL( inputBufferSize );
+	TPtr8 inputBufferPtr( iBufferData->Des() );
+    inputBufferPtr.Append( saveCertInputBuf );
+	inputBufferPtr.Append(aCert);
+	iRequester->RequestDialog(*iBufferData, iDlgResponseBuf);
+    }
+    
+// -----------------------------------------------------------------------------
+// CPKIDialog::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//   
+void CPKIDialog::DeleteCertificate( 
+    const TCTTokenObjectHandle& aCertHandle,
+    TRequestStatus& aStatus  )
+    {
+    iCurrentOperation = EDeleteCert;
+    TRAPD(ret, RequestWithTokenHandleL(KNullDesC, aCertHandle, aStatus));
+    if (ret!=KErrNone)
+        {
+        User::RequestComplete(iClientStatus, ret);
+        }
+    }
+            
+// -----------------------------------------------------------------------------
+// CPKIDialog::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CPKIDialog::SaveSignedText( 
+    const TDesC& aSignedText, 
+    TRequestStatus& aStatus )
+    {
+    TCTTokenObjectHandle tokenHandle;
+    iCurrentOperation = ESaveReceipt;
+    TRAPD(ret, RequestWithTokenHandleL(aSignedText, tokenHandle, aStatus));
+    if (ret!=KErrNone)
+        {
+        User::RequestComplete(iClientStatus, ret);
+        }
+    }
+// -----------------------------------------------------------------------------
+// CPKIDialog::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CPKIDialog::PINBlockedInfo( 
+    const TPINLabel& aLabel, 
+    TRequestStatus& aStatus )
+    {
+    iCurrentOperation = EPinCodeBlockedInfo;
+    InitClientStatus(aStatus);
+
+    iSenderBuffer->Reset();
+	RBufWriteStream stream;
+	CleanupClosePushL( stream );
+	stream.Open( *iSenderBuffer );
+
+	stream.WriteInt32L( EPinCodeBlockedInfo );
+	stream << aLabel;
+    // new stuff begin
+	delete iBufferData;
+	iBufferData = NULL;
+	iBufferData = HBufC8::NewL( iSenderBuffer->Ptr(0).Size() );
+	iBufferData->Des() = iSenderBuffer->Ptr(0);
+    // new stuff end
+	CleanupStack::PopAndDestroy(); // stream.close;
+	iRequester->RequestDialog(*iBufferData, iDlgResponseBuf);
+    }
+
+// -----------------------------------------------------------------------------
+// CPKIDialog::Note
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CPKIDialog::Note( 
+    MPKIDialog::TNoteType aNoteType, 
+    TRequestStatus& aStatus )
+    {
+    ShowNoteL( aStatus, aNoteType );
+    }
+    
+// -----------------------------------------------------------------------------
+// CPKIDialog::ShowNoteL
+// -----------------------------------------------------------------------------
+//
+void CPKIDialog::ShowNoteL(
+                            TRequestStatus& aStatus, 
+                            TInt aDlgType,  
+                            const TDesC& aDynamic)
+    {
+
+	InitClientStatus( aStatus );
+	
+	iSenderBuffer->Reset();
+	RBufWriteStream stream;
+	CleanupClosePushL( stream );
+	stream.Open( *iSenderBuffer );
+
+	stream.WriteInt32L( aDlgType );
+	stream.WriteInt32L( aDynamic.Length() );
+	stream << aDynamic;
+
+	stream.WriteInt32L(0);
+	stream << KNullDesC;
+
+    delete iBufferData;
+    iBufferData = NULL;
+	iBufferData = HBufC8::NewL(iSenderBuffer->Ptr(0).Size());
+	iBufferData->Des() = iSenderBuffer->Ptr(0);
+	CleanupStack::PopAndDestroy(); // stream.close;
+
+    iRequester->RequestDialog(*iBufferData, iDlgResponseBuf);
+    }
+    
+    
+// -----------------------------------------------------------------------------
+// CPKIDialog::Release
+//
+// -----------------------------------------------------------------------------
+//
+void CPKIDialog::Release()
+    {
+    delete this;
+    }
+    
+// -----------------------------------------------------------------------------
+// CPKIDialog::InitClientStatus
+// InitClientStatus initialises the client's RequestStatus object.
+// -----------------------------------------------------------------------------
+//
+void CPKIDialog::InitClientStatus( TRequestStatus& aStatus )
+	{
+	iClientStatus = &aStatus;
+	*iClientStatus = KRequestPending;
+	} 
+	   
+// -----------------------------------------------------------------------------
+// CPKIDialog::HandleResponse
+//
+// -----------------------------------------------------------------------------
+//    
+void CPKIDialog::HandleResponse(TInt aResult)
+    {
+    switch ( iCurrentOperation )
+        {
+        case EUserAuthenticationText:
+        case EUserAuthentication:
+			{
+			*iClientCertInfoHandlePtr = iCertInfoHandleBuf();
+			break;
+			}
+		default:
+		    // Do nothing, just client status complete.
+		    break;
+		    
+        }
+	User::RequestComplete(iClientStatus, aResult);
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/ClientSrc/CTsecuritydialogrequestor.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,162 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Definition of dialog requester
+*
+*/
+
+
+// INCLUDE FILES
+#include "CTSecurityDialogRequestor.h"
+#include "CTSecurityDialogDefs.h"
+#include <secdlgimpldefs.h>
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogs::CCTSecurityDialogs()
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CCTSecurityDialogRequestor::CCTSecurityDialogRequestor(MSecurityDialogResponse& aSecurityDialogs): 
+	CActive(EPriorityStandard),
+	iSecurityDialogs(aSecurityDialogs)
+{
+}
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogs::~CCTSecurityDialogs()
+// -----------------------------------------------------------------------------
+//
+CCTSecurityDialogRequestor::~CCTSecurityDialogRequestor()
+{
+	Cancel();
+	iNotifier.Close();
+}
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogs::NewL()
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CCTSecurityDialogRequestor* CCTSecurityDialogRequestor::NewL(MSecurityDialogResponse& aSecurityDialogs)
+{
+	CCTSecurityDialogRequestor* self = new (ELeave) CCTSecurityDialogRequestor(aSecurityDialogs);
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	CleanupStack::Pop(); // self
+	return self;
+}
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogs::ConstructL()
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogRequestor::ConstructL()
+{
+	User::LeaveIfError(iNotifier.Connect());
+	CActiveScheduler::Add(this);
+}
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogs::RequestDialog()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogRequestor::RequestDialog(const TDesC8& aData, TDes8& aResponse)
+    {
+	iNotifier.StartNotifierAndGetResponse(iStatus, KUidSecurityDialogNotifier, aData, aResponse);
+	iState = EMakingRequest;
+	SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogs::RequestVariableBufferDialog()
+// -----------------------------------------------------------------------------
+//    
+void CCTSecurityDialogRequestor::RequestVariableBufferDialog( const TDesC8& aOperationData,
+										const TDesC8& aVariableData,
+										const RArray<TCTTokenObjectHandle>& aCertHandleList,
+										TDes8& aResponse )
+	{
+	iOperationDataPtr = &aOperationData;
+	iVariableDataPtr = &aVariableData;
+	iCertHandleListPtr = &aCertHandleList;
+	iResponsePtr = &aResponse;
+	iState = EFillingVariableInputBuffer;
+	SetActive();
+	// Complete the AO immediately so that buffer processing can occur in RunL().
+	TRequestStatus* statusPtr = &iStatus;
+	User::RequestComplete( statusPtr, KErrNone );
+	}    
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogs::DoCancel()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogRequestor::DoCancel()
+    {
+	iNotifier.CancelNotifier(KUidSecurityDialogNotifier);
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogs::RunL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogRequestor::RunL()
+    {
+    switch ( iState )
+		{
+		case EFillingVariableInputBuffer:
+			{
+			TInt operationDataSize = iOperationDataPtr->Size();
+			TInt variableDataSize = iVariableDataPtr->Size();
+			TInt arraySize = sizeof( TCTTokenObjectHandle ) * iCertHandleListPtr->Count();
+			TInt bufferSize = operationDataSize + variableDataSize + arraySize;
+			iInputBuffer = HBufC8::NewL( bufferSize );
+			TPtr8 inputBufferPtr( iInputBuffer->Des() );
+			inputBufferPtr.Append( *iOperationDataPtr );
+			for ( TInt h = 0, total = iCertHandleListPtr->Count(); h < total; ++h )
+				{
+				const TCTTokenObjectHandle& certHandle = (*iCertHandleListPtr)[h];
+				TPckgC<TCTTokenObjectHandle> certHandleBuf( certHandle );
+				inputBufferPtr.Append( certHandleBuf );
+				}
+			inputBufferPtr.Append( *iVariableDataPtr );
+			RequestDialog( *iInputBuffer, *iResponsePtr );
+			break;
+			}
+		case EMakingRequest:
+			{
+			delete iInputBuffer;
+			iInputBuffer = NULL;
+			iSecurityDialogs.HandleResponse(iStatus.Int());
+			break;
+			}
+		default:
+			__ASSERT_DEBUG( EFalse, _L( "Invalid state" ) );
+		}
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogs::RunError()
+// -----------------------------------------------------------------------------
+//
+TInt CCTSecurityDialogRequestor::RunError(TInt aError)
+{
+	iSecurityDialogs.HandleResponse(aError);
+	return KErrNone;
+}
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/ClientSrc/DllMain.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,21 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Entry point for the component
+*
+*/
+
+
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/ClientSrc/SecurityDialogBase.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,160 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecurityDialogBase class.
+*
+*/
+
+
+// INCLUDE FILES
+#include    "SecurityDialogBase.h"
+#include <s32mem.h>
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CSecurityDialogBase::CSecurityDialogBase
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CSecurityDialogBase::CSecurityDialogBase()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CSecurityDialogBase::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CSecurityDialogBase::ConstructL()
+    {
+    iRequester = CCTSecurityDialogRequestor::NewL( *this );
+    iSenderBuffer = CBufFlat::NewL( KCTSecDialSendBufLen );
+    }
+
+    
+// Destructor
+CSecurityDialogBase::~CSecurityDialogBase()
+    {
+    if ( iRequester )
+        {
+		iRequester->Cancel();
+        }
+	delete iRequester;
+    delete iSenderBuffer;
+    delete iBufferData; 
+    }
+
+// -----------------------------------------------------------------------------
+// CSecurityDialogBase::HandleResponse
+// HandleResponse handles the dialog Requestor's responses to dialogs 
+// and updates the client component's variables.
+// -----------------------------------------------------------------------------
+//
+void CSecurityDialogBase::HandleResponse( TInt aResult )
+    {
+	User::RequestComplete(iClientStatus, aResult);
+    }
+
+// -----------------------------------------------------------------------------
+// CSecurityDialogBase::InitClientStatus
+// InitClientStatus initialises the client's RequestStatus object.
+// -----------------------------------------------------------------------------
+//
+void CSecurityDialogBase::InitClientStatus( TRequestStatus& aStatus )
+	{
+	iClientStatus = &aStatus;
+	*iClientStatus = KRequestPending;
+	}
+// -----------------------------------------------------------------------------
+// CSecurityDialogBase::ShowNoteL
+// -----------------------------------------------------------------------------
+//
+
+void CSecurityDialogBase::ShowNoteL(
+                            TRequestStatus& aStatus, 
+                            TInt aDlgType,  
+                            const TDesC& aDynamic)
+    {
+
+	InitClientStatus( aStatus );
+	
+	iSenderBuffer->Reset();
+	RBufWriteStream stream;
+	CleanupClosePushL( stream );
+	stream.Open( *iSenderBuffer );
+
+	stream.WriteInt32L( aDlgType );
+	stream.WriteInt32L( aDynamic.Length() );
+	stream << aDynamic;
+
+	stream.WriteInt32L(0);
+	stream << KNullDesC;
+
+    delete iBufferData;
+    iBufferData = NULL;
+	iBufferData = HBufC8::NewL(iSenderBuffer->Ptr(0).Size());
+	iBufferData->Des() = iSenderBuffer->Ptr(0);
+	CleanupStack::PopAndDestroy(); // stream.close;
+
+	RequestDialog(*iBufferData);
+    }
+
+// -----------------------------------------------------------------------------
+// CSecurityDialogBase::RequestDialog
+// -----------------------------------------------------------------------------
+//
+void CSecurityDialogBase::RequestDialog(const TDesC8& aData)
+    {
+    iRequester->RequestDialog(aData, iDlgResponseBuf);
+    }
+
+// -----------------------------------------------------------------------------
+// CSecurityDialogBase::Requester
+// -----------------------------------------------------------------------------
+//    
+CCTSecurityDialogRequestor& CSecurityDialogBase::Requester()
+    {
+    return *iRequester;
+    }
+// -----------------------------------------------------------------------------
+// CSecurityDialogBase::CheckError
+// -----------------------------------------------------------------------------
+//
+void CSecurityDialogBase::CheckError( TInt aError )
+    {
+    if (aError)
+        {
+        User::RequestComplete(iClientStatus, aError);
+        }
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/Group/CTSecDialogImpl.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,93 @@
+/*
+* Copyright (c) 2002-2008 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Project definition for Security Dialog Notifier Plugin
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET          CTSecDialogImpl.dll
+TARGETTYPE      DLL
+UID   0x101fdfae 0x10207446
+
+CAPABILITY      CAP_GENERAL_DLL
+VENDORID        VID_DEFAULT
+
+SOURCEPATH  ../data
+START RESOURCE  CTsecdlgs.rss
+HEADER
+TARGET CTSecDlgs.rsc
+TARGETPATH      RESOURCE_FILES_DIR
+LANGUAGE_IDS
+END
+
+SYSTEMINCLUDE ../../CertmanUi/INC
+SYSTEMINCLUDE ../../CertSaver/inc
+SYSTEMINCLUDE ../../DeviceToken/Inc
+SYSTEMINCLUDE ../../../inc              // securityservices/inc directory
+MW_LAYER_SYSTEMINCLUDE
+
+
+USERINCLUDE ../NotifInc
+USERINCLUDE ../ClientInc
+
+SOURCEPATH  ../NotifSrc
+
+SOURCE    DllMain.cpp
+SOURCE    CTSecuritydialognotifier.cpp
+SOURCE    CTpinquerydialog.cpp
+SOURCE    CTQueryDialog.cpp
+SOURCE    CTSigntextdialog.cpp
+SOURCE    CTSelectcertificatedialog.cpp
+SOURCE    CTPinPinQueryDialog.cpp
+SOURCE    CTCertificateQuery.cpp
+SOURCE    CTSecurityDialogsAO.cpp
+SOURCE    CTNoTrustQuery.cpp
+SOURCE    CTInvalidCertNote.cpp
+
+LIBRARY   EUSER.LIB
+LIBRARY   EIKSRV.LIB
+LIBRARY   CONE.LIB
+LIBRARY   BAFL.LIB
+LIBRARY   EFSRV.LIB
+LIBRARY   AVKON.LIB
+LIBRARY   EIKDLG.LIB
+LIBRARY   EIKCORE.LIB
+LIBRARY   EIKCOCTL.LIB
+LIBRARY   COMMONENGINE.LIB
+LIBRARY   EIKSRVUI.lib
+LIBRARY   apmime.lib
+LIBRARY   CommonUI.lib
+LIBRARY   ctframework.lib
+LIBRARY   certstore.lib
+LIBRARY   X509.lib
+LIBRARY   x509certnameparser.lib    // parsing of label
+LIBRARY   hash.lib
+LIBRARY   crypto.lib
+LIBRARY   aknlayout.lib
+LIBRARY   X500.lib
+LIBRARY   DevTokenClient.lib
+
+DEBUGLIBRARY     flogger.lib
+
+#if defined(ARMCC)
+    DEFFILE ../eabi/CTSecDilogImpl.DEF
+#elif defined( WINSCW )
+    DEFFILE ../BWINSCW/CTSecDilogImpl.DEF
+#endif
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/Group/CTSecDlgNotifier.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2002-2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Project definition for Security Dialog Notifier ECOM Plugin
+*
+*/
+
+
+#include <platform_paths.hrh>
+TARGET      CTSecDlgNotifier.dll
+CAPABILITY  CAP_ECOM_PLUGIN
+TARGETTYPE  PLUGIN 
+
+UID	0x10009D8D 0x10008D4F 
+    	
+USERINCLUDE     ../ClientInc			
+
+MW_LAYER_SYSTEMINCLUDE
+
+LANG SC
+SOURCEPATH      ../ecomsrc	
+SOURCE CTSecDlgWrapper.cpp 
+START RESOURCE  10008D4F.rss
+	TARGET CTSecDlgNotifier.rsc
+END
+
+
+LIBRARY ECOM.LIB
+LIBRARY	AKNNOTIFIERWRAPPER.LIB
+LIBRARY EUSER.LIB
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/Group/CTSecDlgs.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Project definition for CTSecDlgs.dll
+*
+*/
+
+
+#include <platform_paths.hrh>
+TARGETTYPE	dll
+TARGET		CTSecDlgs.dll
+
+UID		0x1000008d 0x10008D4E // KUidSecurityDialogs
+
+CAPABILITY 	CAP_GENERAL_DLL
+VENDORID    VID_DEFAULT
+
+MW_LAYER_SYSTEMINCLUDE
+
+USERINCLUDE	../ClientInc
+
+SOURCEPATH	../ClientSrc
+SOURCE		DllMain.cpp
+SOURCE		CTsecuritydialogrequestor.cpp
+SOURCE		SecurityDialogBase.cpp
+SOURCE		CPKIDlg.cpp
+
+LIBRARY		euser.lib 
+LIBRARY		estor.lib 
+LIBRARY     ctframework.lib
+
+#if defined(ARMCC)
+deffile ../eabi/ 
+#elif defined( WINSCW )
+deffile ../BWINSCW/ 
+#elif defined( WINS )
+deffile ../bwins/ 
+#else
+deffile ../bmarm/ 
+#endif
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/Group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2002-2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Project definition for WIM Security Dialog Components
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+../loc/wmlbrowser_wim.loc  MW_LAYER_LOC_EXPORT_PATH(wmlbrowser_wim.loc)
+
+PRJ_MMPFILES
+CTSecDialogImpl.mmp
+CTSecDlgNotifier.mmp
+#ifdef __JAVA_JSR_177_SECURITY_AND_TRUST_SERVICES
+CTSecDlgs.mmp
+#endif
+
+PRJ_TESTMMPFILES
+
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifInc/CTCertificateQuery.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+
+#ifndef __SECNOT_CERTIFICATE_QUERY_H__
+#define __SECNOT_CERTIFICATE_QUERY_H__
+
+//  INCLUDES
+
+#include <aknmessagequerydialog.h>
+
+// FORWARD DECLARATIONS
+
+class CCTSecurityDialogsAO;
+
+// CLASS DECLARATION
+
+/**
+*  Query class for showing certificate details
+*/
+NONSHARABLE_CLASS( CCTCertificateQuery ) : public CAknMessageQueryDialog
+    {
+    public:     // constructors and destructor
+        static CCTCertificateQuery* NewL(CCTSecurityDialogsAO& aAO);
+        virtual ~CCTCertificateQuery();
+
+    private:    // from CEikDialog
+        TBool OkToExitL( TInt aButtonId );
+
+    private:    // new functions
+        CCTCertificateQuery(CCTSecurityDialogsAO& aAO);
+        void ConstructL();
+
+    private:    // data
+
+        CCTSecurityDialogsAO& iNotifier;        
+        HBufC* iHeader;
+        HBufC* iMessage;
+    };
+
+#endif  // __SECNOT_CERTIFICATE_QUERY_H__
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifInc/CTInvalidCertNote.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Info note shown for invalid and revoked certificates
+*
+*/
+
+
+
+#ifndef CTINVALIDCERTNOTE_H
+#define CTINVALIDCERTNOTE_H
+
+#include <aknnotedialog.h>
+
+class CCTSecurityDialogsAO;
+
+
+/**
+*  Notifier class for showing SSL security dialogs
+*/
+NONSHARABLE_CLASS( CCTInvalidCertificateNote ): public CAknNoteDialog
+    {
+    public:     // constructors and destructor
+        CCTInvalidCertificateNote(
+            CCTSecurityDialogsAO& aNotifier,
+            TRequestStatus& aClientStatus );
+        ~CCTInvalidCertificateNote();
+
+    private:    // from CEikDialog
+        TBool OkToExitL( TInt aButtonId );
+        void PostLayoutDynInitL();
+        
+    private: // New functions
+        void ShowDetailsL();
+
+    private:    // data
+        CCTSecurityDialogsAO& iNotifier;
+        TRequestStatus* iClientStatus;
+    };
+
+#endif  // CTINVALIDCERTNOTE_H
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifInc/CTNoTrustQuery.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,68 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+
+#ifndef CTNOTRUSTQUERY_H
+#define CTNOTRUSTQUERY_H
+
+//  INCLUDES
+
+#include <AknQueryDialog.h>
+
+// FORWARD DECLARATIONS
+
+class CCTSecurityDialogsAO;
+class CAknSinglePopupMenuStyleListBox;
+
+// CLASS DECLARATION
+
+/**
+*  Notifier class for showing SSL security dialogs
+*/
+NONSHARABLE_CLASS( CCTNoTrustQuery ): public CAknQueryDialog
+    {
+    public:     // constructors and destructor
+
+        CCTNoTrustQuery(
+            CCTSecurityDialogsAO& aNotifier,
+            TBool& aRetVal,
+            TRequestStatus& aClientStatus,
+            HBufC* aServerName,
+            TBool aShowPermAccept,
+            TBool& aIsDeleted );
+            
+        virtual ~CCTNoTrustQuery();
+
+    private:    // from CEikDialog
+        TBool OkToExitL( TInt aButtonId );
+        void PostLayoutDynInitL();
+
+    private: // New functions
+        TBool OptionsMenuL();
+
+    private:    // data
+        CCTSecurityDialogsAO& iNotifier;
+        TBool& iRetVal; 		//Dialog response
+        TRequestStatus* iClientStatus;
+        HBufC* iServerName;
+        TBool iShowPermAccept;
+        TBool& iDeleted;
+    };
+
+#endif  // CTNOTRUSTQUERY_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifInc/CTPinPinQueryDialog.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,136 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Header file of the multiline PIN query dialog
+*
+*/
+
+
+#ifndef CCTPINPINQUERYDIALOG_H
+#define CCTPINPINQUERYDIALOG_H
+
+//  INCLUDES
+#include <AknQueryDialog.h>
+
+// CLASS DECLARATION
+
+/**
+*  Multiline PIN query dialog class
+*
+*  @lib CTSecDlgNotifier.dll
+*  @since Series 60 2.8
+*/
+NONSHARABLE_CLASS( CCTPinPinQueryDialog ): public CAknMultiLineDataQueryDialog
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CCTPinPinQueryDialog* NewL(
+            const TDesC& aDlgText1,
+            const TDesC& aDlgText2,
+            TDes&  aPin1,
+            TDes&  aPin2,
+            const TInt aMinTextLength, 
+            const TInt aMaxTextLength, 
+            TBool& aRetVal);
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CCTPinPinQueryDialog();
+
+    public: // New functions
+
+        /**
+        * RunDlgLD Launches the multiline PIN Query Dialog
+        * @param aClientStatus  Reference to Client Status
+        * @param aResourceId  Resource ID
+        */
+        void RunDlgLD(TRequestStatus& aClientStatus, TInt aResourceId);
+
+    private: // Functions from base classes
+
+         /**
+        *
+        */
+	    void UpdateLeftSoftKeyL();
+
+        /**
+        *
+        */
+	    TBool CheckIfEntryTextOk() const;
+
+        /**
+        *
+		* @param	aButtonId 
+		* @return	TBool
+        */
+		TBool OkToExitL( TInt aButtonId );
+
+        /**
+        *
+        */
+	    void PreLayoutDynInitL();
+
+        /**
+        *
+        */	
+		void PostLayoutDynInitL();
+
+        /**
+        *
+		* @param  aKeyEvent
+		* @param  aType
+		* @return TKeyResponse
+        */
+		TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CCTPinPinQueryDialog(
+            const TDesC& aDlgText1,
+            const TDesC& aDlgText2,
+            TDes&  aPin1,
+            TDes&  aPin2,
+            const TInt aMinTextLength, 
+            const TInt aMaxTextLength, 
+            TBool& aRetVal);
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    private:    // Data
+	    const TDesC& iDlgText1;
+        const TDesC& iDlgText2;
+	    TDes& iPinValue1;
+        TDes& iPinValue2;
+	    TInt iMinTextLength;
+	    TInt iMaxTextLength;
+		TRequestStatus* iClientStatus;
+		TBool& iRetVal; //Dialog response
+
+        TBool iFirstOk;
+        TBool iSecondOk;
+    };
+
+#endif      // CCTPINPINQUERYDIALOG_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifInc/CTPinQueryDialog.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,130 @@
+/*
+* Copyright (c) 2003-2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Crypto Token Security Dialogs PIN Query Dialog
+*
+*/
+
+
+
+#ifndef __CTPINQUERYDIALOG_H
+#define __CTPINQUERYDIALOG_H
+
+//  INCLUDES
+#include <AknQueryDialog.h>
+
+// CLASS DECLARATION
+
+/**
+*  PIN query dialog class
+*
+*  @lib CTSecDlgNotifier.dll
+*  @since Series 60 2.6
+*/
+NONSHARABLE_CLASS( CCTPinQueryDialog ): public CAknTextQueryDialog
+    {
+    public: // Constructors and destructor
+
+        ~CCTPinQueryDialog();
+
+    public: // Function from CAknQueryDialog 
+
+	    /**
+	    * RunDlgLD Launches the CT PIN Query Dialog
+		* @param	aClientStatus  Reference to Client Status
+	    * @param	aDlgHeading Text for heading text
+	    * @param	aDlgText	Text for dialog
+	    * @param	aPinValue	Reference to PIN Value.
+	    * @param	aMinTextLength	Minimum length for PIN Value
+	    * @param	aMaxTextLength	Maximum length for PIN Value
+		* @param	aRetVal	 ETrue for positive user response, EFalse for negative
+        * @param	aResourceId	 Resource id
+	    */
+        static void RunDlgLD(
+            TRequestStatus& aClientStatus, 
+            const TDesC& aDlgText, 
+            TDes& aPinValue, 
+            const TInt aMinTextLength, 
+            const TInt aMaxTextLength, 
+            TBool& aRetVal, 
+            TInt aResourceId, 
+            CCTPinQueryDialog*& aDialog, 
+            TBool& aIsDeleted );
+	    
+
+    private:
+        
+        /**
+        * C++ default constructor.
+        */
+	    CCTPinQueryDialog(
+            TRequestStatus& aClientStatus, 
+            const TDesC& aDlgText, 
+            TDes& aPinValue, 
+            const TInt aMinTextLength, 
+            const TInt aMaxTextLength, 
+            TBool& aRetVal,
+            TBool& aIsDeleted );
+
+    private:    // Function from CAknTextQueryDialog
+
+        /**
+        *
+        */
+	    void PreLayoutDynInitL();
+
+    private:    // Functions from CAknTextQueryDialog/CAknQueryDialog
+
+        /**
+        *
+        */
+	    void UpdateLeftSoftKeyL();
+
+        /**
+        *
+        */
+	    TBool CheckIfEntryTextOk() const;
+
+        /**
+        *
+		* @param	aButtonId 
+		* @return	TBool
+        */
+		TBool OkToExitL( TInt aButtonId );
+
+        /**
+        *
+        */	
+		void PostLayoutDynInitL();
+
+        /**
+        *
+		* @param  aKeyEvent
+		* @param  aType
+		* @return TKeyResponse
+        */
+		TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+    private:    // Data
+	    const TDesC& iDlgText;
+	    TDes& iPinValue;
+	    TInt iMinTextLength;
+	    TInt iMaxTextLength;
+		TRequestStatus* iClientStatus;
+		TBool& iRetVal; //Dialog response
+		TBool& iIsDeleted;
+    };
+
+#endif // __CTPINQUERYDIALOG_H
+
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifInc/CTQueryDialog.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,107 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Generic CT Query Dialog
+*
+*/
+
+
+
+#ifndef __CTCONFIRMATIONQUERYDIALOG_H
+#define __CTCONFIRMATIONQUERYDIALOG_H
+
+//  INCLUDES
+#include <AknQueryDialog.h>
+
+// DATA TYPES
+enum TCTQueryDialogType
+    {
+	ECTConfirmationDialog,
+	ECTErrorDialog,
+	ECTInfoDialog,
+	ECTWarningDialog,
+	ECTOkDialog
+    };
+
+
+// CLASS DECLARATION
+
+/**
+*  Query dialog class
+*
+*  @lib CTSecDlgNotifier.dll
+*  @since Series 60 2.6
+*/
+NONSHARABLE_CLASS( CCTQueryDialog ): public CAknQueryDialog
+    {
+    
+    public: // Constructors and destructor
+        
+	    ~CCTQueryDialog();
+
+    public: // Functions from CAknQueryDialog
+        
+	    /**
+	    * RunDlgLD launches the Text Query Dialog
+		* @param	aStatus		Client status
+		* @param	aRetVal		ETrue for positive user response, EFalse for negative
+	    * @param	aQueryText	Text for query dialog
+	    * @param	aDlgButtonResourceId	ID of softkey resource to be used in the dlg (Default is Yes-No).									
+	    * @param	aDlgType	Dialog layout type
+	    */
+	    static void RunDlgLD( 
+            TRequestStatus& aStatus, 
+            TBool& aRetVal, 
+            const TDesC& aQueryText, 
+            TInt aDlgButtonResourceId = 0, 
+            const TCTQueryDialogType aDlgType = ECTConfirmationDialog);
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+	    CCTQueryDialog( 
+            TRequestStatus& aStatus, 
+            TBool& aRetVal, 
+            const TDesC& aQueryText, 
+            TInt aDlgButtonResourceId, 
+            const TCTQueryDialogType aDlgType);
+
+    private: // Functions from CAknQueryDialog 
+
+        /**
+        * 
+        */
+	    void PreLayoutDynInitL();
+        /**
+        * 
+        */
+	    void PostLayoutDynInitL();
+        
+        /**
+        * 
+        */
+        TBool OkToExitL( TInt aButtonId );
+
+    private: // Data
+	    TCTQueryDialogType	iDlgType;
+	    TInt				iDlgButtonResourceId;
+	    const TDesC&		iQueryText;
+		TRequestStatus*		iClientStatus;
+		TBool&				iRetVal;
+    };
+
+#endif // __CTCONFIRMATIONQUERYDIALOG_H
+
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifInc/CTSecurityDialogNotifier.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,139 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Crypto Token Security Dialog Notifier
+*
+*/
+
+
+
+#ifndef __CTSECURITYDIALOGNOTIFIER_H
+#define __CTSECURITYDIALOGNOTIFIER_H
+
+//  INCLUDES
+#include "CTSecurityDialogDefs.h"
+#include "CTSecurityDialogsLogger.h"
+#include <secdlgimpldefs.h>
+#include <eiknotapi.h>
+
+// FORWARD DECLARATIONS
+class RReadStream;
+class CEikonEnv;
+class CUnifiedCertStore;
+class CCTCertInfo;
+class CCertAttributeFilter;
+class CCTSecurityDialogsAO;
+
+// CLASS DECLARATION
+
+/**
+* CCTSecurityDialogNotifier is the Server-side class for Notifier plugin.
+* @lib 
+* @since
+*/
+NONSHARABLE_CLASS( CCTSecurityDialogNotifier ): public CBase, public MEikSrvNotifierBase2
+    {
+    public: // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+	    static CCTSecurityDialogNotifier* NewL();
+        
+        /**
+        * Destructor.
+        */
+	    ~CCTSecurityDialogNotifier();
+    
+    public: // new functions
+
+        // Loads the resource strings etc for TDialogType aType
+	    
+	    HBufC* LoadResourceStringLC( const TInt aType, const TDesC& aDynamicText = KNullDesC, const TDesC& aDynamicText2= KNullDesC );
+        
+        // Finds the corresponding resource items for aType
+	    TDialogTypeItem GetDialogTypeItem( const TInt aType );
+
+    private: // from MEikSrvNotifierBase2
+
+        /**
+        * Deletes this
+        */
+	    void Release();
+
+        /**
+        * 
+        * @return TNotifierInfo
+        */
+	    TNotifierInfo RegisterL();
+        
+        /**
+        *
+        * @return TNotifierInfo
+        */
+	    TNotifierInfo Info() const;
+	    
+	    /**
+	    * StartL is the Notifier request handler.
+	    * @param aBuffer Data that is passed from the client-side. 
+	    * @param aReplySlot Identifies which message argument to use for the reply.
+	    * @param aMessage Encapsulates a client request.
+	    */
+	    void StartL( const TDesC8& aBuffer, TInt aReplySlot, const RMessagePtr2& aMessage );
+	    
+        /**
+        * Does nothing.
+        * @param aBuffer
+        * @return KNullDesC
+        */
+	    TPtrC8 StartL( const TDesC8& aBuffer );
+
+        /**
+        * Does nothing
+        */
+	    void Cancel();
+
+        /**
+        * Does nothing
+        * @param aBuffer
+        * @return KNullDesC
+        */
+	    TPtrC8 UpdateL( const TDesC8& aBuffer );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+	    CCTSecurityDialogNotifier();
+        
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+	    void ConstructL();
+	    
+	    void DoStartL( const TDesC8& aBuffer, TInt aReplySlot, const RMessagePtr2& aMessage );
+		
+    private:    // Data
+        
+	    CEikonEnv* iEikEnv;
+	    TInt iResourceFileOffset;
+	    TInt iResourceFileOffset2;
+		TBool iSaveReceipt; //text to save to notepad
+		TInt32 iDialogType;
+		CCTSecurityDialogsAO* iSecurityDialogAO;
+		TBool iSecurityDialogAODeleted;
+    };
+
+#endif // __CTSECURITYDIALOGNOTIFIER_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifInc/CTSecurityDialogsAO.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,337 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Definition of the CCTSecurityDialogsAO class
+*
+*/
+
+
+#ifndef CTSECURITYDIALOGSAO_H
+#define CTSECURITYDIALOGSAO_H
+
+//  INCLUDES
+#include "CTSecurityDialogDefs.h"
+#include <secdlgimpldefs.h>
+#include <badesca.h>
+#include <mctkeystore.h>
+
+// FORWARD DECLARATIONS
+class CCTSecurityDialogNotifier;
+class CUnifiedCertStore;
+class CUnifiedKeyStore;
+class CCertAttributeFilter;
+class CCTCertInfo;
+class CCTKeyInfo;
+class CX509Certificate;
+class CX500DistinguishedName;
+class MCTWritableCertStore;
+class CAknQueryDialog;
+class CCTPinQueryDialog;
+
+
+// CLASS DECLARATION
+
+/**
+*  Active object class of CT Security Dialogs
+*  Calls from client side are handled in this class.
+*
+*  @lib CTSecDlgNotifier.dll
+*  @since Series 60 2.8
+*/
+NONSHARABLE_CLASS( CCTSecurityDialogsAO ): public CActive
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCTSecurityDialogsAO* NewL( CCTSecurityDialogNotifier* aNotifier, TBool& aDeleted );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCTSecurityDialogsAO();
+
+    public: // New functions
+
+        /**
+        * Starts handling of the message
+        * @param aBuffer  Data passed from client RNotifier::StartNotifierAndGetResponse() call
+        * @param aReplySlot  Identifies which message argument to use for the reply
+        * @param aMessage  Encapsulates the client request
+        */
+        void StartLD( const TDesC8& aBuffer, TInt aReplySlot, const RMessagePtr2& aMessage );
+
+
+        // For server authentication failure
+        /**
+        * Creates the message to be shown in the certificate details query.
+        *
+        * @return message text
+        */
+        HBufC* CreateMessageL();
+
+    protected:  // Functions from CActive
+
+        /**
+        * RunL is called after modeless dialog is dismissed.
+        */
+        void RunL();
+
+        /**
+        * Does nothing.
+        */
+        void DoCancel();
+
+        /**
+        * If RunL leaves, error is handled here.
+        */
+        TInt RunError(TInt aError);
+
+    private:
+
+        enum TOperationStatus
+        {
+            EOperationCompleted = 0xFFF0,
+            EOperationCancel,
+            EOperationSignTextShown,
+            EOperationInitCertStore,
+            EOperationRetrieveCertInfos,
+            EOperationSelectCert,
+            EGetCertInfo,
+            EGetCertificate,
+            EInitKeyStore,
+            EGetKeyInfos,
+            EGetKeyInfoByHandle,
+            EShowCertDialog,
+            EShowCSRDialog,
+            EEnterNewPIN,
+            EEnterUnblockPIN,
+            EVerifyNewPin,
+            EVerifyPINs,
+            EServerCertCheckUserResp,
+            ESaveServerCert,
+            EAddTrustedSite,
+            ERetrieveServerCerts,
+            ECheckServerCerts,
+            EProcessTrustedSite,
+            EUnknownError
+            };
+
+        /**
+        * C++ default constructor.
+        */
+        CCTSecurityDialogsAO( CCTSecurityDialogNotifier* aNotifier, TBool& aDeleted );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        void InitCertStoreL();
+
+        void InitKeyStoreL();
+
+        void GetKeyInfosL();
+
+        void GetKeyInfoByHandleL();
+
+        void DoHandlePinOperationL();
+
+        void DoHandleUnblockPinOperationL();
+
+        void DoHandleMultilinePinQueryL(const TInt& aDlgType);
+
+        void DoHandleSignTextL(const TDesC8& aBuffer);
+
+        void DoHandleCSRL(const TDesC8& aBuffer);
+
+        void DoHandleCertDetailsL(const TDesC8& aBuffer);
+
+        void DoHandleSaveCertL(const TDesC8& aBuffer);
+
+        void DoHandleSaveServerCertL();
+
+        void DoHandleServerAuthFailL(const TDesC8& aBuffer);
+
+        void ShowCertDialogL();
+
+        void ShowNoTrustDialogL();
+
+        void ShowCSRDialogL();
+
+        /**
+        * Saves digital signature receipt
+        */
+        void SaveReceiptL(const TDesC8& aBuffer);
+
+        void DoHandleSelectCertificateL();
+
+        void DoHandleMessageL(
+            const TInt& aDlgType,
+            const TDesC& aDynamicText,
+            const TDesC& aPinQueryHeading,
+            const TInt aMinLength,
+            const TInt aMaxLength);
+
+        /////////////////////////////////
+        // Certificate details functions
+
+        HBufC* MessageQueryCertDetailsL(
+            const TDesC8& aCert,
+            const CCTCertInfo* aCertInfo,
+            TCertificateFormat aCertFormat,
+            const CCTKeyInfo* aKeyInfo);
+
+        void AddSiteL( TDes& aMessage );
+
+        void AddIssuerAndSubjectL(
+            TDes& aMessage,
+            const CX509Certificate& aCert);
+
+        void AddKeyUsageL(
+            TDes& aMessage,
+            const CCTKeyInfo* aKeyInfo );
+
+        void AddKeyUsageL(
+            TDes& aMessage,
+            const CX509Certificate& aCert);
+
+        void AddKeyLocationL(
+            TDes& aMessage,
+            const CCTKeyInfo* aKeyInfo );
+
+        void AddKeySizeL(
+            TDes& aMessage,
+            const CCTKeyInfo* aKeyInfo );
+
+        void AddKeyAlgorithmL(
+            TDes& aMessage,
+            const CCTKeyInfo* aKeyInfo );
+
+        void AddCertLocationL(
+            TDes& aMessage,
+            const CCTCertInfo* aCertInfo );
+
+        void AddLocationInfoL(
+            TDes& aMessage,
+            TUid aUid,
+            TBool aCertificate );
+
+        void AddValidityPeriodL(
+            TDes& aMessage, const CX509Certificate& aCert);
+
+        void AddCertFormatL(
+            TDes& aMessage, TCertificateFormat aCertFormat);
+
+        void AddCertAlgorithmsL(
+            TDes& aMessage, const CX509Certificate& aCert);
+
+        void AddCertSerialNumberL(
+            TDes& aMessage, const CX509Certificate& aCert);
+
+        void AddCertFingerprintsL(
+            TDes& aMessage, const CX509Certificate& aCert);
+
+        void DevideToBlocks( const TDesC8& aInput, TDes& aOutput);
+
+        void DetailsFieldDynamicL(
+            TDes& aMessage,
+            const TDesC& aValue,
+            TInt aResourceOne,
+            TInt aResourceTwo);
+
+        void DetailsFieldResourceL(
+            TDes& aMessage, TInt aResourceOne,
+            TInt aResourceTwo);
+
+        void DetailsResourceL(TDes& aMessage, TInt aResource);
+
+        void DetailsDynamicL(
+            TDes& aMessage,
+            const TDesC& aValue,
+            TInt aResource);
+
+        void MapTlsProviderOperation( TUint aOperation );
+
+        TPtrC CutCertificateField(const TDesC&  aField);
+
+        /**
+        * Completes client's request
+        */
+        void HandleResponseAndCompleteL();
+
+        /**
+        * Checks that are two PINs the same
+        */
+        void VerifyPinsL();
+        
+    private:    // Data
+        RMessagePtr2 iMessagePtr;
+        TSecurityDialogNotification iOperation;
+        TBool iRetry;
+        TSignInput iSignInput;
+        TPINParams iPIN;
+        TPINParams iUnblockPIN;
+        TInt iReplySlot;
+        TPINValue iPINValue1;
+        TPINValue iPINValue2;
+        TPINValue iPINValueVerify;
+        RArray<TCTTokenObjectHandle> iCertHandleList;
+        TBool iRetValue;
+        TCTTokenObjectHandle iTokenHandle;
+
+        TServerAuthenticationFailureInput iServerAuthenticationFailureInput;
+
+        CCTSecurityDialogNotifier* iNotifier;
+        TInt iNextStep;
+        TInt iMultiLineDlgType;
+
+        // For retrieving signText dialog
+        CUnifiedCertStore* iCertStore;
+        CCertAttributeFilter* iFilter;
+        RFs iFs;
+        CCTCertInfo* iCertInfo;
+        CDesCArrayFlat*  iCertArray;        
+        RMPointerArray<CCTCertInfo> iCertInfos;
+        HBufC8* iCertBuf;
+        MCTWritableCertStore *iTrustedSiteCertStore;
+        HBufC* iCertLabel;
+        HBufC8* iServerCert;
+        RMPointerArray<HBufC8> iServerCerts;
+        HBufC* iServerName;
+        TBool iTrustedSite;
+        TInt iHandleIndex;
+        TPtr8 iCertPtr;
+
+        CUnifiedKeyStore* iKeyStore;
+        CCTKeyInfo* iKeyInfo;
+        RMPointerArray<CCTKeyInfo> iKeyInfos;
+        TCTKeyAttributeFilter iKeyFilter;
+        HBufC* iText;
+
+        TSaveCertInput iSaveCertInput;
+        TValidationError iAuthFailReason;
+        
+        TBool& iDeleted;
+        
+        CAknQueryDialog* iQueryDialog;
+        TBool iQueryDialogDeleted;
+        
+        CCTPinQueryDialog* iPinQueryDialog;
+        TBool iPinQueryDialogDeleted;
+        };
+
+#endif      // CTSECURITYDIALOGSAO_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifInc/CTSecurityDialogsLogger.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,106 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implemented logger functionality of the module
+*
+*/
+
+
+#ifndef WIMSECURITYDIALOGS_LOGGER_H
+#define WIMSECURITYDIALOGS_LOGGER_H
+
+#if defined ( _DEBUG )
+
+// INCLUDES
+
+#include <flogger.h>
+
+// log files are stored to KDebugLogDirFull folder
+_LIT(KDebugLogDependency,"C:\\Logs\\");
+_LIT(KDebugLogDoubleBackSlash,"\\");
+
+_LIT(KDebugLogDir, "WimSecurityDialogs");
+_LIT(KDebugLogFile, "WimSecurityDialogsNotifierDebugLog.log");
+_LIT(KDebugLogTitle, "- BrowserTelServiceNotifier Debug Log File -");
+_LIT( KWimsecuritydialogsLogMessageAppBanner,   "WimSecurityDialogs: module (%d.%d.%d) started" );
+_LIT( KDebugLogEnterFn,            "WimSecurityDialogs: -> %S" );
+_LIT( KDebugLogLeaveFn,            "WimSecurityDialogs: <- %S" );
+_LIT( KDebugLogTimeFormatString,   "%H:%T:%S:%*C3" );
+_LIT( KDebugLogExit,               "WimSecurityDialogs: module exit" );
+
+
+// MACROS
+
+/**
+* Use this macro in order to initialize logger :
+* - create log directory,
+* - write version information into the log file
+*/
+#define WIMSECURITYDIALOGS_CREATE { TFileName path( KDebugLogDependency ); path.Append( KDebugLogDir ); path.Append( KDebugLogDoubleBackSlash ); RFs& fs = CEikonEnv::Static()->FsSession(); fs.MkDirAll( path ); RFileLogger::WriteFormat( KDebugLogDir, KDebugLogFile, EFileLoggingModeOverwrite, KWimsecuritydialogsLogMessageAppBanner ); }
+
+/**
+* Use this macro for writing information about exiting.
+*/
+#define WIMSECURITYDIALOGS_DELETE { RFileLogger::Write( KDebugLogDir, KDebugLogFile, EFileLoggingModeAppend, KDebugLogExit ); }
+
+/**
+* Use this function at the entry point of any functions.
+* @param a Entry information of the method.
+*/
+#define WIMSECURITYDIALOGS_ENTERFN( a ) { _LIT( temp, a ); RFileLogger::WriteFormat( KDebugLogDir, KDebugLogFile, EFileLoggingModeAppend, KDebugLogEnterFn, &temp ); }
+
+/**
+* Use this function right before you leave the method.
+* @param a Leaving information of the method.
+*/
+#define WIMSECURITYDIALOGS_LEAVEFN( a ) { _LIT( temp, a ); RFileLogger::WriteFormat( KDebugLogDir, KDebugLogFile, EFileLoggingModeAppend, KDebugLogLeaveFn, &temp ); }
+
+/**
+* Use this function at any points of a function for logging the current state.
+* @param a String to be written into logfile about the current state
+*/
+#define WIMSECURITYDIALOGS_WRITE( a ) { _LIT( temp, a ); RFileLogger::Write( KDebugLogDir, KDebugLogFile, EFileLoggingModeAppend, temp ); }
+
+/**
+* Use this function at any points of a function for logging the current state.
+* You can use printf-like formats, but with only one parameter to be substituted..
+* @param a Format string,
+* @param b Parameter to be substituted.
+*/
+#define WIMSECURITYDIALOGS_WRITE_FORMAT( a, b ) { _LIT( temp, a ); RFileLogger::WriteFormat( KDebugLogDir, KDebugLogFile, EFileLoggingModeAppend, temp, b ); }
+
+/**
+* Use this function at any points of a function for logging the current state.
+* The current date/time stamp is written besides the string you give.
+* @param a String to be written into logfile about the current state
+*/
+#define WIMSECURITYDIALOGS_WRITE_TIMESTAMP( a ) { _LIT( temp, a ); TTime time; time.HomeTime(); TBuf<256> buffer; time.FormatL( buffer, KDebugLogTimeFormatString ); buffer.Insert( 0, temp ); RFileLogger::Write( KDebugLogDir, KDebugLogFile, EFileLoggingModeAppend, buffer); }
+
+
+#else // _DEBUG
+
+// Empty macros
+#define WIMSECURITYDIALOGS_CREATE
+#define WIMSECURITYDIALOGS_DELETE
+#define WIMSECURITYDIALOGS_ENTERFN( a )
+#define WIMSECURITYDIALOGS_LEAVEFN( a )
+#define WIMSECURITYDIALOGS_WRITE( a )
+#define WIMSECURITYDIALOGS_WRITE_FORMAT( a, b )
+#define WIMSECURITYDIALOGS_WRITE_TIMESTAMP( a )
+
+#endif // _DEBUG
+
+
+#endif	// WIMSECURITYDIALOGS_LOGGER_H
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifInc/CTSelectCertificateDialog.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,86 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   CT Select Certificate Dialog
+*
+*/
+
+ 
+
+#ifndef __CTSELECTCERTIFICATEDIALOG_H
+#define __CTSELECTCERTIFICATEDIALOG_H
+
+//  INCLUDES
+#include <aknlistquerydialog.h>
+
+class TCTTokenObjectHandle;
+
+// CLASS DECLARATION
+/**
+*  Certificate selection query class
+*
+*  @lib CTSecDlgNotifier.dll
+*  @since Series 60 2.6
+*/
+NONSHARABLE_CLASS( CCTSelectCertificateDialog ): public CAknListQueryDialog
+    {
+    public: // Constructors and destructor
+        
+        /**
+        * Destructor.
+        */
+	    ~CCTSelectCertificateDialog();
+
+    public: // Functions from CAknQueryDialog
+        
+	    /**
+	    * RunDlgLD Launches the Select Certificate Dialog
+	    * @param	aCertificates	List of certificate labels
+	    * @param	aSelectedIndex	Selected certificate index.
+		* @param	aClientStatus   Client Status 		
+	    * @param	iRetVal ETrue for positive response from the user, EFalse otherwise.
+	    */
+	    static void RunDlgLD( MDesCArray* aCertificates, 
+                              RArray<TCTTokenObjectHandle>& aCertHandleList,
+                              TCTTokenObjectHandle& aSelectedCert,
+                              TRequestStatus& aClientStatus, 
+                              TBool& aRetVal );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */        
+	    CCTSelectCertificateDialog( MDesCArray* aCertificates, 
+                                    RArray<TCTTokenObjectHandle>& aCertHandleList,
+                                    TCTTokenObjectHandle& aSelectedCert,
+                                    TRequestStatus& aClientStatus, 
+                                    TBool& aRetVal );
+
+		TBool OkToExitL( TInt aButtonId );
+		
+		void PostLayoutDynInitL();
+		
+
+	private:
+
+		TRequestStatus* iClientStatus;
+		TBool& iRetVal;
+		TInt iSelectedIndex;
+        RArray<TCTTokenObjectHandle>& iCertHandleList;
+        TCTTokenObjectHandle& iSelectedCert;
+    };
+    
+#endif // __CTSELECTCERTIFICATEDIALOG_H
+
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifInc/CTSignTextDialog.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,103 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   CT Read and Sign Dialog for Digital Signature
+*
+*/
+
+
+
+#ifndef __CTSIGNTEXTDIALOG_H
+#define __CTSIGNTEXTDIALOG_H
+
+//  INCLUDES
+#include "CTSecurityDialogDefs.h"
+#include <aknmessagequerydialog.h>
+
+
+// CLASS DECLARATION
+
+/**
+*
+*
+*  @lib 
+*  @since 
+*/
+NONSHARABLE_CLASS( CCTSignTextDialog ): public CAknMessageQueryDialog
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Destructor.
+        */
+	    ~CCTSignTextDialog();
+
+    public:
+
+	    /**
+	    * RunDlgLD launches the Read And Sign Dialog
+	    * @param	aReceiptToSign	Text to be signed
+		* @param	aStatus			Client status				
+	    * @param	aRetVal			ETrue for positive user response
+	    */
+	    static void RunDlgLD(TInt aResourceId, const TDesC& aReceiptToSign, 
+	                         TRequestStatus& aStatus, TBool& aRetVal);        
+    
+    protected:
+
+        /**
+        * C++ default constructor.
+        */
+	    CCTSignTextDialog(const TDesC& aReceiptToSign, TRequestStatus& aStatus, TBool& aRetVal, TBool aSignText);
+
+    protected:  // Functions from CAknMessageQueryDialog  
+        
+        /**
+        *
+		* @param  aKeyEvent
+		* @param  aType
+		* @return TKeyResponse
+        */
+		TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+        /**
+        * 
+        */
+	    void PreLayoutDynInitL();
+
+        /**
+        * 
+        */
+		void PostLayoutDynInitL();
+
+        /**
+        * 
+        */        
+        TBool OkToExitL( TInt aButtonId );
+
+        
+
+
+    protected:  //Data
+        
+	    const TDesC& iReceiptToSign;
+		TRequestStatus* iClientStatus;
+	
+	private:
+		TBool& iRetVal;
+        TBool iSignText;
+    };
+
+#endif // __CTSIGNTEXTDIALOG_H
+
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifSrc/CTCertificateQuery.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,73 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+
+// INCLUDE FILES
+
+#include "CTCertificateQuery.h"
+#include "CTSecurityDialogsAO.h"
+
+#include <CTSecDlgs.rsg>
+#include <certmanui.rsg>
+#include <aknmessagequerydialog.h>
+#include <aknPopupHeadingPane.h>
+
+// ================= MEMBER FUNCTIONS ==========================================
+
+CCTCertificateQuery::CCTCertificateQuery(CCTSecurityDialogsAO& aAO):  
+    CAknMessageQueryDialog( CAknQueryDialog::ENoTone ), 
+    iNotifier(aAO)    
+    {
+    }
+
+CCTCertificateQuery* CCTCertificateQuery::NewL(CCTSecurityDialogsAO& aAO)
+    {
+    CCTCertificateQuery* query = 
+    new( ELeave ) CCTCertificateQuery(aAO);
+
+    CleanupStack::PushL( query );
+    query->ConstructL();
+    CleanupStack::Pop();
+    
+    return query;
+    }
+
+void CCTCertificateQuery::ConstructL()
+    {    
+    iHeader = CEikonEnv::Static()->AllocReadResourceL( R_TEXT_RESOURCE_DETAILS_VIEW_HEADER );    
+    SetHeaderTextL( *iHeader );    
+    iMessage = iNotifier.CreateMessageL();    
+    SetMessageTextL( *iMessage );          
+    }
+
+CCTCertificateQuery::~CCTCertificateQuery()
+    {
+    delete iHeader;
+    delete iMessage;
+    }
+
+// -----------------------------------------------------------------------------
+// CCTCertificateQuery::OkToExitL()
+// -----------------------------------------------------------------------------
+
+TBool CCTCertificateQuery::OkToExitL( TInt /*aButtonId*/ )
+    {
+    return ETrue;
+    }
+
+// end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifSrc/CTInvalidCertNote.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,93 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Info note shown for invalid and revoked certificates
+*
+*/
+
+
+
+#include "CTInvalidCertNote.h"
+#include "CTCertificateQuery.h"     // CCTCertificateQuery
+#include <uikon/eiksrvui.h>         // CEikServAppUi
+#include <CTSecDlgs.rsg>
+
+
+// ======== MEMBER FUNCTIONS ========
+
+
+// ---------------------------------------------------------------------------
+// Constructor
+// ---------------------------------------------------------------------------
+//
+CCTInvalidCertificateNote::CCTInvalidCertificateNote( 
+    CCTSecurityDialogsAO& aNotifier,
+    TRequestStatus& aClientStatus ) :
+    iNotifier( aNotifier ),
+    iClientStatus( &aClientStatus )
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CCTInvalidCertificateNote::~CCTInvalidCertificateNote()
+    {
+    static_cast<CEikServAppUi*>(iEikonEnv->EikAppUi())->SuppressAppSwitching( EFalse );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CCTInvalidCertificateNote::OkToExitL()
+// ---------------------------------------------------------------------------
+//
+TBool CCTInvalidCertificateNote::OkToExitL( TInt aButtonId )
+    {
+    if( aButtonId == EAknSoftkeyShow )
+        {
+        ShowDetailsL();
+        return EFalse;
+        }
+    else
+        {
+        User::RequestComplete( iClientStatus, KErrNone );
+        }
+    return ETrue;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CCTInvalidCertificateNote::PostLayoutDynInitL()
+// ---------------------------------------------------------------------------
+//
+void CCTInvalidCertificateNote::PostLayoutDynInitL()
+    {
+    CAknNoteDialog::PostLayoutDynInitL();
+    static_cast<CEikServAppUi*>(iEikonEnv->EikAppUi())->SuppressAppSwitching(ETrue);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CCTInvalidCertificateNote::ShowDetailsL()
+// ---------------------------------------------------------------------------
+//
+void CCTInvalidCertificateNote::ShowDetailsL()
+    {
+    CCTCertificateQuery* query = CCTCertificateQuery::NewL( iNotifier );
+    query->ExecuteLD( R_NOTRUST_CERTIFICATE_QUERY );
+    }
+
+
+// end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifSrc/CTNoTrustQuery.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,212 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+
+// INCLUDE FILES
+
+#include "CTNoTrustQuery.h"
+#include "CTSecurityDialogsAO.h"
+#include "CTCertificateQuery.h"
+#include <aknlists.h>
+#include <CTSecDlgs.rsg>
+#include <uikon/eiksrvui.h>
+#include <StringLoader.h>
+
+
+// ================= MEMBER FUNCTIONS ==========================================
+
+// -----------------------------------------------------------------------------
+// CSecNotNoTrustQuery::CCTNoTrustQuery()
+// -----------------------------------------------------------------------------
+//
+CCTNoTrustQuery::CCTNoTrustQuery(
+    CCTSecurityDialogsAO& aNotifier,
+    TBool& aRetVal,
+    TRequestStatus& aClientStatus,
+    HBufC* aServerName,
+    TBool aShowPermAccept,
+    TBool& aIsDeleted ):
+    CAknQueryDialog( CAknQueryDialog::ENoTone ),
+    iNotifier( aNotifier ),
+    iRetVal( aRetVal ),
+    iClientStatus( &aClientStatus ),
+    iServerName( aServerName ),
+    iShowPermAccept( aShowPermAccept ),
+    iDeleted( aIsDeleted )
+    {
+    iDeleted = EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CSecNotNoTrustQuery::~CCTNoTrustQuery()
+// -----------------------------------------------------------------------------
+//
+CCTNoTrustQuery::~CCTNoTrustQuery()
+    {
+    // Allow application switching again
+    CEikonEnv* eikonEnv = CEikonEnv::Static();
+    if( eikonEnv )
+        {
+        CEikServAppUi* eikServAppUi = static_cast<CEikServAppUi*>( eikonEnv->EikAppUi() );
+        if( eikServAppUi )
+            {
+            eikServAppUi->SuppressAppSwitching( EFalse );
+            }
+        }
+
+    // Complete the client request
+    if( iClientStatus && *iClientStatus == KRequestPending )
+        {
+        iRetVal = EFalse;
+        User::RequestComplete( iClientStatus, KErrNone );
+        }
+    
+    // Notify that the dialog has been deleted
+    iDeleted = ETrue;
+    }
+
+// -----------------------------------------------------------------------------
+// CSecNotNoTrustQuery::OkToExitL()
+// -----------------------------------------------------------------------------
+//
+TBool CCTNoTrustQuery::OkToExitL( TInt aButtonId )
+    {
+    if ( aButtonId == EAknSoftkeyOptions || aButtonId == EAknSoftkeyOk )
+        {
+        return OptionsMenuL();
+        }
+    else
+        {
+        iRetVal = EFalse;
+        User::RequestComplete( iClientStatus, KErrNone );
+        }
+    return ETrue;
+    }
+
+// -----------------------------------------------------------------------------
+// CCTNoTrustQuery::PostLayoutDynInitL()
+// -----------------------------------------------------------------------------
+//
+void CCTNoTrustQuery::PostLayoutDynInitL()
+    {
+    CAknQueryControl* control = QueryControl();
+    if (control)
+        control->StartAnimationL();
+    ((CEikServAppUi*)(CEikonEnv::Static())->EikAppUi())->SuppressAppSwitching( ETrue );
+    }
+
+// -----------------------------------------------------------------------------
+// CCTNoTrustQuery::OptionsMenuL()
+// -----------------------------------------------------------------------------
+TBool CCTNoTrustQuery::OptionsMenuL()
+    {
+    TBool ret = EFalse;
+    CAknSinglePopupMenuStyleListBox* list =
+        new( ELeave ) CAknSinglePopupMenuStyleListBox;
+    CleanupStack::PushL( list );
+    CAknPopupList* popupList = CAknPopupList::NewL(
+        list, R_AVKON_SOFTKEYS_SELECT_CANCEL__SELECT, AknPopupLayouts::EMenuWindow );
+    CleanupStack::PushL( popupList );
+    list->ConstructL( popupList, CEikListBox::ELeftDownInViewRect );
+    list->CreateScrollBarFrameL( ETrue );
+    list->ScrollBarFrame()->SetScrollBarVisibilityL(
+        CEikScrollBarFrame::EOff, CEikScrollBarFrame::EAuto );
+
+    TInt resourceid;
+
+    if ( iShowPermAccept )
+        {
+        resourceid = R_NOTRUST_MENUPANE;
+        }
+    else
+        {
+        resourceid = R_NOTRUST_MENUPANE_NO_PERM;
+        }
+
+     CDesCArrayFlat* items =
+            CEikonEnv::Static()->ReadDesCArrayResourceL( resourceid );
+
+    CTextListBoxModel* model = list->Model();
+    model->SetOwnershipType( ELbmOwnsItemArray );
+    model->SetItemTextArray( items );
+
+    CleanupStack::Pop( popupList ); //popupList
+    if ( popupList->ExecuteLD() )
+        {
+        if( !iDeleted )
+            {
+            TInt index = list->CurrentItemIndex();
+            if ( index == 0 )       // Accept now
+                {
+                iRetVal = EServerCertAcceptedTemporarily;
+                User::RequestComplete(iClientStatus, KErrNone);
+                ret = ETrue;
+                }
+            else if (( index == 1 ) && ( resourceid == R_NOTRUST_MENUPANE ))  // Accept permanently
+                {
+    
+                HBufC* prompt = StringLoader::LoadLC( R_QTN_HTTPSEC_QUERY_PERM_ACCEPT_TEXT, *iServerName );
+    
+                CAknMessageQueryDialog* note = CAknMessageQueryDialog::NewL( *prompt );
+    
+                note->PrepareLC( R_HTTPSEC_QUERY_PERM_ACCEPT );
+                note->SetPromptL( *prompt );
+    
+                if ( note->RunLD() )
+                    {
+                    iRetVal = EServerCertAcceptedPermanently;
+                    User::RequestComplete( iClientStatus, KErrNone );
+                    ret = ETrue;
+                    }
+                else
+                    {
+                    ret = EFalse;
+                    }
+    
+                CleanupStack::PopAndDestroy( prompt );
+                }
+            else if ((( index == 2 ) && ( resourceid == R_NOTRUST_MENUPANE ))  ||
+                     (( index == 1 ) && ( resourceid == R_NOTRUST_MENUPANE_NO_PERM )) ) // Details
+                {
+                // We need to delay this implementation in other releases, because
+                // separate ICD was taken to 3.0.
+                CCTCertificateQuery* query =
+                CCTCertificateQuery::NewL( iNotifier );
+                query->ExecuteLD( R_NOTRUST_CERTIFICATE_QUERY );
+                ret = EFalse;
+                }
+            else
+                {
+                iRetVal = EServerCertNotAccepted;
+                User::RequestComplete( iClientStatus, KErrNone );
+                ret = ETrue;
+                }
+            }
+        else
+            {
+            ret = EFalse;
+            }
+        }
+    else
+        {
+        ret = EFalse;
+        }
+    CleanupStack::PopAndDestroy( list );  // list
+    return ret;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifSrc/CTPinPinQueryDialog.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,210 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of multiline PIN query dialog
+*
+*/
+
+
+// INCLUDE FILES
+#include "CTPinPinQueryDialog.h"
+#include <CTSecDlgs.rsg>
+#include <eikenv.h>
+#include <barsread.h>
+#include <uikon/eiksrvui.h>
+#include <secdlg.h>
+#include <layoutmetadata.cdl.h>
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCTPinPinQueryDialog::CCTPinPinQueryDialog
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CCTPinPinQueryDialog::CCTPinPinQueryDialog(
+    const TDesC& aDlgText1,
+    const TDesC& aDlgText2,
+    TDes&  aPin1,
+    TDes&  aPin2,
+    const TInt aMinTextLength, 
+    const TInt aMaxTextLength, 
+    TBool& aRetVal): 
+    CAknMultiLineDataQueryDialog( ENoTone ),
+	iDlgText1(aDlgText1),
+    iDlgText2(aDlgText2),
+	iPinValue1(aPin1),
+    iPinValue2(aPin2),
+	iRetVal(aRetVal)
+    {
+    iMaxTextLength = Min(aPin1.MaxLength(), aMaxTextLength);
+	iMinTextLength = Max(0, aMinTextLength);
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinPinQueryDialog::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CCTPinPinQueryDialog::ConstructL()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinPinQueryDialog::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CCTPinPinQueryDialog* CCTPinPinQueryDialog::NewL(
+    const TDesC& aDlgText1,
+    const TDesC& aDlgText2,
+    TDes&  aPin1,
+    TDes&  aPin2,
+    const TInt aMinTextLength, 
+    const TInt aMaxTextLength, 
+    TBool& aRetVal)
+    {
+    CCTPinPinQueryDialog* self = new( ELeave ) CCTPinPinQueryDialog(
+        aDlgText1, aDlgText2, aPin1, aPin2, aMinTextLength, aMaxTextLength, aRetVal);
+    
+    CleanupStack::PushL( self );
+    self->SetDataL(aPin1, aPin2);
+    CleanupStack::Pop();
+
+    return self;
+    }
+ 
+// Destructor
+CCTPinPinQueryDialog::~CCTPinPinQueryDialog()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinPinQueryDialog::RunDlgLD()
+// -----------------------------------------------------------------------------
+//
+void CCTPinPinQueryDialog::RunDlgLD(TRequestStatus& aClientStatus, TInt aResourceId)
+    {
+    iClientStatus = &aClientStatus;
+	// OkToExitL function handles dialog response
+    ExecuteLD(aResourceId);
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinPinQueryDialog::PreLayoutDynInitL()
+// -----------------------------------------------------------------------------
+//
+void CCTPinPinQueryDialog::PreLayoutDynInitL()
+    {
+	SetMaxLengthOfFirstEditor(iMaxTextLength);
+    SetMaxLengthOfSecondEditor(iMaxTextLength);
+	SetPromptL(iDlgText1, iDlgText2);
+	CAknMultiLineDataQueryDialog::PreLayoutDynInitL();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinPinQueryDialog::CheckIfEntryTextOk()
+// -----------------------------------------------------------------------------
+//
+
+TBool CCTPinPinQueryDialog::CheckIfEntryTextOk() const
+    {
+    TPINValue pin1;
+    TPINValue pin2;
+    if (Layout_Meta_Data::IsLandscapeOrientation())
+        {
+        if ( FirstControl()->IsFocused() )
+            {
+            TPINValue pin1;
+            FirstControl()->GetText(pin1);    
+            return ((pin1.Length() <= iMaxTextLength && pin1.Length() >= iMinTextLength));
+            }
+        else if ( SecondControl()->IsFocused() )
+           {
+           TPINValue pin2;
+           SecondControl()->GetText(pin2);    
+           return ((pin2.Length() <= iMaxTextLength && pin2.Length() >= iMinTextLength));
+           }
+        }
+
+    FirstControl()->GetText(pin1);   
+    SecondControl()->GetText(pin2); 
+    return ((pin1.Length() <= iMaxTextLength && pin1.Length() >= iMinTextLength)&&(pin2.Length() <= iMaxTextLength && pin2.Length() >= iMinTextLength));       
+    }
+// -----------------------------------------------------------------------------
+// CCTPinPinQueryDialog::UpdateLeftSoftKeyL()
+// -----------------------------------------------------------------------------
+//
+void CCTPinPinQueryDialog::UpdateLeftSoftKeyL()
+    {
+	CAknMultiLineDataQueryDialog::UpdateLeftSoftKeyL();
+
+	MakeLeftSoftkeyVisible(CheckIfEntryTextOk());
+    }
+// -----------------------------------------------------------------------------
+// CCTPinPinQueryDialog::PostLayoutDynInitL()
+// -----------------------------------------------------------------------------
+//
+void CCTPinPinQueryDialog::PostLayoutDynInitL()
+    {
+	((CEikServAppUi*)(CEikonEnv::Static())->EikAppUi())->SuppressAppSwitching(ETrue);
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinPinQueryDialog::OkToExitL()
+// -----------------------------------------------------------------------------
+//
+TBool CCTPinPinQueryDialog::OkToExitL( TInt aButtonId )
+    {
+    if (!CAknMultiLineDataQueryDialog::OkToExitL(aButtonId))
+        {
+        return EFalse;
+        }        
+    if ( aButtonId == EEikBidCancel || aButtonId == EAknSoftkeyNo )
+	    {
+	    iRetVal = EFalse;
+	    User::RequestComplete(iClientStatus, KErrNone);  	
+	    }
+    else if ( aButtonId ==EAknSoftkeyYes || aButtonId == EAknSoftkeyOk)
+	    {
+        FirstControl()->GetText(iPinValue1);
+        SecondControl()->GetText(iPinValue2);
+	    iRetVal = ETrue;
+	    User::RequestComplete(iClientStatus, KErrNone); 
+        
+	    }
+	((CEikServAppUi*)(CEikonEnv::Static())->EikAppUi())->SuppressAppSwitching(EFalse);
+	return ETrue; 
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinPinQueryDialog::OfferKeyEventL()
+// -----------------------------------------------------------------------------
+//
+TKeyResponse CCTPinPinQueryDialog::OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+	// '#' key is inactive in Pin query dialog
+	if( (aKeyEvent.iScanCode == EStdKeyHash)  && (aType == EEventKeyDown || aType == EEventKeyUp) )
+	    { 
+		return EKeyWasConsumed;
+	    }
+	// '*' key is inactive in Pin query dialog
+	if (aKeyEvent.iCode == '*')
+	    {
+		return EKeyWasConsumed;
+        }
+	return CAknMultiLineDataQueryDialog::OfferKeyEventL(aKeyEvent, aType);
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifSrc/CTQueryDialog.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,149 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Generic CT Query Dialog
+*
+*/
+
+
+
+// INCLUDE FILES
+
+#include "CTQueryDialog.h"
+#include "CTSecurityDialogsLogger.h"
+#include <CTSecDlgs.rsg>
+#include <uikon/eiksrvui.h>
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCTQueryDialog::CCTQueryDialog()
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CCTQueryDialog::CCTQueryDialog( TRequestStatus& aClienStatus, TBool& aRetVal, const TDesC& aQueryText, TInt aDlgButtonResourceId, const TCTQueryDialogType aDlgType):
+CAknQueryDialog(
+    aDlgType == ECTConfirmationDialog ? EConfirmationTone : 
+    aDlgType == ECTErrorDialog ? EErrorTone : 
+    aDlgType == ECTWarningDialog ? EWarningTone : ENoTone),
+    iDlgType(aDlgType),
+    iDlgButtonResourceId(aDlgButtonResourceId),
+    iQueryText(aQueryText), 
+    iClientStatus(&aClienStatus), 
+    iRetVal(aRetVal)
+    {
+    }
+// ---------------------------------------------------------
+// CCTQueryDialog::~CCTQueryDialog()
+// ---------------------------------------------------------
+//
+
+CCTQueryDialog::~CCTQueryDialog()
+    {
+    }
+
+// ---------------------------------------------------------
+// CCTQueryDialog::RunDlgLD
+// ---------------------------------------------------------
+//
+void CCTQueryDialog::RunDlgLD(TRequestStatus& aClienStatus, TBool& aRetVal, const TDesC& aQueryText, TInt aDlgButtonResourceId, const TCTQueryDialogType aDlgType )
+    {
+	CCTQueryDialog* self = new (ELeave) CCTQueryDialog(aClienStatus, aRetVal, aQueryText, aDlgButtonResourceId, aDlgType);
+	self->ExecuteLD(R_WIM_QUERY_DIALOG);
+    }
+
+// ---------------------------------------------------------
+// CCTQueryDialog::PreLayoutDynInitL
+// ---------------------------------------------------------
+//
+void CCTQueryDialog::PreLayoutDynInitL()
+    {
+	SetPromptL(iQueryText);
+
+	CAknQueryDialog::PreLayoutDynInitL();
+    }
+
+// ---------------------------------------------------------
+// CCTQueryDialog::PostLayoutDynInitL
+// ---------------------------------------------------------
+//
+void CCTQueryDialog::PostLayoutDynInitL()
+    {
+	CAknQueryControl* control = STATIC_CAST(CAknQueryControl*,ControlOrNull(EGeneralQuery));
+
+	TInt animResource = 0;
+	TInt softKeyResource = 0;
+	switch (iDlgType)
+	{
+		case ECTConfirmationDialog:
+			animResource = R_QGN_NOTE_QUERY_ANIM;
+			softKeyResource = R_AVKON_SOFTKEYS_YES_NO;
+			break;
+		case ECTErrorDialog:
+			animResource = R_QGN_NOTE_ERROR_ANIM;
+			softKeyResource = R_AVKON_SOFTKEYS_OK_EMPTY;
+			break;
+		case ECTInfoDialog:
+			animResource = R_QGN_NOTE_INFO_ANIM;
+			softKeyResource = R_AVKON_SOFTKEYS_OK_EMPTY;
+			break;
+		case ECTWarningDialog:
+			animResource = R_QGN_NOTE_WARNING_ANIM;
+			softKeyResource = R_AVKON_SOFTKEYS_OK_EMPTY;
+			break;
+		case ECTOkDialog:
+			animResource = R_QGN_NOTE_OK_ANIM;
+			softKeyResource = R_AVKON_SOFTKEYS_OK_EMPTY;
+			break;
+		default:
+			animResource = R_QGN_NOTE_QUERY_ANIM;
+			softKeyResource = iDlgButtonResourceId == 0 ? R_AVKON_SOFTKEYS_OK_EMPTY : iDlgButtonResourceId;
+			break;
+	}
+
+	control->SetAnimationL(animResource);
+	ButtonGroupContainer().SetCommandSetL(softKeyResource);
+
+	CAknQueryDialog::PostLayoutDynInitL();
+    ((CEikServAppUi*)(CEikonEnv::Static())->EikAppUi())->SuppressAppSwitching(ETrue);
+    }
+
+// ---------------------------------------------------------
+// CCTQueryDialog::OkToExitL
+// ---------------------------------------------------------
+//
+TBool CCTQueryDialog::OkToExitL( TInt aButtonId )
+    {
+
+    if ( aButtonId == EEikBidCancel || aButtonId == EAknSoftkeyNo )
+        {
+
+		iRetVal = EFalse;
+		User::RequestComplete(iClientStatus, KErrNone); 
+		
+        }
+    else if ( aButtonId ==EAknSoftkeyYes || aButtonId == EAknSoftkeyOk)
+        {
+		
+		iRetVal = ETrue;
+		User::RequestComplete(iClientStatus, KErrNone); 		
+        
+        }
+     ((CEikServAppUi*)(CEikonEnv::Static())->EikAppUi())->SuppressAppSwitching(EFalse);
+
+     return ETrue; 
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifSrc/CTSecurityDialogsAO.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,2495 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+// INCLUDE FILES
+#include "CTSecurityDialogsAO.h"
+#include "CTSecurityDialogNotifier.h"
+#include "CTPinQueryDialog.h"
+#include "CTSignTextDialog.h"
+#include "CTSelectCertificateDialog.h"
+#include "CTQueryDialog.h"
+#include "CTPinPinQueryDialog.h"
+#include "CTNoTrustQuery.h"
+#include "CTInvalidCertNote.h"
+#include <PKIDlg.h>
+#include <badesca.h>
+#include <StringLoader.h>
+#include <aknnotewrappers.h>
+#include <unifiedcertstore.h>
+#include <unifiedkeystore.h>
+#include <mctkeystore.h>
+#include <cctcertinfo.h>
+#include <DocumentHandler.h>
+#include <apmstd.h>
+#include <DigSigningNote.h>
+#include <certmanui.rsg>
+#include <X509CertNameParser.h>
+#include <x509cert.h>
+#include <x500dn.h>
+#include <hash.h>
+#include <x509certext.h>
+#include <TrustedSitesStore.h>
+#include <mctwritablecertstore.h>
+
+// LOCAL CONSTANTS AND MACROS
+const TInt KCertArrayGranularity = 3;
+const TInt KMaxLengthTextDetailsBody = 5000;
+// CertLabel, Issuer, Owner max length 510 bytes
+const TInt KMaxLengthTextCertLabel = 510;
+// CertLabel, Issuer, Owner max visible length
+const TInt KMaxLengthTextCertLabelVisible = 200;
+// "dd/mm/yyyy0"
+const TInt KMaxLengthTextDateString = 20;
+// HH0
+const TInt KMaxLengthTextSerialNumberFormatting = 3;
+// Maximum length of a certificate
+const TInt KMaxCertificateLength = 5000;
+
+// Maximum length of key store password
+const TInt KMaxKeystorePwLength = 6;
+
+const TInt KMinImportKeyPwLen = 1;
+
+const TInt KMaxCNLength = 64;
+
+_LIT(KCertManUIDetailsViewHexFormat, "%02X");
+
+const TInt KFileCertStoreUid( 0x101F501A );
+const TInt KWIMCertStoreUid ( 0x101F79D9 );
+const TUid KTrustedServerTokenUid = { 0x101FB66F };
+const TUid KDeviceCertStoreTokenUid = { 0x101FB668 };
+
+_LIT( KBlockSeparator, " " );
+_LIT( KEnter, "\n" );
+_LIT( KEnterEnter, "\n\n" );
+_LIT( KKeyStoreEnterPwLabel, "Key store passphrase" );
+_LIT( KKeyStoreCreatePwLabel, "New key store passphrase" );
+_LIT( KKeyStoreImportKeyLabel, "Passphrase of the imported key file" );
+_LIT( KKeyStoreExportKeyLabel, "Passphrase of the exported key file" );
+_LIT( KPKCS12TokenLabel, "PKCS12");
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::CCTSecurityDialogsAO
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CCTSecurityDialogsAO::CCTSecurityDialogsAO( CCTSecurityDialogNotifier* aNotifier,
+        TBool& aDeleted ) :
+    CActive( EPriorityStandard ), iNotifier( aNotifier ),
+    iNextStep( EOperationCompleted ), iTrustedSiteCertStore( 0 ),
+    iHandleIndex( -1 ), iCertPtr( 0, 0 ), iDeleted( aDeleted )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::ConstructL()
+    {
+    iDeleted = EFalse;
+
+    iQueryDialog = NULL;
+    iQueryDialogDeleted = ETrue;
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CCTSecurityDialogsAO* CCTSecurityDialogsAO::NewL( CCTSecurityDialogNotifier* aNotifier,
+        TBool& aDeleted )
+    {
+    CCTSecurityDialogsAO* self = new( ELeave ) CCTSecurityDialogsAO( aNotifier, aDeleted );
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::~CCTSecurityDialogsAO
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CCTSecurityDialogsAO::~CCTSecurityDialogsAO()
+    {
+    Cancel();
+    delete iText;
+    delete iFilter;
+    iCertHandleList.Close();
+    if ( iCertArray )
+        {
+        //iCertArray->Reset(); // Should we reset this?
+        //delete iCertArray;
+        }
+    iCertInfos.Close();
+    if ( iCertInfo )
+        {
+        iCertInfo->Release(); // Should we release this?
+        }
+    iKeyInfos.Close();
+    if ( iKeyInfo )
+        {
+        iKeyInfo->Release(); // Should we release this?
+        }
+
+    iServerCerts.ResetAndDestroy();
+    delete iCertBuf;
+    delete iServerName;
+    delete iCertLabel;
+    delete iKeyStore;
+    delete iCertStore;
+    iFs.Close();
+    
+    iDeleted = ETrue;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::StartLD()
+// Handles all the operations calls appropriate handler functionq
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::StartLD(
+    const TDesC8& aBuffer,
+    TInt aReplySlot,
+    const RMessagePtr2& aMessage )
+    {
+    iOperation = *reinterpret_cast<const TInt *>( aBuffer.Ptr() ) & KSecurityDialogOperationMask;
+    iRetry = *reinterpret_cast<const TInt *>( aBuffer.Ptr() ) & EPINValueIncorrect;
+    iReplySlot = aReplySlot;
+    iMessagePtr = aMessage;
+
+    WIMSECURITYDIALOGS_WRITE_FORMAT( "CCTSecurityDialogsAO::StartLD iOperation=%d", iOperation );
+    
+    MapTlsProviderOperation( iOperation );
+
+    switch ( iOperation )
+        {
+        case EEnablePIN:  // flow thru
+        case EDisablePIN: // flow thru
+        case EEnterPIN:
+        case EChangePIN:
+            {
+            TPINInput PINInput = reinterpret_cast<const TPINInput&>( *aBuffer.Ptr() );
+            iPIN = PINInput.iPIN;
+            DoHandlePinOperationL();
+            iStatus = KRequestPending;
+            SetActive();
+            break;
+            }
+        case EUnblockPIN:
+            {
+            TUnblockPINInput unblockPINInput = reinterpret_cast<const TUnblockPINInput&>( *aBuffer.Ptr() );
+            iPIN = unblockPINInput.iPIN;
+            iUnblockPIN = unblockPINInput.iUnblockPIN;
+            DoHandleUnblockPinOperationL();
+            iStatus = KRequestPending;
+            SetActive();
+            break;
+            }
+
+        case EPINBlocked:
+            {
+            TPINInput PINInput = reinterpret_cast<const TPINInput&>( *aBuffer.Ptr() );
+            iPIN = PINInput.iPIN;
+            DoHandleMessageL( EErrorPinCodeBlocked, iPIN.iPINLabel, iPIN.iTokenLabel, 0, 0 );
+            iMessagePtr.Complete( KErrNone );
+            break;
+            }
+        case ETotalBlocked:
+            {
+            TPINInput PINInput = reinterpret_cast<const TPINInput&>( *aBuffer.Ptr() );
+            iPIN = PINInput.iPIN;
+            DoHandleMessageL( EErrorPukCodeBlocked, iPIN.iPINLabel, iPIN.iTokenLabel, 0, 0 );
+            iMessagePtr.Complete( KErrNone );
+            break;
+            }
+        case ESignText:
+        case EUserAuthenticationText:
+        case EUserAuthentication:
+            {
+            iSignInput = reinterpret_cast<const TSignInput&>( *aBuffer.Ptr() );
+            DoHandleSignTextL( aBuffer );
+            break;
+            }
+        case ECreateCSR:
+            {
+            DoHandleCSRL( aBuffer.Mid( sizeof(TInt) ) );
+            break;
+            }
+        case EDeleteCert:
+        case ECertDetails:
+            {
+            DoHandleCertDetailsL( aBuffer.Mid( sizeof(TInt) ) );
+            break;
+            }
+        case ESaveCert:
+            {
+            DoHandleSaveCertL( aBuffer );
+            break;
+            }
+        case EUnblockPINInClear:
+            {
+            User::Leave( KErrNotSupported );
+            break;
+            }
+        case EPinCodeBlockedInfo:
+            {
+            TPtrC8 pinLabelPtr = aBuffer.Mid( sizeof(TInt) + 1 );
+            TPINLabel pinLabel;
+            pinLabel.Copy( pinLabelPtr );
+            HBufC* text = iNotifier->LoadResourceStringLC( iOperation, pinLabel );
+
+            CCTSignTextDialog::RunDlgLD( R_WIM_UNBLOCK_INFO_DIALOG, *text, iStatus, iRetValue );
+            CleanupStack::PopAndDestroy( text );
+            iStatus = KRequestPending;
+            SetActive();
+            break;
+            }
+        case EServerAuthenticationFailure:
+            {
+            DoHandleServerAuthFailL( aBuffer );
+            break;
+            }
+        case MPKIDialog::ESignatureRequested:
+            {
+            DoHandleMessageL( EInfoSignTextRequested, KNullDesC, KNullDesC, 1, KMaxTInt );
+            iRetValue = ETrue;
+            HandleResponseAndCompleteL();
+            break;
+            }
+        case MPKIDialog::ESignatureDone:
+            {
+            DoHandleMessageL( EInfoSignTextDone, KNullDesC, KNullDesC, 1, KMaxTInt );
+            iRetValue = ETrue;
+            HandleResponseAndCompleteL();
+            break;
+            }
+        case MPKIDialog::ESigningCancelled:
+            {
+            DoHandleMessageL( EInfoSignTextCancelled, KNullDesC, KNullDesC, 1, KMaxTInt );
+            iRetValue = ETrue;
+            HandleResponseAndCompleteL();
+            break;
+            }
+        case MPKIDialog::ENoMatchCert:
+            {
+            DoHandleMessageL( ENoMatchingPersonalCert, KNullDesC, KNullDesC, 1, KMaxTInt );
+            break;
+            }
+        case MPKIDialog::ENoSecurityModule:
+            {
+            DoHandleMessageL( EErrorWimNotAvailable, KNullDesC, KNullDesC, 1, KMaxTInt );
+            iRetValue = ETrue;
+            HandleResponseAndCompleteL();
+            break;
+            }
+        case MPKIDialog::EInternalError:
+            {
+            DoHandleMessageL( EErrorInternal, KNullDesC, KNullDesC, 1, KMaxTInt );
+            iRetValue = ETrue;
+            HandleResponseAndCompleteL();
+            break;
+            }
+        case ESaveReceipt:
+            {
+            SaveReceiptL( aBuffer.Mid( sizeof(TInt) ) );
+            break;
+            }
+        default:
+            User::Panic( _L("CTestSecDlgNotifier"), 0 );
+            break;
+        }
+    
+    // Note that CCTSecurityDialogsAO::StartLD() must complete the given message and
+    // delete itself when ready. However, there may be several steps before it can be
+    // deleted. CCTSecurityDialogsAO::HandleResponseAndCompleteL() completes the given
+    // message and deletes CCTSecurityDialogsAO object. Hence, every operation handling
+    // function called above must call HandleResponseAndCompleteL() when it is ready.
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::DoHandleServerAuthFailL(const TDesC8& aBuffer)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DoHandleServerAuthFailL( const TDesC8& aBuffer )
+    {
+    CServerAuthenticationFailureInput* srvAuthFail =
+        CServerAuthenticationFailureInput::NewLC( aBuffer );
+    TPtrC8 cert;
+    TPtrC8 serverName;
+
+    srvAuthFail->GetEncodedCert( cert );
+    srvAuthFail->GetServerName( serverName );
+    iAuthFailReason = srvAuthFail->FailureReason();
+    CleanupStack::PopAndDestroy( srvAuthFail );
+
+    iServerName = HBufC::NewL( serverName.Length() );
+    iServerName->Des().Copy( serverName );
+
+    HBufC* cn = NULL;
+    iCertLabel = NULL;
+    // Site will be checked later. For now it is not trusted
+    iTrustedSite = EFalse;
+
+
+    CX509Certificate* serverCert = CX509Certificate::NewLC( cert );
+    // Retrieve subject name
+    const CX500DistinguishedName& dName = serverCert->SubjectName();
+    // Retrieve CN
+    cn = dName.ExtractFieldL( KX520CommonName );
+    if ( cn != NULL )
+        {
+        // commonName exist in the certificate.
+        // Check the length of CN. RFC 3280 states
+        // that max length of CN is 64.
+        if ( cn->Length() <= KMaxCNLength )
+            {
+            iCertLabel = HBufC::NewL( cn->Length() );
+            iCertLabel->Des().Append( cn->Des() );
+            }
+        }
+
+    if ( iCertLabel == NULL )
+        {
+        // No or invalid commonName. Use domain name as label
+        iCertLabel = HBufC::NewL( iServerName->Length() );
+        iCertLabel->Des().Append( iServerName->Des() );
+        }
+
+    CleanupStack::PopAndDestroy( serverCert );
+
+    iCertBuf = HBufC8::NewL( cert.Length() );
+    *iCertBuf = cert;
+
+    InitCertStoreL();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::DoHandleCertDetailsL(const TDesC8& aBuffer)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DoHandleCertDetailsL( const TDesC8& aBuffer )
+    {
+    TCTTokenObjectHandle tokenHandle =
+        reinterpret_cast<const TCTTokenObjectHandle&>( *aBuffer.Ptr() );
+
+    iTokenHandle.iTokenHandle.iTokenTypeUid = tokenHandle.iTokenHandle.iTokenTypeUid;
+    iTokenHandle.iTokenHandle.iTokenId = tokenHandle.iTokenHandle.iTokenId;
+    iTokenHandle.iObjectId = tokenHandle.iObjectId;
+
+    InitCertStoreL();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::DoHandleSaveCertL(const TDesC8& aBuffer)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DoHandleSaveCertL( const TDesC8& aBuffer )
+    {
+    TSaveCertInput saveCertInput =
+        reinterpret_cast<const TSaveCertInput&>( *aBuffer.Ptr() );
+
+    TInt start = sizeof( TSaveCertInput );
+    delete iCertBuf;
+    iCertBuf = NULL;
+    iCertBuf = HBufC8::NewL( saveCertInput.iDataSize );
+    const TUint8* certPtr = reinterpret_cast<const TUint8*>( aBuffer.Mid(start).Ptr() );
+    iCertBuf->Des().Append( certPtr, saveCertInput.iDataSize );
+    ShowCertDialogL();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::DoHandleCSRL(const TDesC8& aBuffer)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DoHandleCSRL( const TDesC8& aBuffer )
+    {
+    WIMSECURITYDIALOGS_ENTERFN("CCTSecurityDialogsAO::DoHandleCSRL");
+    TInt length = reinterpret_cast<const TInt&>( *aBuffer.Ptr() );
+    TInt start = sizeof( TInt ) + 1;
+    iText = HBufC::NewL( length );
+    iText->Des().Copy( aBuffer.Mid( start, length ) );
+
+    start = start + length;
+
+    const TUint8* bufferPtr = aBuffer.Ptr();
+    bufferPtr += start;
+
+    TCTTokenObjectHandle tokenHandle;
+    TCTTokenObjectHandle* tokenHandlePtr = &tokenHandle;
+    TUint8* copyPtr = reinterpret_cast< TUint8* >( tokenHandlePtr );
+    for( TInt i = 0; i < 12; i++ )
+        {
+        copyPtr[ i ] = bufferPtr[ i ];
+        }
+
+    iTokenHandle.iTokenHandle.iTokenTypeUid = tokenHandle.iTokenHandle.iTokenTypeUid;
+    iTokenHandle.iTokenHandle.iTokenId = tokenHandle.iTokenHandle.iTokenId;
+    iTokenHandle.iObjectId = tokenHandle.iObjectId;
+
+    InitKeyStoreL();
+    iNextStep = EGetKeyInfoByHandle;
+    WIMSECURITYDIALOGS_LEAVEFN("CCTSecurityDialogsAO::DoHandleCSRL");
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::DoHandleSignTextL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DoHandleSignTextL( const TDesC8& aBuffer )
+    {
+    TInt arraySize = sizeof( TCTTokenObjectHandle ) * iSignInput.iCertHandleArrayTotal;
+    TInt start = sizeof( TSignInput );
+    TInt end = start + arraySize;
+    for (; start < end; start+=sizeof( TCTTokenObjectHandle ))
+        {
+        TCTTokenObjectHandle handle =
+            reinterpret_cast<const TCTTokenObjectHandle&>(*aBuffer.Mid(start).Ptr());
+        User::LeaveIfError( iCertHandleList.Append( handle ) );
+        }
+    start = end;
+    HBufC* textToSign = NULL;
+    if ( iOperation != EUserAuthentication )
+        {
+        textToSign = HBufC::NewLC( iSignInput.iVariableDataSize / 2 ); // 8 bit -> 16 bit descriptor
+        //textToSign->Des().Copy(aBuffer.Mid(start));
+        const TUint16* textToSignPtr = reinterpret_cast<const TUint16*>( aBuffer.Mid(start).Ptr() );
+        textToSign->Des().Append( textToSignPtr, (iSignInput.iVariableDataSize / 2) );
+        }
+
+    if ( iCertHandleList.Count() > 0 )
+        {
+        iNextStep = EOperationSignTextShown;
+        }
+    else
+        {
+        iNextStep = EOperationCompleted;
+        iCertHandleList.Close();
+        }
+    switch( iOperation )
+        {
+        case EUserAuthenticationText:
+            {
+            CCTSignTextDialog::RunDlgLD( R_WIM_USERAUTHTEXT_DIALOG,
+                *textToSign, iStatus, iRetValue );
+            break;
+            }
+        case EUserAuthentication:
+            {
+            DoHandleMessageL( EUserAuthentication, KNullDesC, KNullDesC, 1, KMaxTInt );
+            break;
+            }
+        case ESignText:
+            {
+            CCTSignTextDialog::RunDlgLD( R_WIM_SIGNTEXT_DIALOG,*textToSign, iStatus, iRetValue );
+            break;
+            }
+        default:
+            {
+            __ASSERT_DEBUG( EFalse,
+                _L( "CCTSecurityDialogsAO::DoHandleSignTextL: Invalid operation" ) );
+            break;
+            }
+        }
+    iStatus = KRequestPending;
+    SetActive();
+    if ( iOperation == EUserAuthentication )
+        {
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        }
+    else
+        {
+        CleanupStack::PopAndDestroy( textToSign );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::DoHandleUnblockPinOperationL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DoHandleUnblockPinOperationL()
+    {
+    if ( iRetry ) // Is this new try?
+      {
+        // Previous attempt was failed
+        DoHandleMessageL( EErrorPukCodeIncorrect, KNullDesC, KNullDesC, 0, 0 );
+      }
+    // Ask the PUK code
+    // The label is iPIN instead of iUnblockPIN, since we need to show to 
+    // the user which PIN to unblock
+    DoHandleMessageL( EEnterPukNR, iPIN.iPINLabel,
+        iPIN.iTokenLabel, iUnblockPIN.iMinLength, iUnblockPIN.iMaxLength );
+    iNextStep = EEnterNewPIN;
+    iMultiLineDlgType = EEnterNewPinNR;
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::DoHandlePinOperationL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DoHandlePinOperationL()
+    {
+    if ( iRetry ) // Is this new try?
+      {
+        // Previous attempt was failed
+        DoHandleMessageL( EErrorPinCodeIncorrect, KNullDesC, KNullDesC, 0, 0 );
+      }
+    // Ask the PIN code or PUK code
+    if ( iPIN.iPINLabel == KKeyStoreEnterPwLabel )
+        {
+        HBufC* header = StringLoader::LoadLC(
+            R_QTN_CM_HEADING_PHONE_KEYSTORE, CEikonEnv::Static() );
+        iPIN.iMinLength = KMaxKeystorePwLength;
+        DoHandleMessageL( EEnterKeyStorePw, KNullDesC, *header,
+            iPIN.iMinLength, iPIN.iMaxLength );
+        iMultiLineDlgType = EEnterNewKeyStorePw;
+        CleanupStack::PopAndDestroy( header );
+        }
+    else if ( iPIN.iPINLabel == KKeyStoreImportKeyLabel )
+        {
+        iPIN.iMinLength = KMaxKeystorePwLength;
+        DoHandleMessageL( EImportKeyPw, KNullDesC, KNullDesC,
+            KMinImportKeyPwLen, iPIN.iMaxLength );
+        iMultiLineDlgType = EEnterNewKeyStorePw;
+        }
+    else if ( iPIN.iPINLabel == KKeyStoreExportKeyLabel )
+        {
+        DoHandleMultilinePinQueryL( EExportKeyPw );
+        iNextStep = EVerifyPINs;
+        }
+    else if ( iPIN.iPINLabel == KKeyStoreCreatePwLabel )
+        {
+        iPIN.iMinLength = KMaxKeystorePwLength;
+        DoHandleMessageL( EInfoPwCreating, KNullDesC, KNullDesC, 0, 0 );
+        DoHandleMultilinePinQueryL( EEnterNewKeyStorePw );
+        iNextStep = EVerifyPINs;
+        }
+    else if ( iPIN.iTokenLabel == KPKCS12TokenLabel )
+        {
+        DoHandleMessageL( EEnterPw, iPIN.iPINLabel, KNullDesC,
+          iPIN.iMinLength, iPIN.iMaxLength );
+        }
+    else
+        {
+        DoHandleMessageL( EEnterPinNR, iPIN.iPINLabel, iPIN.iTokenLabel,
+          iPIN.iMinLength, iPIN.iMaxLength );
+        iMultiLineDlgType = EEnterNewPinNR;
+        }
+    if ( EChangePIN == iOperation )
+        {
+        iNextStep = EEnterNewPIN;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::DoHandleMultilinePinQueryL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DoHandleMultilinePinQueryL( const TInt& aDlgType )
+    {
+    iMultiLineDlgType = aDlgType;
+    HBufC* dlgText1 = NULL;
+    HBufC* dlgText2 = NULL;
+    CCTPinPinQueryDialog* dlg = NULL;
+    TDialogType dlgType = ( TDialogType )aDlgType;
+    if ( EEnterNewKeyStorePw == dlgType )
+        {
+        dlgText1 = iNotifier->LoadResourceStringLC( dlgType, KNullDesC );
+        dlgText2 = iNotifier->LoadResourceStringLC( EVerifyKeyStorePw, KNullDesC );
+        dlg = CCTPinPinQueryDialog::NewL( *dlgText1, *dlgText2, iPINValue2,
+            iPINValueVerify, iPIN.iMinLength, iPIN.iMaxLength, iRetValue );
+        dlg->RunDlgLD( iStatus, R_WIM_PWPW_QUERY_DIALOG );
+        CleanupStack::PopAndDestroy( 2, dlgText1 ); // dlgText1, dlgText2
+        }
+    else if ( EExportKeyPw == dlgType )
+        {
+        dlgText1 = iNotifier->LoadResourceStringLC( dlgType, KNullDesC );
+        dlgText2 = iNotifier->LoadResourceStringLC( EVerifyKeyStorePw, KNullDesC );
+        dlg = CCTPinPinQueryDialog::NewL( *dlgText1, *dlgText2, iPINValue2,
+            iPINValueVerify, iPIN.iMinLength, iPIN.iMaxLength, iRetValue );
+        dlg->RunDlgLD( iStatus, R_WIM_PWPW_QUERY_DIALOG );
+        CleanupStack::PopAndDestroy( 2, dlgText1 ); // dlgText1, dlgText2
+        }
+    else // Enter new PIN
+        {
+        dlgText1 = iNotifier->LoadResourceStringLC( dlgType, iPIN.iPINLabel );
+        dlgText2 = iNotifier->LoadResourceStringLC( EVerifyPinNR, iPIN.iPINLabel );
+        dlg = CCTPinPinQueryDialog::NewL( *dlgText1, *dlgText2, iPINValue2,
+            iPINValueVerify, iPIN.iMinLength, iPIN.iMaxLength, iRetValue );
+        dlg->RunDlgLD( iStatus, R_WIM_PINPIN_QUERY_DIALOG );
+        CleanupStack::PopAndDestroy( 2, dlgText1 ); // dlgText1, dlgText2
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::DoHandleMessageL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DoHandleMessageL(
+    const TInt& aDlgType,
+    const TDesC& aDynamicText,
+    const TDesC& aPinQueryHeading,
+    const TInt aMinLength,
+    const TInt aMaxLength )
+    {
+  TDialogType dlgType = ( TDialogType )aDlgType;
+
+  HBufC* dlgText = iNotifier->LoadResourceStringLC( dlgType, aDynamicText, aPinQueryHeading );
+
+  TDialogTypeItem item = iNotifier->GetDialogTypeItem( dlgType );
+
+  CAknResourceNoteDialog* dlg = NULL;
+
+  TInt resource = 0;
+
+  switch ( item.iNoteType )
+        {
+        case EInfoNote:
+            {
+            dlg = new ( ELeave ) CAknInformationNote( ETrue );
+            break;
+            }
+
+        case EErrorNote:
+            {
+            dlg = new ( ELeave ) CAknErrorNote( ETrue );
+            break;
+            }
+        case EConfirmationNote:
+            {
+            dlg = new ( ELeave ) CAknConfirmationNote( ETrue );
+            break;
+            }
+        case EInfoDialog:
+            {
+            CCTQueryDialog::RunDlgLD( iStatus,
+                                        iRetValue,
+                                        *dlgText, item.iSoftKeyResource,
+                                        ECTInfoDialog );
+            iStatus = KRequestPending;
+            SetActive();
+            break;
+            }
+        case EEnterPwPwDialog:
+            {
+            CCTPinPinQueryDialog* dialog =
+                CCTPinPinQueryDialog::NewL( *dlgText, *dlgText,
+                iPINValue2, iPINValueVerify, aMinLength, aMaxLength, iRetValue );
+            dialog->RunDlgLD( iStatus, R_WIM_PWPW_QUERY_DIALOG );
+            break;
+            }
+        case EEnterPinPinCodeDialog:
+            {
+            CCTPinPinQueryDialog* dialog =
+                CCTPinPinQueryDialog::NewL( *dlgText, *dlgText,
+                iPINValue2, iPINValueVerify, aMinLength, aMaxLength, iRetValue );
+            dialog->RunDlgLD( iStatus, R_WIM_PINPIN_QUERY_DIALOG );
+            break;
+            }
+        case EEnterPwDialog:
+        case EEnterPinNRCodeDialog:
+        case EVerifyPinNRCodeDialog:
+            {
+            if ( item.iNoteType == EEnterPwDialog )
+                {
+                resource = R_WIM_PASSWORD_QUERY_DIALOG;
+                }
+            else
+                {
+                resource = R_WIM_PIN_QUERY_DIALOG;
+                }
+
+            TPINValue* pinValue = NULL;
+            switch ( aDlgType )
+                {
+                case EEnterPinNR: // fall thru
+                case EEnterPukNR:
+                case EEnterKeyStorePw:
+                case EImportKeyPw:
+                    {
+                    pinValue = &iPINValue1;
+                    break;
+                    }
+                case EEnterNewPinNR:
+                case EEnterNewKeyStorePw:
+                case EExportKeyPw:
+                    {
+                    pinValue = &iPINValue2;
+                    break;
+                    }
+                case EVerifyPinNR:
+                    {
+                    pinValue = &iPINValueVerify;
+                    break;
+                    }
+                default:
+                    {
+                    User::Panic(_L("CSecDlgNotifier"), 0);
+                    }
+                }
+               iPinQueryDialogDeleted = EFalse;
+                CCTPinQueryDialog::RunDlgLD( iStatus,
+                                        *dlgText,
+                                        *pinValue,
+                                        aMinLength,
+                                        aMaxLength,
+                                        iRetValue,
+                                        resource, 
+                                        iPinQueryDialog, 
+                                        iPinQueryDialogDeleted );
+                break;
+            }
+    default:
+            {
+            break;
+            }
+
+      }
+
+  if ( dlg )
+      {
+      dlg->ExecuteLD( *dlgText );
+      dlg = NULL;
+      }
+
+    CleanupStack::PopAndDestroy( dlgText ); // dlgText
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::RunError(TInt aError)
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+TInt CCTSecurityDialogsAO::RunError( TInt aError )
+    {
+    iMessagePtr.Complete( aError );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::InitCertStoreL()
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::InitCertStoreL()
+    {
+    switch(iOperation)
+        {
+        case ESignText:
+        case EUserAuthenticationText:
+        case EUserAuthentication:
+            {
+            iNextStep = EOperationRetrieveCertInfos;
+            break;
+            }
+        case EDeleteCert:
+        case ECertDetails:
+            {
+            iNextStep = EGetCertInfo;
+            break;
+            }
+        case EServerAuthenticationFailure:
+            {
+            iNextStep = EProcessTrustedSite;;
+            break;
+            }
+        default:
+            {
+            User::Panic( _L("CTestSecDlgNotifier"), 0 );
+            }
+        }
+
+    if ( iCertStore == NULL )
+        {
+        TInt err = KErrNone;
+        err = iFs.Connect();
+
+        if( err != KErrNone && err != KErrAlreadyExists )
+            {
+            User::Leave( KErrGeneral );
+            }
+
+        iCertStore = CUnifiedCertStore::NewL( iFs, ETrue );
+        iCertArray = new (ELeave) CDesCArrayFlat( KCertArrayGranularity );
+        iCertStore->Initialize( iStatus );
+        iStatus = KRequestPending;
+        SetActive();
+        }
+    else
+        {
+        iStatus = KRequestPending;
+        SetActive();
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::InitKeyStoreL()
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::InitKeyStoreL()
+    {
+    if ( NULL == iKeyStore )
+        {
+        TInt err = KErrNone;
+        err  = iFs.Connect();
+        if( err != KErrNone && err != KErrAlreadyExists )
+            {
+            User::Leave( KErrGeneral );
+            }
+
+        iKeyStore = CUnifiedKeyStore::NewL( iFs );
+        iKeyStore->Initialize( iStatus );
+        iStatus = KRequestPending;
+        SetActive();
+        }
+    else
+        {
+        iStatus = KRequestPending;
+        SetActive();
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        }
+    }
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::GetKeyInfosL()
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::GetKeyInfosL()
+    {
+    if ( NULL == iKeyStore )
+        {
+        iStatus = KRequestPending;
+        SetActive();
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        }
+    else
+        {
+        iStatus = KRequestPending;
+        iKeyFilter.iKeyId = iCertInfo->SubjectKeyId();
+        iKeyStore->List( iKeyInfos, iKeyFilter, iStatus );
+        SetActive();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::GetKeyInfoByHandleL()
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::GetKeyInfoByHandleL()
+    {
+    if ( NULL == iKeyStore )
+        {
+        User::Panic( _L("CCTSecurityDialogsAO::GetKeyInfoByHandleL()"), 0 );
+        }
+    else
+        {
+        iStatus = KRequestPending;
+        iKeyStore->GetKeyInfo( iTokenHandle, iKeyInfo, iStatus );
+        SetActive();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::RunL()
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::RunL()
+    {
+    WIMSECURITYDIALOGS_WRITE_FORMAT( "CCTSecurityDialogsAO::RunL, iStatus %d", iStatus.Int() );
+    WIMSECURITYDIALOGS_WRITE_FORMAT( "  iNextStep %d", iNextStep );
+
+    if ( iStatus != KErrNone )
+        {
+        User::Leave( iStatus.Int() );
+        } // if
+
+    switch ( iNextStep )
+      {
+      case EOperationCompleted:
+        {
+        WIMSECURITYDIALOGS_WRITE( "EOperationCompleted" );
+        HandleResponseAndCompleteL();
+        break;
+        }
+      case ECheckServerCerts:
+        {
+        WIMSECURITYDIALOGS_WRITE( "ECheckServerCerts" );
+
+        TBool foundCert( EFalse );
+
+        if ( iServerCerts.Count() )
+            {
+            // Found certificates in the trusted site certificate storage.
+            // Compare them with the one received from TlsProvider
+            iCertPtr.Set( iCertBuf->Des() );
+            CX509Certificate* serverCert = CX509Certificate::NewLC( iCertPtr );
+
+            for (TInt i=0; i<iServerCerts.Count(); i++ )
+                {
+                TPtr8 certPtr( iServerCerts[i]->Des() );
+
+                CX509Certificate* cert = CX509Certificate::NewLC( certPtr );
+
+                // Compare fingerprints
+                if ( cert->Fingerprint() == serverCert->Fingerprint() )
+                    {
+                    // Fingerprints match
+                    foundCert = ETrue;
+                    }
+                CleanupStack::PopAndDestroy( cert );
+                }
+             CleanupStack::PopAndDestroy( serverCert );
+             if ( foundCert )
+                {
+                // Found matching certificate. Complete the operation
+                iRetValue = EServerCertAcceptedPermanently;
+                iNextStep = EOperationCompleted;
+                HandleResponseAndCompleteL();
+                }
+            }
+
+            if ( !foundCert )
+                {
+                // Couldn't find matching certificate. Prompt user
+                ShowNoTrustDialogL();
+                }
+
+        break;
+        }
+      case EProcessTrustedSite:
+        {
+        WIMSECURITYDIALOGS_WRITE( "EProcessTrustedSite" );
+            TInt count = iCertStore->WritableCertStoreCount();
+            for ( TInt i = 0; i < count; i++ )
+                {
+                MCTWritableCertStore *certstore = &iCertStore->WritableCertStore( i );
+                MCTToken& token = certstore->Token();
+                TUid tokenuid = token.Handle().iTokenTypeUid;
+                if ( tokenuid == KTrustedServerTokenUid )
+                    {
+                    iTrustedSiteCertStore = certstore;
+                    }
+                }
+
+                CTrustSitesStore* trustedSitesStore = CTrustSitesStore::NewL();
+                CleanupStack::PushL( trustedSitesStore );
+
+                // Find out whether or not site associated with certificate is trusted
+                iTrustedSite = trustedSitesStore->IsTrustedSiteL( *iCertBuf, *iServerName );
+
+                if ( iTrustedSite )
+                    {
+                    TBool allowOutOfDate = trustedSitesStore->IsOutOfDateAllowedL(*iCertBuf, *iServerName );	
+                
+                    if (!allowOutOfDate)
+                        {
+                        CX509Certificate* cert = CX509Certificate::NewLC( iCertBuf->Des() );
+
+                        const CValidityPeriod& validityPeriod = cert->ValidityPeriod();
+                        const TTime& startValue = validityPeriod.Start();
+                        const TTime& finishValue = validityPeriod.Finish();
+                        TTime current;
+                        current.UniversalTime();
+
+                        // First check certificate validity period
+                        if ( ( startValue > current ) || ( finishValue < current ) )
+                            {
+                            iTrustedSite = EFalse;	
+                            }
+                    
+                        CleanupStack::PopAndDestroy(); //cert
+                        }
+                    }
+                CleanupStack::PopAndDestroy( trustedSitesStore ); // trustedSitesStore
+
+                if ( iTrustedSite )
+                    {
+                    // Site is trusted. Next step is to check that server
+                    // certificate is in the trusted site certificate storage
+                    iNextStep = ERetrieveServerCerts;
+                    iStatus = KRequestPending;
+                    SetActive();
+                    TRequestStatus* status = &iStatus;
+                    User::RequestComplete( status, KErrNone );
+                    }
+                 else
+                    {
+                    // Site is not trusted. Prompt user
+                    ShowNoTrustDialogL();
+                    }
+
+        break;
+        }
+
+      case ERetrieveServerCerts:
+        {
+        WIMSECURITYDIALOGS_WRITE( "ERetrieveServerCerts" );
+        if ( iHandleIndex == -1 )
+            {
+                iFilter = CCertAttributeFilter::NewL();
+                iFilter->SetOwnerType( EPeerCertificate );
+                if ( iTrustedSiteCertStore )
+                    {
+                    // Thet the list of all certificates from Trusted site certificate
+                    // storage
+                    iTrustedSiteCertStore->List( iCertInfos, *iFilter, iStatus );
+                    iNextStep = ERetrieveServerCerts;
+                    iStatus = KRequestPending;
+                    SetActive();
+                    ++iHandleIndex;
+                    }
+                else
+                    {
+                    // Trusted Site certificate storage doesn't exist
+                    // or something went wrong.
+                    User::Leave( KErrGeneral );
+                    }
+            }
+        else if ( iHandleIndex < iCertInfos.Count() )
+            {
+            iStatus = KRequestPending;
+            iServerCert = HBufC8::NewL( KMaxCertificateLength );
+            iCertPtr.Set( iServerCert->Des() );
+
+            iTrustedSiteCertStore->Retrieve( *(iCertInfos[iHandleIndex]), iCertPtr, iStatus );
+
+            iServerCerts.Append( iServerCert );
+
+            iNextStep = ERetrieveServerCerts;
+            SetActive();
+            ++iHandleIndex;
+            }
+        else
+            {
+            iNextStep = ECheckServerCerts;
+            iStatus = KRequestPending;
+            SetActive();
+            TRequestStatus* status = &iStatus;
+            User::RequestComplete( status, KErrNone );
+            }
+        break;
+        }
+      case EAddTrustedSite:
+          {
+          if ( iStatus.Int() == KErrNone )
+              {
+              //Added server certificate succesfully
+              CTrustSitesStore* trustedSitesStore = CTrustSitesStore::NewL();
+              CleanupStack::PushL( trustedSitesStore );
+
+              TInt status = trustedSitesStore->AddL( *iCertBuf, *iServerName );
+
+              CleanupStack::PopAndDestroy( trustedSitesStore );
+              if ( status  == KErrNone )
+                  {
+                  iRetValue = EServerCertAcceptedPermanently;
+                  }
+              else
+                  {
+                  iRetValue = EServerCertNotAccepted;
+                  }
+
+              iNextStep = EOperationCompleted;
+              HandleResponseAndCompleteL();
+              }
+          else
+              {
+              //Adding server certificate failed
+              iNextStep = EOperationCompleted;
+              iRetValue = EServerCertNotAccepted;
+              HandleResponseAndCompleteL();
+              }
+              break;
+          }
+
+      case ESaveServerCert:
+          {
+          WIMSECURITYDIALOGS_WRITE( "ESaveServerCert" );
+          DoHandleSaveServerCertL();
+          break;
+          }
+      case EServerCertCheckUserResp:
+          {
+          WIMSECURITYDIALOGS_WRITE( "EServerCertCheckUserResp" );
+          if ( iRetValue == EServerCertAcceptedPermanently )
+              {
+              // User accepted to select certificate permanently.
+              // First add server certificate
+              iNextStep = ESaveServerCert;
+              iStatus = KRequestPending;
+              SetActive();
+              TRequestStatus* status = &iStatus;
+              User::RequestComplete( status, KErrNone );
+              }
+          else
+              {
+              // User declined or temporarily accepted server certificate
+              HandleResponseAndCompleteL();
+              }
+          break;
+          }
+      case EOperationSignTextShown:
+          {
+          if ( iRetValue || iOperation == EUserAuthentication )
+              {
+              iNextStep = EOperationInitCertStore;
+              }
+          else
+              {
+              iNextStep = EOperationCompleted;
+              }
+          iStatus = KRequestPending;
+          SetActive();
+          TRequestStatus* status = &iStatus;
+          User::RequestComplete( status, KErrNone );
+          break;
+          }
+      case EOperationInitCertStore:
+          {
+          TInt err = KErrNone;
+          err = iFs.Connect();
+          if( err != KErrNone && err != KErrAlreadyExists )
+             {
+             User::Leave( KErrGeneral );
+             }
+
+          iCertStore = CUnifiedCertStore::NewL( iFs, EFalse );
+          iCertArray = new (ELeave) CDesCArrayFlat( KCertArrayGranularity );
+          iCertStore->Initialize( iStatus );
+          iStatus = KRequestPending;
+          SetActive();
+          iNextStep = EOperationRetrieveCertInfos;
+          break;
+          }
+      case EOperationRetrieveCertInfos:
+          {
+          if ( iCertInfo )
+              {
+              iCertArray->AppendL( iCertInfo->Label() );
+              iCertInfo = NULL;
+              }
+          if ( iHandleIndex == -1 )
+              {
+              iFilter = CCertAttributeFilter::NewL();
+              iCertStore->List( iCertInfos, *iFilter, iStatus );
+              iNextStep = EOperationRetrieveCertInfos;
+              iStatus = KRequestPending;
+              SetActive();
+              ++iHandleIndex;
+              }
+          else if ( iHandleIndex < iCertHandleList.Count() )
+              {
+              iStatus = KRequestPending;
+              iCertStore->GetCert( iCertInfo, iCertHandleList[iHandleIndex], iStatus );
+              ++iHandleIndex;
+              iNextStep = EOperationRetrieveCertInfos;
+              SetActive();
+              }
+          else
+              {
+              iHandleIndex = -1;
+              iNextStep = EOperationSelectCert;
+              iStatus = KRequestPending;
+              SetActive();
+              TRequestStatus* status = &iStatus;
+              User::RequestComplete( status, KErrNone );
+              }
+          break;
+          }
+      case EOperationSelectCert:
+          {
+          DoHandleSelectCertificateL();
+          break;
+          }
+      case EGetCertInfo:
+          {
+          iStatus = KRequestPending;
+          iCertInfo = NULL;
+          iCertStore->GetCert( iCertInfo, iTokenHandle, iStatus );
+          iNextStep = EGetCertificate;
+          SetActive();
+          break;
+          }
+      case EGetCertificate:
+          {
+          iStatus = KRequestPending;
+          if ( iCertInfo )
+              {
+              iCertBuf = HBufC8::NewL( KMaxCertificateLength );
+              iCertPtr.Set( iCertBuf->Des() );
+              iCertStore->Retrieve( *iCertInfo, iCertPtr, iStatus );
+              SetActive();
+              }
+          else
+              {
+              SetActive();
+              TRequestStatus* status = &iStatus;
+              User::RequestComplete( status, KErrNone );
+              }
+          iNextStep = EInitKeyStore;
+          break;
+          }
+      case EInitKeyStore:
+          {
+          InitKeyStoreL();
+          iNextStep = EGetKeyInfos;
+          break;
+          }
+      case EGetKeyInfos:
+          {
+          GetKeyInfosL();
+          iNextStep = EShowCertDialog;
+          break;
+          }
+      case EGetKeyInfoByHandle:
+          {
+          GetKeyInfoByHandleL();
+          iNextStep = EShowCSRDialog;
+          break;
+          }
+      case EShowCSRDialog:
+          {
+          ShowCSRDialogL();
+          iNextStep = EOperationCompleted;
+          break;
+          }
+      case EShowCertDialog:
+          {
+          ShowCertDialogL();
+          iNextStep = EOperationCompleted;
+          break;
+          }
+      /////////////
+      // PIN steps
+      /////////////
+      case EEnterNewPIN:
+          {
+          if ( iRetValue)
+              {
+              DoHandleMultilinePinQueryL( iMultiLineDlgType );
+              iNextStep = EVerifyPINs;
+              iStatus = KRequestPending;
+              SetActive();
+              }
+          else
+              {
+              iNextStep = EOperationCompleted;
+              iPINValue1 = KNullDesC;
+              iPINValue2 = KNullDesC;
+              HandleResponseAndCompleteL();
+              }
+          break;
+          }
+
+      case EVerifyNewPin:
+          {
+          if ( iRetValue )
+              {
+              DoHandleMessageL( EVerifyPinNR, iPIN.iPINLabel, iPIN.iTokenLabel,
+                    iPIN.iMinLength, iPIN.iMaxLength );
+              iNextStep = EVerifyPINs;
+              iStatus = KRequestPending;
+              SetActive();
+              }
+            //Dialog was cancelled by user
+          else
+              {
+              iNextStep = EOperationCompleted;
+              iPINValue1 = KNullDesC;
+              iPINValue2 = KNullDesC;
+              HandleResponseAndCompleteL();
+              }
+          break;
+          }
+      case EVerifyPINs:
+          {
+          VerifyPinsL();
+          break;
+          }
+      default:
+          {
+          User::Panic( _L("CTestSecDlgNotifier"), 0 );
+          }
+      }
+
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::VerifyPinsL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::VerifyPinsL()
+    {
+    if ( iRetValue )
+        {
+        if ( iPINValue2 == iPINValueVerify )
+            {
+            HandleResponseAndCompleteL();
+            }
+        else
+            {
+            DoHandleMessageL( EErrorCodesDoNotMatch, KNullDesC, KNullDesC, 0, 0 );
+            iNextStep = EVerifyPINs;
+            iPINValue2.Zero();
+            iPINValueVerify.Zero();
+            DoHandleMultilinePinQueryL( iMultiLineDlgType );
+            iStatus = KRequestPending;
+            SetActive();
+            }
+        }
+    else
+        {
+        iPINValue1 = KNullDesC;
+        iPINValue2 = KNullDesC;
+        iNextStep = EOperationCompleted;
+        HandleResponseAndCompleteL();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::DoHandleSelectCertificateL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DoHandleSelectCertificateL()
+    {
+    TBool foundDevCert = EFalse;
+    
+    // Check certificate list to find out if there is certificate from
+    // Device Certificate Store.
+    for ( TInt ii = 0; ii < iCertHandleList.Count(); ii++)
+        {
+        TCTTokenObjectHandle handle = iCertHandleList[ii];
+        if ( handle.iTokenHandle.iTokenTypeUid == KDeviceCertStoreTokenUid )
+            {
+            // Found a certificate from Device Certificate Store. 
+            foundDevCert = ETrue;
+            iTokenHandle = handle;                        
+            iRetValue = ETrue;            
+            iNextStep = EOperationCompleted;
+            iStatus = KRequestPending;
+            SetActive();
+            TRequestStatus* status = &iStatus;
+            User::RequestComplete( status, KErrNone );            
+            break;
+            }
+        
+        }
+    
+    if ( !foundDevCert )
+        { 
+        // No certificate from Device Certificate Store. Prompt user
+        // for certificate selection
+        CCTSelectCertificateDialog::RunDlgLD(
+            iCertArray, iCertHandleList, iTokenHandle,
+            iStatus, iRetValue ); // Takes ownerhip of array
+        
+        iNextStep = EOperationCompleted;
+        iStatus = KRequestPending;
+        SetActive();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::ShowNoTrustDialogL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::ShowNoTrustDialogL()
+    {
+    CX509Certificate* cert = CX509Certificate::NewLC( iCertBuf->Des() );
+    TInt resourceid = R_WIM_NO_TRUST_QUERY_UNTRUSTED;
+    TBool showPermAccept = ETrue;
+    
+    if( iAuthFailReason == ESignatureInvalid || iAuthFailReason == ECertificateRevoked )
+        {
+        // Invalid or revoked certificate
+        CCTInvalidCertificateNote* note =
+            new( ELeave ) CCTInvalidCertificateNote( *this, iStatus );
+        note->ExecuteLD( R_WIM_INVALID_CERTIFICATE_INFORMATION_NOTE );
+        iRetValue = EServerCertNotAccepted;
+        }
+    else
+        {
+        if( iAuthFailReason == EValidatedOK || iAuthFailReason == EDateOutOfRange )
+            {
+            // Trusted certificate, but problems with CN or date
+            
+            // Retrieve subject name
+            const CX500DistinguishedName& dName = cert->SubjectName();
+    
+            // Retrieve common name
+            HBufC* cn = dName.ExtractFieldL( KX520CommonName );
+    
+            // Check common name first and then date
+            if( !cn )
+                {
+                // Couldn't retrieve CN from certificate
+                resourceid = R_WIM_NO_TRUST_QUERY_UNTRUSTED;
+                }
+            else if( iServerName->Des() != cn->Des() )
+                {
+                // Domain name doesn't match with CN
+                resourceid = R_WIM_NO_TRUST_QUERY_SITE;
+                }
+            else if( iAuthFailReason == EDateOutOfRange )
+                {
+                // Certificate is out of date
+                resourceid = R_WIM_NO_TRUST_QUERY_OOD;
+                showPermAccept = EFalse;
+                }
+            else
+                {
+                // Otherwise show general untrusted note
+                resourceid = R_WIM_NO_TRUST_QUERY_UNTRUSTED;
+                }
+            }
+        else
+            {
+            // Untrusted certificate
+            resourceid = R_WIM_NO_TRUST_QUERY_UNTRUSTED;
+            }
+
+        // No "Accept Permanently" option if certificate is out of date, or
+        // if domain name is not defined.
+        const CValidityPeriod& validityPeriod = cert->ValidityPeriod();
+        const TTime& startValue = validityPeriod.Start();
+        const TTime& finishValue = validityPeriod.Finish();
+        TTime current;
+        current.UniversalTime();
+    
+        if( (( startValue > current ) || ( finishValue < current )) ||
+                ( iServerName->Des().Length() == 0 ) )
+            {
+            showPermAccept = EFalse;
+            }
+
+        iQueryDialog = new( ELeave ) CCTNoTrustQuery( *this, iRetValue, iStatus, iServerName,
+                    showPermAccept, iQueryDialogDeleted );
+        iQueryDialog->ExecuteLD( resourceid );
+        }
+
+    CleanupStack::PopAndDestroy( cert );
+
+    iNextStep = EServerCertCheckUserResp;
+    iStatus = KRequestPending;
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::ShowCSRDialogL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::ShowCSRDialogL()
+    {
+    HBufC* message = HBufC::NewLC( KMaxLengthTextDetailsBody );
+    TPtr messagePtr = message->Des();
+
+    DetailsResourceL( messagePtr, R_QTN_SN_CERT_SIGN_EXPLANATION );
+
+    messagePtr.Append( KEnter );
+
+    DetailsFieldDynamicL( messagePtr, *iText,
+        R_TEXT_RESOURCE_DETAILS_VIEW_SUBJECT,
+        R_TEXT_RESOURCE_VIEW_NO_SUBJECT_DETAILS );
+
+    AddKeyUsageL( messagePtr, iKeyInfo );
+    AddKeyAlgorithmL( messagePtr, iKeyInfo );
+    AddKeySizeL( messagePtr, iKeyInfo );
+    AddKeyLocationL( messagePtr, iKeyInfo );
+
+    CCTSignTextDialog::RunDlgLD( R_WIM_CSR_DIALOG, *message, iStatus, iRetValue );
+    CleanupStack::PopAndDestroy( message );
+
+    iStatus = KRequestPending;
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::ShowCertDialogL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::ShowCertDialogL()
+    {
+    CCTKeyInfo* keyInfo = NULL;
+    if ( 0 < iKeyInfos.Count() )
+        {
+        keyInfo = iKeyInfos[0]; // There should be only one keyInfo.
+        }
+    else if ( iKeyInfo )
+        {
+        keyInfo = iKeyInfo;
+        }
+    else
+        {
+        }
+
+    HBufC* message = NULL;
+
+    if (iOperation == ESaveCert)
+        {
+        message = MessageQueryCertDetailsL( *iCertBuf, NULL, iSaveCertInput.iCertFormat, NULL );
+        }
+    else
+        {
+        message = MessageQueryCertDetailsL( *iCertBuf, iCertInfo, iCertInfo->CertificateFormat(), keyInfo );
+        }
+
+    CleanupStack::PushL( message );
+    TInt resource = 0;
+    switch( iOperation )
+        {
+        case ECertDetails:
+            {
+            resource = R_WIM_CERTDETAILS_DIALOG;
+            break;
+            }
+        case ESaveCert:
+            {
+            resource = R_WIM_SAVE_CERT_DIALOG;
+            break;
+            }
+        case EDeleteCert:
+            {
+            resource = R_WIM_DELETE_CERT_DIALOG;
+            break;
+            }
+        default:
+            {
+            User::Panic(_L("CTestSecDlgNotifier"), 0);
+            }
+        }
+    CCTSignTextDialog::RunDlgLD( resource, *message, iStatus, iRetValue );
+    CleanupStack::PopAndDestroy( message );
+
+    iStatus = KRequestPending;
+    SetActive();
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::MessageQueryViewDetailsL(TInt aIndex)
+// Creates the whole of certificate details view
+// Appends strings from both resources and CertManAPI to one
+// message body text and displays it.
+// ---------------------------------------------------------
+//
+HBufC* CCTSecurityDialogsAO::MessageQueryCertDetailsL(
+    const TDesC8& aCert,
+    const CCTCertInfo* aCertInfo,
+    TCertificateFormat aCertFormat,
+    const CCTKeyInfo* aKeyInfo)
+    {
+    // Create message buffer
+    HBufC* message = HBufC::NewLC( KMaxLengthTextDetailsBody );
+    TPtr messagePtr = message->Des();
+    // Label
+    if ( aCertInfo )
+        {
+        DetailsFieldDynamicL( messagePtr, aCertInfo->Label(),
+            R_TEXT_RESOURCE_DETAILS_VIEW_LABEL,
+            R_TEXT_RESOURCE_VIEW_NO_LABEL_DETAILS );
+        }
+
+    switch ( aCertFormat )
+        {
+        case EX509Certificate:
+            {
+            CX509Certificate* cert = CX509Certificate::NewLC( aCert );
+            // Let's append all the fields to the message
+            AddSiteL( messagePtr );
+            AddIssuerAndSubjectL( messagePtr, *cert );
+            if( aKeyInfo )
+                {
+                AddKeyUsageL( messagePtr, aKeyInfo );
+                }
+            else
+                {
+                AddKeyUsageL( messagePtr, *cert );
+                }
+
+            AddValidityPeriodL( messagePtr, *cert );
+            AddCertLocationL( messagePtr, aCertInfo );
+            AddCertFormatL( messagePtr, aCertFormat );
+            AddKeyLocationL( messagePtr, aKeyInfo );
+            AddCertAlgorithmsL( messagePtr, *cert );
+            AddCertSerialNumberL( messagePtr, *cert );
+            AddCertFingerprintsL( messagePtr, *cert );
+            CleanupStack::PopAndDestroy( cert );
+            break;
+            }
+        case EX509CertificateUrl:
+            {
+            AddKeyUsageL( messagePtr, aKeyInfo );
+
+            if( aCertInfo )
+                {
+                DetailsFieldDynamicL( messagePtr, aCertInfo->Label(),
+                        R_TEXT_RESOURCE_DETAILS_VIEW_LABEL,
+                        R_TEXT_RESOURCE_VIEW_NO_LABEL_DETAILS );
+                }
+            HBufC* url = HBufC::NewLC( aCert.Length() );
+            url->Des().Copy( aCert );
+            DetailsFieldDynamicL( messagePtr, *url,
+                    R_TEXT_RESOURCE_DETAILS_VIEW_CERTIFICATE_LOCATION,
+                    R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED );
+            CleanupStack::PopAndDestroy( url );
+            AddCertFormatL( messagePtr, aCertFormat );
+            AddKeyLocationL( messagePtr, aKeyInfo );
+            break;
+            }
+        default:
+            {
+            User::Leave( KErrNotSupported );
+            }
+        }
+
+    CleanupStack::Pop( message );
+    return message;
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddIssuerAndSubjectL(...)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::AddSiteL( TDes& aMessage )
+    {
+    if ( iServerName )
+        {
+        DetailsFieldDynamicL( aMessage, iServerName->Des(),
+            R_QTN_CM_SITE,
+            R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddIssuerAndSubjectL(...)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::AddIssuerAndSubjectL( TDes& aMessage, const CX509Certificate& aCert )
+    {
+    HBufC* issuer = NULL;
+    HBufC* owner = NULL;
+    X509CertNameParser::SubjectFullNameL( aCert, owner );
+    CleanupStack::PushL( owner );
+    X509CertNameParser::IssuerFullNameL( aCert, issuer );
+    CleanupStack::PushL( issuer );
+
+    DetailsFieldDynamicL( aMessage, issuer->Des(),
+        R_TEXT_RESOURCE_DETAILS_VIEW_ISSUER,
+        R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED );
+    CleanupStack::PopAndDestroy( issuer );   //issuer
+
+    // certificate subject
+    DetailsFieldDynamicL( aMessage, owner->Des(),
+        R_TEXT_RESOURCE_DETAILS_VIEW_SUBJECT,
+        R_TEXT_RESOURCE_VIEW_NO_SUBJECT_DETAILS );
+    CleanupStack::PopAndDestroy( owner );   //owner
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddKeySizeL(...)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::AddKeySizeL( TDes& aMessage, const CCTKeyInfo* aKeyInfo )
+    {
+    TUint keySize = aKeyInfo->Size();
+
+    TBuf<KMaxLengthTextDateString> sizeBuf;
+    if ( 0 < keySize )
+        {
+        sizeBuf.AppendNum( keySize, EDecimal );
+        }
+
+    DetailsFieldDynamicL( aMessage, sizeBuf,
+        R_QTN_SN_KEY_LENGTH_LABEL,
+        R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED );
+
+    aMessage.Append( KEnterEnter );
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddKeyUsageL(...)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::AddKeyUsageL( TDes& aMessage, const CCTKeyInfo* aKeyInfo )
+    {
+    if ( aKeyInfo != NULL )
+        {
+        TKeyUsagePKCS15 keyUsage = aKeyInfo->Usage();
+
+        TInt usage = 0;
+        switch( keyUsage )
+            {
+            case EPKCS15UsageSignSignRecover:
+            case EPKCS15UsageSign:
+            case EPKCS15UsageSignDecrypt:
+                usage = R_TEXT_RESOURCE_DETAILS_VIEW_CLIENT_AUTHENTICATION;
+                break;
+            case EPKCS15UsageNonRepudiation:
+                usage = R_TEXT_RESOURCE_DETAILS_VIEW_DIGITAL_SIGNING;
+                break;
+            default:
+                usage = R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED;
+                break;
+            }
+        DetailsFieldResourceL( aMessage,
+            R_TEXT_RESOURCE_DETAILS_VIEW_KEY_USAGE, usage);
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddKeyUsageL(...)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::AddKeyUsageL( TDes& aMessage, const CX509Certificate& aCert )
+    {
+  TKeyUsageX509 x509Usage = EX509UsageNone;
+  TKeyUsagePKCS15 pkcs15KeyUsage = EPKCS15UsageNone;
+  const CX509CertExtension* ext = aCert.Extension(KKeyUsage);
+  if ( ext )
+      {
+      CX509KeyUsageExt* keyUsageExt =
+      CX509KeyUsageExt::NewLC(ext->Data());
+      if ( keyUsageExt->IsSet( EX509DigitalSignature ) )
+          {
+          x509Usage |= EX509UsageDigitalSignature;
+          }
+      if ( keyUsageExt->IsSet( EX509NonRepudiation ) )
+          {
+          x509Usage |= EX509UsageNonRepudiation;
+          }
+      if ( keyUsageExt->IsSet( EX509KeyEncipherment ) )
+          {
+          x509Usage |= EX509UsageKeyEncipherment;
+          }
+      if ( keyUsageExt->IsSet( EX509DataEncipherment ) )
+          {
+          x509Usage |= EX509UsageDataEncipherment;
+          }
+      if ( keyUsageExt->IsSet( EX509KeyAgreement ) )
+          {
+          x509Usage |= EX509UsageKeyAgreement;
+          }
+      if ( keyUsageExt->IsSet( EX509KeyCertSign ) )
+          {
+          x509Usage |= EX509UsageKeyCertSign;
+          }
+      if ( keyUsageExt->IsSet( EX509CRLSign ) )
+          {
+          x509Usage |= EX509UsageCRLSign;
+          }
+      if ( keyUsageExt->IsSet( EX509EncipherOnly ) )
+          {
+          x509Usage |= EX509UsageEncipherOnly;
+          }
+      if ( keyUsageExt->IsSet( EX509DecipherOnly ) )
+          {
+          x509Usage |= EX509UsageDecipherOnly;
+          }
+      CleanupStack::PopAndDestroy( keyUsageExt );
+      }
+
+  pkcs15KeyUsage = KeyUsageX509ToPKCS15Private( x509Usage );
+
+  TInt usage = 0;
+  switch( pkcs15KeyUsage )
+      {
+      case EPKCS15UsageSignSignRecover:
+      case EPKCS15UsageSign:
+      case EPKCS15UsageSignDecrypt:
+          {
+          usage = R_TEXT_RESOURCE_DETAILS_VIEW_CLIENT_AUTHENTICATION;
+          break;
+          }
+      case EPKCS15UsageNonRepudiation:
+          {
+          usage = R_TEXT_RESOURCE_DETAILS_VIEW_DIGITAL_SIGNING;
+          break;
+          }
+      default:
+          {
+          usage = R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED;
+          break;
+          }
+
+      }
+   DetailsFieldResourceL( aMessage,
+          R_TEXT_RESOURCE_DETAILS_VIEW_KEY_USAGE, usage );
+   }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddKeyAlgorithmL(...)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::AddKeyAlgorithmL( TDes& aMessage, const CCTKeyInfo* aKeyInfo )
+    {
+    TInt algRes = 0;
+    switch( aKeyInfo->Algorithm())
+        {
+        case CKeyInfoBase::ERSA:
+            {
+            algRes = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_RSA;
+            break;
+            }
+        case CKeyInfoBase::EDSA:
+            {
+            algRes = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_DSA;
+            break;
+            }
+        case CKeyInfoBase::EDH:
+            {
+            algRes = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_DH;
+            break;
+            }
+        case CKeyInfoBase::EInvalidAlgorithm:
+            {
+            algRes = R_TEXT_RESOURCE_DETAILS_VIEW_UNKNOWN;
+            break;
+            }
+        default:
+            {
+            algRes = R_TEXT_RESOURCE_DETAILS_VIEW_UNKNOWN;
+            }
+        }
+    DetailsFieldResourceL( aMessage,
+            R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM, algRes);
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddCertLocationL(...)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::AddCertLocationL( TDes& aMessage, const CCTCertInfo* aCertInfo )
+    {
+    if ( aCertInfo )
+        {
+        AddLocationInfoL( aMessage, aCertInfo->Token().TokenType().Type(), ETrue );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddKeyLocationL(...)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::AddKeyLocationL( TDes& aMessage, const CCTKeyInfo* aKeyInfo )
+    {
+    if ( aKeyInfo )
+        {
+        AddLocationInfoL( aMessage, aKeyInfo->Token().TokenType().Type(), EFalse );
+        }
+    }
+
+// ---------------------------------------------------------
+// CCTSecurityDialogsAO::SetLocationInfo( (HBufC& aMessage,
+//                                               TBool aCertificate,
+//                                               TUid* aLocUid)
+// Adds certificate/private key's location info to certificate details
+// ---------------------------------------------------------
+//
+void CCTSecurityDialogsAO::AddLocationInfoL(
+    TDes& aMessage, TUid aUid, TBool aCertificate )
+    {
+    TInt location = 0;
+    TInt locationRes =0;
+
+    switch ( aUid.iUid )
+        {
+        case KFileCertStoreUid:
+        case KTokenTypeFileKeystore:
+            {
+            location = R_TEXT_RESOURCE_DETAILS_VIEW_LOCATION_PHONE_MEMORY;
+            break;
+            }
+        case KWIMCertStoreUid:
+            {
+            location = R_TEXT_RESOURCE_DETAILS_VIEW_LOCATION_SMART_CARD;
+            break;
+            }
+        default:
+            {
+            if ( aCertificate )
+                {
+                location = R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED;
+                }
+            else
+                {
+                location = R_TEXT_RESOURCE_DETAILS_VIEW_NO_PRIVATE_KEY;
+                }
+            break;
+            }
+        }
+
+    if ( aCertificate )
+        {
+        locationRes = R_TEXT_RESOURCE_DETAILS_VIEW_CERTIFICATE_LOCATION;
+        }
+    else
+        {
+        locationRes = R_TEXT_RESOURCE_DETAILS_VIEW_PRIVATE_KEY_LOCATION;
+        }
+
+    DetailsFieldResourceL( aMessage, locationRes, location );
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddValidityPeriodL(...)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::AddValidityPeriodL(
+    TDes& aMessage, const CX509Certificate& aCert )
+    {
+    TLocale locale;
+    TTimeIntervalSeconds offSet = locale.UniversalTimeOffset();
+    DetailsResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_VALID_FROM );
+    const CValidityPeriod& validityPeriod = aCert.ValidityPeriod();
+    TTime startValue = validityPeriod.Start();
+    startValue += offSet;
+    TBuf<KMaxLengthTextDateString> startString;
+    // read format string from AVKON resource
+    HBufC* dateFormatString = CEikonEnv::Static()->AllocReadResourceLC(
+        R_QTN_DATE_USUAL_WITH_ZERO );
+    // format the date to user readable format. The format is locale dependent
+    startValue.FormatL( startString, *dateFormatString );
+    AknTextUtils::DisplayTextLanguageSpecificNumberConversion( startString );
+    CleanupStack::PopAndDestroy(); // dateFormatString
+    aMessage.Append( startString );
+    aMessage.Append( KEnterEnter );
+
+    DetailsResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_VALID_UNTIL );
+    TTime finishValue = validityPeriod.Finish();
+    finishValue += offSet;
+    TBuf<KMaxLengthTextDateString> finishString;
+    // read format string from AVKON resource
+    dateFormatString = CEikonEnv::Static()->AllocReadResourceLC(
+        R_QTN_DATE_USUAL_WITH_ZERO );
+    // format the date to user readable format. The format is locale dependent
+    finishValue.FormatL( finishString, *dateFormatString );
+    AknTextUtils::DisplayTextLanguageSpecificNumberConversion(finishString);
+    CleanupStack::PopAndDestroy(); // dateFormatString
+    aMessage.Append( finishString );
+    aMessage.Append( KEnterEnter );
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddCertFormatL(...)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::AddCertFormatL( TDes& aMessage, TCertificateFormat aCertFormat)
+    {
+    TInt fieldType = 0;
+    switch ( aCertFormat )
+        {
+        case EX509CertificateUrl:
+        case EX509Certificate:
+            {
+            fieldType = R_TEXT_RESOURCE_DETAILS_VIEW_CERT_FORMAT_X509;
+            break;
+            }
+        default:
+            {
+            fieldType = R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED;
+            break;
+            }
+        }
+    DetailsFieldResourceL( aMessage,
+        R_TEXT_RESOURCE_DETAILS_VIEW_CERT_FORMAT, fieldType );
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddCertAlgorithmsL(...)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::AddCertAlgorithmsL( TDes& aMessage, const CX509Certificate& aCert )
+    {
+    TInt fieldType = 0;
+    TInt fieldType2 = 0;
+    // digest algorithm
+    TAlgorithmId algorithmId =
+        aCert.SigningAlgorithm().DigestAlgorithm().Algorithm();
+    switch ( algorithmId )
+        {
+        case EMD2:
+            {
+            fieldType = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_MD2;
+            break;
+            }
+        case EMD5:
+            {
+            fieldType = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_MD5;
+            break;
+            }
+        case ESHA1:
+            {
+            fieldType = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_SHA1;
+            break;
+            }
+        default:
+            {
+            fieldType = R_TEXT_RESOURCE_DETAILS_VIEW_UNKNOWN;
+            break;
+            }
+        }
+
+    // public-key algorithm
+    algorithmId =
+        aCert.SigningAlgorithm().AsymmetricAlgorithm().Algorithm();
+    switch ( algorithmId )
+        {
+        case ERSA:
+            {
+            fieldType2 = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_RSA;
+            break;
+            }
+        case EDSA:
+            {
+            fieldType2 = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_DSA;
+            break;
+            }
+        case EDH:
+            {
+            fieldType2 = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_DH;
+            break;
+            }
+        default:
+            {
+            fieldType2 = R_TEXT_RESOURCE_DETAILS_VIEW_UNKNOWN;
+            }
+        }
+
+    // If other algorithm is unknown
+    if ( fieldType == R_TEXT_RESOURCE_DETAILS_VIEW_UNKNOWN ||
+        fieldType2 == R_TEXT_RESOURCE_DETAILS_VIEW_UNKNOWN )
+        {
+        DetailsFieldResourceL( aMessage,
+        R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM, R_TEXT_RESOURCE_DETAILS_VIEW_UNKNOWN );
+        }
+    else // Both are known.
+        {
+        DetailsResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM);
+        HBufC* stringHolder = StringLoader::LoadLC( fieldType );
+        aMessage.Append( stringHolder->Des() );
+        CleanupStack::PopAndDestroy();
+        stringHolder = StringLoader::LoadLC( fieldType2 );
+        aMessage.Append( stringHolder->Des() );
+        CleanupStack::PopAndDestroy();  // stringHolder
+        aMessage.Append( KEnterEnter );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddCertSerialNumberL(...)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::AddCertSerialNumberL( TDes& aMessage, const CX509Certificate& aCert )
+    {
+    // certificate serial number
+    DetailsResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_SERIAL_NUMBER );
+    TPtrC8 serialNumber = aCert.SerialNumber();
+    TBuf<KMaxLengthTextSerialNumberFormatting> buf2;
+
+    for ( TInt i = 0; i < serialNumber.Length(); i++ )
+       {
+       buf2.Format( KCertManUIDetailsViewHexFormat, serialNumber[i] );
+       aMessage.Append( buf2 );
+       }
+
+    aMessage.Append( KEnterEnter );
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddCertFingerprintsL(...)
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::AddCertFingerprintsL( TDes& aMessage, const CX509Certificate& aCert )
+    {
+     // certificate fingerprint SHA-1
+    DetailsResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_FINGERPRINT );
+
+    TPtrC8 sha1_fingerprint = aCert.Fingerprint();
+    DevideToBlocks( sha1_fingerprint, aMessage );
+
+    aMessage.Append( KEnterEnter );
+
+    // certificate fingerprint MD5
+    DetailsResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_FINGERPRINT_MD5 );
+
+    CMD5* md5 = CMD5::NewL();
+    CleanupStack::PushL( md5 );
+    TBuf8<20> fingerprint = md5->Hash( aCert.Encoding() );
+    CleanupStack::PopAndDestroy( md5 );
+
+    DevideToBlocks( fingerprint, aMessage );
+    }
+
+// ---------------------------------------------------------
+// CCTSecurityDialogsAO::DevideToBlocks
+// ---------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DevideToBlocks( const TDesC8& aInput, TDes& aOutput )
+    {
+    const TInt KBlockLength = 2;
+    TInt blockIndex = 0;
+    for ( TInt j = 0 ; j < aInput.Length() ; j++ )
+        {
+        if ( blockIndex == KBlockLength )
+            {
+            aOutput.Append( KBlockSeparator );
+            blockIndex = 0;
+            }
+        aOutput.AppendNumFixedWidthUC( (TUint)(aInput[ j ]), EHex, 2 );
+        ++blockIndex;
+        }
+    }
+
+// ---------------------------------------------------------
+// CCTSecurityDialogsAO::DetailsFieldResourceL(
+// HBufC& aMessage, TInt aResourceOne, TInt aResourceTwo);
+// Appends a field that has two strings from resources
+// to the details view message body
+// ---------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DetailsFieldResourceL(
+    TDes& aMessage, TInt aResourceOne,
+    TInt aResourceTwo )
+    {
+    DetailsResourceL( aMessage, aResourceOne );
+    DetailsResourceL( aMessage, aResourceTwo );
+    aMessage.Append( KEnter );
+    }
+
+// ---------------------------------------------------------
+// CCTSecurityDialogsAO::DetailsFieldDynamicL(HBufC& aMessage, TPtrC aValue,
+//                                        TInt aResourceOne, TInt aResourceTwo);
+// Appends a field that has string from resources and string from CertManAPI
+// to the details view message body
+// ---------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DetailsFieldDynamicL(
+    TDes& aMessage,
+    const TDesC& aValue,
+    TInt aResourceOne,
+    TInt aResourceTwo)
+    {
+    DetailsResourceL( aMessage, aResourceOne );
+    DetailsDynamicL( aMessage, aValue, aResourceTwo );
+    aMessage.Append( KEnter );
+    }
+
+// ---------------------------------------------------------
+// CCTSecurityDialogsAO::DetailsResourceL(
+// HBufC& aMessage, TInt aResourceOne);
+// Reads line from resources
+// ---------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DetailsResourceL(
+    TDes& aMessage, TInt aResource)
+    {
+    HBufC* stringHolder = StringLoader::LoadLC( aResource );
+    aMessage.Append( stringHolder->Des() );
+    CleanupStack::PopAndDestroy();  // stringHolder
+    aMessage.Append( KEnter );
+    }
+
+// ---------------------------------------------------------
+// CCTSecurityDialogsAO::DetailsDynamicL(
+// HBufC& aMessage, TPtrC aValue, TInt aResourceOne)
+// Reads dynamic text, if the string is empty
+// put a not defined text from the resource in its place
+// KMaxLengthTextCertLabel = 510, used by CertLabel(), Issuer(), Owner()
+// ---------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DetailsDynamicL(
+    TDes& aMessage, const TDesC& aValue, TInt aResource)
+    {
+    HBufC* buf = HBufC::NewLC( KMaxLengthTextCertLabel );
+    buf->Des() = aValue;
+    buf->Des().TrimLeft();
+    // Cut CertLabel after fourth semi colon
+    TPtrC trimmedCertLabel = CutCertificateField( buf->Des() );
+    buf->Des().Copy( trimmedCertLabel );
+    TInt length = buf->Des().Length();
+    if (length == 0 )
+        {
+        DetailsResourceL( aMessage, aResource );
+        }
+    else
+        {
+        aMessage.Append( buf->Des() );
+        aMessage.Append( KEnter );
+        }
+    CleanupStack::PopAndDestroy();  // buf
+    }
+
+// ---------------------------------------------------------
+// CCTSecurityDialogsAO::CutCertificateField(TPtrC aField)
+// If CertLabel, Issuer and Owner length is over 80 characters,
+// cut it down to 80
+// Returns the cut certificate field.
+// ---------------------------------------------------------
+//
+TPtrC CCTSecurityDialogsAO::CutCertificateField( const TDesC&  aField )
+    {
+    TInt fieldLength = aField.Length();
+    if ( fieldLength >= KMaxLengthTextCertLabelVisible )
+        {
+        TPtrC cutCertLabel = aField.Mid( 0, KMaxLengthTextCertLabelVisible );
+        return cutCertLabel;
+        }
+    return aField;
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::HandleResponseAndCompleteL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::HandleResponseAndCompleteL()
+    {
+    WIMSECURITYDIALOGS_WRITE_FORMAT( "HandleResponseAndCompleteL: %d", iRetValue );
+
+    MapTlsProviderOperation(iOperation);
+
+    switch (iOperation)
+        {
+        case EEnablePIN: // flow thru
+        case EDisablePIN: // flow thru
+        case EEnterPIN:
+            {
+            TPINValueBuf pinValueBufPtr;
+            if ( iPIN.iPINLabel == KKeyStoreCreatePwLabel ||
+                iPIN.iPINLabel == KKeyStoreExportKeyLabel )
+                {
+                pinValueBufPtr = iPINValue2;
+                }
+            else
+                {
+                pinValueBufPtr = iPINValue1;
+                }
+            iMessagePtr.WriteL( iReplySlot, pinValueBufPtr );
+            break;
+            }
+        case EChangePIN:
+        case EUnblockPIN:
+            {
+            TTwoPINOutput twoPINOutput;
+            twoPINOutput.iPINValueToCheck = iPINValue1;
+            twoPINOutput.iNewPINValue = iPINValue2;
+            TTwoPINOutputBuf twoPINOutputBuf( twoPINOutput );
+            iMessagePtr.WriteL( iReplySlot, twoPINOutputBuf );
+            break;
+            }
+        case ESignText: // flow thru
+        case EUserAuthenticationText: // flow thru
+        case EUserAuthentication:
+            {
+            TCTTokenObjectHandleBuf tokenObjectHandleBuf( iTokenHandle );
+            iMessagePtr.WriteL( iReplySlot, tokenObjectHandleBuf );
+            break;
+            }
+        case EServerAuthenticationFailure:
+            {
+            TServerAuthenticationFailureDialogResult result = EStop;
+
+            if ( iRetValue != EServerCertAcceptedPermanently )
+                {
+                if ( iRetValue == EServerCertAcceptedTemporarily )
+                    {
+                    result = EContinue;
+                    }
+                else
+                    {
+                    result = EStop;
+                    }
+                }
+            else
+                {
+                // User permanently accepted server certificate.
+                result = EContinue;
+                }
+
+            TServerAuthenticationFailureOutputBuf output( result );
+            iMessagePtr.WriteL( iReplySlot, output );
+            iMessagePtr.Complete( KErrNone );
+
+            break;
+            }
+        case EPINBlocked:
+        case EUnblockPINInClear:
+            {
+            User::Leave( KErrNotSupported );
+            break;
+            }
+        case ECreateCSR:
+        case ECertDetails:
+        case ESaveCert:
+        case EDeleteCert:
+        case ESaveReceipt:
+        case EPinCodeBlockedInfo:
+        case MDigSigningNote::ESignatureRequested:
+        case MDigSigningNote::ESignatureDone:
+        case MDigSigningNote::ESigningCancelled:
+        case MDigSigningNote::ENoMatchCert:
+        case MDigSigningNote::ENoSecurityModule:
+        case MDigSigningNote::EInternalError:
+            {
+            break; // Complete is enough
+            }
+        default:
+            User::Panic( _L("CTestSecDlgNotifier"), 0 );
+        }
+    
+    if( iOperation != EServerAuthenticationFailure )
+        {
+        iMessagePtr.Complete( iRetValue ? KErrNone : KErrCancel );
+        }
+    
+    delete this;
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::SaveReceiptL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::SaveReceiptL( const TDesC8& aBuffer )
+    {
+    TInt size = reinterpret_cast<const TInt&>( *aBuffer.Ptr() );
+    TInt start = sizeof(TInt) + 1;
+    HBufC* signedText = HBufC::NewLC( size );
+    signedText->Des().Copy( aBuffer.Mid(start) );
+    CEikProcess* process = CEikonEnv::Static()->Process();
+    CDocumentHandler* docHandler =  CDocumentHandler::NewLC( process );
+    _LIT8( KPlainText, "text/plain" );
+    TDataType dataType( KPlainText );
+    // convert 16->8bits
+    HBufC8* content = HBufC8::NewLC( signedText->Length() );
+    content->Des().Copy( *signedText );
+
+    docHandler->SaveL( *content,
+    dataType,
+    KEntryAttNormal);
+
+    CleanupStack::PopAndDestroy( 3, signedText );   // content, docHandler, signedText
+    HandleResponseAndCompleteL();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::DoCancel()
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DoCancel()
+    {
+    WIMSECURITYDIALOGS_WRITE( "CCTSecurityDialogsAO::DoCancel" );
+
+    // Note that iQueryDialog may point to already deleted memory.
+    // Dialogs need to set and reset iQueryDialogDeleted flag to
+    // allow deleting the dialog from CCTSecurityDialogsAO.
+    if( !iQueryDialogDeleted )
+        {
+        delete iQueryDialog;
+        iQueryDialogDeleted = ETrue;
+        }
+    iQueryDialog = NULL;
+    
+    if ( !iPinQueryDialogDeleted )
+        {
+        delete iPinQueryDialog;
+        iPinQueryDialogDeleted = ETrue;
+        }
+    iPinQueryDialog = NULL;
+    
+    // Complete message if it has not been completed earlier.
+    if( !iMessagePtr.IsNull() )
+        {
+        iMessagePtr.Complete( KErrCancel );
+        }
+    }
+
+// For server authentication failure
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::CreateMessageLC()
+// -----------------------------------------------------------------------------
+
+HBufC* CCTSecurityDialogsAO::CreateMessageL()
+    {
+    //TPtrC8 certPtrC;
+    //iSrvAuthFail->GetEncodedCert(certPtrC);
+    return MessageQueryCertDetailsL(
+        *iCertBuf, NULL, EX509Certificate, NULL );
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::DoHandleSaveServerCertL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::DoHandleSaveServerCertL()
+    {
+    if ( iTrustedSiteCertStore )
+        {
+        iTrustedSiteCertStore->Add( *iCertLabel, EX509Certificate,
+                                EPeerCertificate, NULL, NULL, *iCertBuf, iStatus );
+
+        // Next step is to update trust site db
+        iNextStep = EAddTrustedSite;
+        iStatus = KRequestPending;
+        SetActive();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::MapTlsProviderOperation()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogsAO::MapTlsProviderOperation( TUint aOperation )
+    {
+    switch (aOperation)
+        {
+        case ESecureConnection:
+            {
+            iOperation = EUserAuthentication;
+            break;
+            }
+        default:
+            break;
+        }
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifSrc/CTSecuritydialognotifier.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,385 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Crypto Token Security Dialog Notifier
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CTSecurityDialogNotifier.h"
+#include "CTSecurityDialogsAO.h" 
+#include <eikenv.h>
+#include <coemain.h>
+#include <bautils.h>
+#include <StringLoader.h>
+#include <data_caging_path_literals.hrh>
+
+
+
+// CONSTANTS
+_LIT(KCTSecDlgDiskAndFile, "z:CTSecDlgs.rsc");
+_LIT(KCTCertManUiResDiskAndFile, "z:CertManUi.rsc");
+
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+GLDEF_C void Panic(TInt aPanicCode)
+    {
+	_LIT(KComponentName, "CTSecNotifier");
+	User::Panic(KComponentName, aPanicCode);
+    }
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogNotifier::CCTSecurityDialogNotifier
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CCTSecurityDialogNotifier::CCTSecurityDialogNotifier(): 
+    iSaveReceipt(EFalse) 
+    {    
+    WIMSECURITYDIALOGS_CREATE
+    WIMSECURITYDIALOGS_WRITE_TIMESTAMP( "CCTSecurityDialogNotifier::CCTSecurityDialogNotifier()" );
+	iEikEnv = CEikonEnv::Static();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogNotifier::~CCTSecurityDialogNotifier()
+// -----------------------------------------------------------------------------
+//
+CCTSecurityDialogNotifier::~CCTSecurityDialogNotifier()
+    {
+    WIMSECURITYDIALOGS_DELETE
+    Cancel();
+	if ( iResourceFileOffset )
+        {
+		iEikEnv->DeleteResourceFile( iResourceFileOffset );
+        }
+    if ( iResourceFileOffset2 )
+        {
+		iEikEnv->DeleteResourceFile( iResourceFileOffset2 );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogNotifier::NewL()
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CCTSecurityDialogNotifier* CCTSecurityDialogNotifier::NewL()
+    {
+	CCTSecurityDialogNotifier* self = new (ELeave) CCTSecurityDialogNotifier;
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	CleanupStack::Pop(); // self
+	return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogNotifier::ConstructL()
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogNotifier::ConstructL()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogNotifier::Release()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogNotifier::Release()
+    {
+    WIMSECURITYDIALOGS_WRITE_TIMESTAMP( "CCTSecurityDialogNotifier::Release" );
+	delete this;
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogNotifier::RegisterL()
+// -----------------------------------------------------------------------------
+//
+CCTSecurityDialogNotifier::TNotifierInfo CCTSecurityDialogNotifier::RegisterL()
+    {
+	// Resource file loading
+	RFs& fs = iEikEnv->FsSession();
+
+	TFileName fileName;
+
+	TParse parse;
+    parse.Set(KCTSecDlgDiskAndFile, &KDC_RESOURCE_FILES_DIR, NULL);
+	
+	fileName = parse.FullName();
+
+	BaflUtils::NearestLanguageFile( fs, fileName );
+	iResourceFileOffset = iEikEnv->AddResourceFileL( fileName );
+	
+	parse.Set(KCTCertManUiResDiskAndFile, &KDC_RESOURCE_FILES_DIR, NULL); 
+    fileName = parse.FullName();
+    BaflUtils::NearestLanguageFile( fs, fileName );
+    iResourceFileOffset2 = iEikEnv->AddResourceFileL( fileName );
+
+	return Info();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogNotifier::Info() 
+// -----------------------------------------------------------------------------
+//
+CCTSecurityDialogNotifier::TNotifierInfo CCTSecurityDialogNotifier::Info() const
+    {
+	TNotifierInfo info;
+	info.iUid = KUidSecurityDialogNotifier;
+	info.iChannel = KUidSecurityDialogNotifier;
+    info.iPriority = ENotifierPriorityAbsolute;
+	return info;
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogNotifier::StartL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogNotifier::StartL( const TDesC8& aBuffer, TInt aReplySlot,
+        const RMessagePtr2& aMessage )
+    {
+    WIMSECURITYDIALOGS_WRITE( "CCTSecurityDialogNotifier::StartL" );
+
+    TRAPD( err, DoStartL( aBuffer, aReplySlot, aMessage ) );
+    if( err )
+        {
+        if( !iSecurityDialogAODeleted )
+            {
+            delete iSecurityDialogAO;
+            iSecurityDialogAO = NULL;
+            }
+        if( !aMessage.IsNull() )
+            {
+            aMessage.Complete( err );
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogNotifier::DoStartL()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogNotifier::DoStartL( const TDesC8& aBuffer, TInt aReplySlot,
+        const RMessagePtr2& aMessage )
+    {
+    // CCTSecurityDialogsAO sets the boolean iSecurityDialogAODeleted when it is
+    // constructed and resets it when it is destructed, so iSecurityDialogAODeleted
+    // tells whether the iSecurityDialogAO pointer is valid or not.
+    iSecurityDialogAO = CCTSecurityDialogsAO::NewL( this, iSecurityDialogAODeleted );
+    
+    iSecurityDialogAO->StartLD( aBuffer, aReplySlot, aMessage );
+    // StartLD() deletes the iSecurityDialogAO object when it is ready processing the
+    // request. This may take some time, as CCTSecurityDialogsAO is active object, so
+    // iSecurityDialogAO object exists when the above StartLD() returns here. It will
+    // be deleted later when the operation completes. Started operation can be cancelled
+    // before it is completed by deleting the iSecurityDialogAO object.
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogNotifier::StartL()
+// -----------------------------------------------------------------------------
+//
+TPtrC8 CCTSecurityDialogNotifier::StartL(const TDesC8& /*aBuffer*/)
+    {
+	return KNullDesC8();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogNotifier::Cancel()
+// -----------------------------------------------------------------------------
+//
+void CCTSecurityDialogNotifier::Cancel()
+    {
+    WIMSECURITYDIALOGS_WRITE( "CCTSecurityDialogNotifier::Cancel" );
+    
+    // If iSecurityDialogAO is not completed yet, we need to cancel it now.
+    // We can simply delete iSecurityDialogAO to cancel pending actions.
+    if( !iSecurityDialogAODeleted )
+        {
+        delete iSecurityDialogAO;
+        }
+    iSecurityDialogAO = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogNotifier::UpdateL()
+// -----------------------------------------------------------------------------
+//
+TPtrC8 CCTSecurityDialogNotifier::UpdateL(const TDesC8& /*aBuffer*/)
+    {
+	return KNullDesC8();
+    }
+    
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogNotifier::LoadResourceStringLC()
+// -----------------------------------------------------------------------------
+//
+HBufC* CCTSecurityDialogNotifier::LoadResourceStringLC( const TInt aType, const TDesC& aDynamicText, const TDesC& aDynamicText2 )
+    {
+    if ( aDynamicText2.Length() ) 
+        {
+        TDialogTypeItem item = GetDialogTypeItem( aType );
+        HBufC* stringWithDynamics = StringLoader::LoadL(item.iResourceIdentifier, iEikEnv);
+        CleanupStack::PushL(stringWithDynamics);
+        
+        if ( aDynamicText.Length() && aDynamicText2.Length() )
+            {
+            _LIT(dynamicTextIdentifier, "%0U");
+            
+            if (stringWithDynamics->Find(dynamicTextIdentifier) != KErrNotFound)
+                {
+                CleanupStack::PopAndDestroy(stringWithDynamics);
+                
+                CDesCArrayFlat* strings = new (ELeave) CDesCArrayFlat(2);
+                CleanupStack::PushL(strings);
+                      
+                strings->AppendL( aDynamicText );
+                strings->AppendL( aDynamicText2 );
+                
+                stringWithDynamics = 
+                    StringLoader::LoadL(item.iResourceIdentifier, 
+                        *strings, iEikEnv);
+          
+                CleanupStack::PopAndDestroy(strings);
+      
+                CleanupStack::PushL(stringWithDynamics);
+                }
+            else
+                {
+                HBufC* dynamicText = NULL;
+                _LIT(dynamicTextIdentifier, "%U");
+                
+                if (stringWithDynamics->Find(dynamicTextIdentifier) != KErrNotFound)
+                    {
+                    CleanupStack::PopAndDestroy(stringWithDynamics); // stringWithDynamics, it wasn't final
+                    TPtrC param; 
+                    if (item.iDynamicResourceIdentifier)
+                        {
+                        dynamicText = StringLoader::LoadL( item.iDynamicResourceIdentifier, iEikEnv );
+                        CleanupStack::PushL( dynamicText );
+                        param.Set( dynamicText->Des() );
+                        }
+                    else
+                        {
+                        param.Set( aDynamicText );
+                        }
+                    stringWithDynamics = 
+                        StringLoader::LoadL(item.iResourceIdentifier, 
+                                             param, iEikEnv);
+                    if (dynamicText)
+                        {
+                        CleanupStack::PopAndDestroy(dynamicText);
+                        }
+                    CleanupStack::PushL(stringWithDynamics);
+                    }
+                else
+                    {
+                    }
+                     
+                }
+            }
+        return stringWithDynamics;      
+        }
+    else
+        {
+        TDialogTypeItem item = GetDialogTypeItem( aType );
+        HBufC* stringWithDynamics = StringLoader::LoadL(item.iResourceIdentifier, iEikEnv);
+        CleanupStack::PushL(stringWithDynamics);
+        HBufC* dynamicText = NULL;
+    
+        if (item.iDynamicResourceIdentifier || aDynamicText.Length())
+            {
+            _LIT(dynamicTextIdentifier, "%U");
+            
+            if (stringWithDynamics->Find(dynamicTextIdentifier) != KErrNotFound)
+                {
+                CleanupStack::PopAndDestroy(stringWithDynamics); // stringWithDynamics, it wasn't final
+                TPtrC param; 
+                if (item.iDynamicResourceIdentifier)
+                    {
+                    dynamicText = StringLoader::LoadL( item.iDynamicResourceIdentifier, iEikEnv );
+                    CleanupStack::PushL( dynamicText );
+                    param.Set( dynamicText->Des() );
+                    }
+                else
+                    {
+                    param.Set( aDynamicText );
+                    }
+          stringWithDynamics = 
+                    StringLoader::LoadL(item.iResourceIdentifier, 
+                                         param, iEikEnv);
+                if (dynamicText)
+                    {
+                    CleanupStack::PopAndDestroy(dynamicText);
+                    }
+                CleanupStack::PushL(stringWithDynamics);
+                }
+            else
+                {
+                }
+            }
+            
+          return stringWithDynamics;
+          }
+    
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogNotifier::GetDialogTypeItem()
+// -----------------------------------------------------------------------------
+//
+TDialogTypeItem CCTSecurityDialogNotifier::GetDialogTypeItem(const TInt aType)
+    {
+    // If the code panics here, then there's a TDialogType without 
+	// any TDialogTypeItem-> Check KDialogTypeToResourceMapper, and add to the mapper!
+
+
+	// Find the corresponding resource to aType.
+	// Algorithm: Best guess : Let's take KDialogTypeToResourceMapper[aType]
+	// if its iDialogType field matches with aType -> HIT, OK
+	// if not, then browse through the whole resource mapper array. If found, ok, 
+	// but if not, we will have to panic, as it is a developer error (fatal).
+
+	const TInt mapperCount = sizeof(KDialogTypeToResourceMapper) / sizeof(TDialogTypeItem);
+	__ASSERT_ALWAYS(aType < mapperCount, Panic(KErrOverflow));
+
+	TDialogTypeItem item = KDialogTypeToResourceMapper[aType];
+
+	if (item.iDialogType != aType)
+	    {   
+		TBool found(EFalse);
+
+		for (TInt i = 0; i < mapperCount; i++)
+		    {
+			item = KDialogTypeToResourceMapper[i];
+			if (item.iDialogType == aType)
+			    {
+				found = ETrue;
+				break;
+                } // if
+            } // for 
+		__ASSERT_ALWAYS(found, Panic(KErrNotFound));
+        } // if
+	return item; 
+    } 
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifSrc/CTSelectcertificatedialog.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,112 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   CT Select Certificate Dialog
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CTSelectCertificateDialog.h"
+#include "CTSecurityDialogDefs.h"
+#include <CTSecDlgs.rsg>
+#include <uikon/eiksrvui.h>
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCTSelectCertificateDialog::CCTSelectCertificateDialog
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+
+CCTSelectCertificateDialog::CCTSelectCertificateDialog(
+    MDesCArray* /*aCertificates*/, 
+    RArray<TCTTokenObjectHandle>& aCertHandleList, 
+    TCTTokenObjectHandle& aSelectedCert,
+    TRequestStatus& aClientStatus, 
+    TBool& aRetVal)
+    : CAknListQueryDialog(&iSelectedIndex), 
+      iClientStatus(&aClientStatus), 
+      iRetVal(aRetVal), 
+      iSelectedIndex( 0 ),
+      iCertHandleList( aCertHandleList ),
+      iSelectedCert( aSelectedCert )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSelectCertificateDialog::~CCTSelectCertificateDialog()
+// -----------------------------------------------------------------------------
+//
+CCTSelectCertificateDialog::~CCTSelectCertificateDialog()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSelectCertificateDialog::RunDlgLD()
+// -----------------------------------------------------------------------------
+//
+void  CCTSelectCertificateDialog::RunDlgLD( 
+    MDesCArray* aCertificates, 
+    RArray<TCTTokenObjectHandle>& aCertHandleList,
+    TCTTokenObjectHandle& aSelectedCert,
+    TRequestStatus& aClientStatus, 
+    TBool& aRetVal )
+    {
+	CCTSelectCertificateDialog* self = 
+        new (ELeave) CCTSelectCertificateDialog(
+        aCertificates, aCertHandleList, aSelectedCert, aClientStatus, aRetVal );
+
+	self->PrepareLC(R_WIM_SELECT_CERTIFICATE_DIALOG);
+	self->SetItemTextArray(aCertificates);
+	self->SetOwnershipType(ELbmOwnsItemArray);
+	self->RunLD();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSelectCertificateDialog::PostLayoutDynInitL()
+// -----------------------------------------------------------------------------
+//
+void CCTSelectCertificateDialog::PostLayoutDynInitL()
+    {
+	((CEikServAppUi*)(CEikonEnv::Static())->EikAppUi())->SuppressAppSwitching(ETrue);
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSelectCertificateDialog::OkToExitL()
+// -----------------------------------------------------------------------------
+//
+TInt CCTSelectCertificateDialog::OkToExitL(TInt aButtonId)
+    {
+    if ( aButtonId == EEikBidCancel )
+	{
+		iRetVal = EFalse;
+		User::RequestComplete(iClientStatus, KErrNone);
+	}
+	//Left softkey or Selection key was pressed
+    else if ( aButtonId ==EAknSoftkeySelect || aButtonId == EAknSoftkeyOk)
+	{
+		iRetVal = ETrue;
+		iSelectedIndex = ListBox()->CurrentItemIndex();
+        iSelectedCert = iCertHandleList[iSelectedIndex];
+		User::RequestComplete(iClientStatus, KErrNone);  		
+	}
+	((CEikServAppUi*)(CEikonEnv::Static())->EikAppUi())->SuppressAppSwitching(EFalse);
+	return ETrue; 	
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifSrc/CTSigntextdialog.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,130 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   CT Read and Sign Dialog for Digital Signature
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CTSignTextDialog.h"
+#include "CTSecurityDialogsLogger.h"
+#include <barsread.h>
+#include <CTSecDlgs.rsg>
+#include <uikon/eiksrvui.h>
+#include <StringLoader.h>
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCTSignTextDialog::CCTSignTextDialog
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CCTSignTextDialog::CCTSignTextDialog(const TDesC& aReceiptToSign, TRequestStatus& aStatus, 
+                                       TBool& aRetVal, TBool aSignText)
+: CAknMessageQueryDialog(EConfirmationTone),
+iReceiptToSign(aReceiptToSign), iClientStatus(&aStatus), iRetVal(aRetVal), iSignText(aSignText)
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSignTextDialog::~CCTSignTextDialog()
+// -----------------------------------------------------------------------------
+//
+CCTSignTextDialog::~CCTSignTextDialog()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSignTextDialog::RunDlgLD()
+// -----------------------------------------------------------------------------
+//
+void  CCTSignTextDialog::RunDlgLD(
+    TInt aResourceId, const TDesC& aReceiptToSign, 
+	TRequestStatus& aStatus, TBool& aRetVal)
+    {
+    CCTSignTextDialog* self = new (ELeave) CCTSignTextDialog(aReceiptToSign, aStatus, aRetVal, ETrue);  
+    self->ExecuteLD(aResourceId);
+    
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSignTextDialog::PreLayoutDynInitL()
+// -----------------------------------------------------------------------------
+//
+void CCTSignTextDialog::PreLayoutDynInitL()
+    {
+    SetMessageTextL(iReceiptToSign);
+	CAknMessageQueryDialog::PreLayoutDynInitL();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSignTextDialog::PostLayoutDynInitL()
+// -----------------------------------------------------------------------------
+//
+void CCTSignTextDialog::PostLayoutDynInitL()
+    {
+	((CEikServAppUi*)(CEikonEnv::Static())->EikAppUi())->SuppressAppSwitching(ETrue);
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSignTextDialog::OkToExitL()
+// -----------------------------------------------------------------------------
+//
+TBool CCTSignTextDialog::OkToExitL( TInt aButtonId )
+
+    {
+    if ( iSignText )
+        {
+        if ( aButtonId == EAknSoftkeyYes )
+            {    
+		    iRetVal = ETrue;
+		    User::RequestComplete(iClientStatus, KErrNone); 
+            }
+
+	    else if ( aButtonId == EAknSoftkeyNo || aButtonId == EEikBidCancel
+            || aButtonId == EAknSoftkeyOk )
+		    {
+		    iRetVal = EFalse;
+		    User::RequestComplete(iClientStatus, KErrNone); 
+		    }
+        }
+    else
+        {
+        if (aButtonId == EAknSoftkeyOk) 
+            {
+            User::RequestComplete(iClientStatus, KErrNone); 
+            }
+        else
+            {
+
+            }
+        }
+
+	((CEikServAppUi*)(CEikonEnv::Static())->EikAppUi())->SuppressAppSwitching(EFalse);
+	return ETrue;
+    }   
+
+// -----------------------------------------------------------------------------
+// CCTSignTextDialog::OfferKeyEventL()
+// -----------------------------------------------------------------------------
+//
+TKeyResponse CCTSignTextDialog::OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+	return CAknMessageQueryDialog::OfferKeyEventL(aKeyEvent, aType);
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifSrc/CTpinquerydialog.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,188 @@
+/*
+* Copyright (c) 2003-2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Crypto Token Security Dialogs PIN Query Dialog
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CTPinQueryDialog.h"
+#include "CTSecurityDialogsLogger.h"
+#include <CTSecDlgs.rsg>
+#include <eikenv.h>
+#include <barsread.h>
+#include <uikon/eiksrvui.h>
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCTPinQueryDialog::CCTPinQueryDialog
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CCTPinQueryDialog::CCTPinQueryDialog(
+    TRequestStatus& aClientStatus,
+    const TDesC& aDlgText, TDes& aPinValue, 
+    const TInt aMinTextLength, const TInt aMaxTextLength, TBool& aRetVal, TBool& aIsDeleted ): 
+    CAknTextQueryDialog(aPinValue),
+	iDlgText(aDlgText),
+	iPinValue(aPinValue),
+	iClientStatus(&aClientStatus),
+	iRetVal(aRetVal),
+	iIsDeleted(aIsDeleted)
+    {
+	iMaxTextLength = Min(aPinValue.MaxLength(), aMaxTextLength);
+	iMinTextLength = Max(0, aMinTextLength);
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinQueryDialog::~CCTPinQueryDialog()
+// -----------------------------------------------------------------------------
+//
+CCTPinQueryDialog::~CCTPinQueryDialog()
+    {
+    // Allow application switching again
+   CEikonEnv* eikonEnv = CEikonEnv::Static();
+    if( eikonEnv )
+        {
+        CEikServAppUi* eikServAppUi = static_cast<CEikServAppUi*>( eikonEnv->EikAppUi() );
+        if( eikServAppUi )
+            {
+            eikServAppUi->SuppressAppSwitching( EFalse );
+            }
+        }
+
+    // Complete the client request
+    if( iClientStatus && *iClientStatus == KRequestPending )
+        {
+        iRetVal = EFalse;
+        User::RequestComplete( iClientStatus, KErrNone );
+        }
+    
+    // Notify that the dialog has been deleted
+    iIsDeleted = ETrue;
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinQueryDialog::RunDlgLD()
+// -----------------------------------------------------------------------------
+//
+void CCTPinQueryDialog::RunDlgLD(
+    TRequestStatus& aClientStatus, 
+    const TDesC& aDlgText, 
+    TDes& aPinValue, 
+    const TInt aMinTextLength, 
+    const TInt aMaxTextLength, 
+    TBool& aRetVal, 
+    TInt aResourceId, CCTPinQueryDialog*& aDialog, TBool& aIsDeleted )
+    {
+	CCTPinQueryDialog* self = new (ELeave) CCTPinQueryDialog(aClientStatus, aDlgText, aPinValue, aMinTextLength, aMaxTextLength, aRetVal, aIsDeleted );
+	aDialog = self;
+	// OkToExitL function handles dialog response
+	self->ExecuteLD(aResourceId);
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinQueryDialog::PreLayoutDynInitL()
+// -----------------------------------------------------------------------------
+//
+void CCTPinQueryDialog::PreLayoutDynInitL()
+    {
+	SetMaxLength(iMaxTextLength);
+	SetPromptL(iDlgText);
+	CAknTextQueryDialog::PreLayoutDynInitL();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinQueryDialog::CheckIfEntryTextOk()
+// -----------------------------------------------------------------------------
+//
+TBool CCTPinQueryDialog::CheckIfEntryTextOk() const
+    {
+    CAknQueryControl* control = QueryControl();
+    if (control)
+        {
+        control->GetText(iDataText);
+        }
+    const TInt textLength = Text().Length();
+    return (textLength <= iMaxTextLength && textLength >= iMinTextLength);
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinQueryDialog::UpdateLeftSoftKeyL()
+// -----------------------------------------------------------------------------
+//
+void CCTPinQueryDialog::UpdateLeftSoftKeyL()
+    {
+    CAknTextQueryDialog::UpdateLeftSoftKeyL();
+    MakeLeftSoftkeyVisible(CheckIfEntryTextOk());
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinQueryDialog::PostLayoutDynInitL()
+// -----------------------------------------------------------------------------
+//
+void CCTPinQueryDialog::PostLayoutDynInitL()
+    {
+	((CEikServAppUi*)(CEikonEnv::Static())->EikAppUi())->SuppressAppSwitching(ETrue);
+    }
+// -----------------------------------------------------------------------------
+// CCTPinQueryDialog::OkToExitL()
+// -----------------------------------------------------------------------------
+//
+TBool CCTPinQueryDialog::OkToExitL( TInt aButtonId )
+    {
+
+    if ( aButtonId == EEikBidCancel || aButtonId == EAknSoftkeyNo )
+        {
+        iRetVal = EFalse;
+        User::RequestComplete(iClientStatus, KErrNone);   
+        }
+
+    else if ( aButtonId ==EAknSoftkeyYes || aButtonId == EAknSoftkeyOk)
+        {
+        CAknQueryControl* control = QueryControl();
+        if (control)
+            {
+            control->GetText(iPinValue);
+            }
+        iRetVal = ETrue;
+        User::RequestComplete(iClientStatus, KErrNone); 
+        }
+
+    return ETrue; 
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinQueryDialog::OfferKeyEventL()
+// -----------------------------------------------------------------------------
+//
+TKeyResponse CCTPinQueryDialog::OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+	// '#' key is inactive in Pin query dialog
+	if( (aKeyEvent.iScanCode == EStdKeyHash)  && (aType == EEventKeyDown || aType == EEventKeyUp) )
+	    { 
+		return EKeyWasConsumed;
+	    }
+	// '*' key is inactive in Pin query dialog
+	if (aKeyEvent.iCode == '*')
+	    {
+		return EKeyWasConsumed;
+	    }
+	return CAknTextQueryDialog::OfferKeyEventL(aKeyEvent, aType);
+    }
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/NotifSrc/DllMain.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2002-2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   DLL Entry Point
+*
+*/
+
+
+
+#include "CTSecurityDialogNotifier.h"
+#include <e32base.h>
+#include <eiknotapi.h>
+
+// Entry point for Notifiers
+EXPORT_C CArrayPtr<MEikSrvNotifierBase2>* NotifierArray()
+	{
+	//The notifierArray function CAN leave, despite no trailing L
+	CArrayPtrFlat<MEikSrvNotifierBase2>* subjects = new (ELeave) CArrayPtrFlat<MEikSrvNotifierBase2>( 1 );
+	CleanupStack::PushL(subjects);
+	CCTSecurityDialogNotifier* notifier = CCTSecurityDialogNotifier::NewL();
+	CleanupStack::PushL( notifier );
+	subjects->AppendL( notifier );
+	CleanupStack::Pop( 2,subjects);	//notifier, subjects
+	return subjects;
+	}
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/data/CTsecdlgs.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,879 @@
+/*
+* Copyright (c) 2002-2008 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Resource file for CT Security Dialog
+*
+*/
+
+
+//  INCLUDES
+
+#include <eikon.rh>
+#include <avkon.rsg>
+#include <avkon.hrh>
+#include <avkon.rh>
+#include <avkon.loc>
+#include <bldvariant.hrh>
+#include <certmanui.loc>
+#include <certsaver.loc>
+#include <wmlbrowser_wim.loc>
+
+
+//  RESOURCE IDENTIFIER
+
+NAME WIMS
+
+RESOURCE RSS_SIGNATURE { }
+
+RESOURCE TBUF { buf=""; }
+
+
+// -----------------------------------------------------------------------------
+//
+// r_wim_pin_query_dialog
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE DIALOG r_wim_pin_query_dialog
+  {
+  flags=EEikDialogFlagNotifyEsc | EEikDialogFlagVirtualInput;
+  buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+    {
+        DLG_LINE
+          {
+          type=EAknCtQuery;
+          id=EGeneralQuery;
+          control= AVKON_DATA_QUERY
+                {
+                layout = EPinLayout;
+                control = SECRETED
+                    {
+                    num_letters=4;
+                    };
+                };
+          }
+    };
+  }
+
+// -----------------------------------------------------------------------------
+//
+// r_wim_password_query_dialog
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE DIALOG r_wim_password_query_dialog
+  {
+  flags=EEikDialogFlagNotifyEsc | EEikDialogFlagVirtualInput;
+  buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+    {
+    DLG_LINE
+      {
+      type=EAknCtQuery;
+      id=EGeneralQuery;
+      control= AVKON_DATA_QUERY
+          {
+          label=r_qtn_cm_heading_phone_keystore;
+          layout = ECodeLayout;
+          control = SECRETED
+              {
+              num_letters=4;
+              };
+        };
+      }
+    };
+  }
+// -----------------------------------------------------------------------------
+//
+// r_wim_pinpin_query_dialog
+// Multiline data query for two PINs
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE DIALOG r_wim_pinpin_query_dialog
+  {
+  flags=EEikDialogFlagNotifyEsc;
+  buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+  items=
+    {
+    DLG_LINE
+      {
+      type=EAknCtMultilineQuery;
+      id=EMultilineFirstLine;
+      control= AVKON_DATA_QUERY
+        {
+        layout = EMultiDataFirstPinEd;
+        control = SECRETED
+            {
+            num_letters=4;
+            };
+        };
+      },
+    DLG_LINE
+      {
+      type=EAknCtMultilineQuery;
+      id=EMultilineSecondLine;
+      control= AVKON_DATA_QUERY
+          {
+          layout = EMultiDataSecondPinEd;
+          control = SECRETED
+            {
+            num_letters=4;
+            };
+        };
+      }
+    };
+  }
+// -----------------------------------------------------------------------------
+//
+// r_wim_pwpw_query_dialog
+// Multiline data query for two passwords
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE DIALOG r_wim_pwpw_query_dialog
+  {
+  flags=EEikDialogFlagNotifyEsc;
+  buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+  items=
+    {
+    DLG_LINE
+      {
+      type=EAknCtMultilineQuery;
+      id=EMultilineFirstLine;
+      control= AVKON_DATA_QUERY
+        {
+        layout = EMultiDataFirstSecEd;
+        control = SECRETED
+            {
+            num_letters=6;
+            };
+        };
+      },
+    DLG_LINE
+      {
+      type=EAknCtMultilineQuery;
+      id=EMultilineSecondLine;
+      control= AVKON_DATA_QUERY
+        {
+        layout = EMultiDataSecondSecEd;
+        control = SECRETED
+            {
+            num_letters=6;
+            };
+        };
+      }
+    };
+  }
+
+
+// -----------------------------------------------------------------------------
+//
+// r_wim_query_dialog
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE DIALOG r_wim_query_dialog
+  {
+  // Stolen from aknnotpi.rss, added EEikDialogFlagWait
+  flags =  EEikDialogFlagNoDrag | EEikDialogFlagNoTitleBar | EEikDialogFlagCbaButtons | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow | EEikDialogFlagNotifyEsc;
+  buttons = R_AVKON_SOFTKEYS_YES_NO__YES;
+    items =
+    {
+        DLG_LINE
+          {
+          type = EAknCtPopupHeadingPane;
+          id = EAknMessageQueryHeaderId;
+          control = AVKON_HEADING
+              {
+              };
+      },
+    DLG_LINE
+      {
+      type = EAknCtQuery;
+      id = EGeneralQuery;
+      control= AVKON_CONFIRMATION_QUERY
+        {
+          layout = EConfirmationLayout;
+          animation = R_QGN_NOTE_QUERY_ANIM;
+        };
+      }
+    };
+  }
+
+// -----------------------------------------------------------------------------
+//
+// r_wim_signtext_dialog
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE DIALOG r_wim_userauthtext_dialog
+  {
+  // Stolen from aknnotpi.rss, added EEikDialogFlagWait
+  flags = EEikDialogFlagNoDrag | EEikDialogFlagNoTitleBar | EEikDialogFlagCbaButtons | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow | EEikDialogFlagNotifyEsc;
+  buttons = r_wimdlg_softkey_accept_cancel;
+    items =
+    {
+        DLG_LINE
+          {
+          type = EAknCtPopupHeadingPane;
+          id = EAknMessageQueryHeaderId;
+          control = AVKON_HEADING
+              {
+              label= qtn_sn_auth_query_heading;
+              };
+          },
+      DLG_LINE
+          {
+          type = EAknCtMessageQuery;
+          id = EAknMessageQueryContentId;
+            control = AVKON_MESSAGE_QUERY
+              {
+              };
+        }
+    };
+  }
+
+// -----------------------------------------------------------------------------
+//
+// r_wim_signtext_dialog
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE DIALOG r_wim_signtext_dialog
+  {
+  // Stolen from aknnotpi.rss, added EEikDialogFlagWait
+  flags = EEikDialogFlagNoDrag | EEikDialogFlagNoTitleBar | EEikDialogFlagCbaButtons | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow | EEikDialogFlagNotifyEsc;
+  buttons = r_wimdlg_softkey_sign_cancel;
+    items =
+    {
+        DLG_LINE
+          {
+          type = EAknCtPopupHeadingPane;
+          id = EAknMessageQueryHeaderId;
+          control = AVKON_HEADING
+              {
+              label=qtn_wim_confirm_text;
+              };
+          },
+      DLG_LINE
+          {
+          type = EAknCtMessageQuery;
+          id = EAknMessageQueryContentId;
+          control = AVKON_MESSAGE_QUERY
+              {
+              };
+        }
+    };
+  }
+
+// -----------------------------------------------------------------------------
+//
+// r_wim_csr_dialog
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE DIALOG r_wim_csr_dialog
+  {
+  // Stolen from aknnotpi.rss, added EEikDialogFlagWait
+  flags = EEikDialogFlagNoDrag | EEikDialogFlagNoTitleBar | EEikDialogFlagCbaButtons | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow | EEikDialogFlagNotifyEsc;
+  buttons = r_wimdlg_softkey_accept_cancel;
+    items =
+    {
+        DLG_LINE
+          {
+          type = EAknCtPopupHeadingPane;
+          id = EAknMessageQueryHeaderId;
+          control = AVKON_HEADING
+              {
+              label=qtn_sn_cert_sign_heading;
+              };
+          },
+      DLG_LINE
+          {
+          type = EAknCtMessageQuery;
+          id = EAknMessageQueryContentId;
+          control = AVKON_MESSAGE_QUERY
+              {
+              };
+          }
+    };
+  }
+
+// -----------------------------------------------------------------------------
+//
+// r_wim_certdetails_dialog
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE DIALOG r_wim_certdetails_dialog
+  {
+  // Stolen from aknnotpi.rss, added EEikDialogFlagWait
+  flags = EEikDialogFlagNoDrag | EEikDialogFlagNoTitleBar | EEikDialogFlagCbaButtons | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow | EEikDialogFlagNotifyEsc;
+  buttons = R_AVKON_SOFTKEYS_OK_EMPTY__OK;
+    items =
+    {
+        DLG_LINE
+          {
+          type = EAknCtPopupHeadingPane;
+          id = EAknMessageQueryHeaderId;
+          control = AVKON_HEADING
+              {
+              label=qtn_cm_details_heading;
+              };
+          },
+      DLG_LINE
+          {
+          type = EAknCtMessageQuery;
+          id = EAknMessageQueryContentId;
+          control = AVKON_MESSAGE_QUERY
+              {
+              };
+        }
+    };
+  }
+
+// -----------------------------------------------------------------------------
+//
+// r_wim_delete_cert_dialog
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE DIALOG r_wim_delete_cert_dialog
+  {
+  // Stolen from aknnotpi.rss, added EEikDialogFlagWait
+  flags = EEikDialogFlagNoDrag | EEikDialogFlagNoTitleBar | EEikDialogFlagCbaButtons | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow | EEikDialogFlagNotifyEsc;
+  buttons = r_wimdlg_softkey_delete_cancel;
+    items =
+    {
+        DLG_LINE
+          {
+          type = EAknCtPopupHeadingPane;
+          id = EAknMessageQueryHeaderId;
+          control = AVKON_HEADING
+              {
+              label=qtn_sn_delete_cert_heading;
+              };
+          },
+      DLG_LINE
+          {
+          type = EAknCtMessageQuery;
+          id = EAknMessageQueryContentId;
+          control = AVKON_MESSAGE_QUERY
+              {
+              };
+          }
+    };
+  }
+
+// -----------------------------------------------------------------------------
+//
+// r_wim_save_cert_dialog
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE DIALOG r_wim_save_cert_dialog
+  {
+  // Stolen from aknnotpi.rss, added EEikDialogFlagWait
+  flags = EEikDialogFlagNoDrag | EEikDialogFlagNoTitleBar | EEikDialogFlagCbaButtons | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow | EEikDialogFlagNotifyEsc;
+  buttons = r_wimdlg_softkey_save_cancel;
+    items =
+    {
+        DLG_LINE
+          {
+          type = EAknCtPopupHeadingPane;
+          id = EAknMessageQueryHeaderId;
+          control = AVKON_HEADING
+              {
+              label=qtn_wmlsec_query_downl_cert;
+              };
+          },
+      DLG_LINE
+          {
+          type = EAknCtMessageQuery;
+          id = EAknMessageQueryContentId;
+          control = AVKON_MESSAGE_QUERY
+              {
+              };
+        }
+    };
+  }
+// -----------------------------------------------------------------------------
+//
+// r_wim_unblock_info_dialog
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE DIALOG r_wim_unblock_info_dialog
+  {
+  // Stolen from aknnotpi.rss, added EEikDialogFlagWait
+  flags = EEikDialogFlagNoDrag | EEikDialogFlagNoTitleBar | EEikDialogFlagCbaButtons | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow | EEikDialogFlagNotifyEsc;
+  buttons = R_AVKON_SOFTKEYS_OK_EMPTY__OK;
+    items =
+    {
+        DLG_LINE
+          {
+          type = EAknCtPopupHeadingPane;
+          id = EAknMessageQueryHeaderId;
+          control = AVKON_HEADING
+              {
+              //label=qtn_wim_confirm_text;
+              label=qtn_wim_err_pin_blocked;
+              };
+          },
+      DLG_LINE
+          {
+          type = EAknCtMessageQuery;
+          id = EAknMessageQueryContentId;
+          control = AVKON_MESSAGE_QUERY
+              {
+              };
+        }
+    };
+  }
+
+// -----------------------------------------------------------------------------
+// R_NO_TRUST_QUERY
+// -----------------------------------------------------------------------------
+RESOURCE DIALOG r_wim_no_trust_query
+    {
+    // Query needs to be asynchronous -> no wait flag
+    // Notify esc flag is needed for OkToExitL() call when cancel key is pressed
+
+    flags = EEikDialogFlagNoDrag |
+            EEikDialogFlagNoTitleBar |
+            EEikDialogFlagCbaButtons |
+            EEikDialogFlagNotifyEsc;
+
+    buttons = r_wim_no_trust_query_softkeys;
+    items =
+        {
+        DLG_LINE
+            {
+            type = EAknCtQuery;
+            id = EGeneralQuery;
+            control= AVKON_CONFIRMATION_QUERY
+                {
+                layout = EConfirmationLayout;
+                label = qtn_ics_ssl_conf_q_continue;
+                };
+            }
+        };
+    }
+
+// -----------------------------------------------------------------------------
+// R_NO_TRUST_QUERY_OOD
+// -----------------------------------------------------------------------------
+RESOURCE DIALOG r_wim_no_trust_query_ood
+    {
+    // Query needs to be asynchronous -> no wait flag
+    // Notify esc flag is needed for OkToExitL() call when cancel key is pressed
+
+    flags = EEikDialogFlagNoDrag |
+            EEikDialogFlagNoTitleBar |
+            EEikDialogFlagCbaButtons |
+            EEikDialogFlagNotifyEsc;
+
+    buttons = r_wim_no_trust_query_softkeys;
+    items =
+        {
+        DLG_LINE
+            {
+            type = EAknCtQuery;
+            id = EGeneralQuery;
+            control= AVKON_CONFIRMATION_QUERY
+                {
+                layout = EConfirmationLayout;
+                label = qtn_ics_ssl_conf_q_accept_ood;
+                };
+            }
+        };
+    }
+
+// -----------------------------------------------------------------------------
+// R_NO_TRUST_QUERY_UNTRUSTED
+// -----------------------------------------------------------------------------
+RESOURCE DIALOG r_wim_no_trust_query_untrusted
+    {
+    // Query needs to be asynchronous -> no wait flag
+    // Notify esc flag is needed for OkToExitL() call when cancel key is pressed
+
+    flags = EEikDialogFlagNoDrag |
+            EEikDialogFlagNoTitleBar |
+            EEikDialogFlagCbaButtons |
+            EEikDialogFlagNotifyEsc;
+
+    buttons = r_wim_no_trust_query_softkeys;
+    items =
+        {
+        DLG_LINE
+            {
+            type = EAknCtQuery;
+            id = EGeneralQuery;
+            control= AVKON_CONFIRMATION_QUERY
+                {
+                layout = EConfirmationLayout;
+                label = qtn_ics_ssl_conf_q_accept_untrusted;
+                };
+            }
+        };
+    }
+
+
+// -----------------------------------------------------------------------------
+// R_NO_TRUST_QUERY_SITE
+// -----------------------------------------------------------------------------
+RESOURCE DIALOG r_wim_no_trust_query_site
+    {
+    // Query needs to be asynchronous -> no wait flag
+    // Notify esc flag is needed for OkToExitL() call when cancel key is pressed
+
+    flags = EEikDialogFlagNoDrag |
+            EEikDialogFlagNoTitleBar |
+            EEikDialogFlagCbaButtons |
+            EEikDialogFlagNotifyEsc;
+
+    buttons = r_wim_no_trust_query_softkeys;
+    items =
+        {
+        DLG_LINE
+            {
+            type = EAknCtQuery;
+            id = EGeneralQuery;
+            control= AVKON_CONFIRMATION_QUERY
+                {
+                layout = EConfirmationLayout;
+                label = qtn_ics_ssl_conf_q_accept_site;
+                };
+            }
+        };
+    }
+
+// -----------------------------------------------------------------------------
+// R_WIM_INVALID_CERTIFICATE_INFORMATION_NOTE
+// -----------------------------------------------------------------------------
+RESOURCE DIALOG r_wim_invalid_certificate_information_note
+    {
+    // Query needs to be asynchronous -> no wait flag
+    // Notify esc flag is needed for OkToExitL() call when cancel key is pressed
+
+    flags = EEikDialogFlagNoDrag |
+            EEikDialogFlagNoTitleBar |
+            EEikDialogFlagCbaButtons |
+            EEikDialogFlagNotifyEsc;
+
+    buttons = r_wim_invalid_cert_softkeys;
+    items =
+        {
+        DLG_LINE
+            {
+            type = EAknCtNote;
+            id = EGeneralNote;
+            control= AVKON_NOTE
+                {
+                layout = EGeneralLayout;
+                singular_label = qtn_ics_ssl_conf_q_accept_signature;
+                };
+            }
+        };
+    }
+
+// -----------------------------------------------------------------------------
+// R_CERTIFICATE_QUERY
+// -----------------------------------------------------------------------------
+
+RESOURCE DIALOG r_notrust_certificate_query
+    {
+    flags = EGeneralQueryFlags |
+            EEikDialogFlagNoBorder |
+            EEikDialogFlagNoShadow |
+            EEikDialogFlagNotifyEsc;
+
+    buttons = R_AVKON_SOFTKEYS_CLOSE;
+    items =
+        {
+        DLG_LINE
+            {
+            type = EAknCtPopupHeadingPane;
+            id = EAknMessageQueryHeaderId;
+            control = AVKON_HEADING
+                {
+                };
+            },
+        DLG_LINE
+            {
+            type = EAknCtMessageQuery;
+            id = EAknMessageQueryContentId;
+            control = AVKON_MESSAGE_QUERY
+                {
+                };
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//    r_certsaver_trusted_site_query
+//    Multiselection list query for trusted site
+//    certificate.
+//
+//----------------------------------------------------
+//
+RESOURCE DIALOG r_httpsec_query_perm_accept
+    {
+    flags = EGeneralQueryFlags | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow;
+    buttons = R_AVKON_SOFTKEYS_YES_NO;
+    items=
+         {
+        DLG_LINE
+              {
+            type = EAknCtPopupHeadingPane;
+            id = EAknMessageQueryHeaderId;
+            control = AVKON_HEADING
+                    {
+                    label = qtn_httpsec_query_perm_accept_title;
+                    };
+            },
+         DLG_LINE
+              {
+              type = EAknCtMessageQuery;
+              id = EAknMessageQueryContentId;
+              control = AVKON_MESSAGE_QUERY
+                    {
+                     };
+              }
+        };
+    }
+
+// -----------------------------------------------------------------------------
+//
+// r_wim_select_certificate_dialog
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE AVKON_LIST_QUERY r_wim_select_certificate_dialog
+    {
+  flags = EEikDialogFlagNotifyEsc;
+    softkeys = R_AVKON_SOFTKEYS_SELECT_CANCEL__SELECT;
+    items =
+      {
+      AVKON_LIST_QUERY_DLG_LINE
+          {
+          control = AVKON_LIST_QUERY_CONTROL
+            {
+            listtype = EAknCtSinglePopupMenuListBox;
+            listbox = AVKON_LIST_QUERY_LIST
+                {
+                array_id=0;
+                };
+            heading = qtn_wim_select_cert;
+            };
+          }
+      };
+    }
+
+// -----------------------------------------------------------------------------
+//
+// r_wimdlg_softkey_accept_reject
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE CBA r_wimdlg_softkey_accept_cancel
+    {
+  buttons=
+      {
+      CBA_BUTTON {id=EAknSoftkeyYes; txt=text_softkey_accept; },
+      CBA_BUTTON {id=EAknSoftkeyNo; txt=text_softkey_cancel; },
+      CBA_BUTTON {id=EAknSoftkeyYes; txt=text_softkey_accept; }
+      };
+    }
+
+// -----------------------------------------------------------------------------
+//
+// r_wimdlg_softkey_accept_reject
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE CBA r_wimdlg_softkey_save_cancel
+    {
+  buttons=
+      {
+      CBA_BUTTON {id=EAknSoftkeyYes; txt=text_softkey_save; },
+      CBA_BUTTON {id=EAknSoftkeyNo; txt=text_softkey_cancel; },
+      CBA_BUTTON {id=EAknSoftkeyYes; txt=text_softkey_save; }
+      };
+    }
+// -----------------------------------------------------------------------------
+//
+// r_wimdlg_softkey_accept_reject
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE CBA r_wimdlg_softkey_delete_cancel
+    {
+  buttons=
+      {
+      CBA_BUTTON {id=EAknSoftkeyYes; txt=qtn_sn_softkey_delete; },
+      CBA_BUTTON {id=EAknSoftkeyNo; txt=text_softkey_cancel; },
+      CBA_BUTTON {id=EAknSoftkeyYes; txt=qtn_sn_softkey_delete; }
+      };
+    }
+
+// -----------------------------------------------------------------------------
+//
+// r_wimdlg_softkey_sign_cancel
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE CBA r_wimdlg_softkey_sign_cancel
+    {
+  buttons=
+      {
+      CBA_BUTTON {id=EAknSoftkeyYes; txt=gtn_wim_softk_dsign_sign; },
+      CBA_BUTTON {id=EAknSoftkeyNo; txt=text_softkey_cancel; },
+      CBA_BUTTON {id=EAknSoftkeyYes; txt=gtn_wim_softk_dsign_sign; }
+      };
+    }
+
+// -----------------------------------------------------------------------------
+// R_NO_TRUST_QUERY_SOFTKEYS
+// -----------------------------------------------------------------------------
+
+RESOURCE CBA r_wim_no_trust_query_softkeys
+    {
+    buttons =
+        {
+        CBA_BUTTON { id = EAknSoftkeyOptions; txt = text_softkey_option; },
+        CBA_BUTTON { id = EAknSoftkeyCancel; txt = text_softkey_back; },
+        CBA_BUTTON { id = EAknSoftkeyOptions; txt = text_softkey_option; }
+        };
+    }
+
+// -----------------------------------------------------------------------------
+// R_INVALID_CERT_SOFTKEYS
+// -----------------------------------------------------------------------------
+
+RESOURCE CBA r_wim_invalid_cert_softkeys
+    {
+    buttons =
+        {
+        CBA_BUTTON { id = EAknSoftkeyClose; txt = text_softkey_close; },
+        CBA_BUTTON { id = EAknSoftkeyShow; txt = text_softkey_details; },
+        CBA_BUTTON { id = EAknSoftkeyClose; txt = text_softkey_close; }
+        };
+    }
+
+// -----------------------------------------------------------------------------
+// R_NOTRUST_MENUPANE
+// -----------------------------------------------------------------------------
+RESOURCE ARRAY r_notrust_menupane
+  {
+  items =
+    {
+    LBUF { txt = qtn_httpsec_opt_menu_accept_now;   },
+    LBUF { txt = qtn_httpsec_opt_menu_accept_perm;  },
+    LBUF { txt = qtn_httpsec_opt_menu_details;  }
+    };
+  }
+  
+// -----------------------------------------------------------------------------
+// R_NOTRUST_MENUPANE_NO_PERM
+// -----------------------------------------------------------------------------  
+RESOURCE ARRAY r_notrust_menupane_no_perm
+  {
+  items =
+    {
+    LBUF { txt = qtn_httpsec_opt_menu_accept_now;   },
+    LBUF { txt = qtn_httpsec_opt_menu_details;  }
+    };
+  }
+
+RESOURCE TBUF r_qtn_wim_select_cert { buf=qtn_wim_select_cert; }
+
+RESOURCE TBUF r_qtn_wim_prmt_gen_wim_pin { buf=qtn_wim_prmt_gen_wim_pin; }
+
+RESOURCE TBUF r_qtn_wim_info_digit_sign_req { buf=qtn_wim_info_digit_sign_req; }
+
+RESOURCE TBUF r_qtn_sn_authentication_note { buf=qtn_sn_authentication_note; }
+
+RESOURCE TBUF r_qtn_wim_confirm_text { buf=qtn_wim_confirm_text; }
+
+RESOURCE TBUF r_qtn_wim_not_available { buf=qtn_wim_not_available; }
+
+RESOURCE TBUF r_qtn_wim_err_wrong_pin { buf=qtn_wim_err_wrong_pin; }
+
+RESOURCE TBUF r_qtn_wim_info_pin_unblocked { buf=qtn_wim_info_pin_unblocked; }
+
+RESOURCE TBUF r_qtn_wim_err_pin_blocked { buf=qtn_wim_err_pin_blocked; }
+
+RESOURCE TBUF r_qtn_wim_pin_totalblocked { buf=qtn_wim_pin_totalblocked; }
+
+RESOURCE TBUF r_qtn_wim_wrong_unblock_code { buf=qtn_wim_wrong_unblock_code; }
+
+RESOURCE TBUF r_qtn_wim_pin_unblock_query { buf=qtn_wim_pin_unblock_query; }
+
+RESOURCE TBUF r_qtn_wim_new_pin { buf=qtn_wim_new_pin; }
+
+RESOURCE TBUF r_qtn_wim_verify_pin { buf=qtn_wim_verify_pin; }
+
+RESOURCE TBUF r_qtn_wim_err_codes_do_not_match { buf=qtn_wim_err_codes_do_not_match; }
+
+RESOURCE TBUF r_qtn_wim_sign_cancelled { buf=qtn_wim_sign_cancelled; }
+
+RESOURCE TBUF r_qtn_wim_info_signature_made { buf=qtn_wim_info_signature_made; }
+
+RESOURCE TBUF r_qtn_wim_unblock_info { buf=qtn_wim_unblock_info; }
+
+RESOURCE TBUF r_qtn_wim_err_io_error { buf=qtn_wim_err_io_error; }
+
+RESOURCE TBUF r_qtn_wim_no_matching_certificate { buf=qtn_wim_no_matching_certificate; }
+
+RESOURCE TBUF r_qtn_cm_creating_keystore { buf=qtn_cm_creating_keystore; }
+
+RESOURCE TBUF r_qtn_cm_heading_phone_keystore { buf=qtn_cm_heading_phone_keystore; }
+
+RESOURCE TBUF r_qtn_cm_title_p12_password { buf=qtn_cm_title_p12_password; }
+
+RESOURCE TBUF r_qtn_wim_receipt_saved { buf=qtn_wim_receipt_saved; }
+
+RESOURCE TBUF r_qtn_sn_cert_sign_explanation  { buf=qtn_sn_cert_sign_explanation ; }
+
+RESOURCE TBUF r_qtn_sn_prompt_import_key { buf=qtn_sn_prompt_import_key; }
+
+RESOURCE TBUF r_qtn_sn_prompt1_create_code { buf=qtn_sn_prompt1_create_code; }
+
+RESOURCE TBUF r_qtn_sn_enter_phone_keystore { buf=qtn_sn_enter_phone_keystore; }
+
+RESOURCE TBUF r_qtn_sn_new_phone_keystore { buf=qtn_sn_new_phone_keystore; }
+
+RESOURCE TBUF r_qtn_httpsec_query_perm_accept_text { buf=qtn_httpsec_query_perm_accept_text; }
+
+RESOURCE TBUF r_qtn_cm_site { buf=qtn_cm_site; }
+
+// End of file
Binary file pkiutilities/CTSecurityDialogs/data/qgn_stat_dsign.bmp has changed
Binary file pkiutilities/CTSecurityDialogs/data/qgn_stat_dsign_mask.bmp has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/eabi/CTSecDilogImplU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	_Z13NotifierArrayv @ 1 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/eabi/CTSecDlgsU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	_ZN16PKIDialogFactory11CreateNoteLEv @ 1 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/ecomsrc/10008D4F.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  App-framework notifier plug-in resource file.
+*
+*/
+
+
+#include <ecom/registryinfov2.rh>
+#include <uikon.hrh>
+
+RESOURCE REGISTRY_INFO r_registry
+	{
+	resource_format_version = RESOURCE_FORMAT_VERSION_2;
+	dll_uid = 0x10008D4F; //should match name of this file
+	interfaces =
+		{
+		INTERFACE_INFO
+			{
+			interface_uid = KUikonUidPluginInterfaceNotifiers;  // need to create this uid in the uid database
+			implementations =
+				{
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x101F883C;
+					version_no = 1;
+					display_name = "CTSecurityDialogs Plugin";
+					default_data = "CTSecurityDialogs";    
+					opaque_data = "0";
+					rom_only = 1;	// This plugin can be loaded only from ROM										
+					}
+				};
+			}
+		};
+	} 
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/ecomsrc/CTSecDlgWrapper.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,107 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   CTSecDlgWrapper.cpp
+*
+*/
+
+
+// INCLUDE FILES
+#include <ecom/implementationproxy.h>
+#include <AknNotifierWrapper.h> // link against aknnotifierwrapper.lib
+#include <secdlgimpldefs.h>
+#include "CTSecurityDialogDefs.h"
+
+// CONSTANTS
+const TInt KMyPriority =  MEikSrvNotifierBase2::ENotifierPriorityAbsolute;
+ 
+// ---------------------------------------------------------
+// CleanupArray()
+// ---------------------------------------------------------
+//
+void CleanupArray( TAny* aArray )
+    {
+    CArrayPtrFlat<MEikSrvNotifierBase2>* subjects = 
+                static_cast<CArrayPtrFlat<MEikSrvNotifierBase2>*>( aArray );
+        
+    TInt lastInd = subjects->Count()-1;
+    
+    for ( TInt i = lastInd; i >= 0; i-- )
+        {            
+        subjects->At( i )->Release();	    	    
+        }
+        
+    delete subjects;
+    }
+    
+// ---------------------------------------------------------
+// DoCreateNotifierArrayL()
+// ---------------------------------------------------------
+//
+CArrayPtr<MEikSrvNotifierBase2>* DoCreateNotifierArrayL()
+    {
+    CArrayPtrFlat<MEikSrvNotifierBase2>* subjects =
+        new ( ELeave )CArrayPtrFlat<MEikSrvNotifierBase2>( 1 );
+    
+    CleanupStack::PushL( TCleanupItem( CleanupArray, subjects ) );
+
+    // Create Wrappers
+
+    // Session owning notifier(if default implementation is enough)
+    CAknCommonNotifierWrapper* master = 
+        CAknCommonNotifierWrapper::NewL( KUidSecurityDialogNotifier,
+                                   KUidSecurityDialogNotifier,
+                                   KMyPriority,
+                                   _L("CTSecDialogImpl.dll"),
+                                   1 ); // we don't use synch reply                               
+	  	
+    CleanupStack::PushL( master );   
+    subjects->AppendL( master );
+    CleanupStack::Pop( master );
+    
+    CleanupStack::Pop();	// array cleanup
+    return( subjects );
+    }
+
+// ---------------------------------------------------------
+// NotifierArray()
+// ---------------------------------------------------------
+//
+CArrayPtr<MEikSrvNotifierBase2>* NotifierArray()
+    // old Lib main entry point
+    {
+    CArrayPtr<MEikSrvNotifierBase2>* array = 0;
+    TRAP_IGNORE( array = DoCreateNotifierArrayL() ); 	
+    return array;
+    }
+
+// ---------------------------------------------------------
+// ImplementationTable
+// ---------------------------------------------------------
+//
+const TImplementationProxy ImplementationTable[] =
+	{
+	{{0x101F883C},(TProxyNewLPtr)NotifierArray}
+	};
+// ---------------------------------------------------------
+// ImplementationGroupProxy
+// entry point
+// ---------------------------------------------------------
+//
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+	{
+	aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy) ;
+	return ImplementationTable;
+	}
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CTSecurityDialogs/loc/wmlbrowser_wim.loc	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,324 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is a localisation file of CTSecurityDialogs.
+*               Used only in WIM enabled build.
+*
+*/
+
+
+	
+//	Included localisation string resource headers
+
+//  LOCALISATION STRINGS
+
+
+//d:Header text of list query during personal certificates.
+//l:heading_pane_t1
+//w:
+//r:2.6 
+#define qtn_wim_select_cert             "Matching certificates:"
+
+//d:Data query for PIN request in keystore where %0U is the PIN's name %1U is the keystore's name.
+//l:popup_query_code_window
+//w:
+//r:2.6
+#define qtn_wim_prmt_gen_wim_pin         "Enter code for %0U in %1U"
+
+//d:When digital signature is needed from the user.
+//l:popup_note_window
+//w:
+//r:2.6
+#define qtn_wim_info_digit_sign_req     "Digital signature requested"
+
+//d:Digital signing query pop up window
+//l:heading_pane_t1
+//w:
+//r:2.6
+#define qtn_wim_confirm_text            "Read and sign"
+
+//d:Security module error note
+//d:Shown if Security Module not available
+//l:popup_note_window
+//w:
+//r:2.6
+#define qtn_wim_not_available "Security module unavailable" 
+
+//d:When the user entered wrong PIN to the secure password dialog
+//l:popup_note_window
+//w:
+//r:2.6
+#define qtn_wim_err_wrong_pin           "Code incorrect"
+
+//d:Confirmation note shown after code unblock
+//d:
+//l:popup_note_window
+//w:
+//r:2.6
+#define qtn_wim_info_pin_unblocked "Code unblocked"
+
+//d:PIN code unblocked information note
+//l:popup_note_window
+//w:
+//r:2.6
+#define qtn_wim_err_pin_blocked         "%U is blocked. PUK code is needed to unblock the code"
+
+//d:Entered unblocking code was incorrect
+//l:popup_note_window
+//w:
+//r:2.6
+#define qtn_wim_wrong_unblock_code      "Unblocking code incorrect"
+
+//d:prompt text for unblocking pin code in keystore where %0U is the PIN's name %1U is the keystore's name.
+//l:popup_query_code_window
+//w:
+//r:2.6
+#define qtn_wim_pin_unblock_query       "Enter unblocking code for %0U in %1U:"
+
+//d:New PIN code query prompt text
+//l:popup_query_code_window/opt1
+//w:
+//r:2.6
+#define qtn_wim_new_pin                 "Enter new code for: \n%U"
+
+//d:New PIN code verification query prompt text
+//l:popup_query_code_window/opt1
+//w:
+//r:2.6
+#define qtn_wim_verify_pin              "Verify new code:"
+
+//d:If the new PIN-G code and its verification do not match
+//l:popup_note_window
+//w:
+//r:2.6
+#define qtn_wim_err_codes_do_not_match  "Codes do not match"
+
+//d:Digital Signatures prompt text
+//l:popup_note_window
+//w:
+//r:2.6
+#define qtn_wim_sign_cancelled			"Digital signing cancelled"
+
+//d:After the user has entered correct PIN-NR to the query
+//l:popup_note_window
+//w:
+//r:2.6
+#define qtn_wim_info_signature_made		"Digital signature done" 
+
+//d:Digital sign dialog left softkey text 
+//l:control_pane_t1/opt7
+//w:
+//r:2.6
+#define gtn_wim_softk_dsign_sign				 "Sign"
+
+//d:Detailed instructions about unblocking
+//l:popup_info_list_pane_t1
+//w:
+//r:2.6
+#define qtn_wim_unblock_info                    "To unblock %U, a PUK code from your security module's manufacturer is needed."
+
+//d:Security module error note
+//d:Internal error with Security module
+//l:popup_note_window
+//w:
+//r:2.6
+#define qtn_wim_err_io_error "Security module internal error" 
+
+//d:Detailed instructions about unblocking
+//l:popup_note_window
+//w:
+//r:2.6
+#define qtn_wim_no_matching_certificate         "Unable to sign. Matching certificate not found"
+
+//d:Receipt saving confirmation query
+//l:popup_note_window
+//w:
+//r:2.6
+#define qtn_wim_receipt_saved                   "Signed text saved to Notepad"
+
+//d:Keystore password creation note.
+//l:popup_note_window
+//w:
+//r:2.8
+#define qtn_cm_creating_keystore                "Keystore password must be created for using private keys."
+
+//d:Heading of the file keystore password query
+//l:heading_pane_t1
+//w:
+//r:2.8
+#define qtn_cm_heading_phone_keystore           "Phone keystore"
+
+//d:Heading of user authentication query pop up window
+//l:heading_pane_t1
+//w:
+//r:3.0
+#define qtn_sn_auth_query_heading           "Authentication request:"
+
+//d:Heading of certificate signing request query pop up window
+//l:heading_pane_t1
+//w:
+//r:3.0
+#define qtn_sn_cert_sign_heading           "Certificate signing request"
+
+//d:User authentication pop up note
+//l:popup_note_window
+//w:
+//r:3.0
+#define qtn_sn_authentication_note	    "User authentication requested"
+
+//d:Delete certificate query left softkey text 
+//l:control_pane_t1/opt7
+//w:
+//r:3.0
+#define qtn_sn_softkey_delete		    "Delete"
+
+//d:Heading of delete certificate query pop up window
+//l:heading_pane_t1
+//w:
+//r:3.0
+#define qtn_sn_delete_cert_heading	    "Delete certificate:"
+
+//d:Explanation text in the certificate signing request message query
+//l:popup_info_list_pane_t1
+//w:
+//r:3.0
+#define qtn_sn_cert_sign_explanation "This new personal certificate is requested from certificate authority"
+
+//d:Information note text
+//d:Shown when PIN is total blocked
+//l:popup_note_window
+//w:
+//r:3.0
+#define qtn_wim_pin_totalblocked "%U totalblocked, contact your module vendor."
+
+// d:Prompt for a confirmation query for continuing when a site has sent a
+// d:non-trusted certificate.
+// l:popup_note_window
+// w:
+// r:3.0
+#define qtn_ics_ssl_conf_q_continue "This site has sent a not trusted certificate. Continue anyway?"
+
+// d:Command in options menu.
+// d:Continues secured connection creation process, despite the fact that
+// d:server certificate was not from trusted source.
+// l:list_single_pane_t1_cp2
+// w:
+// r:3.0
+#define qtn_httpsec_opt_menu_continue "Continue"
+
+
+// d:Command in options menu.
+// d:Opens the certificate details view.
+// l:list_single_pane_t1_cp2
+// w:
+// r:3.0
+#define qtn_httpsec_opt_menu_details "Details"
+
+//d:Imported key password query prompt
+//l:popup_query_code_window
+//w:
+//r:3.0
+#define qtn_sn_prompt_import_key "Enter code for imported key:"
+
+//d:Imported key password query prompt
+//l:popup_query_code_window/opt1
+//w:
+//r:3.0
+#define qtn_sn_prompt1_create_code "Enter new code for exported key:"
+
+//d:Phone key store password query prompt
+//l:popup_query_code_window
+//w:
+//r:3.0
+#define qtn_sn_enter_phone_keystore "Enter code for phone keystore:"
+
+//d:Imported key password query prompt
+//l:popup_query_code_window/opt1
+//w:
+//r:3.0
+#define qtn_sn_new_phone_keystore "Enter new code for phone keystore:"
+
+
+//d:Item in the context menu for accepting server
+//d:certificate temporarily
+//l:list_single_pane_t1_cp2
+//w:
+//r:3.2
+//
+#define qtn_httpsec_opt_menu_accept_now		"Accept now"
+
+
+//d:Item in the context menu for accepting server
+//d:certificate permanently
+//l:list_single_pane_t1_cp2
+//w:
+//r:3.2
+//
+#define qtn_httpsec_opt_menu_accept_perm		"Accept permanently"
+
+
+//d::Title of Permanent accept query
+//l:title_pane_t2/opt9
+//w:
+//r:3.2
+//
+#define qtn_httpsec_query_perm_accept_title		"Permanent access"
+
+
+//d:Confirmation query text of Permanent accept query.
+//d:%U stands for the name of the site where the connection is
+//d:requested.
+//l:popup_note_window
+//w:
+//r:3.2
+//
+#define qtn_httpsec_query_perm_accept_text		"Connection to site %U will be made in future without any warnings. Continue?"
+
+
+//d:Confirmation query text shown if the server certificate contains 
+//d:site name that does not match to the one that was given in request the query contains text
+//l:popup_note_window
+//w:
+//r:3.2
+//
+#define qtn_ics_ssl_conf_q_accept_site		"This site has sent a certificate with different site name than requested. Accept anyway?"
+
+
+//d:Confirmation query text shown if the server certificate is out-of date
+//l:popup_note_window
+//w:
+//r:3.2
+//
+#define qtn_ics_ssl_conf_q_accept_ood		"This site has sent a certificate which is out of date. Accept anyway?"
+
+
+//d:Confirmation query text shown if the server certificate issued by unknown 
+//d:Certification Authority
+//l:popup_note_window
+//w:
+//r:3.2
+//
+#define qtn_ics_ssl_conf_q_accept_untrusted		"This site has sent an untrusted certificate. Accept anyway?"
+
+//d:Information note text shown if the server certificate has an invalid signature
+//d:Softkeys are SK1 'Close' (text_softkey_close) and SK2 'Details' (text_softkey_details)
+//d:Certification Authority
+//l:popup_note_window
+//w:
+//r:5.0
+//
+#define qtn_ics_ssl_conf_q_accept_signature     "This site has sent an invalid certificate. Connection cannot be created."
+
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/aif/CertSaveraif.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*     This file contains all the aif resources for the module.
+*     CertSaver
+*
+*/
+
+
+//  RESOURCE IDENTIFIER
+NAME    CSAF
+
+//  INCLUDES
+#include <aiftool.rh>
+
+RESOURCE AIF_DATA
+    {
+    app_uid=0x100059D2;
+
+    num_icons=0;
+    newfile=KAppDoesNotSupportNewFile;
+    embeddability = KAppEmbeddableOnly;
+    hidden=KAppIsHidden;
+
+    datatype_list=
+        {
+        DATATYPE
+            {
+            priority = EDataTypePriorityHigh;
+            type = "application/x-x509-ca-cert";
+            },
+        DATATYPE
+            {
+            priority = EDataTypePriorityHigh;
+            type = "application/x-pkcs12";
+            }
+        };
+    }
+ 
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/data/CertSaver.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,477 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Resource definitions for CertSaver
+*
+*/
+
+
+
+//  RESOURCE IDENTIFIER
+NAME    CESA // 4 letter ID
+
+//  INCLUDES
+#include <eikon.rh>
+#include <eikon.rsg>
+#include <avkon.rsg>
+#include <avkon.hrh>
+#include <avkon.rh>
+#include <avkon.mbg>
+#include <avkon.loc>
+#include <appinfo.rh>
+#include <certmanui.loc>  //qtn_cm_not_valid_yet
+#include <certsaver.loc>
+#include "certsaver.hrh"
+
+//  CONSTANTS
+
+//  MACROS
+
+//  RESOURCE DEFINITIONS
+
+RESOURCE RSS_SIGNATURE { }
+
+RESOURCE TBUF { buf="CertSaver"; }
+
+RESOURCE EIK_APP_INFO
+    {
+    }
+
+RESOURCE LOCALISABLE_APP_INFO r_certsaver_localisable_app_info
+    {
+    short_caption = qtn_certsaver_app_title;
+    caption_and_icon =
+    CAPTION_AND_ICON_INFO
+        {
+        caption = qtn_certsaver_app_title;
+        number_of_icons = 0;
+        };
+    }
+
+
+
+//----------------------------------------------------
+//
+//    Resource buffers.
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_certsaver_memory { buf=qtn_memlo_not_enough_memory; }
+RESOURCE TBUF r_certsaver_cert_discarded { buf=qtn_wmlsec_certificate_discarded; }
+RESOURCE TBUF r_certsaver_details_heading { buf=qtn_wmlsec_query_downl_cert; }
+RESOURCE TBUF r_certsaver_text_label { buf=qtn_wmlsec_cert_subject; }
+RESOURCE TBUF r_certsaver_text_issuer { buf=qtn_wmlsec_scert_issuer; }
+RESOURCE TBUF r_certsaver_text_fingerprint { buf=qtn_cm_fingerprint "\n%U"; }
+RESOURCE TBUF r_certsaver_text_fingerprint_md5 { buf=qtn_cm_fingerprint_md "\n%U"; }
+RESOURCE TBUF r_certsaver_text_validity { buf=qtn_wmlsec_cert_validity; }
+RESOURCE TBUF r_certsaver_error_saveok { buf=qtn_wmlsec_certificate_saved; }
+RESOURCE TBUF r_certsaver_error_unsupported_cert { buf=qtn_wmlsec_cert_unsupported; }
+RESOURCE TBUF r_certsaver_error_already_exists { buf=qtn_wmlsec_cert_duplicate; }
+RESOURCE TBUF r_certsaver_error_label_already_exists { buf = qtn_cm_label_already_exist; }
+RESOURCE TBUF r_certsaver_error_cert_corrupted { buf=qtn_wmlsec_cert_corrupted; }
+RESOURCE TBUF r_certsaver_error_cert_not_valid { buf=qtn_wmlsec_dload_expired_cert;}
+RESOURCE TBUF r_certsaver_error_cert_not_valid_yet { buf = qtn_cm_not_valid_yet; }
+RESOURCE TBUF r_certsaver_error_cacerts_db_corrupted { buf = qtn_memlo_database_corrupted; }
+RESOURCE TBUF r_certsaver_enter_label { buf = qtn_certsaver_enter_label; }
+RESOURCE TBUF r_certsaver_select_trusted_apps { buf = qtn_cm_select_trusted_apps; }
+RESOURCE TBUF r_certsaver_item_mail_image_conn { buf = qtn_cm_list_mail_image_conn; }
+RESOURCE TBUF r_certsaver_item_ocsp { buf = qtn_cm_list_ocsp; }
+RESOURCE TBUF r_certsaver_item_vpn { buf = qtn_cm_list_vpn; }
+
+RESOURCE TBUF r_certsaver_header_pkcs12_file_contains { buf = qtn_cm_header_pkcs12_file_contains; }
+RESOURCE TBUF r_certsaver_private_keys { buf = qtn_cm_private_keys; }
+RESOURCE TBUF r_certsaver_personal_certificates { buf = qtn_cm_personal_certificates; }
+RESOURCE TBUF r_certsaver_authority_certificates { buf = qtn_cm_authority_certificates; }
+RESOURCE TBUF r_certsaver_pkcs12_discarded { buf = qtn_cm_pkcs12_discarded; }
+
+RESOURCE TBUF r_certsaver_private_key_corrupted { buf = qtn_cm_private_key_corrupted; }
+RESOURCE TBUF r_certsaver_key_type_not_supported { buf = qtn_cm_key_type_not_supported; }
+RESOURCE TBUF r_certsaver_keystore_corrupted { buf = qtn_cm_keystore_corrupted; }
+RESOURCE TBUF r_certsaver_pkcs12_file_corrupted { buf = qtn_cm_pkcs12_file_corrupted; }
+RESOURCE TBUF r_certsaver_header_saved { buf = qtn_cm_header_saved; }
+RESOURCE TBUF r_qtn_cm_title_p12_password { buf = qtn_cm_title_p12_password; }
+RESOURCE TBUF r_qtn_cm_incorrect_password { buf = qtn_cm_incorrect_password; }
+RESOURCE TBUF r_qtn_cm_pkcs12_saving_failed { buf = qtn_cm_pkcs12_saving_failed; }
+RESOURCE TBUF r_certsaver_qtn_cm_valid_from { buf=qtn_cm_valid_from; }
+RESOURCE TBUF r_certsaver_qtn_cm_valid_until { buf=qtn_cm_valid_until; }
+RESOURCE TBUF r_certsaver_qtn_cm_pkcs12_expired { buf=qtn_cm_pkcs12_expired;}
+RESOURCE TBUF r_qtn_cm_pkcs12_format_not_supported { buf=qtn_cm_pkcs12_format_not_supported;}
+
+//----------------------------------------------------
+//
+//     r_qtn_cm_key_usage
+//     Key usage item label in details query.
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_cm_key_usage
+    {
+    buf = qtn_cm_key_usage;
+    }
+
+//----------------------------------------------------
+//
+//     r_qtn_cm_digital_signing
+//     Key usage is digital signing
+//     used in client certificate details view
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_cm_digital_signing
+    {
+    buf = qtn_cm_digital_signing;
+    }
+
+//----------------------------------------------------
+//
+//     r_qtn_cm_client_authentication
+//     Key usage is client authentication
+//     used in client certificate details view
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_cm_client_authentication
+    {
+    buf = qtn_cm_client_authentication;
+    }
+
+//----------------------------------------------------
+//
+//     r_qtn_cm_not_defined
+//     used in certificate details view
+//
+//----------------------------------------------------
+//
+
+RESOURCE TBUF r_qtn_cm_not_defined
+    {
+    buf = qtn_cm_not_defined;
+    }
+
+//----------------------------------------------------
+//
+//    r_certsaver_softkeys_save_discard
+//    Softkeys in r_message_query_dosave.
+//
+//----------------------------------------------------
+//
+RESOURCE CBA r_certsaver_softkeys_save_discard
+    {
+    buttons =
+        {
+        CBA_BUTTON { id=EAknSoftkeyOk; txt=text_softkey_save; },
+        CBA_BUTTON { id=EAknSoftkeyCancel; txt=text_wmls_list_disc_recvd_cert; },
+        CBA_BUTTON { id=EAknSoftkeyOk; txt=text_softkey_save; }
+        };
+    }
+
+//----------------------------------------------------
+//
+//    r_message_query_dosave
+//    Dialog shown to query if received certificate
+//    should be saved. Certificate details are
+//    shown.
+//
+//----------------------------------------------------
+//
+RESOURCE DIALOG r_message_query_dosave
+    {
+    flags = EGeneralQueryFlags | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow;
+    buttons = r_certsaver_softkeys_save_discard;
+    items=
+        {
+        DLG_LINE
+            {
+            type = EAknCtPopupHeadingPane;
+            id = EAknMessageQueryHeaderId;
+            control = AVKON_HEADING
+                {
+                };
+            },
+        DLG_LINE
+            {
+            type = EAknCtMessageQuery;
+            id = EAknMessageQueryContentId;
+            control = AVKON_MESSAGE_QUERY
+                {
+                };
+            }
+        };
+    }
+
+
+
+//----------------------------------------------------
+//
+//    r_message_query_dosave
+//    Dialog shown to query when pkcs#12 file saved
+//    succesfully.
+//
+//----------------------------------------------------
+//
+RESOURCE DIALOG r_message_query_saved
+    {
+    flags = EGeneralQueryFlags | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow;
+    buttons = R_AVKON_SOFTKEYS_OK_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type = EAknCtPopupHeadingPane;
+            id = EAknMessageQueryHeaderId;
+            control = AVKON_HEADING
+                {
+                };
+            },
+        DLG_LINE
+            {
+            type = EAknCtMessageQuery;
+            id = EAknMessageQueryContentId;
+            control = AVKON_MESSAGE_QUERY
+                {
+                };
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//    r_certsaver_label_query
+//    Dialog to query label for certificate.
+//
+//----------------------------------------------------
+//
+RESOURCE DIALOG r_certsaver_label_query
+    {
+    flags = EGeneralQueryFlags;
+    buttons = R_AVKON_SOFTKEYS_OK_CANCEL;
+    items=
+        {
+        DLG_LINE
+            {
+            type = EAknCtQuery;
+            id = EGeneralQuery;
+            control= AVKON_DATA_QUERY
+                {
+                layout = EDataLayout;
+                label = qtn_certsaver_enter_label;
+                control = EDWIN
+                    {
+                    maxlength = CERTSAVER_MAX_LABEL_LEN;
+                    };
+                };
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//    r_certsaver_warning_note
+//    Confirmation query to warn security risk of
+//    certificate downloading.
+//
+//----------------------------------------------------
+//
+RESOURCE DIALOG r_certsaver_warning_note
+    {
+    flags = EGeneralQueryFlags;
+    buttons = r_certsaver_softkeys_save_discard;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_CONFIRMATION_QUERY
+                {
+                layout = EConfirmationLayout;
+                label = qtn_httpsec_save_rootcertificate;
+                };
+            }
+        };
+    }
+
+//-----------------------------------------------------------------------------
+//
+//  r_certsaver_trust_settings_listbox
+//  Items in CertSaver trust settings multiselection query
+//
+//-----------------------------------------------------------------------------
+//
+RESOURCE ARRAY r_certsaver_trust_settings_listbox
+     {
+    items =
+        {
+        LBUF
+            {//mail and image connection
+            txt = "1\t"qtn_cm_lipri_mail_image_conn"";
+            },
+        LBUF
+            {//Native installer
+            txt = "1\t"qtn_cm_lipri_native_installing"";
+            },
+        LBUF
+            {//Java installer
+            txt = "1\t"qtn_cm_lipri_java_installing"";
+            },
+        LBUF
+            {//OCSP validation
+            txt = "1\t"qtn_cm_lipri_ocsp"";
+            }
+        };
+    }
+
+
+
+//----------------------------------------------------
+//
+//    r_certsaver_softkeys_ok_cancel
+//
+//----------------------------------------------------
+//
+
+RESOURCE CBA r_certsaver_softkeys_ok_cancel
+    {
+    buttons =
+        {
+        CBA_BUTTON {id=EAknSoftkeyYes; txt=text_softkey_ok;},
+        CBA_BUTTON {id=EAknSoftkeyCancel; txt= text_softkey_cancel;},
+        CBA_BUTTON {id=EAknSoftkeyYes; txt=text_softkey_ok;}
+        };
+    }
+
+//----------------------------------------------------
+//
+//    r_certsaver_softkeys_ok_cancel_mark
+//
+//----------------------------------------------------
+//
+
+RESOURCE CBA r_certsaver_softkeys_ok_cancel_mark
+    {
+    buttons =
+        {
+        CBA_BUTTON {id=EAknSoftkeyYes; txt=text_softkey_ok;},
+        CBA_BUTTON {id=EAknSoftkeyCancel; txt= text_softkey_cancel;},
+        CBA_BUTTON {id=EAknSoftkeyMark; txt=qtn_msk_mark;}
+        };
+    }
+
+
+//----------------------------------------------------
+//
+//    r_certsaver_trust_settings_query
+//    Multiselection list query for trust settings of
+//    certificate.
+//
+//----------------------------------------------------
+//
+
+RESOURCE AVKON_MULTISELECTION_LIST_QUERY r_certsaver_trust_settings_query
+    {
+    flags = EGeneralQueryFlags;
+    softkeys = r_certsaver_softkeys_ok_cancel_mark;
+    items =
+        {
+        AVKON_MULTISELECTION_LIST_QUERY_DLG_LINE
+          {
+          control = AVKON_LIST_QUERY_CONTROL
+            {
+            listtype = EAknCtSingleGraphicPopupMenuListBox;
+            listbox = AVKON_MULTISELECTION_LIST_QUERY_LIST
+                {
+                flags = EAknListBoxMultiselectionList | EAknListBoxPointerMultiselectionList;
+                array_id=r_certsaver_trust_settings_listbox;
+                };
+            heading = qtn_cm_select_trusted_apps;
+            };
+          }
+        };
+    }
+
+// -----------------------------------------------------------------------------
+//
+// r_wim_password_query_dialog
+// ?description
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE DIALOG r_pkcs12_pw_query_dialog
+    {
+    flags=EGeneralQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_CANCEL;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY
+                {
+                layout = ECodeLayout;
+                control = SECRETED
+                    {
+                    num_letters=32;
+                    };
+                };
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//    r_certsaver_trusted_site_query
+//    Multiselection list query for trusted site
+//    certificate.
+//
+//----------------------------------------------------
+//
+
+RESOURCE DIALOG r_certsaver_trusted_site_query
+    {
+    flags = EGeneralQueryFlags | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow;
+    buttons = r_certsaver_softkeys_save_discard;
+    items=
+         {
+        DLG_LINE
+              {
+            type = EAknCtPopupHeadingPane;
+            id = EAknMessageQueryHeaderId;
+            control = AVKON_HEADING
+                    {
+                    label = qtn_cm_save_trustedsite_certificate_warning_title;
+                    };
+            },
+         DLG_LINE
+              {
+            type = EAknCtMessageQuery;
+              id = EAknMessageQueryContentId;
+                control = AVKON_MESSAGE_QUERY
+                    {
+                     };
+              }
+        };
+    }
+
+//----------------------------------------------------
+//
+//    Resource buffers.
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_certsaver_one_private_key{ buf = qtn_cm_one_private_key; }
+RESOURCE TBUF r_certsaver_one_personal_certificate { buf = qtn_cm_one_personal_certificate; }
+RESOURCE TBUF r_certsaver_one_authority_certificate { buf = qtn_cm_one_authority_certificate; }
+RESOURCE TBUF r_certsaver_trustedsite_warning { buf = qtn_cm_save_trustedsite_certificate_warning_text; }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/data/CertSaver_caption.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,44 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This file contains caption resources for the module
+*
+*/
+
+
+//  RESOURCE IDENTIFIER
+NAME    CSCA
+
+//  INCLUDES
+#include <apcaptionfile.rh>
+#include "certsaver.loc"
+
+//  CONSTANTS
+
+//  MACROS
+
+//  RESOURCE DEFINITIONS
+// ---------------------------------------------------------
+//
+//    Caption definitions.
+//
+// ---------------------------------------------------------
+//
+RESOURCE CAPTION_DATA
+  {
+  caption = qtn_certsaver_app_title;
+  shortcaption = qtn_certsaver_app_title;
+  }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/data/CertSaver_reg.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Application Registration Resource file for CertSaver
+*
+*/
+
+
+#include <appinfo.rh>
+#include <CertSaver.rsg>
+#include <bldvariant.hrh>
+#include <data_caging_paths_strings.hrh>
+
+UID2 KUidAppRegistrationResourceFile
+UID3 0x100059D2 // CertSaver application UID
+
+RESOURCE APP_REGISTRATION_INFO
+    {
+    app_file = "CertSaver";
+
+    localisable_resource_file = APP_RESOURCE_DIR"\\CertSaver";
+    localisable_resource_id = R_CERTSAVER_LOCALISABLE_APP_INFO;
+
+    newfile=KAppDoesNotSupportNewFile;
+    embeddability = KAppEmbeddable;
+    hidden=KAppIsHidden;
+
+    datatype_list=
+        {
+        DATATYPE
+            {
+            priority = EDataTypePrioritySystem;
+            type = "application/x-x509-ca-cert";
+            },
+        DATATYPE
+            {
+            priority = EDataTypePrioritySystem;
+            type = "application/x-x509-user-cert";
+            },
+        DATATYPE
+            {
+            priority = EDataTypePrioritySystem;
+            type = "application/x-pkcs12";
+            }
+        };
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/group/CertSaver.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,85 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Project definition file for CertSaver
+*
+*/
+
+
+
+#include <platform_paths.hrh>
+#include <bldvariant.hrh>
+#include <data_caging_paths.hrh>
+
+
+TARGET        CertSaver.exe
+TARGETTYPE    exe
+EPOCSTACKSIZE 0x5000
+UID           0x100039CE 0x100059D2
+
+CAPABILITY    CAP_APPLICATION
+VENDORID      VID_DEFAULT
+
+START RESOURCE ../data/CertSaver.rss
+HEADER
+TARGETPATH APP_RESOURCE_DIR
+LANGUAGE_IDS
+END  // RESOURCE
+
+START RESOURCE ../data/CertSaver_reg.rss
+DEPENDS certsaver.rsg
+DEPENDS certsaver.rsg
+TARGETPATH /private/10003a3f/apps
+END
+
+
+SOURCEPATH ../src
+SOURCE  CertSaverApp.cpp
+SOURCE  CertSaverAppUi.cpp
+SOURCE  CertSaverContainer.cpp
+SOURCE  CertSaverDocument.cpp
+SOURCE  CertSaverSyncWrapper.cpp
+SOURCE  certparser.cpp
+SOURCE  CertSaverModel.cpp
+
+USERINCLUDE ../inc
+USERINCLUDE ../../Include
+
+MW_LAYER_SYSTEMINCLUDE
+SYSTEMINCLUDE   ../../PKCS12/CrPkcs12/Inc
+SYSTEMINCLUDE   ../../DeviceToken/Inc
+
+LIBRARY euser.lib
+LIBRARY apparc.lib
+LIBRARY cone.lib
+LIBRARY eikcore.lib
+LIBRARY avkon.lib
+LIBRARY efsrv.lib
+LIBRARY commonengine.lib
+LIBRARY sysutil.lib
+LIBRARY CTFramework.lib     // CCertAttributeFilter
+LIBRARY certstore.lib
+LIBRARY X509CertNameParser.lib
+LIBRARY x509.lib            // CX509Certificate
+LIBRARY crypto.lib          // CSignedObject
+LIBRARY hash.lib            // SHA-1
+//LIBRARY x500.lib          // Certificate parsing
+LIBRARY bafl.lib            // CDesC16ArrayFlat
+LIBRARY cryptography.lib
+LIBRARY FeatMgr.lib
+LIBRARY asnpkcs.lib
+LIBRARY aknskins.lib
+LIBRARY DevTokenClient.lib
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Build information file for CertSaver
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT -ARMI
+
+PRJ_EXPORTS
+../loc/certsaver.loc  MW_LAYER_LOC_EXPORT_PATH(certsaver.loc)
+
+PRJ_MMPFILES
+CertSaver.mmp
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/inc/CertSaverApp.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Application class
+*
+*/
+
+
+#ifndef CERTSAVERAPP_H
+#define CERTSAVERAPP_H
+
+#include <aknapp.h>
+
+// CONSTANTS
+// UID of the application
+const TUid KUidCertSaver = { 0x100059D2 };
+
+// CLASS DECLARATION
+
+/**
+* CCertSaverApp application class.
+* Provides factory to create concrete document object.
+*
+*/
+class CCertSaverApp : public CAknApplication
+    {
+
+    private:
+
+        /**
+        * From CApaApplication, creates CCertSaverDocument document object.
+        * @return A pointer to the created document object.
+        */
+        CApaDocument* CreateDocumentL();
+
+        /**
+        * From CApaApplication, returns application's UID (KUidCertSaver).
+        * @return The value of KUidCertSaver.
+        */
+        TUid AppDllUid() const;
+    };
+
+#endif  // CERTSAVERAPP_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/inc/CertSaverAppUi.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,140 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Application UI class
+*
+*/
+
+
+#ifndef CERTSAVERAPPUI_H
+#define CERTSAVERAPPUI_H
+
+// INCLUDES
+#include <eikapp.h>
+#include <eikdoc.h>
+#include <e32std.h>
+#include <coeccntx.h>
+#include <aknappui.h>
+#include <eikdialg.h>
+
+// FORWARD DECLARATIONS
+class CCertSaverDialog;
+class CCertSaverDocument;
+class CCertSaverContainer;
+
+
+// CONSTANTS
+
+// CLASS DECLARATION
+class CCertSaverModel;
+
+/**
+* Application UI class.
+* Provides support for the following features:
+* - detects if an unhandled leave occurs
+*
+*/
+class CCertSaverAppUi : public CAknAppUi
+    {
+    public: // // Constructors and destructor
+
+        /**
+        * EPOC default constructor.
+        */
+        void ConstructL();
+
+        /**
+        * Destructor.
+        */
+        ~CCertSaverAppUi();
+
+    public: // New functions
+
+        /**
+        * Starts certificate saving.
+        * @param void
+        */
+        void RunFileL();
+
+        void RunFileL( RFile& aFile );
+
+        /**
+        * Returns pointer to control environment.
+        * @param void
+        */
+        const CCoeEnv* CoeEnv() const;
+
+        /**
+        * Notifies iDoorObserver about exit, and then exits.
+            * In this case iDoorObserver is Document Handler.
+        * @param void
+        */
+        void doExit();
+
+    public: // Functions from base classes
+
+        //From CEikAppUi
+        TErrorHandlerResponse HandleError (
+              TInt aError,
+              const SExtendedError& aExtErr,
+              TDes& aErrorText,
+              TDes& aContextText );
+
+    protected: // Functions from base classes
+        // From CEikAppUi
+        TBool ProcessCommandParametersL(
+              TApaCommand aCommand ,
+              TFileName& aDocumentName,
+              const TDesC8& Tail );
+
+        //From CCoeAppUi
+        void HandleForegroundEventL( TBool aForeground );
+
+    private:
+        // From MEikMenuObserver
+        void DynInitMenuPaneL( TInt aResourceId,CEikMenuPane* aMenuPane );
+
+        /**
+        * From CEikAppUi, takes care of command handling.
+        * @param aCommand command to be handled
+        */
+        void HandleCommandL( TInt aCommand );
+
+    private:
+
+
+        CCertSaverDocument* Document() const
+            {
+            return( (CCertSaverDocument*)iDocument );
+            }
+
+        void ConstructPKCS12QueryMsgL( HBufC* aMessage ) const;
+
+        /**
+        * From CEikAppUi, handles key events.
+        * @param aKeyEvent Event to handled.
+        * @param aType Type of the key event.
+        * @return Response code (EKeyWasConsumed, EKeyWasNotConsumed).
+        */
+        virtual TKeyResponse HandleKeyEventL(
+            const TKeyEvent& aKeyEvent,TEventCode aType );
+
+    private: //Data
+        CCertSaverModel*      iModel;
+        TBool                 iErrorOccured;
+        CCertSaverContainer*  iContainer;
+    };
+
+#endif  // CERTSAVERAPPUI_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/inc/CertSaverContainer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,92 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of class CCertSaverContainer
+*
+*/
+
+
+#ifndef CERTSAVERCONTAINER_H
+#define CERTSAVERCONTAINER_H
+
+// INCLUDES
+#include <coecntrl.h>
+#include <AknsBasicBackgroundControlContext.h>
+
+// FORWARD DECLARATIONS
+
+// CONSTANTS
+
+// CLASS DECLARATION
+
+class CCertSaverContainer : public CCoeControl
+  {
+public:
+
+        /**
+        * Second-phase constructor.
+        */
+        void ConstructL( const TRect& aRect );
+
+        /**
+        * Destructor.
+        */
+        ~CCertSaverContainer();
+
+
+public:
+        /**
+        * From CCoeControl : Return count of controls contained in a compound control.
+        * @return Count of controls contained in a compound control
+        */
+        TInt CountComponentControls() const;
+
+        /**
+        * From CCoeControl : Get the components of a compound control
+        * @param aIndex : index of control
+        * @return Control of argument aIndex
+        */
+        CCoeControl* ComponentControl( TInt aIndex ) const;
+
+        /**
+        * From CCoeControl : Notifier for changing language
+        * @param aType : Type of resource change
+        */
+        void HandleResourceChange( TInt aType );
+
+
+private:
+        /**
+        * From CCoeControl : Clear whole rectangle.
+        * @param aRect : rectangle of control
+        */
+        void Draw( const TRect& aRect ) const;
+
+        /**
+        * From CCoeControl : Control size is set.
+        */
+        void SizeChanged();
+
+        /**
+        * From CCoeControl.
+        * Pass skin information if need.
+        */
+        TTypeUid::Ptr MopSupplyObject( TTypeUid aId );
+
+private:
+        CAknsBasicBackgroundControlContext* iBgContext;
+  };
+
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/inc/CertSaverDocument.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Document class
+*
+*/
+
+
+#ifndef CERTSAVERDOCUMENT_H
+#define CERTSAVERDOCUMENT_H
+
+// INCLUDES
+#include "certparser.h"
+#include <eikdoc.h>
+
+// CONSTANTS
+
+// FORWARD DECLARATIONS
+class  CEikAppUi;
+class CShutterAO;
+
+// CLASS DECLARATION
+
+/**
+*  CCertSaverDocument document class.
+*/
+class CCertSaverDocument : public CEikDocument
+    {
+    public: // Constructors and destructor
+        /**
+        * Two-phased constructor.
+        */
+        static CCertSaverDocument* NewL( CEikApplication& aApp );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCertSaverDocument();
+
+    public: // New functions
+
+        /**
+        * Returns reference to parser.
+        */
+        CCertParser& Parser() const;
+
+    public: // Functions from base classes
+
+        /**
+        * From CEikDocument class.
+        * When file-based epoc application started, Uikon framework
+        * uses OpenFileL function to open the file with file name
+        */
+        CFileStore* OpenFileL( TBool aDoOpen, const TDesC& aFilename, RFs& aFs );
+
+        /**
+        * From CEikDocument class.
+        * When file-based epoc application started, Uikon framework
+        * uses OpenFileL function to open the file
+        */
+        void OpenFileL( CFileStore*& aFileStore, RFile& aFile );
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * EPOC default constructor.
+        */
+        CCertSaverDocument( CEikApplication& aApp ): CEikDocument( aApp ) { }
+        void ConstructL();
+
+    private:
+
+        /**
+        * From CEikDocument, create CCertSaverAppUi "App UI" object.
+        */
+        CEikAppUi* CreateAppUiL();
+
+  private:    // Data
+
+        CCertParser* iParser;
+        CShutterAO* iAO;
+    };
+
+
+// CLASS DECLARATION
+
+/**
+*  CShutterAO document class.
+*  Active object used to shut down application.
+*/
+
+class CShutterAO : public CActive
+    {
+    public:
+        /**
+        * Constructor.
+        */
+        CShutterAO();
+
+        /**
+        * Constructor.
+        */
+        virtual ~CShutterAO();
+
+        /**
+        * Exits the application in RunL
+        */
+        void Exit();
+
+    private:
+        void DoCancel();
+        void RunL();
+    };
+
+#endif  // CERTSAVERDOCUMENT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/inc/CertSaverModel.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,343 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Model of the CertSaver. Saves the keys and certificates
+*              : to the databases and shows appropriate dialogs for user
+*
+*/
+
+
+#ifndef CERTSAVERMODEL_H
+#define CERTSAVERMODEL_H
+
+// INCLUDES
+#include <f32file.h>
+#include <e32std.h>
+#include <ct/rmpointerarray.h>
+#include <securitydefs.h>
+#include <mpkcs12.h>
+#include <cctcertinfo.h>
+#include <signed.h>
+
+// FORWARD DECLARATIONS
+class CCertSaverDocument;
+class CCertSaverAppUi;
+class RFs;
+class CCertSaverSyncWrapper;
+class CUnifiedCertStore;
+class CCTCertInfo;
+class CX509Certificate;
+class TCertificateAppInfo;
+class CCertParser;
+
+// CONSTANTS
+
+
+// CLASS DECLARATION
+
+
+/**
+* CCertSaverModel dialog class.
+* Saves certificates and shows
+* needed queries and error notes for user.
+*/
+class CCertSaverModel : public CBase
+    {
+
+    public: // Constructors and destructor
+
+        CCertSaverModel( CCertSaverAppUi* aAppUi, const CCertParser& aParser );
+
+        /**
+        * Destructor.
+        */
+        ~CCertSaverModel();
+
+    public: // New functions
+
+        void SaveCertificateL(
+                const CX509Certificate& aCertificate,
+                const TCertificateOwnerType& aOwnerType,
+                const TCertificateFormat& aCertFormat );
+
+         /**
+        * Saves content of the PKCS#12 PDU.
+        * @param void
+        */
+        void SavePKCS12L();
+
+
+        /**
+        * Shows a error note with given text.
+        * @param aResourceID Id of the resource text to be shown.
+        */
+        void ShowErrorNoteL( TInt aResourceID ) const;
+
+    private:  // New functions
+
+        /**
+        * Initialises unified certstore.
+        */
+        void InitCertStoreL();
+
+         /**
+        * Checks that there is enough space in filesystem
+        * @param aDataToSave Data to be saved.
+        */
+        void CheckFSSpaceL( const TDesC8& aDataToSave );
+
+        void SaveCertL();
+
+        void SavePrivateKeyL();
+
+        void DoSavePrivateKeyL( const TDesC8& aKey );
+
+        void CreateKeyLabelL( TDes& aLabel );
+
+        void GetKeyValidityPeriodL(
+            TTime& aStartDate,
+            TTime& aEndDate,
+            const TKeyIdentifier& aKeyIdentifier );
+
+        TKeyUsagePKCS15 KeyUsageL(
+            const TKeyIdentifier& aKeyIdentifier,
+            TAlgorithmId aAlgorithm );
+
+        TBool KeyAlreadyExistsL(
+            TTime& aStartDate,
+            TTime& aEndDate,
+            const TKeyIdentifier& aKeyIdentifier,
+            TKeyUsagePKCS15& aKeyUsage );
+
+        /**
+        * Saves certificate to database in phone memory.
+        */
+        void DoSaveCertL();
+
+        /**
+        * Shows appropriate error note if something odd happeneds
+        * certificate is saved. Shows also note if everything
+        * goes fine.
+        * @param aStatus Status of the save operation.
+        */
+        void HandleSaveErrorL( TInt aStatus ) const;
+
+        /**
+        * Adds string to aMessage.
+        * @param aMessage Buffer where message is saved.
+        * @param aStringResID id of the string to be added. Read from resources.
+        */
+        void AddToMessageL( TDes& aMessage, TInt aStringResID ) const;
+
+        /**
+        * Constructs the message shown to user in details-dialog.
+        * @param aMessage Buffer where message is saved.
+        */
+        void ConstructMessageL( TDes& aMessage ) const;
+
+        /**
+        * Constructs the message shown to user in pkcs#12
+        * file contents and saving completed queries.
+        * @param aMessage Buffer where message is saved.
+        */
+        void ConstructPKCS12QueryMsgL(
+            TDes& aMessage,
+            TInt aPrivateKeys,
+            TInt aUserCerts,
+            TInt aCACerts ) const;
+
+        /**
+        * Adds string to aMessage.
+        * @param aMessage Buffer where message is saved.
+        * @param aStringResID id of the string to be added. Read from resources.
+        * @param aString Replaces the first (and only) %U parameter in resources.
+        */
+        void AddToMessageWithStringL(
+            TDes& aMessage,
+            TInt aStringResID,
+            const TDesC& aString ) const;
+
+        /**
+        * Adds string to aMessage.
+        * @param aMessage Buffer where message is saved.
+        * @param aStringResID id of the string to be added. Read from resources.
+        * @param aString Replaces the first (and only) %U parameter in resources.
+        */
+        void AddToMessageWithIntL(
+            TDes& aMessage,
+            TInt aStringResID,
+            TInt aInt ) const;
+
+        /**
+        * Adds validity period of the certificate to aMessage.
+        * @param aMessage Buffer where message is appended.
+        * @param aCert Certificate
+        */
+        void AddValidityPeriodL( TDes& aMessage, const CX509Certificate& ) const;
+
+        /**
+        * Adds key usage of the certificate to aMessage.
+        * @param aMessage Buffer where message is appended.
+        * @param aCert Certificate
+        */
+        void AddKeyUsageL( TDes& aMessage, const CX509Certificate& aCert ) const;
+
+        /**
+        * Adds new lines to message.
+        * @param aMessage Buffer where message is saved.
+        */
+        void AddNewlinesToMessage( TDes& aMessage ) const;
+
+        /**
+        * Shows a confirmation note with given text.
+        * @param aResourceID Id of the resource text to be shown.
+        */
+        void ShowConfirmationNoteL( TInt aResourceID ) const;
+
+        /**
+        * Shows a information note with given text.
+        * @param aResourceID Id of the resource text to be shown.
+        */
+        void ShowInformationNoteL( TInt aResourceID ) const;
+
+        /**
+        * Checks that certificate is ok. That is, it's not
+        * corrupted and it's of supported type. If certificate
+        * is not ok an error note is displayed. If certificate
+        * is not valid yet/anymore an error note is displayed
+        * but certificate is considered to be ok ie. can be saved anyway.
+        * @return TBool ETrue if ok else EFalse.
+        */
+        TBool CertificateOkL() const;
+
+        /**
+        * Checks that certificate is of supported type.
+        * @return TBool ETrue if supported else EFalse.
+        */
+        TBool CertificateSupported() const;
+
+        /**
+        * Checks if certificate isn't valid anymore.
+        * @return TBool ETrue if not valid else EFalse.
+        */
+        TBool CertNotValidAnymore() const;
+
+        /**
+        * Checks if certificate isn't valid yet.
+        * @return TBool ETrue if not valid else EFalse.
+        */
+        TBool CertNotValidYet() const;
+
+        /**
+        * Trims given descriptor so that everything after and
+        * including the fourth semicolon (;) is cropped. .
+        * @param aField data to be trimmed.
+        * @return TPtrC trimmed content
+        */
+        TPtrC TrimCertificateFields( TPtrC aField ) const;
+
+        /**
+        * If given descriptor contains more than 80
+        * characters, this function cut it to 80.
+        * @param aField data to be possibly cut.
+        * @return TPtrC trimmed content
+        */
+        TPtrC CutCertificateField( TPtrC aField ) const;
+
+        /**
+        * Queries label from user and confirms that label doesn't already
+        * exist.
+        * @param aLabel IN Default label of the Certificate
+        *               OUT Unique label that might been changed by user
+        * @param aStore Unified Certificate Store
+        * @return KErrNone if everything is ok.
+        *         KErrCancel if user pressed cancel
+        *         Otherwise status of the list operation.
+        *
+        */
+        TInt QueryLabelL( TCertLabel& aLabel, CUnifiedCertStore& aStore );
+
+        /**
+        * Queries trust settings from user
+        * @param OUT aUids contains user selected uids of
+        * the trusted applications
+        * @return KErrNone if everything is ok.
+        *         KErrCancel if user pressed cancel
+        *         Otherwise status of the list operation.
+        *
+        */
+        TInt QueryTrusterUidsL( RArray<TUid>& aUids );
+
+        /**
+        * Queries trust site certificate from user
+        * @param
+        * @return KErrNone if everything is ok.
+        *         KErrCancel if user pressed cancel
+        *         Otherwise status of the list operation.
+        *
+        */
+        TInt QueryTrustedSiteL();
+
+        /**
+        * Updates localised strings to listbox item array
+        * @param aApps All trusted applications
+        * @param aAppsInItemArray Trusted applications in right order.
+        * @param aItemsArray Localised strings in same order.
+        * @return void
+        *
+        */
+        void UpdateTrustListboxItemL(
+            const RArray<TCertificateAppInfo>& aApps,
+            RArray<TCertificateAppInfo>& aAppsInItemArray,
+            CDesCArray& aItemsArray ) const;
+
+        /**
+        * Divides string to four characters blocks
+        * and delimits them with space.
+        * @param aInput String to devide
+        * @param aOutput Descriptor where result is appended
+        * @return void
+        */
+        void DivideToBlocks( const TDesC8& aInput, TDes& aOutput ) const;
+
+        TBool DoMessageQueryL(
+            TInt aDialogResId,
+            TInt aHeadingResId,
+            TDesC& aMessage );
+
+    private: //data
+        TCertificateOwnerType     iCertOwnerType;
+        TCertificateFormat        iCertFormat;
+        const CCertSaverDocument* iDocument;
+        CCertSaverAppUi*          iAppUi;
+        CCertSaverSyncWrapper*    iWrapper;    // synchronous wrapper
+
+        // variables for SaveCertL
+        CUnifiedCertStore*          iUnifiedCertStore;
+        RMPointerArray<CCTCertInfo> iEntries;
+        const CCertificate*         iNewCert;
+        RArray<TUid>                iTrusterUids;
+        RFs& iFs;
+
+        const CCertParser& iParser;
+
+        TInt  iSavedCACertsCount;
+        TInt  iSavedKeysCount;
+        TInt  iSavedUserCertsCount;
+        TInt  iSelectedKeyStore;
+        TBool iKeyAlreadyExists;
+    };
+
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/inc/CertSaverSyncWrapper.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,260 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Header file of the CCertSaverSyncWrapper class
+*
+*/
+
+
+#ifndef CERTSAVERSYNCWRAPPER_H
+#define CERTSAVERSYNCWRAPPER_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <securitydefs.h>   // TCertificateFormat, TCertificateOwnerType
+#include <ct/rmpointerarray.h> // RMPointerArray
+#include <mpkcs12.h>
+#include <mctkeystore.h>
+
+typedef TBuf8<20> TKeyIdBuf;
+
+// FORWARD DECLARATIONS
+class CUnifiedCertStore;
+class MCTWritableCertStore;
+class CCTCertInfo;
+class CCertAttributeFilter;
+class CCertificate;
+class CUnifiedKeyStore;
+
+// CLASS DECLARATION
+
+/**
+*  Synchronous wrapper for asynchronous functions of Crypto Token fw.
+*
+*  @lib CertSaver.app
+*  @since 2.0
+*/
+class CCertSaverSyncWrapper : public CActive
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCertSaverSyncWrapper* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCertSaverSyncWrapper();
+
+    public: // New functions
+
+        /**
+        * Initialise unified cert store
+        * @since 2.0
+        * @param aStore unified cert store
+        * @return status code from CUnifiedCertStore
+        */
+        TInt InitializeCertStore( CUnifiedCertStore& aStore );
+
+        /**
+        * Initialise unified cert store
+        * @since 2.0
+        * @param aStore unified cert store
+        * @return status code from CUnifiedCertStore
+        */
+        TInt InitializeKeyStoreL( RFs& aFs );
+
+        /**
+        * Add certificate to certman.
+        * @since 2.0
+        * @param aStore writable certstore interface
+        * @param aLabel label of the certificate
+        * @param aCertFormat format of the certificate
+        * @param aCertType type of the certificate
+        * @param aSubjectKeyId subject key ID
+        * @param aIssuerKeyId issuer key ID
+        * @param aCert certificate to be added
+        * @return status code from MCTWritableCertStore
+        */
+        TInt AddCert( MCTWritableCertStore& aStore,
+                      const TDesC& aLabel,
+                      TCertificateFormat aCertFormat,
+                      TCertificateOwnerType aCertType,
+                      TKeyIdentifier* aSubjectKeyId,
+                      TKeyIdentifier* aIssuerKeyId,
+                      TPtrC8 aCert );
+
+        /**
+        * List certificates matching to filter.
+        * @since 2.0
+        * @param aStore unified cert store
+        * @param aEntries found certificates
+        * @param aFilter filter defining which certs are listed
+        * @return status code from CUnifiedCertStore
+        */
+        TInt ListCerts( CUnifiedCertStore& aStore,
+                        RMPointerArray<CCTCertInfo>& aEntries,
+                        CCertAttributeFilter& aFilter );
+
+        /**
+        * Set applicability for certificate.
+        * @since 2.0
+        * @param aStore writable certstore interface
+        * @param aCertInfo certificate
+        * @param aApplications UIDs of applicable applications
+        * @return status code from MCTWritableCertStore
+        */
+        TInt SetApplicability( MCTWritableCertStore& aStore,
+            const CCTCertInfo& aCertInfo, RArray<TUid>& aApplications );
+
+        /**
+        * Set trust for certificate.
+        * @since 2.0
+        * @param aStore writable certstore interface
+        * @param aCertInfo certificate
+        * @param aTrust trusted or not
+        * @return status code from MCTWritableCertStore
+        */
+        TInt SetTrust( MCTWritableCertStore& aStore,
+            const CCTCertInfo& aCertInfo, TBool aTrust );
+
+        /**
+        * Retrieve certificate
+        * @since 2.0
+        * @param aStore writable certstore interface
+        * @param aCertInfo certificate
+        * @param aCert IN NULL
+        *              OUT Constructed object.
+        *              Ownership moves to caller.
+        * @return status code from MCTWritableCertStore
+        */
+        TInt Retrieve( CUnifiedCertStore& aStore,
+            const CCTCertInfo& aCertInfo, CCertificate*& aCert );
+
+        /**
+        * Add key to the sw keystore
+        * @since 2.8
+        * @param aKeyStoreIndex Index of the keystore
+        * @param aKeyData PKCS#8 encoded keypair
+        * @param aUsage PKCS#15 usage flags of the key
+        * @param aLabel Label of the key
+        * @param aAccessType Access type of the key
+        * @param aStartDate Start date of the validation period
+        * @param aEndDate End date of the validation period
+        * @param aKeyInfoOut Key info of the added key
+        * @return status code from UnifiedKeyStore
+        */
+        TInt AddKey( TInt aKeyStoreIndex,
+                     const TDesC8& aKeyData,
+                     TKeyUsagePKCS15 aUsage,
+                     const TDesC& aLabel,
+                     TInt aAccessType,
+                     TTime aStartDate,
+                     TTime aEndDate,
+                     CCTKeyInfo*& aKeyInfoOut );
+
+        /**
+        * List keys matching to filter.
+        * @since 3.0
+        * @param aEntries Found Keys
+        * @param aFilter Filter defining which keys are listed
+        * @return status code from UnifiedKeystore
+        */
+        TInt ListKeys( RMPointerArray<CCTKeyInfo>& aEntries,
+                       TCTKeyAttributeFilter& aFilter );
+
+        /**
+        * Sets the security policy for key management.
+        *
+        * Specifies which processes are allowed to perform management operations on
+        * the key.
+        *
+        * @param aHandle  The handle of the key
+        * @param aPolicy  The new security policy.
+        *
+        * @leave KErrPermissionDenied If the caller does not have WriteUserData capability,
+        *               or is not the owner of the key.
+        * @leave KErrNotFound     If the key the handle referes to does not exist.
+        */
+        TInt SetManagementPolicy( TCTTokenObjectHandle aHandle,
+                  const TSecurityPolicy& aPolicy );
+
+        /**
+        * Sets the security policy for key use.
+        *
+        * Specifies which processes are allowed to use the key for cryptographic
+        * operations.
+        *
+        * @param aHandle  The handle of the key
+        * @param aPolicy  The new security policy.
+        *
+        * @leave KErrPermissionDenied If the caller does not have WriteUserData capability,
+        *               or is not the owner of the key.
+        * @leave KErrNotFound     If the key the handle referes to does not exist.
+        */
+        TInt SetUsePolicy( TCTTokenObjectHandle aHandle,
+               const TSecurityPolicy& aPolicy );
+
+        /**
+        * Get reference to UnifiedKeyStore.
+        * @since 3.0
+        * @return Reference to UnifiedKeyStore;
+        */
+        CUnifiedKeyStore& UnifiedKeyStore();
+
+    public: // Functions from base classes
+
+
+    protected:  // New functions
+
+
+    protected:  // Functions from base classes
+
+        /**
+        * From CActive
+        */
+        void DoCancel();
+        void RunL();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CCertSaverSyncWrapper();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Wait until asynchronous call is completed and return status
+        */
+        TInt SetActiveAndWait();
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+        CActiveSchedulerWait  iWait;
+        CUnifiedKeyStore*     iUnifiedKeyStore;
+
+    };
+
+#endif      // CERTSAVERSYNCWRAPPER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/inc/certparser.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,175 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Header of class used to parse and validate a certificate or PKCS#12 PFX.
+*
+*/
+
+
+#ifndef CERTPARSER_H
+#define CERTPARSER_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <mpkcs12.h>
+
+// CONSTANTS
+const TInt KHashLength( 20 );
+// CertSaver panic category
+_LIT( KCertSaverPanic, "Certificate saver" );
+// Panic reasons
+const TInt KPanicNullPointer( 0 );
+const TInt KErrWrongCryptoLib( 1 );
+const TInt KErrExitApp( -333333 );
+
+// FORWARD DECLARATIONS
+class CCertificate;
+class CX509Certificate;
+class CX500DistinguishedName;
+class CPKCS12;
+class RFs;
+class CEikonEnv;
+
+// CLASS DECLARATION
+
+/**
+*  CCertParser - X.509 certificate and PKCS#12 PFX parsing class.
+*/
+class CCertParser :public CBase
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCertParser* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCertParser();
+
+    public: // New functions
+
+        enum TCertType
+            {
+            ETypeX509,
+            ETypeURL,
+            ETypeX509CA,
+            ETypeX509Peer,
+            ETypePKCS12,
+            ETypeCorrupt
+            };
+
+        /**
+        * Sets parsers state according to aBuffer. If certificate or PKCS#12
+        * is corrupted, any of the query functions can't be called.
+        * @param aBuffer, buffer containing the certificate
+        * @return Type of certificate, can also be corrupted.
+        */
+        void SetContentL( RFile& aFile );
+
+        /**
+        * Returns the type of the certificate.
+        * @return TCertType, type of certificate.
+        */
+        TCertType CertType() const;
+
+        /**
+        * Returns the content of the certificate.
+        * Returned data is valid so long as state of this object
+        * is not modified.
+        * @return TPtrC8, the certificate
+        */
+        const TPtrC8 CertificateBuf() const;
+
+        /**
+        * Returns the X.509 certificate object.
+        * Returned data is valid so long as state of this object
+        * is not modified.
+        * @return TPtrC8, the certificate
+        */
+        const CX509Certificate& Certificate() const;
+
+
+        /**
+        * Returns the private key of the PKCS#12 PDU.
+        * Returned data is valid so long as state of this object
+        * is not modified.
+        * @return TPtrC8, the certificate
+        */
+        const CArrayPtr<HBufC8>& Keys() const;
+
+        /**
+        * Returns the CA certificates from the PKCS#12 PDU.
+        * Returned data is valid so long as state of this object
+        * is not modified.
+        * @return TPtrC8, the certificate
+        */
+        const CArrayPtr<CX509Certificate>& CACertificates() const;
+
+        /**
+        * Returns the user certificates from the PKCS#12 PDU.
+        * Returned data is valid so long as state of this object
+        * is not modified.
+        * @return TPtrC8, the certificate
+        */
+        const CArrayPtr<CX509Certificate>& UserCertificates() const;
+
+    public: // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CCertParser();
+
+        /**
+        * By default EPOC constructor is private.
+        */
+        void ConstructL();
+
+        TInt CheckIfX509CertificateL( const TDesC8& aCert );
+
+        void CreatePKCS12L();
+        TBool CheckIfPKCS12L( const TDesC8& aPKCS12, const TDesC& aFileName );
+
+        TInt GetPasswordL( TDes& aPassword, const TDesC& aFileName );
+
+        void ShowErrorNoteL( TInt aResourceID );
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+        TCertType         iCertType;    // The type of the response
+        CX509Certificate* iCert;
+        MPKCS12*          iPKCS12;
+        RLibrary          iLibrary;
+        CEikonEnv*        iEikEnv;
+
+    public:     // Friend classes
+    protected:  // Friend classes
+    private:    // Friend classes
+
+    };
+
+#endif      // CERTPARSER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/inc/certsaver.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This file contains declarations for resources of CertSaver
+*
+*/
+
+
+#ifndef CERTSAVER_HRH
+#define CERTSAVER_HRH
+
+#define CERTSAVER_MAX_LABEL_LEN 64
+
+#endif      //  CERTSAVER_HRH
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/loc/certsaver.loc	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,246 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Localization strings for CertSaver
+*
+*/
+
+
+
+// LOCALISATION STRINGS
+
+//d:Heading of save-confirmation query pop up.
+//d:This popup is shown to query if user wants to
+//d:save received certificate.
+//l:heading_pane_t1
+#define qtn_wmlsec_query_downl_cert    "Received certificate:"
+
+//d:Softkey in certificate details popup.
+//d:Discards certificate (cancels operation).
+//l:control_pane_t1/opt7
+#define text_wmls_list_disc_recvd_cert    "Discard"
+
+//d:Item in save-confirmation query pop up.
+//d:This represents to whom the certificate
+//d:has been issued to.
+//l:popup_info_list_pane_t1
+#define qtn_wmlsec_cert_subject    "Subject:\n%U"
+
+//d:Item in save-confirmation query pop up.
+//d:Tells who issued the certificate.
+//l:popup_info_list_pane_t1
+#define qtn_wmlsec_scert_issuer    "Issuer:\n%U"
+
+//d:Item in save-confirmation query popup.
+//d:Tells the time period in witch the certificate
+//d:is valid.
+//d:%U is the validity period in format "date - date"
+//d:where dates are in R_QTN_DATE_USUAL_WITH_ZERO-format.
+//l:popup_info_list_pane_t1
+#define qtn_wmlsec_cert_validity    "Validity:\n%U"
+
+//d:Item in save-confirmation query pop up.
+//d:Fingerprint (hash) of the whole certificate.
+//l:popup_info_list_pane_t1
+#define qtn_wmlsec_scert_fingerp    "Fingerprint:\n%U"
+
+//d:Text shown when certificate is succesfully added to database.
+//l:popup_note_window
+#define qtn_wmlsec_certificate_saved    "Certificate saved"
+
+//d:Text show when user presses text_wmls_list_disc_recvd_cert
+//d:in certificate details dialog.
+//l:popup_note_window
+#define qtn_wmlsec_certificate_discarded    "Certificate discarded"
+
+//d:Text shown when certificate tried to save is not of supported type.
+//d:Certificate could be a x.509 certificate, for example. Download
+//d:of x.509 certificates is not supported in N7650.
+//l:popup_note_window
+#define qtn_wmlsec_cert_unsupported    "Certificate unsupported. Not saved."
+
+//d:Text shown when certificate tried to be save is corrupted in some way.
+//d:Certificate could have invalid fingerprint etc.
+//l:popup_note_window
+#define qtn_wmlsec_cert_corrupted    "Certificate corrupted."
+
+//d:Text shown when downloaded certificate is expired, eg. its validity
+//d:period has expired. Note! This error could be interpreted as certificate
+//d:being corrupted. This is the only type of corrupted certificate for
+//d:what a specific error note is displayed.
+//l:popup_note_window
+#define qtn_wmlsec_dload_expired_cert    "Downloaded certificate is expired"
+
+//d:Text shown when downloaded certificate is already in database.
+//d:Old certificate remains in database and downloaeded certificate is
+//d:discarded.
+//l:popup_note_window
+#define qtn_wmlsec_cert_duplicate    "Certificate already exists. Not saved."
+
+//d:Applications long caption string. Short one is not
+//d:given as it has no use.
+//l:title_pane_t2/opt9
+#define qtn_certsaver_app_title    "Certificate Saver"
+
+//d:Text in data query dialog when label for downloaded certificate is asked
+//d:from user.
+//l:popup_query_data_window
+#define qtn_certsaver_enter_label    "Label:"
+
+//d:Warning note displayed to user when he/she is about to save downloaded
+//d:certificate.
+//l:popup_note_window
+#define qtn_httpsec_save_rootcertificate  "Adding a new certificate might be security risk. Save anyway?"
+
+//d:Text shown when label of the certificate is already in database.
+//d:Label is queried again from user.
+//l:popup_note_window
+#define qtn_cm_label_already_exist   "Label already exist. Insert new label."
+
+//d:Heading of multiselection list query pop up.
+//d:Popup is shown to query trusted applications
+//d:of the saved certificate.
+//l:heading_pane_t1
+#define qtn_cm_select_trusted_apps    "Select trusted applications:"
+
+//d:Heading of PKCS#12 file contents message query
+//d:This popup is shown when user has opened PKCS#12 file.
+//l:heading_pane_t1
+#define qtn_cm_header_pkcs12_file_contains    "The file contains:"
+
+//d:Item PKCS#12 file contents message query
+//d:Number of private keys in PKCS#12 file.
+//l:popup_info_list_pane_t1
+#define qtn_cm_private_keys    "%N private keys"
+
+//d:Item PKCS#12 file contents message query
+//d:Number of personal certificates in PKCS#12 file.
+//l:popup_info_list_pane_t1
+#define qtn_cm_personal_certificates    "%N personal certificates"
+
+//d:Item PKCS#12 file contents message query
+//d:Number of authority certificates in PKCS#12 file.
+//l:popup_info_list_pane_t1
+#define qtn_cm_authority_certificates    "%N authority certificates"
+
+//d:Text show after user has discarded PKCS#12 file
+//d:in PKCS#12 file content dialog.
+//l:popup_note_window
+#define qtn_cm_pkcs12_discarded    "Not saved"
+
+//d:Text shown when private key tried to be saved is corrupted in some way.
+//l:popup_note_window
+#define qtn_cm_private_key_corrupted    "The private key is corrupted."
+
+//d:Text shown when the type of the key is not supported.
+//l:popup_note_window
+#define qtn_cm_key_type_not_supported    "The key type is not supported."
+
+//d:Text shown when the type of the key is not supported.
+//l:popup_note_window
+#define qtn_cm_keystore_corrupted    "The keystore is corrupted."
+
+//d:Text shown when the type of the key is not supported.
+//l:popup_note_window
+#define qtn_cm_pkcs12_file_corrupted    "The file is corrupted."
+
+//d:Heading of PKCS#12 saving completed message query
+//d:This popup is shown when contents of PKCS#12 is saved succesfully.
+//l:heading_pane_t1
+#define qtn_cm_header_saved    "Saved:"
+
+//d:PKCS#12 password query prompt
+//l:popup_query_data_window
+//w:
+//r:3.0
+#define qtn_cm_title_p12_password   "Password for %U:"
+
+//d:Incorrect password error note
+//l:popup_note_window
+//w:
+//r:3.0
+#define qtn_cm_incorrect_password   "Incorrect password"
+
+//d:Information note shown if nothing was saved
+//l:popup_note_window
+//w:
+//r:3.0
+#define qtn_cm_pkcs12_saving_failed "The contents could not be saved"
+
+//d:Text shown when validity period of the private key is expired.
+//l:popup_note_window
+//w:
+//r:3.0
+#define qtn_cm_pkcs12_expired    "Not saved. Validity period expired."
+
+//d:Text shown when the format of the PKCS#12 is not supported.
+//l:popup_note_window
+//w:
+//r:3.0
+#define qtn_cm_pkcs12_format_not_supported "The file format is not supported."
+
+//d:Selectable item in the trust setting multiselection list pop-up query
+//l:list_single_graphic_pane_t1_cp2
+//w:
+//r:3.0
+#define qtn_cm_list_mail_image_conn "Internet"
+
+//d:Selectable item in the trust setting multiselection list pop-up query
+//l:list_single_graphic_pane_t1_cp2
+//w:
+//r:3.0
+#define qtn_cm_list_ocsp "Online certicate checking"
+
+//d:Selectable item in the trust setting multiselection list pop-up query
+//l:list_single_graphic_pane_t1_cp2
+//w:
+//r:3.0
+#define qtn_cm_list_vpn "VPN"
+
+//d:Item PKCS#12 file contents message query
+//d:Shown when one private key
+//l:popup_info_list_pane_t1
+//w:
+//r:3.0
+#define qtn_cm_one_private_key    "1 private key"
+
+//d:Item PKCS#12 file contents message query
+//d:Shown when one personal certificate
+//l:popup_info_list_pane_t1
+//w:
+//r:3.0
+#define qtn_cm_one_personal_certificate   "1 personal certificate"
+
+//d:Item PKCS#12 file contents message query
+//d:Shown when one authority certificate
+//l:popup_info_list_pane_t1
+//w:
+//r:3.0
+#define qtn_cm_one_authority_certificate    "1 authority certificate"
+
+//d:Heading text for Trusted site warning query
+//l:heading_pane_t1
+//w:
+//r:3.2
+//
+#define qtn_cm_save_trustedsite_certificate_warning_title   "Warning"
+
+//d:Confirmation query for Trusted site warning query
+//d:%U stands for the name of the site of the certificate.
+//l:popup_note_window
+//w:
+//r:3.2
+//
+#define qtn_cm_save_trustedsite_certificate_warning_text    "Certificate will be added as a Trusted site certificate. Future connections to site %U will be made without certificate warning. Save anyway?"
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/src/CertSaverApp.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,67 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of Application class
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CertSaverApp.h"
+#include    "CertSaverDocument.h"
+
+#include    <eikstart.h>
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertSaverApp::AppDllUid()
+// Returns application UID
+// ---------------------------------------------------------
+//
+TUid CCertSaverApp::AppDllUid() const
+    {
+    return KUidCertSaver;
+    }
+
+// ---------------------------------------------------------
+// CCertSaverApp::CreateDocumentL()
+// Creates CCertSaverDocument object
+// ---------------------------------------------------------
+//
+CApaDocument* CCertSaverApp::CreateDocumentL()
+    {
+    return CCertSaverDocument::NewL( *this );
+    }
+
+// ---------------------------------------------------------
+// NewApplication()
+// Returns created application object
+// ---------------------------------------------------------
+//
+LOCAL_C CApaApplication* NewApplication()
+    {
+    return new CCertSaverApp;
+    }
+
+// ---------------------------------------------------------
+// E32Main()
+// Main startup entry point
+// ---------------------------------------------------------
+//
+GLDEF_C TInt E32Main()
+    {
+    return EikStart::RunApplication( NewApplication );
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/src/CertSaverAppUi.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,230 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of Application UI class
+*
+*/
+
+
+// INCLUDE FILES
+#include <sysutil.h>            // For FFSSpaceBelowCriticalLevelL(..)
+#include <aknnotewrappers.h>    // Note dialogs
+#include <mpkcs12.h>
+#include <cryptostrength.h>
+#include <CertSaver.rsg>
+#include "CertSaverAppUi.h"
+#include "CertSaverContainer.h"
+#include "CertSaverDocument.h"
+#include "CertSaverModel.h"
+
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CCertSaverAppUi::ConstructL()
+// Epoc second phase constructor.
+// ----------------------------------------------------------
+//
+void CCertSaverAppUi::ConstructL()
+    {
+    BaseConstructL( EAknEnableSkin | EAknEnableMSK );
+
+    iContainer = new( ELeave ) CCertSaverContainer();
+    iContainer->ConstructL( ClientRect() );
+    iContainer->SetMopParent( this );
+    AddToStackL( iContainer );
+    }
+
+// ----------------------------------------------------
+// CCertSaverAppUi::~CCertSaverAppUi()
+// Destructor
+// Frees reserved resources
+// ----------------------------------------------------
+//
+CCertSaverAppUi::~CCertSaverAppUi()
+    {
+    delete iModel;
+
+    if( iContainer )
+       {
+       RemoveFromStack( iContainer );
+       delete iContainer;
+       }
+    }
+
+// ------------------------------------------------------------------------------
+// CCertSaverAppUi::::DynInitMenuPaneL(TInt aResourceId,CEikMenuPane* aMenuPane)
+// This function is called by the EIKON framework just before it displays
+// a menu pane. Its default implementation is empty, and by overriding it,
+// the application can set the state of menu items dynamically according
+// to the state of application data.
+// ------------------------------------------------------------------------------
+//
+void CCertSaverAppUi::DynInitMenuPaneL(
+    TInt /*aResourceId*/,CEikMenuPane* /*aMenuPane*/ )
+    {
+    }
+
+// ----------------------------------------------------
+// CCertSaverAppUi::HandleKeyEventL(
+//     const TKeyEvent& aKeyEvent,TEventCode /*aType*/)
+// No key events are handled by the application.
+// ----------------------------------------------------
+//
+TKeyResponse CCertSaverAppUi::HandleKeyEventL(
+    const TKeyEvent& /*aKeyEvent*/,TEventCode /*aType*/ )
+    {
+    return EKeyWasNotConsumed;
+    }
+
+// ----------------------------------------------------
+// CCertSaverAppUi::HandleCommandL(TInt aCommand)
+// In principle, this function does nothing, because all
+// input is handled by dialogs.
+// ----------------------------------------------------
+//
+void CCertSaverAppUi::HandleCommandL( TInt aCommand )
+    {
+    switch ( aCommand )
+        {
+        case EEikCmdExit:
+            {
+            doExit();
+            break;
+            }
+        default:
+            break;
+        }
+    }
+
+// ----------------------------------------------------
+// CCertSaverAppUi::RunFileL(const TDesC& aFileName)
+// Create CCertSaver dialog class and activates the
+// dialog.
+// ----------------------------------------------------
+//
+void CCertSaverAppUi::RunFileL(RFile& aFile)
+    {
+    TCrypto::TStrength cryptoStrength = TCrypto::Strength();
+    if ( TCrypto::EWeak == cryptoStrength )
+        {
+        User::Panic( KCertSaverPanic, KErrWrongCryptoLib );
+        }
+    ((CCertSaverDocument*)iDocument)->Parser().SetContentL( aFile );
+
+    iModel = new (ELeave) CCertSaverModel(
+        this, ((CCertSaverDocument*)iDocument)->Parser());
+
+    switch ( Document()->Parser().CertType() )
+        {
+        case CCertParser::ETypeX509CA:
+            {
+            iModel->SaveCertificateL( (Document()->Parser().Certificate()),
+                ECACertificate, EX509Certificate );
+            break;
+            }
+        case CCertParser::ETypeX509Peer:
+            {
+            iModel->SaveCertificateL( (Document()->Parser().Certificate()),
+                EPeerCertificate, EX509Certificate );
+            break;
+            }
+        case CCertParser::ETypePKCS12:
+            {
+            iModel->SavePKCS12L();
+            break;
+            }
+        case CCertParser::ETypeCorrupt:
+            {
+            // Do nothing
+            break;
+            }
+        default:
+            {
+            break;
+            }
+        }
+    }
+
+// ----------------------------------------------------
+// CCertSaverAppUi::CoeEnv()
+// Returns pointer to the control environment.
+// ----------------------------------------------------
+//
+const CCoeEnv* CCertSaverAppUi::CoeEnv() const
+    {
+    return iCoeEnv;
+    }
+
+// ----------------------------------------------------
+// CCertSaverAppUi::doExit()
+// Exits the application and notifies iDoorObserver about it.
+// ----------------------------------------------------
+//
+void CCertSaverAppUi::doExit()
+    {
+    if ( iDoorObserver )
+        {
+        iDoorObserver->NotifyExit( MApaEmbeddedDocObserver::EEmpty );
+        }
+    Exit();
+    }
+
+// ----------------------------------------------------
+// CCertSaverAppUi::HandleError(TInt aError,
+// const SExtendedError& aExtErr, TDes& aErrorText,
+// TDes& aContextText)
+// When a leave that is not trapped by application occurs,
+// this function is called.
+// ----------------------------------------------------
+//
+TErrorHandlerResponse CCertSaverAppUi::HandleError(
+    TInt aError,
+    const SExtendedError& aExtErr,
+    TDes& aErrorText,
+    TDes& aContextText )
+    {
+    iErrorOccured = ETrue;
+    return CAknAppUi::HandleError( aError, aExtErr, aErrorText, aContextText );
+    }
+
+// ----------------------------------------------------
+// CCertSaverAppUi::HandleForegroundEventL(TBool aForeground)
+// Exits the application if leave occurs. Leave is noticed by
+// member varible iErrorOccured. It is set to ETrue in
+// CCertSaverAppUi::HandleError. After error note has been
+// shown (by HandleError), this function is called by
+// framework.
+// ----------------------------------------------------
+//
+void CCertSaverAppUi::HandleForegroundEventL( TBool aForeground )
+    {
+    if ( iErrorOccured )
+        {
+        doExit();
+        }
+    CAknAppUi::HandleForegroundEventL( aForeground );
+    }
+// ----------------------------------------------------
+// CCertSaverAppUi::ProcessCommandParametersL()
+// ----------------------------------------------------
+//
+TBool CCertSaverAppUi::ProcessCommandParametersL(
+    TApaCommand /*aCommand*/,
+    TFileName& /*aDocumentName*/,
+    const TDesC8& /*aTail*/ )
+    {
+    return ETrue;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/src/CertSaverContainer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,135 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of CCertSaverContainer class
+*
+*/
+
+
+// INCLUDE FILES
+#include <AknDef.h>
+#include <AknsDrawUtils.h>
+#include <AknUtils.h>
+#include "CertSaverContainer.h"
+
+
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CCertSaverContainer::ConstructL()
+// EPOC second phase constructor.
+// ----------------------------------------------------------
+//
+void CCertSaverContainer::ConstructL( const TRect& aRect )
+    {
+    iBgContext = CAknsBasicBackgroundControlContext::NewL( KAknsIIDQsnBgAreaMain,
+                   Rect(), EFalse );
+
+    CreateWindowL();
+    SetRect(aRect);
+    ActivateL();
+    }
+
+// ----------------------------------------------------
+// CCertSaverContainer::~CCertSaverAppUi()
+// Destructor
+// Frees reserved resources
+// ----------------------------------------------------
+//
+CCertSaverContainer::~CCertSaverContainer()
+    {
+    delete iBgContext;
+    }
+
+
+// ----------------------------------------------------
+// CCertSaverContainer::CountComponentControls()
+// Return count of control components.
+// ----------------------------------------------------
+//
+TInt CCertSaverContainer::CountComponentControls() const
+    {
+    return 0;
+    }
+
+
+// ----------------------------------------------------
+// CCertSaverContainer::ComponentControl()
+// Return control pointer.
+// ----------------------------------------------------
+//
+CCoeControl* CCertSaverContainer::ComponentControl( TInt /*aIndex*/ ) const
+    {
+    return NULL;
+    }
+
+// ----------------------------------------------------
+// CCertSaverContainer::Draw()
+// Clear whole screen.
+// ----------------------------------------------------
+//
+void CCertSaverContainer::Draw( const TRect& aRect ) const
+    {
+    CWindowGc& gc = SystemGc();
+
+    MAknsSkinInstance* skin = AknsUtils::SkinInstance();
+    MAknsControlContext* cc = AknsDrawUtils::ControlContext( this );
+
+    AknsDrawUtils::Background( skin, cc, this, gc, aRect );
+    }
+
+
+// ----------------------------------------------------
+// CCertSaverContainer::HandleResourceChange()
+// Notifier for changing language
+// ----------------------------------------------------
+//
+void CCertSaverContainer::HandleResourceChange( TInt aType )
+    {
+    CCoeControl::HandleResourceChange( aType );
+
+    if ( aType == KEikDynamicLayoutVariantSwitch )
+        {
+        TRect mainPaneRect;
+        AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::EMainPane, mainPaneRect );
+        SetRect( mainPaneRect );
+        DrawNow();
+        }
+    }
+
+// ----------------------------------------------------
+// CCertSaverContainer::SizeChanged()
+// Control size is set
+// ----------------------------------------------------
+//
+void CCertSaverContainer::SizeChanged()
+    {
+    iBgContext->SetRect( Rect() );
+    }
+
+// ----------------------------------------------------
+// CCertSaverContainer::MopSupplyObject()
+// Pass skin information if need.
+// ----------------------------------------------------
+//
+TTypeUid::Ptr CCertSaverContainer::MopSupplyObject( TTypeUid aId )
+    {
+    if( aId.iUid == MAknsControlContext::ETypeId )
+      {
+      return MAknsControlContext::SupplyMopObject( aId, iBgContext );
+      }
+    return CCoeControl::MopSupplyObject( aId );
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/src/CertSaverDocument.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,164 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Document class
+*
+*/
+
+
+// INCLUDE FILES
+#include "CertSaverDocument.h"
+#include "CertSaverAppUi.h"
+
+// Class CShutterAO
+// ================= MEMBER FUNCTIONS =======================
+// Constructor
+CShutterAO::CShutterAO(): CActive( EPriorityStandard )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// Destructor
+CShutterAO::~CShutterAO()
+    {
+    Cancel();
+    }
+
+//------------------------------------------------------
+// CShutterAO::Exit()
+//
+//------------------------------------------------------
+//
+void CShutterAO::Exit()
+    {
+    SetActive();
+    // Complete the AO immediately so that buffer processing can occur in RunL().
+    TRequestStatus* statusPtr = &iStatus;
+    User::RequestComplete( statusPtr, KErrNone );
+    }
+
+//------------------------------------------------------
+// CShutterAO::DoCancel()
+//
+//------------------------------------------------------
+//
+void CShutterAO::DoCancel()
+    {
+    }
+
+//------------------------------------------------------
+// CShutterAO::RunL()
+//
+//------------------------------------------------------
+//
+void CShutterAO::RunL()
+    {
+    iAvkonAppUi->Exit();
+    }
+
+// class CCertSaverDocument
+// ================= MEMBER FUNCTIONS =======================
+// destructor
+CCertSaverDocument::~CCertSaverDocument()
+    {
+    delete iParser;
+    delete iAO;
+    }
+
+// EPOC default constructor can leave.
+void CCertSaverDocument::ConstructL()
+    {
+    iParser = CCertParser::NewL();
+    }
+
+// Two-phased constructor.
+CCertSaverDocument* CCertSaverDocument::NewL(
+        CEikApplication& aApp )     // CCertSaverApp reference
+    {
+    CCertSaverDocument* self =
+        new (ELeave) CCertSaverDocument( aApp );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop(self);
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverDocument::OpenFileL
+// Called by the framework to open a certificate file with file name.
+// -----------------------------------------------------------------------------
+//
+
+CFileStore* CCertSaverDocument::OpenFileL(TBool /*aDoOpen*/,
+    const TDesC& aFilename, RFs& aFs )
+    {
+    CFileStore* docStore=NULL;
+
+    RFile file;
+    TInt err = file.Open( aFs, aFilename, EFileRead );
+    User::LeaveIfError( err );
+    CleanupClosePushL<RFile>( file );
+
+    OpenFileL( docStore, file );
+
+    CleanupStack::PopAndDestroy(); // Close file
+
+    return docStore;
+    }
+
+// ----------------------------------------------------
+// CCertSaverDocument::OpenFileL
+// Since Uikon framework always starts application from
+// this function, Certificate Saver uses this function
+// to handle the certificate file. Doc Handler sets
+// aDoOpen to ETrue.
+// ----------------------------------------------------
+//
+void CCertSaverDocument::OpenFileL(CFileStore*& /*aFileStore*/, RFile& aFile)
+    {
+    TRAPD( err, STATIC_CAST(CCertSaverAppUi*,iAppUi)->RunFileL( aFile ) );
+
+    if ( err != KErrNone && err != KErrExitApp && err != KErrCancel )
+        {
+        User::Leave( err );
+        }
+
+    iAO = new (ELeave) CShutterAO;
+    iAO->Exit();
+    #ifdef _DEBUG
+        RDebug::Print( _L("Exiting OpenFileL") );
+    #endif
+    }
+
+//------------------------------------------------------
+// CCertSaverDocument::Parser()
+//
+//------------------------------------------------------
+//
+CCertParser& CCertSaverDocument::Parser() const
+    {
+    return *iParser;
+    }
+
+// ----------------------------------------------------
+// CCertSaverDocument::CreateAppUiL()
+// constructs CCertSaverAppUi
+// ----------------------------------------------------
+//
+CEikAppUi* CCertSaverDocument::CreateAppUiL()
+    {
+    return new (ELeave) CCertSaverAppUi;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/src/CertSaverModel.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1634 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Class that handles user input and launching of dialogs
+*
+*/
+
+
+// INCLUDE FILES
+#include <aknnotewrappers.h>        // Note dialogs
+#include <aknmessagequerydialog.h>  // For CAknMessageQueryDialog
+#include <StringLoader.h>           // For loading resource strings
+#include <unifiedcertstore.h>       // For saving the certificates
+#include <mctwritablecertstore.h>   // For saving the certificates
+#include <sysutil.h>                // For FFSSpaceBelowCriticalLevelL(..)
+#include <X509CertNameParser.h>     // For default label
+#include <x509cert.h>               // For CX509Certificate
+#include <wtlscert.h>               // For WTLSCertificate
+#include <hash.h>                   // MD5 fingerprint
+#include <certificateapps.h>
+#include <mctkeystore.h>
+#include <securityerr.h>
+#include <asnpkcs.h>
+#include <unifiedkeystore.h>
+#include <x509certext.h>
+#include <mctkeystore.h>
+#include <TrustedSitesStore.h>
+
+#include <CertSaver.rsg>
+#include "CertSaverModel.h"
+#include "CertSaverDocument.h"
+#include "CertSaverAppUi.h"
+#include "CertSaverSyncWrapper.h"
+#include "certsaver.hrh"
+#include "securityuisvariant.hrh"
+
+// CONSTANTS
+const TInt32 KWTLSTrusterUID( 268479059 );
+const TInt32 KInternetTrusterUID( 268441661 );
+const TInt32 KApplicationControllerTrusterUID( 268452523 );
+const TInt32 KJavaInstallTrusterUID( 270506792 );
+const TInt32 KOCSPTrusterUID( 268478646 );
+const TInt32 KVPNUID( 270498195 );
+
+const TInt KTrusterArrayInitSize( 2 );
+
+const TInt KMaxLengthTextMeassageBody( 5000 );
+const TInt KMaxLengthTextDateString( 11 );    // "dd/mm/yyyy0"
+
+//Issuer and Owner max visible length
+const TInt KMaxLengthTextCertIdentifierVisible( 1000 );
+const TInt KAttempts( 3 );
+
+const TInt KFingerprintLength( 50 );
+
+_LIT( KCertSaverListBoxItemPrefix, "1\t" );
+const TInt KItemBufLen = 2 + KMaxName;
+
+_LIT( KPrivateKeyLabel, "PrivateKey " );
+const TInt KPrivaKeyLabelLength( 50 );
+_LIT( KDateString,"%D%M%Y%1%2%3" );
+_LIT( KTimeString,"%-B%:0%J%:1%T%:2%S%:3%+B" );
+_LIT( KSpace, " " );
+_LIT( KDoubleEnter, "\n\n" );
+_LIT( KEnter, "\n" );
+
+const TUid KTrustedServerTokenUid = { 0x101FB66F };
+const TUid KFileTokensUid = { 0x101F501A };
+
+_LIT_SECURITY_POLICY_V1( KSymbianKeyStoreMgmtPolicy,
+                         VID_DEFAULT, ECapabilityWriteUserData );
+_LIT_SECURITY_POLICY_C1( KSymbianKeyStoreUsePolicy, ECapabilityReadUserData );
+
+
+// ================= MEMBER FUNCTIONS =======================
+
+// Destructor
+CCertSaverModel::~CCertSaverModel()
+    {
+    delete iWrapper;
+    iEntries.Close();
+    delete iUnifiedCertStore;
+    iTrusterUids.Close();
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::CCertSaverModel(
+//    const CCertSaverDocument* aDocument, CCertSaverAppUi* aAppUi)
+// ----------------------------------------------------------
+//
+CCertSaverModel::CCertSaverModel(
+    CCertSaverAppUi* aAppUi,
+    const CCertParser& aParser ):
+    iAppUi( aAppUi ), iFs( iAppUi->CoeEnv()->FsSession() ), iParser( aParser ),
+    iSavedCACertsCount( 0 ), iSavedKeysCount( 0 ),
+    iSavedUserCertsCount( 0 ), iKeyAlreadyExists( EFalse )
+    {
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::SaveCertificateL()
+// ----------------------------------------------------------
+//
+void CCertSaverModel::SaveCertificateL(
+            const CX509Certificate& aCertificate,
+            const TCertificateOwnerType& aOwnerType,
+            const TCertificateFormat& aCertFormat )
+    {
+    iCertOwnerType = aOwnerType;
+    iCertFormat = aCertFormat;
+    iNewCert = &aCertificate;
+
+    if ( aOwnerType == EPeerCertificate )
+        {
+        TInt ret = QueryTrustedSiteL();
+        if ( ret != KErrNone )
+            {
+             return;
+            }
+        }
+
+    SaveCertL();
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::DoSavePrivateKeyL()
+//
+// ----------------------------------------------------------
+//
+void CCertSaverModel::DoSavePrivateKeyL( const TDesC8& aKey )
+    {
+    CheckFSSpaceL( aKey );
+
+    TKeyIdentifier keyIdentifier;
+    CDecPKCS8Data* pkcs8Data = TASN1DecPKCS8::DecodeDERL( aKey );
+    CleanupStack::PushL( pkcs8Data );
+    MPKCS8DecodedKeyPairData* keyPairData = pkcs8Data->KeyPairData();
+    keyPairData->GetKeyIdentifierL( keyIdentifier );
+
+    TTime startDate;
+    TTime endDate;
+    GetKeyValidityPeriodL( startDate, endDate, keyIdentifier );
+
+    TInt err = KErrNone;
+    CCTKeyInfo* keyInfo = NULL;
+    TBuf<KPrivaKeyLabelLength> keyLabel( KPrivateKeyLabel );
+    TKeyUsagePKCS15 keyUsage = KeyUsageL( keyIdentifier, pkcs8Data->Algorithm() );
+    CleanupStack::PopAndDestroy( pkcs8Data );
+    if (KeyAlreadyExistsL( startDate, endDate, keyIdentifier, keyUsage) )
+        {
+        User::Leave( KErrNone );
+        }
+
+    TInt accessType( 0 );
+
+    accessType |= CCTKeyInfo::EExtractable;
+
+    for ( TInt i = 0; i < KAttempts; i++ )
+        {
+        CreateKeyLabelL( keyLabel );
+        // Should not use hardcoded index
+        err = iWrapper->AddKey( 0, aKey, keyUsage, keyLabel,
+            accessType, startDate, endDate, keyInfo );
+        if ( err != KErrAlreadyExists )
+            {
+            i = KAttempts;
+            }
+        keyLabel.Zero();
+        }
+
+    TCTTokenObjectHandle handle;
+    if ( keyInfo )
+        {
+        handle = keyInfo->Handle();
+        keyInfo->Release();
+        keyInfo = NULL;
+        }
+
+    switch ( err )
+        {
+        case KErrNone:
+            {
+            ++iSavedKeysCount;
+            break;
+            }
+        case KErrKeySize:
+        case KErrArgument:
+            {
+            ShowErrorNoteL( R_CERTSAVER_KEY_TYPE_NOT_SUPPORTED );
+            User::Leave( KErrCancel );
+            break;
+            }
+        case KErrKeyValidity:
+            {
+            ShowInformationNoteL( R_CERTSAVER_QTN_CM_PKCS12_EXPIRED );
+            User::Leave( KErrCancel );
+            }
+        case KErrKeyUsage:
+            {
+            ShowErrorNoteL( R_CERTSAVER_PRIVATE_KEY_CORRUPTED );
+            User::Leave( KErrCancel );
+            break;
+            }
+        case KErrCancel:
+        case KErrPermissionDenied:
+            {
+            ShowErrorNoteL( R_CERTSAVER_PKCS12_DISCARDED );
+            User::Leave( KErrCancel );
+            break;
+            }
+        case KErrCorrupt:
+        case KErrEof:
+            {
+            ShowErrorNoteL( R_CERTSAVER_KEYSTORE_CORRUPTED );
+            User::Leave( KErrCancel );
+            break;
+            }
+        case KErrAlreadyExists:
+            {
+            User::Leave( KErrCancel );
+            break;
+            }
+        default:
+            {
+            User::Leave( err );
+            break;
+            }
+        }
+
+    User::LeaveIfError(
+        iWrapper->SetManagementPolicy( handle, KSymbianKeyStoreMgmtPolicy) );
+    User::LeaveIfError(
+        iWrapper->SetUsePolicy( handle, KSymbianKeyStoreUsePolicy ) );
+    }
+
+// ----------------------------------------------------------
+// TBool CCertSaverModel::KeyAlreadyExistsL()
+//
+// ----------------------------------------------------------
+//
+TBool CCertSaverModel::KeyAlreadyExistsL(
+    TTime& aStartDate,
+    TTime& aEndDate,
+    const TKeyIdentifier& aKeyIdentifier,
+    TKeyUsagePKCS15& aKeyUsage )
+    {
+    TBool ret = EFalse;
+    TCTKeyAttributeFilter keyFilter;
+    keyFilter.iKeyAlgorithm = CKeyInfoBase::EInvalidAlgorithm;
+    keyFilter.iKeyId = aKeyIdentifier;
+    keyFilter.iPolicyFilter = TCTKeyAttributeFilter::EManageableKeys;
+    keyFilter.iUsage = aKeyUsage;
+    RMPointerArray<CCTKeyInfo> keyArray;
+    TInt err = iWrapper->ListKeys( keyArray, keyFilter );
+    CleanupClosePushL( keyArray );
+    switch ( err )
+        {
+        case KErrNone:
+            {
+            break;
+            }
+        case KErrCorrupt:
+        case KErrEof:
+            {
+            ShowErrorNoteL( R_CERTSAVER_KEYSTORE_CORRUPTED );
+            User::Leave( KErrCancel );
+            }
+        default:
+            {
+            User::Leave( err );
+            }
+        }
+    for ( TInt i = 0; ret == EFalse && i < keyArray.Count(); i++ )
+        {
+        if ( keyArray[i]->StartDate() == aStartDate &&
+             keyArray[i]->EndDate() == aEndDate )
+            {
+            ret = ETrue;
+            iKeyAlreadyExists = ETrue;
+            }
+        }
+    CleanupStack::PopAndDestroy( &keyArray );
+    return ret;
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::GetKeyValidityPeriodL()
+//
+// ----------------------------------------------------------
+//
+void CCertSaverModel::GetKeyValidityPeriodL(
+    TTime& aStartDate,
+    TTime& aEndDate,
+    const TKeyIdentifier& aKeyIdentifier )
+    {
+
+    for ( TInt i = 0; i < iParser.UserCertificates().Count(); i++ )
+        {
+        const CX509Certificate* cert = iParser.UserCertificates().At( i );
+        if ( cert->KeyIdentifierL() == aKeyIdentifier )
+            {
+            // Associated certificate found
+            // In the first round aStartDate and aEndDate is initialised.
+            if ( i == 0 || aStartDate > cert->ValidityPeriod().Start() )
+                {
+                aStartDate = cert->ValidityPeriod().Start();
+                }
+            if ( i == 0 || aEndDate < cert->ValidityPeriod().Finish() )
+                {
+                aEndDate = cert->ValidityPeriod().Finish();
+                }
+            }
+        }
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::CreateKeyLabelL()
+//
+// ----------------------------------------------------------
+//
+void CCertSaverModel::CreateKeyLabelL( TDes& aLabel )
+    {
+    TTime time;
+    time.UniversalTime();
+    TBuf<KPrivaKeyLabelLength> dateBuf;
+    time.FormatL( dateBuf, KDateString );
+    aLabel.Append( dateBuf );
+    dateBuf.Zero();
+    aLabel.Append( KSpace );
+
+    time.FormatL( dateBuf, KTimeString );
+    aLabel.Append( dateBuf );
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::SavePrivateKeyL()
+//
+// ----------------------------------------------------------
+//
+void CCertSaverModel::SavePrivateKeyL()
+    {
+    if ( iParser.Keys().Count() <= 0 )
+        {
+        return;
+        }
+    if ( NULL == iWrapper )
+        {
+        iWrapper = CCertSaverSyncWrapper::NewL();
+        }
+    TInt err = iWrapper->InitializeKeyStoreL( iFs );
+
+    TInt keyStoreCount = iWrapper->UnifiedKeyStore().KeyStoreManagerCount();
+    if ( keyStoreCount <= 0 )
+        {
+        User::Leave( KErrCancel );
+        }
+    else
+        {
+        for ( TInt i = 0; i < keyStoreCount; ++i )
+            {
+            TUid uid =
+            iWrapper->UnifiedKeyStore().KeyStoreManager(i).Token().TokenType().Type();
+            if ( uid == TUid::Uid( KTokenTypeFileKeystore ) )
+                // if this is not found, we use the first one,
+                // which is already initialised
+                {
+                iSelectedKeyStore = i;
+                }
+            }
+        }
+
+    for ( TInt i = 0; i < iParser.Keys().Count(); i++ )
+        {
+        const HBufC8* key = iParser.Keys().At( i );
+        TRAP(err, DoSavePrivateKeyL( *key ));
+        User::LeaveIfError( err );
+        }
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::KeyUsageL(
+//    const TKeyIdentifier& aKeyIdentifier, TAlgorithmId aAlgorithm)
+// ----------------------------------------------------------
+//
+TKeyUsagePKCS15 CCertSaverModel::KeyUsageL(
+    const TKeyIdentifier& aKeyIdentifier,
+    TAlgorithmId aAlgorithm )
+    {
+
+    TKeyUsagePKCS15 pkcs15KeyUsage = EPKCS15UsageNone;
+    TKeyUsageX509 x509Usage = EX509UsageNone;
+
+    for ( TInt i = 0; i < iParser.UserCertificates().Count(); i++ )
+        {
+        const CX509Certificate* cert = iParser.UserCertificates().At( i );
+        if ( cert->KeyIdentifierL() == aKeyIdentifier )
+            {
+            const CX509CertExtension* ext = cert->Extension( KKeyUsage );
+            if (ext)
+                {
+                CX509KeyUsageExt* keyUsageExt =
+                    CX509KeyUsageExt::NewLC( ext->Data() );
+                if ( keyUsageExt->IsSet( EX509DigitalSignature ) )
+                  {
+                  x509Usage |= EX509UsageDigitalSignature;
+                  }
+                if ( keyUsageExt->IsSet( EX509NonRepudiation ) )
+                  {
+                  x509Usage |= EX509UsageNonRepudiation;
+                  }
+                if ( keyUsageExt->IsSet( EX509KeyEncipherment ) )
+                  {
+                  x509Usage |= EX509UsageKeyEncipherment;
+                  }
+                if ( keyUsageExt->IsSet( EX509DataEncipherment ) )
+                  {
+                  x509Usage |= EX509UsageDataEncipherment;
+                  }
+                if ( keyUsageExt->IsSet( EX509KeyAgreement ) )
+                  {
+                  x509Usage |= EX509UsageKeyAgreement;
+                  }
+                if ( keyUsageExt->IsSet( EX509KeyCertSign ) )
+                  {
+                  x509Usage |= EX509UsageKeyCertSign;
+                  }
+                if ( keyUsageExt->IsSet( EX509CRLSign ) )
+                  {
+                  x509Usage |= EX509UsageCRLSign;
+                  }
+                if ( keyUsageExt->IsSet( EX509EncipherOnly ) )
+                  {
+                  x509Usage |= EX509UsageEncipherOnly;
+                  }
+                if ( keyUsageExt->IsSet( EX509DecipherOnly ) )
+                  {
+                  x509Usage |= EX509UsageDecipherOnly;
+                  }
+                CleanupStack::PopAndDestroy( keyUsageExt );
+                }
+            }
+        }
+
+    pkcs15KeyUsage = KeyUsageX509ToPKCS15Private( x509Usage );
+    // If any certificate in the file did not include key usage,
+    // let's use default values.
+    if ( EPKCS15UsageNone == pkcs15KeyUsage )
+        {
+        switch ( aAlgorithm )
+            {
+            case ERSA:
+                {
+                pkcs15KeyUsage |= EPKCS15UsageSignSignRecover;
+                pkcs15KeyUsage |= EPKCS15UsageDecryptUnwrap;
+                break;
+                }
+            case EDSA:
+                {
+                pkcs15KeyUsage |= EPKCS15UsageSignSignRecover;
+                break;
+                }
+            default:
+                {
+                break;
+                }
+            }
+        }
+    return pkcs15KeyUsage;
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::CheckFSSpaceL(
+//    const TDesC8& aDataToSave)
+// ----------------------------------------------------------
+//
+void CCertSaverModel::CheckFSSpaceL( const TDesC8& aDataToSave )
+    {
+    if (SysUtil::FFSSpaceBelowCriticalLevelL( &iFs, aDataToSave.Size() ))
+        {
+        HBufC* p = StringLoader::LoadLC( R_CERTSAVER_MEMORY );
+        CAknErrorNote* note = new (ELeave) CAknErrorNote( ETrue );
+        note->ExecuteLD( p->Des() );
+        CleanupStack::PopAndDestroy( p );
+        User::Leave( KErrExitApp );
+        }
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::SaveCertL()
+// Saves certificate
+// ----------------------------------------------------------
+//
+void CCertSaverModel::SaveCertL()
+  {
+    if ( !CertificateOkL() )
+        {
+        User::Leave( KErrCancel );
+        }
+
+    HBufC* message = HBufC::NewLC( KMaxLengthTextMeassageBody );
+    TPtr msgPtr = message->Des();
+    ConstructMessageL( msgPtr );
+    CAknMessageQueryDialog* dlg = CAknMessageQueryDialog::NewL( *message );
+    CleanupStack::PopAndDestroy( message );
+    CleanupStack::PushL( dlg );
+
+
+    dlg->PrepareLC( R_MESSAGE_QUERY_DOSAVE );
+
+    HBufC* header = StringLoader::LoadLC( R_CERTSAVER_DETAILS_HEADING );
+    dlg->QueryHeading()->SetTextL( header->Des() );
+    CleanupStack::PopAndDestroy( header );
+    CleanupStack::Pop( dlg );
+    TBool doSave = dlg->RunLD();
+
+    if ( doSave && iCertOwnerType == ECACertificate )
+        {
+        // warn user about security risk
+        CAknQueryDialog* warningDialog = CAknQueryDialog::NewL();
+        doSave = warningDialog->ExecuteLD( R_CERTSAVER_WARNING_NOTE );
+        }
+
+    if ( doSave )
+        {
+        //Check that there still is enough space to store the
+        //certificate.
+        CheckFSSpaceL( iNewCert->Encoding() );
+        DoSaveCertL();
+        }
+    else
+        {
+        ShowConfirmationNoteL( R_CERTSAVER_CERT_DISCARDED );
+        User::Leave( KErrCancel );
+        }
+  }
+
+// ----------------------------------------------------------
+// CCertSaverModel::InitCertStoreL()
+//
+// ----------------------------------------------------------
+//
+void CCertSaverModel::InitCertStoreL()
+    {
+    if ( !iUnifiedCertStore )
+        {
+        TRAPD( status, iUnifiedCertStore = CUnifiedCertStore::NewL( iFs, ETrue ) );
+        if ( status != KErrNone )
+            {
+            ShowErrorNoteL( R_CERTSAVER_ERROR_CACERTS_DB_CORRUPTED );
+            User::Leave( KErrExitApp );
+            }
+        // initialize unified cert store
+        status = iWrapper->InitializeCertStore( *iUnifiedCertStore );
+        if ( status )
+            {
+            HandleSaveErrorL( status );
+            User::Leave( KErrExitApp );
+            }
+        }
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::DoSaveCertL()
+// Tries to save the certificate to phone memory.
+// ----------------------------------------------------------
+//
+void CCertSaverModel::DoSaveCertL()
+    {
+    TInt status = KErrNone;
+    CCertAttributeFilter* filter = NULL;
+    TCertificateFormat certFormat = EX509Certificate;
+    HBufC* secondaryName = NULL;
+    TCertLabel labelBuf;
+    CCertificate* certificate = NULL;
+    HBufC* label = NULL;
+
+    if ( NULL == iWrapper )
+        {
+        iWrapper = CCertSaverSyncWrapper::NewL();
+        }
+    // Init unified certstore
+    InitCertStoreL();
+
+    // Check that certificate doesn't already exist.
+    // Fingerprint of certificate is used to confirm this.
+    filter = CCertAttributeFilter::NewL();
+    filter->SetFormat( iCertFormat );
+    filter->SetOwnerType( iCertOwnerType );
+    // Delete old array first
+    iEntries.Close();
+    status = iWrapper->ListCerts( *iUnifiedCertStore, iEntries, *filter );
+    delete filter;
+    filter = NULL;
+    if ( status )
+        {
+        if ( status != KErrCancel )
+            {
+            HandleSaveErrorL( status );
+            }
+        User::Leave( KErrExitApp );
+        }
+
+    TBool found = EFalse;
+
+    for ( TInt i = 0; i < iEntries.Count() && !found; ++i )
+        {
+        iWrapper->Retrieve( *iUnifiedCertStore, *iEntries[i], certificate );
+        // Compare fingerprint of listed certificates to
+        // fingerprint of new certificate
+        // If the certificate is already in CACerts.dat,
+        // then don't save it
+        if ( iNewCert->Fingerprint() == certificate->Fingerprint() &&
+            (( *iEntries[i]).Handle().iTokenHandle.iTokenTypeUid == KFileTokensUid ) )
+            {
+            found = ETrue;
+            }
+        delete certificate;
+        certificate = NULL;
+        }
+
+    // Cancel if certificate already exists.
+    if ( found )
+        {
+        HandleSaveErrorL( KErrAlreadyExists );
+        User::Leave( KErrCancel );
+        }
+
+    // Create default label from the certificate
+    X509CertNameParser::PrimaryAndSecondaryNameL(
+        (*(CX509Certificate*)iNewCert), label, secondaryName );
+    CleanupStack::PushL( label );
+    delete secondaryName;
+    secondaryName = NULL;
+    labelBuf = label->Des().Left( CERTSAVER_MAX_LABEL_LEN );
+    CleanupStack::PopAndDestroy( label );
+    label = NULL;
+    // Asks unique label from user.
+    status = QueryLabelL( labelBuf, *iUnifiedCertStore );
+    if ( status )
+        {
+        if ( status != KErrCancel )
+            {
+            HandleSaveErrorL( status );
+            }
+        User::Leave( KErrCancel );
+        }
+
+    if ( ECACertificate == iCertOwnerType )
+        {
+        // Query trusted UIDs
+        status = QueryTrusterUidsL( iTrusterUids );
+        if ( status )
+            {
+            HandleSaveErrorL( status );
+            User::Leave( KErrCancel );
+            }
+        }
+
+    // Get interface to writable store.
+    TInt certstoreIndex( -1 );
+    TInt count = iUnifiedCertStore->WritableCertStoreCount();
+    if ( count > 0 )
+        {
+        for ( TInt i = 0; i < count; i++ )
+            {
+            MCTWritableCertStore& writableCertStore =
+                    iUnifiedCertStore->WritableCertStore( i );
+
+            MCTToken& token = writableCertStore.Token();
+            TUid tokenuid = token.Handle().iTokenTypeUid;
+            if ( ( tokenuid == KTrustedServerTokenUid ) && ( iCertOwnerType == EPeerCertificate ) ||
+                 ( tokenuid == KFileTokensUid ) && ( iCertOwnerType == ECACertificate ) ||
+                 ( tokenuid == KFileTokensUid ) && ( iCertOwnerType == EUserCertificate ) )
+                {
+                certstoreIndex = i;
+                break;
+                }
+            }
+
+        if ( certstoreIndex < 0 )
+            {
+            // Couldn't find certificate storage
+            ShowErrorNoteL( R_CERTSAVER_ERROR_CACERTS_DB_CORRUPTED );
+            User::Leave( KErrExitApp );
+            }
+
+        status = iWrapper->AddCert( iUnifiedCertStore->WritableCertStore( certstoreIndex ),
+                        labelBuf, iCertFormat, iCertOwnerType, 0, 0, iNewCert->Encoding() );
+
+        if ( ( status == KErrNone ) && ( iCertOwnerType == EPeerCertificate) )
+            {
+            // Adding certificate succeded. Update trust site storage
+            CTrustSitesStore* trustedSitesStore = CTrustSitesStore::NewL();
+            CleanupStack::PushL( trustedSitesStore );
+            TPtrC8 certBuf = iParser.CertificateBuf();
+            TInt err = trustedSitesStore->AddL( certBuf, labelBuf );
+            CleanupStack::PopAndDestroy( trustedSitesStore );
+            }
+
+        // If error happened, show error note and give up. Otherwise, continue
+        HandleSaveErrorL( status );
+        if ( status )
+            {
+            User::Leave( KErrCancel );
+            }
+        else
+            {
+            if ( ECACertificate == iCertOwnerType )
+                {
+                ++iSavedCACertsCount;
+                }
+            else
+                {
+                ++iSavedUserCertsCount;
+                }
+            }
+        }
+    else
+        {
+        // If there is none WritableCertStore,
+        // then at least cacerts.dat is corrupted.
+        ShowErrorNoteL( R_CERTSAVER_ERROR_CACERTS_DB_CORRUPTED );
+        User::Leave( KErrExitApp );
+        }
+
+    if ( ECACertificate == iCertOwnerType )
+        {
+        // get just saved certificate
+        // first, create a filter
+        filter = CCertAttributeFilter::NewL();
+        filter->SetLabel( labelBuf );
+        filter->SetFormat( certFormat );
+        filter->SetOwnerType( ECACertificate );
+
+        // Delete array
+        iEntries.Close();
+        // then list certificates
+        status = iWrapper->ListCerts( *iUnifiedCertStore, iEntries, *filter );
+        delete filter;
+        filter = NULL;
+
+        // If error happened, show error note and give up. Otherwise, continue
+        if ( status )
+            {
+            HandleSaveErrorL( status );
+            User::Leave( KErrExitApp );
+            }
+
+        // takes ownership of trusterUids
+        status = iWrapper->SetApplicability(
+            iUnifiedCertStore->WritableCertStore( certstoreIndex ), *(iEntries[0]), iTrusterUids );
+
+        // If error happened, show error note and give up. Otherwise, continue
+        if ( status )
+            {
+            HandleSaveErrorL( status );
+            User::Leave( KErrExitApp );
+            }
+
+        // Downloaded certificate is trusted by default
+        status = iWrapper->SetTrust(
+            iUnifiedCertStore->WritableCertStore(certstoreIndex), *(iEntries[0]), ETrue );
+        if ( status )
+            {
+            HandleSaveErrorL( status );
+            }
+
+
+        } // if ( ECACertificate == iCertOwnerType )
+    }
+// ----------------------------------------------------------
+// CCertSaverModel::QueryLabel()
+// Queries label from user and confirms that it doesn't
+// already exist.
+// ----------------------------------------------------------
+//
+TInt CCertSaverModel::QueryLabelL( TCertLabel& aLabel, CUnifiedCertStore& aStore )
+    {
+    CCertAttributeFilter* filter = NULL;
+    TInt status = KErrNone;
+    RMPointerArray<CCTCertInfo> entries;
+    TBool loop = ETrue;
+
+    while ( loop )
+        {
+        CAknTextQueryDialog* dialog = CAknTextQueryDialog::NewL( aLabel );
+      if ( !dialog->ExecuteLD( R_CERTSAVER_LABEL_QUERY ) )
+            {
+            // cancel
+            ShowConfirmationNoteL( R_CERTSAVER_CERT_DISCARDED );
+            return KErrCancel;
+            }
+        // Create filter to confirm that label doesn't already exist.
+        filter = CCertAttributeFilter::NewL();
+        filter->SetLabel( aLabel );
+
+        // then list certificates
+        status = iWrapper->ListCerts( aStore, entries, *filter );
+        CleanupClosePushL( entries );
+        delete filter;
+
+        // If error happened, show error note and give up. Otherwise, continue
+        if ( status )
+            {
+            HandleSaveErrorL( status );
+            User::Leave( KErrExitApp );
+            }
+
+        if ( entries.Count() )
+            {
+            // Label already exists. Label is queried again.
+            HandleSaveErrorL( KErrBadName );
+            }
+        else
+            {
+            // Label didn't exist.
+            loop = EFalse;
+            }
+        CleanupStack::PopAndDestroy( &entries ); // entries
+        } // while
+
+    return status;
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::HandleSaveErrorL() const
+// Shows a note according to aStatus. aStatus is the status
+// of the save operation.
+// ----------------------------------------------------------
+//
+void CCertSaverModel::HandleSaveErrorL( TInt aStatus ) const
+    {
+    switch ( aStatus )
+        {
+        case KErrNone:
+            {
+            ShowConfirmationNoteL( R_CERTSAVER_ERROR_SAVEOK );
+            break;
+            }
+        case KErrNotSupported:
+            {
+            ShowErrorNoteL( R_CERTSAVER_ERROR_UNSUPPORTED_CERT );
+            break;
+            }
+        case KErrBadName:
+            {
+            ShowErrorNoteL( R_CERTSAVER_ERROR_LABEL_ALREADY_EXISTS );
+            break;
+            }
+        case KErrAlreadyExists:
+            {
+            ShowErrorNoteL( R_CERTSAVER_ERROR_ALREADY_EXISTS );
+            break;
+            }
+        case KErrArgument:
+            {
+            ShowErrorNoteL( R_CERTSAVER_ERROR_CACERTS_DB_CORRUPTED );
+            break;
+            }
+        default:
+            {
+            //No error note defined for unknown error.
+            User::Leave( aStatus );
+            break;
+            }
+        }   //switch
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::AddToMessageWithStringL() const
+// String loaded from resources with StringLoader.
+// ----------------------------------------------------------
+//
+void CCertSaverModel::AddToMessageWithStringL(
+    TDes& aMessage, TInt aStringResID, const TDesC& aString ) const
+    {
+    HBufC* promptPtr = NULL;
+    promptPtr = StringLoader::LoadL( aStringResID, aString );
+    CleanupStack::PushL( promptPtr );
+    TPtrC prompt( promptPtr->Des() );
+
+    aMessage.Append( prompt );
+
+    CleanupStack::PopAndDestroy( promptPtr ); // promptPtr
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::AddToMessageWithStringL() const
+// String loaded from resources with StringLoader.
+// ----------------------------------------------------------
+//
+void CCertSaverModel::AddToMessageWithIntL(
+    TDes& aMessage,
+    TInt aStringResID,
+    TInt aInt ) const
+    {
+    HBufC* promptPtr = NULL;
+    promptPtr = StringLoader::LoadL( aStringResID, aInt );
+    CleanupStack::PushL( promptPtr );
+    TPtrC prompt( promptPtr->Des() );
+
+    aMessage.Append( prompt );
+    aMessage.Append( KEnter );
+
+    CleanupStack::PopAndDestroy( promptPtr ); // promptPtr
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::AddToMessageL() const
+// String loaded from resources with StringLoader.
+// ----------------------------------------------------------
+//
+void CCertSaverModel::AddToMessageL( TDes& aMessage, TInt aStringResID ) const
+    {
+    HBufC* promptPtr = NULL;
+    promptPtr = StringLoader::LoadL( aStringResID );
+    CleanupStack::PushL( promptPtr );
+    TPtrC prompt( promptPtr->Des() );
+
+    aMessage.Append( prompt );
+    aMessage.Append( KEnter );
+
+    CleanupStack::PopAndDestroy( promptPtr ); // promptPtr
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::ConstructMessageL() const
+// Creates the certificate details message shown to the user.
+// ----------------------------------------------------------
+//
+void CCertSaverModel::ConstructMessageL( TDes& aMessage ) const
+    {
+    HBufC16* issuerName = NULL;
+    HBufC16* subjectName = NULL;
+
+
+    X509CertNameParser::SubjectFullNameL( *((CX509Certificate*)iNewCert),
+        subjectName );
+    CleanupStack::PushL( subjectName );
+
+    X509CertNameParser::IssuerFullNameL( *((CX509Certificate*)iNewCert),
+        issuerName );
+    CleanupStack::PushL( issuerName );
+
+    AddToMessageWithStringL( aMessage, R_CERTSAVER_TEXT_LABEL,
+        CutCertificateField(*subjectName) );
+    AddNewlinesToMessage( aMessage );
+
+    AddToMessageWithStringL( aMessage, R_CERTSAVER_TEXT_ISSUER,
+        CutCertificateField( *issuerName ) );
+    CleanupStack::PopAndDestroy( 2, subjectName );
+    AddNewlinesToMessage( aMessage );
+
+    if ( iCertOwnerType==EUserCertificate )
+        {
+        AddKeyUsageL( aMessage, *((CX509Certificate*)iNewCert) );
+        }
+
+    AddValidityPeriodL( aMessage, *((CX509Certificate*)iNewCert) );
+
+    // SHA-1 fingerprint
+    TBuf<KFingerprintLength> divided_fingerprint;
+    DivideToBlocks( iNewCert->Fingerprint(), divided_fingerprint );
+    AddToMessageWithStringL( aMessage, R_CERTSAVER_TEXT_FINGERPRINT,
+        divided_fingerprint );
+
+    AddNewlinesToMessage( aMessage );
+    divided_fingerprint.Zero();
+
+    // MD5 fingerprint
+    CMD5* md5 = CMD5::NewL();
+    CleanupStack::PushL( md5 );
+    TPtrC8 MD5fingerprint = md5->Hash( iNewCert->Encoding() );
+
+    // Divide fingerprint to blocks
+    DivideToBlocks( MD5fingerprint, divided_fingerprint );
+    CleanupStack::PopAndDestroy( md5 );
+    AddToMessageWithStringL( aMessage, R_CERTSAVER_TEXT_FINGERPRINT_MD5,
+        divided_fingerprint );
+    AddNewlinesToMessage( aMessage );
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddKeyUsageL(...)
+// -----------------------------------------------------------------------------
+//
+void CCertSaverModel::AddKeyUsageL( TDes& aMessage, const CX509Certificate& aCert ) const
+    {
+    TKeyUsageX509 x509Usage = EX509UsageNone;
+    TKeyUsagePKCS15 pkcs15KeyUsage = EPKCS15UsageNone;
+    const CX509CertExtension* ext = aCert.Extension( KKeyUsage );
+    if (ext)
+        {
+        CX509KeyUsageExt* keyUsageExt =
+            CX509KeyUsageExt::NewLC( ext->Data() );
+        if ( keyUsageExt->IsSet( EX509DigitalSignature ) )
+            {
+            x509Usage |= EX509UsageDigitalSignature;
+            }
+        if ( keyUsageExt->IsSet( EX509NonRepudiation ) )
+            {
+            x509Usage |= EX509UsageNonRepudiation;
+            }
+        if ( keyUsageExt->IsSet( EX509KeyEncipherment ) )
+            {
+            x509Usage |= EX509UsageKeyEncipherment;
+            }
+        if ( keyUsageExt->IsSet( EX509DataEncipherment ) )
+            {
+            x509Usage |= EX509UsageDataEncipherment;
+            }
+        if ( keyUsageExt->IsSet( EX509KeyAgreement ) )
+            {
+            x509Usage |= EX509UsageKeyAgreement;
+            }
+        if ( keyUsageExt->IsSet( EX509KeyCertSign ) )
+            {
+            x509Usage |= EX509UsageKeyCertSign;
+            }
+        if ( keyUsageExt->IsSet( EX509CRLSign ) )
+            {
+            x509Usage |= EX509UsageCRLSign;
+            }
+        if ( keyUsageExt->IsSet( EX509EncipherOnly ) )
+            {
+            x509Usage |= EX509UsageEncipherOnly;
+            }
+        if ( keyUsageExt->IsSet( EX509DecipherOnly ) )
+            {
+            x509Usage |= EX509UsageDecipherOnly;
+            }
+        CleanupStack::PopAndDestroy( keyUsageExt );
+        }
+
+    pkcs15KeyUsage = KeyUsageX509ToPKCS15Private( x509Usage );
+
+    TInt usage = 0;
+    switch( pkcs15KeyUsage )
+        {
+        case EPKCS15UsageSignSignRecover:
+        case EPKCS15UsageSign:
+        case EPKCS15UsageSignDecrypt:
+            {
+            usage = R_QTN_CM_CLIENT_AUTHENTICATION;
+            break;
+            }
+        case EPKCS15UsageNonRepudiation:
+            {
+            usage = R_QTN_CM_DIGITAL_SIGNING;
+            break;
+            }
+        default:
+            {
+            usage = R_QTN_CM_NOT_DEFINED;
+            break;
+            }
+        }
+    AddToMessageL( aMessage, R_QTN_CM_KEY_USAGE );
+    HBufC* usageString = iAppUi->CoeEnv()->AllocReadResourceLC( usage );
+    aMessage.Append( *usageString );
+    CleanupStack::PopAndDestroy( usageString );
+    AddNewlinesToMessage( aMessage );
+    }
+
+// -----------------------------------------------------------------------------
+// CCTSecurityDialogsAO::AddValidityPeriodL(...)
+// -----------------------------------------------------------------------------
+//
+void CCertSaverModel::AddValidityPeriodL(
+    TDes& aMessage, const CX509Certificate& aCert ) const
+    {
+    // Hometime's offset to UTC
+    TLocale locale;
+    TTimeIntervalSeconds offSet = locale.UniversalTimeOffset();
+    AddToMessageL( aMessage, R_CERTSAVER_QTN_CM_VALID_FROM );
+
+    const CValidityPeriod& validityPeriod = aCert.ValidityPeriod();
+    TTime startValue = validityPeriod.Start();
+    startValue += offSet;
+    TBuf<KMaxLengthTextDateString> startString;
+    // read format string from AVKON resource
+    HBufC* dateFormatString = iAppUi->CoeEnv()->AllocReadResourceLC(
+        R_QTN_DATE_USUAL_WITH_ZERO );
+    // format the date to user readable format. The format is locale dependent
+    startValue.FormatL( startString, *dateFormatString );
+    AknTextUtils::DisplayTextLanguageSpecificNumberConversion( startString );
+    CleanupStack::PopAndDestroy( dateFormatString ); // dateFormatString
+    aMessage.Append( startString );
+    AddNewlinesToMessage( aMessage );
+
+    AddToMessageL( aMessage, R_CERTSAVER_QTN_CM_VALID_UNTIL );
+    TTime finishValue = validityPeriod.Finish();
+    finishValue += offSet;
+    TBuf<KMaxLengthTextDateString> finishString;
+    // read format string from AVKON resource
+    dateFormatString = iAppUi->CoeEnv()->AllocReadResourceLC(
+        R_QTN_DATE_USUAL_WITH_ZERO );
+    // format the date to user readable format. The format is locale dependent
+    finishValue.FormatL( finishString, *dateFormatString );
+    AknTextUtils::DisplayTextLanguageSpecificNumberConversion( finishString );
+    CleanupStack::PopAndDestroy(); // dateFormatString
+    aMessage.Append( finishString );
+    AddNewlinesToMessage( aMessage );
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::AddNewlinesToMessage() const
+// Adds two new lines to message.
+// ----------------------------------------------------------
+//
+void CCertSaverModel::AddNewlinesToMessage( TDes& aMessage ) const
+    {
+    aMessage.Append( KDoubleEnter );
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::CertificateSupported() const
+// Checks that cert is of supported type.
+// ----------------------------------------------------------
+//
+TBool CCertSaverModel::CertificateSupported() const
+    {
+    if ( iCertFormat == EX509Certificate &&
+       ( iCertOwnerType == ECACertificate ||
+         iCertOwnerType == EPeerCertificate ||
+         iCertOwnerType == EUserCertificate))
+        {
+        return ETrue;
+        }
+    return EFalse;
+    }
+
+
+// ----------------------------------------------------------
+// CCertSaverModel::CertificateOkL() const
+// Checks that cert is ok. Shows an error note if not.
+// If certificate is not valid yet/anymore an error note is shown
+// but ETrue is returned so that user can still save the
+// certificate.
+// ----------------------------------------------------------
+//
+TBool CCertSaverModel::CertificateOkL() const
+    {
+    if ( !CertificateSupported() )
+        {
+        ShowErrorNoteL( R_CERTSAVER_ERROR_UNSUPPORTED_CERT );
+        return EFalse;
+        }
+    if ( CertNotValidAnymore() )
+        {
+        ShowErrorNoteL( R_CERTSAVER_ERROR_CERT_NOT_VALID );
+        return ETrue;
+        }
+    else if ( CertNotValidYet() )
+        {
+        ShowErrorNoteL( R_CERTSAVER_ERROR_CERT_NOT_VALID_YET );
+        }
+    return ETrue;
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::CertNotValidAnymore() const
+// Checks if cert isn't valid anymore.
+// ----------------------------------------------------------
+//
+TBool CCertSaverModel::CertNotValidAnymore() const
+    {
+    TTime homeTime;
+    homeTime.HomeTime();
+    if ( iNewCert->ValidityPeriod().Finish() < homeTime )
+        {
+        return ETrue;
+        }
+    return EFalse;
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::CertNotValidYet() const
+// Checks if cert isn't valid yet.
+// ----------------------------------------------------------
+//
+TBool CCertSaverModel::CertNotValidYet() const
+    {
+    TTime homeTime;
+    homeTime.HomeTime();
+    if ( iNewCert->ValidityPeriod().Start() > homeTime )
+        {
+        return ETrue;
+        }
+    return EFalse;
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::ShowInformationNoteL() const
+// Creates and shows a confirmation note.
+// ----------------------------------------------------------
+//
+void CCertSaverModel::ShowInformationNoteL( TInt aResourceID ) const
+    {
+    HBufC* buffer = iAppUi->CoeEnv()->AllocReadResourceLC( aResourceID );
+    CAknInformationNote* note = new (ELeave) CAknInformationNote( ETrue );
+    note->ExecuteLD( buffer->Des() );
+    CleanupStack::PopAndDestroy( buffer );
+    }
+// ----------------------------------------------------------
+// CCertSaverModel::ShowConfirmationNoteL() const
+// Creates and shows a confirmation note.
+// ----------------------------------------------------------
+//
+void CCertSaverModel::ShowConfirmationNoteL( TInt aResourceID ) const
+    {
+    HBufC* buffer = iAppUi->CoeEnv()->AllocReadResourceLC( aResourceID );
+    CAknConfirmationNote* note = new (ELeave) CAknConfirmationNote( ETrue );
+    note->ExecuteLD( buffer->Des() );
+    CleanupStack::PopAndDestroy( buffer );
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::ShowErrorNoteL() const
+// Creates and shows an error note.
+// ----------------------------------------------------------
+//
+void CCertSaverModel::ShowErrorNoteL( TInt aResourceID ) const
+    {
+    HBufC* buffer = iAppUi->CoeEnv()->AllocReadResourceLC( aResourceID );
+    CAknErrorNote* note = new (ELeave) CAknErrorNote( ETrue );
+    note->ExecuteLD(buffer->Des());
+    CleanupStack::PopAndDestroy( buffer );
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::TrimCertificateFields() const
+// Trims given descriptor so that everything after and
+// including the fourth semicolon (;) is cropped.
+// Returns the trimmed certificate field.
+// ----------------------------------------------------------
+//
+TPtrC CCertSaverModel::TrimCertificateFields( TPtrC aField ) const
+    {
+    TPtrC cutField = CutCertificateField( aField );
+    // Find one semicolon at a time and crop the
+    // helpField from the left to search for the next semicolon
+    TInt position = cutField.Locate( ';' ); // 1st semicolon
+    TInt fieldLength = cutField.Length();
+
+    // Need to check that position is not bigger than the length of cutField
+    if ( position != KErrNotFound && position < fieldLength )
+        {
+        // Locate function counts from zero, Mid function
+        // counts also from zero, add one to exclude the found semicolon
+        TInt totalPosition = position;
+        TPtrC field = cutField.Mid(totalPosition + 1);
+        position = field.Locate(';'); // 2nd semicolon
+        fieldLength = field.Length();
+
+        if ( position != KErrNotFound && position < fieldLength )
+            {
+            totalPosition += position + 1;
+            TPtrC field = cutField.Mid( totalPosition + 1 );
+            position = field.Locate( ';' ); // 3rd semicolon
+            fieldLength = field.Length();
+
+            if ( position != KErrNotFound && position < fieldLength )
+                {
+                totalPosition += position + 1;
+                TPtrC field = cutField.Mid( totalPosition + 1 );
+                position = field.Locate( ';' ); // 4th semicolon
+                fieldLength = field.Length();
+
+                if ( position != KErrNotFound && position < fieldLength )
+                  {
+                  totalPosition += position + 1;
+                  // Extract the leftmost part of the data field up to n:th character
+                  TPtrC field = cutField.Mid( 0, totalPosition );
+                  return field;
+                  } // if
+                } // if
+            } // if
+        } // if
+    return cutField;
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::CutCertificateField() const
+// If given descriptor is larger than defined maximum length
+// this function cuts it.
+// ----------------------------------------------------------
+//
+TPtrC CCertSaverModel::CutCertificateField( TPtrC aField ) const
+    {
+    TInt fieldLength = aField.Length();
+    if ( fieldLength >= KMaxLengthTextCertIdentifierVisible )
+        {
+        TPtrC cutCertLabel = aField.Mid( 0, KMaxLengthTextCertIdentifierVisible );
+        return cutCertLabel;
+        }
+    return aField;
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::QueryTrusterUidsL()
+// Does needed tasks to exit.
+// ----------------------------------------------------------
+//
+TInt CCertSaverModel::QueryTrusterUidsL( RArray<TUid>& aUids )
+    {
+    TInt ret = KErrCancel;
+    CArrayFixFlat<TInt>* selectionArray =
+        new (ELeave)  CArrayFixFlat<TInt>( KTrusterArrayInitSize );
+    CleanupStack::PushL( selectionArray );
+    CDesCArray* itemsArray = new (ELeave) CDesCArrayFlat( KTrusterArrayInitSize );
+    CleanupStack::PushL( itemsArray );
+
+    CCertificateAppInfoManager* appInfoManager =
+        CCertificateAppInfoManager::NewL( iFs, EFalse );
+    CleanupStack::PushL( appInfoManager );
+    // copy applications to own array
+    const RArray<TCertificateAppInfo>& apps = appInfoManager->Applications();
+    RArray<TCertificateAppInfo> appsInItemArray( KTrusterArrayInitSize );
+    CleanupClosePushL( appsInItemArray );
+    UpdateTrustListboxItemL( apps, appsInItemArray, *itemsArray );
+
+    CAknListQueryDialog* dlg = new (ELeave) CAknListQueryDialog( selectionArray );
+    CleanupStack::PushL( dlg );
+    dlg->PrepareLC( R_CERTSAVER_TRUST_SETTINGS_QUERY );
+    dlg->SetItemTextArray( itemsArray );
+    dlg->SetOwnershipType( ELbmDoesNotOwnItemArray );
+    if ( dlg->RunLD() )
+        {
+        for ( TInt i = 0; i < selectionArray->Count(); ++i )
+            {
+            TInt ii = (*selectionArray)[ i ];
+            aUids.Append( appsInItemArray[ ii ].Id() );
+            }
+        ret = KErrNone;
+        }
+    else
+        {
+        ShowConfirmationNoteL( R_CERTSAVER_CERT_DISCARDED );
+        ret = KErrCancel;
+        }
+    CleanupStack::Pop( dlg );
+    CleanupStack::PopAndDestroy( 4, selectionArray );
+    return ret;
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::QueryTrustedSiteL()
+// Shows query for trusted site certificate
+// ----------------------------------------------------------
+//
+TInt CCertSaverModel::QueryTrustedSiteL()
+    {
+    TInt ret = KErrCancel;
+    HBufC* label = NULL;
+    HBufC* secondaryName = NULL;
+    TCertLabel labelBuf;
+
+    X509CertNameParser::PrimaryAndSecondaryNameL(
+        (*(CX509Certificate*)iNewCert), label, secondaryName );
+    CleanupStack::PushL( label );
+    delete secondaryName;
+    secondaryName = NULL;
+    labelBuf = label->Des().Left( CERTSAVER_MAX_LABEL_LEN );
+
+
+    HBufC* prompt = StringLoader::LoadLC( R_CERTSAVER_TRUSTEDSITE_WARNING, labelBuf );
+
+    CAknMessageQueryDialog* note = CAknMessageQueryDialog::NewL( *prompt );
+
+    note->PrepareLC( R_CERTSAVER_TRUSTED_SITE_QUERY );
+    note->SetPromptL( *prompt );
+
+    if ( note->RunLD() )
+        {
+        ret = KErrNone;
+        }
+    else
+        {
+        ShowConfirmationNoteL( R_CERTSAVER_CERT_DISCARDED );
+        ret = KErrCancel;
+        }
+
+    CleanupStack::PopAndDestroy( prompt );
+
+    CleanupStack::PopAndDestroy( label );
+    return ret;
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::UpdateTrustListboxItemL()
+// Updates trust setting listbox items
+// ----------------------------------------------------------
+//
+void CCertSaverModel::UpdateTrustListboxItemL(
+    const RArray<TCertificateAppInfo>& aApps,
+    RArray<TCertificateAppInfo>& aAppsInItemArray,
+    CDesCArray& aItemsArray ) const
+  {
+    for ( TInt i = 0; i < aApps.Count(); i++ )
+        {
+        TCertificateAppInfo appInfo = aApps[ i ];
+        TBuf<KItemBufLen> item;
+        item.Append( KCertSaverListBoxItemPrefix );
+        TBuf<KMaxName> resource;
+
+        switch( appInfo.Id().iUid )
+            {
+            case KWTLSTrusterUID:
+                {
+                // X.509 certiticate isn't needed with WTLS
+                break;
+                }
+            case KInternetTrusterUID:
+                {
+               iAppUi->CoeEnv()->ReadResource(
+                resource, R_CERTSAVER_ITEM_MAIL_IMAGE_CONN );
+                break;
+                }
+            case KApplicationControllerTrusterUID:
+                {
+                // SWI certs are ROM based in platsec world.
+                break;
+                }
+            case KJavaInstallTrusterUID:
+                {
+                // MIDP certstore is read-only..
+                break;
+                }
+            case KOCSPTrusterUID:
+                {
+                iAppUi->CoeEnv()->ReadResource( resource, R_CERTSAVER_ITEM_OCSP );
+                break;
+                }
+            case KVPNUID:
+                {
+                iAppUi->CoeEnv()->ReadResource( resource, R_CERTSAVER_ITEM_VPN );
+                break;
+                }
+            default:
+                {
+                resource = appInfo.Name();
+                break;
+                }
+            }
+        if ( 0 < resource.Length())
+            {
+            item.Append( resource );
+            aItemsArray.AppendL( item );
+            aAppsInItemArray.Append( appInfo );
+            resource.Zero();
+            }
+        }
+  }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::DevideToBlocks
+// ---------------------------------------------------------
+//
+void CCertSaverModel::DivideToBlocks( const TDesC8& aInput, TDes& aOutput ) const
+    {
+    _LIT( KBlockSeparator, " " );
+    const TInt KBlockLength = 2;
+    TInt blockIndex = 0;
+    for ( TInt j = 0 ; j < aInput.Length() ; j++ )
+        {
+        if ( blockIndex == KBlockLength )
+            {
+            aOutput.Append( KBlockSeparator );
+            blockIndex = 0;
+            }
+        aOutput.AppendNumFixedWidthUC( (TUint)(aInput[ j ]), EHex, 2 );
+        ++blockIndex;
+        }
+    }
+
+// ----------------------------------------------------
+// CCertSaverModel::SavePKCS12L()
+// Saves content of the PKCS#12 file
+// ----------------------------------------------------
+//
+void CCertSaverModel::SavePKCS12L()
+    {
+    HBufC* message = HBufC::NewLC( KMaxLengthTextMeassageBody );
+    TPtr msgPtr = message->Des();
+    ConstructPKCS12QueryMsgL(msgPtr, iParser.Keys().Count(),
+                            iParser.UserCertificates().Count(),
+                            iParser.CACertificates().Count() );
+    TBool save = DoMessageQueryL(
+        R_MESSAGE_QUERY_DOSAVE, R_CERTSAVER_HEADER_PKCS12_FILE_CONTAINS,
+        *message );
+    CleanupStack::PopAndDestroy( message );
+    message = NULL;
+    if ( !save )
+        {
+        ShowInformationNoteL( R_CERTSAVER_PKCS12_DISCARDED );
+        User::Leave( KErrExitApp );
+        }
+    TInt status = KErrNone;
+    // save private keys
+    TRAP( status, SavePrivateKeyL() );
+
+    // save user certificates if private key was saved.
+    if ( ( iSavedKeysCount > 0 || iKeyAlreadyExists ) && iParser.UserCertificates().Count() > 0 )
+        {
+        for ( TInt i = 0; i < iParser.UserCertificates().Count(); i++ )
+            {
+            const CX509Certificate* cert = iParser.UserCertificates().At(i);
+            iCertOwnerType = EUserCertificate;
+            iCertFormat = EX509Certificate;
+            iNewCert = cert;
+            TRAP( status, SaveCertL() );
+            if ( KErrExitApp == status )
+                {
+                User::Leave( KErrExitApp );
+                }
+            }
+        }
+    // save CA certificates
+    if ( iParser.CACertificates().Count() > 0 )
+        {
+        for ( TInt i = 0; i < iParser.CACertificates().Count(); i++ )
+            {
+            const CX509Certificate* cert = iParser.CACertificates().At( i );
+            iCertOwnerType = ECACertificate;
+            iCertFormat = EX509Certificate;
+            iNewCert = cert;
+            TRAP( status, SaveCertL() );
+            if ( KErrExitApp == status )
+                {
+                User::Leave( KErrExitApp );
+                }
+            }
+        }
+    if ( iSavedCACertsCount != 0 || iSavedKeysCount != 0
+        || iSavedUserCertsCount != 0 )
+        {
+        message = HBufC::NewLC( KMaxLengthTextMeassageBody );
+        TPtr msgPtr2 = message->Des();
+        ConstructPKCS12QueryMsgL(
+            msgPtr2, iSavedKeysCount, iSavedUserCertsCount, iSavedCACertsCount );
+        DoMessageQueryL(
+            R_MESSAGE_QUERY_SAVED, R_CERTSAVER_HEADER_SAVED, *message );
+        CleanupStack::PopAndDestroy( message );
+        }
+    else
+        {
+        ShowInformationNoteL( R_QTN_CM_PKCS12_SAVING_FAILED );
+        }
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::DoMessageQuery()
+// Displays message query dialog for user.
+// ----------------------------------------------------------
+//
+TBool CCertSaverModel::DoMessageQueryL(
+    TInt aDialogResId,
+    TInt aHeadingResId,
+    TDesC& aMessage )
+    {
+    CAknMessageQueryDialog* dlg = CAknMessageQueryDialog::NewL( aMessage );
+    CleanupStack::PushL( dlg );
+    dlg->PrepareLC( aDialogResId );
+
+    HBufC* header = StringLoader::LoadLC( aHeadingResId );
+    dlg->QueryHeading()->SetTextL( header->Des() );
+    CleanupStack::PopAndDestroy( header );
+    CleanupStack::Pop( dlg );
+    return dlg->RunLD();
+    }
+
+// ----------------------------------------------------------
+// CCertSaverModel::ConstructPKCS12QueryMsgL() const
+// Creates the certificate details message shown to the user.
+// ----------------------------------------------------------
+//
+void CCertSaverModel::ConstructPKCS12QueryMsgL(
+    TDes& aMessage,
+    TInt aPrivateKeys,
+    TInt aUserCerts,
+    TInt aCACerts ) const
+    {
+    if ( aPrivateKeys > 0 )
+        {
+        if ( aPrivateKeys == 1 )
+            {
+            AddToMessageL( aMessage, R_CERTSAVER_ONE_PRIVATE_KEY );
+            }
+        else
+            {
+            AddToMessageWithIntL( aMessage, R_CERTSAVER_PRIVATE_KEYS, aPrivateKeys );
+            }
+        }
+    if ( aUserCerts > 0 )
+        {
+        if ( aUserCerts == 1 )
+            {
+            AddToMessageL(
+                aMessage, R_CERTSAVER_ONE_PERSONAL_CERTIFICATE );
+            }
+        else
+            {
+            AddToMessageWithIntL(
+                aMessage, R_CERTSAVER_PERSONAL_CERTIFICATES, aUserCerts );
+            }
+        }
+    if ( aCACerts > 0 )
+        {
+
+        if ( aCACerts == 1 )
+            {
+            AddToMessageL(
+                aMessage, R_CERTSAVER_ONE_AUTHORITY_CERTIFICATE );
+            }
+        else
+            {
+            AddToMessageWithIntL(
+                aMessage, R_CERTSAVER_AUTHORITY_CERTIFICATES, aCACerts );
+            }
+        }
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/src/CertSaverSyncWrapper.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,283 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of CCertSaverSyncWrapper class
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CertSaverSyncWrapper.h"
+#include    <unifiedcertstore.h>
+#include    <mctwritablecertstore.h>
+#include    <unifiedkeystore.h>
+#include    <mctkeystore.h>
+
+_LIT( KCertSaverName, "CertSaver" );
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::CCertSaverSyncWrapper
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CCertSaverSyncWrapper::CCertSaverSyncWrapper() : CActive( EPriorityStandard )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CCertSaverSyncWrapper::ConstructL()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CCertSaverSyncWrapper* CCertSaverSyncWrapper::NewL()
+    {
+    CCertSaverSyncWrapper* self = new( ELeave ) CCertSaverSyncWrapper;
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop(self);
+
+    return self;
+    }
+
+// Destructor
+CCertSaverSyncWrapper::~CCertSaverSyncWrapper()
+    {
+    Cancel();
+    delete iUnifiedKeyStore;
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::InitializeCertStore
+//
+// -----------------------------------------------------------------------------
+//
+TInt CCertSaverSyncWrapper::InitializeCertStore(
+    CUnifiedCertStore& aStore )
+    {
+    aStore.Initialize( iStatus );
+    return SetActiveAndWait();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::InitializeKeyStore
+//
+// -----------------------------------------------------------------------------
+//
+TInt CCertSaverSyncWrapper::InitializeKeyStoreL( RFs& aFs )
+    {
+    iUnifiedKeyStore = CUnifiedKeyStore::NewL( aFs );
+    iUnifiedKeyStore->Initialize( iStatus );
+    return SetActiveAndWait();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::AddCert
+//
+// -----------------------------------------------------------------------------
+//
+TInt CCertSaverSyncWrapper::AddCert(
+    MCTWritableCertStore& aStore,
+    const TDesC& aLabel,
+    TCertificateFormat aCertFormat,
+    TCertificateOwnerType aCertType,
+    TKeyIdentifier* aSubjectKeyId,
+    TKeyIdentifier* aIssuerKeyId,
+    TPtrC8 aCert )
+    {
+    aStore.Add( aLabel, aCertFormat, aCertType, aSubjectKeyId, aIssuerKeyId,
+        aCert, iStatus );
+    return SetActiveAndWait();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::ListCerts
+//
+// -----------------------------------------------------------------------------
+//
+TInt CCertSaverSyncWrapper::ListCerts(
+    CUnifiedCertStore& aStore,
+    RMPointerArray<CCTCertInfo>& aEntries,
+    CCertAttributeFilter& aFilter )
+    {
+    aStore.List( aEntries, aFilter, iStatus );
+    return SetActiveAndWait();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::ListKeys
+//
+// -----------------------------------------------------------------------------
+//
+TInt CCertSaverSyncWrapper::ListKeys( RMPointerArray<CCTKeyInfo>& aEntries,
+                       TCTKeyAttributeFilter& aFilter )
+    {
+    iUnifiedKeyStore->List( aEntries, aFilter, iStatus );
+    return SetActiveAndWait();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::SetApplicability
+//
+// -----------------------------------------------------------------------------
+//
+TInt CCertSaverSyncWrapper::SetApplicability(
+    MCTWritableCertStore& aStore,
+    const CCTCertInfo& aCertInfo,
+    RArray<TUid>& aApplications )
+    {
+    aStore.SetApplicability( aCertInfo, aApplications, iStatus );
+    return SetActiveAndWait();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::SetTrust
+//
+// -----------------------------------------------------------------------------
+//
+TInt CCertSaverSyncWrapper::SetTrust(
+    MCTWritableCertStore& aStore,
+    const CCTCertInfo& aCertInfo,
+    TBool aTrust )
+    {
+    aStore.SetTrust( aCertInfo, aTrust, iStatus );
+    return SetActiveAndWait();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::SetTrust
+//
+// -----------------------------------------------------------------------------
+//
+TInt CCertSaverSyncWrapper::Retrieve(
+    CUnifiedCertStore& aStore,
+    const CCTCertInfo& aCertInfo,
+    CCertificate*& aCert )
+    {
+    aStore.Retrieve( aCertInfo, aCert, iStatus );
+    return SetActiveAndWait();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::AddKey
+//
+// -----------------------------------------------------------------------------
+//
+TInt CCertSaverSyncWrapper::AddKey(
+    TInt aKeyStoreIndex,
+    const TDesC8& aKeyData,
+    TKeyUsagePKCS15 aUsage,
+    const TDesC& aLabel,
+    TInt aAccessType,
+    TTime aStartDate,
+    TTime aEndDate,
+    CCTKeyInfo*& aKeyInfoOut )
+    {
+    iUnifiedKeyStore->ImportKey( aKeyStoreIndex, aKeyData, aUsage, aLabel,
+        aAccessType, aStartDate, aEndDate, aKeyInfoOut, iStatus );
+    return SetActiveAndWait();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::SetManagementPolicy
+//
+// -----------------------------------------------------------------------------
+//
+TInt CCertSaverSyncWrapper::SetManagementPolicy(
+    TCTTokenObjectHandle aHandle,
+  const TSecurityPolicy& aPolicy )
+    {
+    iUnifiedKeyStore->SetManagementPolicy( aHandle, aPolicy, iStatus );
+    return SetActiveAndWait();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::SetUsePolicy
+//
+// -----------------------------------------------------------------------------
+//
+TInt CCertSaverSyncWrapper::SetUsePolicy(
+    TCTTokenObjectHandle aHandle,
+    const TSecurityPolicy& aPolicy )
+    {
+    iUnifiedKeyStore->SetUsePolicy( aHandle, aPolicy, iStatus );
+    return SetActiveAndWait();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::UnifiedKeyStore
+//
+// -----------------------------------------------------------------------------
+//
+CUnifiedKeyStore& CCertSaverSyncWrapper::UnifiedKeyStore()
+    {
+    __ASSERT_ALWAYS( iUnifiedKeyStore, User::Panic( KCertSaverName, KErrBadHandle ) );
+    return *iUnifiedKeyStore;
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::DoCancel
+//
+// -----------------------------------------------------------------------------
+//
+void CCertSaverSyncWrapper::DoCancel()
+    {
+
+    if ( iUnifiedKeyStore )
+        {
+        iUnifiedKeyStore->Cancel();
+        }
+
+    if ( iWait.IsStarted() )
+        {
+        iWait.AsyncStop();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::RunL()
+//
+// -----------------------------------------------------------------------------
+//
+void CCertSaverSyncWrapper::RunL()
+    {
+
+    iWait.AsyncStop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertSaverSyncWrapper::SetActiveAndWait
+//
+// -----------------------------------------------------------------------------
+//
+TInt CCertSaverSyncWrapper::SetActiveAndWait()
+    {
+    SetActive();
+    iWait.Start();
+    return iStatus.Int();
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertSaver/src/certparser.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,378 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of CCertParser class
+*
+*/
+
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <apmrec.h>
+#include <x509cert.h>
+#include <x509certext.h>
+#include <hash.h>
+#include <X509CertNameParser.h>
+#include <featmgr.h>
+#include <data_caging_path_literals.hrh>
+#include <AknQueryDialog.h>
+#include <CertSaver.rsg>
+#include <StringLoader.h>
+#include <securityerr.h>
+#include <aknnotewrappers.h>              // Note dialogs
+#include <apmrec.h>
+#include "certparser.h"
+
+// CONSTANTS
+_LIT( KPKCS12DllName, "crpkcs12.dll" );   // PKCS12 DLL name
+const TInt KX509Version3 = 3;
+const TInt KPwMaxLength = 32;
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// ==================== LOCAL FUNCTIONS ====================
+
+// ================= MEMBER FUNCTIONS =======================
+
+// C++ default constructor can NOT contain any code, that
+// might leave.
+//
+CCertParser::CCertParser()
+    {
+    }
+
+// EPOC default constructor can leave.
+void CCertParser::ConstructL()
+    {
+    }
+
+// Two-phased constructor.
+CCertParser* CCertParser::NewL()
+    {
+    CCertParser* self = new (ELeave) CCertParser;
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+
+// Destructor
+CCertParser::~CCertParser()
+    {
+    delete iCert;
+    if ( iPKCS12 )
+        {
+        iPKCS12->Release();
+        }
+    iLibrary.Close();
+    }
+
+// ----------------------------------------------------------
+// CCertParser::SetContentL()
+// Checks if given buffer is a WTLS or a X.509 certificate and
+// sets member data accordingly.
+// ----------------------------------------------------------
+//
+void CCertParser::SetContentL( RFile& aFile )
+    {
+    delete iCert;
+    iCert = NULL;
+    TInt fileSize = 0;
+    CleanupClosePushL( aFile );
+    User::LeaveIfError( aFile.Size( fileSize ) );
+
+    HBufC8* buffer = HBufC8::NewL( fileSize );
+    CleanupStack::PushL( buffer );
+
+    TPtr8 ptr8(buffer->Des());
+    User::LeaveIfError( aFile.Read( ptr8 ) );
+
+    if ( !CheckIfX509CertificateL( *buffer ) )
+        {
+        TFileName fileName;
+        User::LeaveIfError( aFile.Name( fileName ) );
+        if ( !CheckIfPKCS12L( *buffer, fileName ) )
+            {
+            iCertType = ETypeCorrupt;
+            }
+        }
+    CleanupStack::PopAndDestroy( buffer );
+    CleanupStack::PopAndDestroy( &aFile );
+    }
+
+// ----------------------------------------------------------
+// CCertParser::CreatePKCS12L()
+// Creates PKCS#12 DLL
+// ----------------------------------------------------------
+//
+void CCertParser::CreatePKCS12L()
+    {
+    // Load PKCS#12 dll
+#ifdef __WINS__
+    User::LeaveIfError ( iLibrary.Load( KPKCS12DllName ) );
+#else
+    User::LeaveIfError ( iLibrary.Load( KPKCS12DllName, KDC_SHARED_LIB_DIR ) );
+#endif
+
+    // Define the function that returns pointer to MPKCS12
+    typedef MPKCS12* ( *TLibraryFunc )();
+    // Find CreateL() method from pkcs12.dll that implements the function
+    TLibraryFunc createL =
+        reinterpret_cast<TLibraryFunc>( iLibrary.Lookup( 1 ) );
+    // Create new instance of MPKCS12
+    iPKCS12 = createL();
+    }
+
+// ----------------------------------------------------------
+// CCertParser::CheckIfPKCS12L()
+// Checks if PKCS#12 file
+// ----------------------------------------------------------
+//
+TBool CCertParser::CheckIfPKCS12L(
+    const TDesC8& aPKCS12,
+    const TDesC& aFileName )
+    {
+    CreatePKCS12L();
+
+    if ( !iPKCS12->IsPKCS12Data( aPKCS12 ) )
+        {
+        ShowErrorNoteL( R_CERTSAVER_PKCS12_FILE_CORRUPTED );
+        return EFalse;
+        }
+
+    TBool done = EFalse;
+    TBuf<KPwMaxLength> password;
+    HBufC* buffer = NULL;
+
+    if ( !iEikEnv )
+        {
+        iEikEnv = CEikonEnv::Static();
+        }
+
+    while ( !done )
+        {
+        if ( !GetPasswordL( password, aFileName ) )
+            {
+            buffer = iEikEnv->AllocReadResourceLC( R_CERTSAVER_PKCS12_DISCARDED );
+            CAknInformationNote* note = new (ELeave) CAknInformationNote( ETrue );
+            note->ExecuteLD(buffer->Des());
+            CleanupStack::PopAndDestroy( buffer );
+            User::Leave( KErrExitApp );
+            }
+        TRAPD( err, iPKCS12->ParseL( aPKCS12, password ) );
+        if ( err != KErrBadPassphrase )
+            {
+            switch ( err )
+                {
+                case KErrNone:
+                    {
+                    iCertType = ETypePKCS12;
+                    break;
+                    }
+                case KErrNoMemory:
+                    {
+                    User::Leave( KErrNoMemory );
+                    }
+                case KErrNotSupported:
+                    {
+                    ShowErrorNoteL( R_QTN_CM_PKCS12_FORMAT_NOT_SUPPORTED );
+                    break;
+                    }
+                default:
+                    {
+                    ShowErrorNoteL( R_CERTSAVER_PKCS12_FILE_CORRUPTED );
+                    break;
+                    }
+                }
+            if ( err != KErrNone )
+                {
+                return EFalse;
+                }
+            done = ETrue;
+            }
+        else
+            {
+            password.Zero();
+            // Show error note
+            ShowErrorNoteL( R_QTN_CM_INCORRECT_PASSWORD );
+            }
+        }
+    return ETrue;
+    }
+
+// ----------------------------------------------------------
+// CCertParser::GetPasswordL(...)
+//
+// ----------------------------------------------------------
+//
+TInt CCertParser::GetPasswordL( TDes& aPassword, const TDesC& aFileName )
+    {
+    CAknTextQueryDialog* query = CAknTextQueryDialog::NewL( aPassword );
+    CleanupStack::PushL( query );
+    HBufC* prompt =
+        StringLoader::LoadLC( R_QTN_CM_TITLE_P12_PASSWORD, aFileName );
+    query->SetPromptL( *prompt );
+    CleanupStack::PopAndDestroy( prompt );
+    CleanupStack::Pop( query );
+    return query->ExecuteLD( R_PKCS12_PW_QUERY_DIALOG );
+    }
+
+// ----------------------------------------------------------
+// CCertParser::CheckIfX509CertificateL()
+// Returns the type of the certificate.
+// ----------------------------------------------------------
+//
+TBool CCertParser::CheckIfX509CertificateL(const TDesC8& aCert)
+    {
+    TRAPD( err,
+           iCert = CX509Certificate::NewL(aCert);
+         );
+
+    if ( err != KErrNone )
+        {
+        iCertType = ETypeCorrupt;
+        if ( err == KErrNoMemory )
+            {
+            User::Leave( err );
+            }
+        else
+            {
+            return EFalse;
+            }
+        }
+
+  if ( iCert )
+      {
+      // Check certificate version
+      if ( iCert->Version() != KX509Version3 )
+          {
+          // X509 v1 or v2 certificate. Certificate type is CA
+          iCertType = ETypeX509CA;
+          }
+      else
+          {
+          // X509 v3 certificate. Check basicConstrains
+          const CX509CertExtension* certExt = iCert->Extension( KBasicConstraints );
+          if ( certExt )
+              {
+              CX509BasicConstraintsExt* basic = CX509BasicConstraintsExt::NewLC( certExt->Data() );
+              if ( basic->IsCA() )
+                  {
+                  iCertType = ETypeX509CA;
+                  }
+              else
+                  {
+                  iCertType = ETypeX509Peer;
+                  }
+              CleanupStack::PopAndDestroy( basic ); //basic
+              }
+           else
+              {
+              // No basicConstrains extension
+              iCertType = ETypeX509Peer;
+              }
+          }
+      }
+
+    return ETrue;
+    }
+
+// ----------------------------------------------------------
+// CCertParser::CACertificates()
+// ----------------------------------------------------------
+//
+const CArrayPtr<CX509Certificate>&  CCertParser::CACertificates() const
+    {
+    __ASSERT_ALWAYS( iPKCS12, User::Panic( KCertSaverPanic, KPanicNullPointer ) );
+    return iPKCS12->CACertificates();
+    }
+
+// ----------------------------------------------------------
+// CCertParser::UserCertificates()
+// ----------------------------------------------------------
+//
+const CArrayPtr<CX509Certificate>&  CCertParser::UserCertificates() const
+    {
+    __ASSERT_ALWAYS( iPKCS12, User::Panic( KCertSaverPanic, KPanicNullPointer ) );
+    return iPKCS12->UserCertificates();
+    }
+
+// ----------------------------------------------------------
+// CCertParser::Keys()
+// ----------------------------------------------------------
+//
+const CArrayPtr<HBufC8>& CCertParser::Keys() const
+    {
+    __ASSERT_ALWAYS( iPKCS12, User::Panic( KCertSaverPanic, KPanicNullPointer ) );
+    return iPKCS12->PrivateKeys();
+    }
+
+// ----------------------------------------------------------
+// CCertParser::CertType()
+// ----------------------------------------------------------
+//
+ CCertParser::TCertType CCertParser::CertType() const
+    {
+    return iCertType;
+    }
+
+// ----------------------------------------------------------
+// CCertParser::CertificateBuf()
+// Returns the content of the certificate.
+// ----------------------------------------------------------
+//
+const TPtrC8 CCertParser::CertificateBuf() const
+    {
+    __ASSERT_ALWAYS( iCert, User::Panic( KCertSaverPanic, KPanicNullPointer ) );
+    return iCert->Encoding();
+    }
+
+// ----------------------------------------------------------
+// CCertParser::Certificate()
+// Returns the X.509 certificate object.
+// ----------------------------------------------------------
+//
+const CX509Certificate& CCertParser::Certificate() const
+    {
+    __ASSERT_ALWAYS( iCert, User::Panic( KCertSaverPanic, KPanicNullPointer ) );
+    return *((CX509Certificate*)iCert);
+    }
+
+// ----------------------------------------------------------
+// CCertParser::ShowErrorNoteL() const
+// Creates and shows an error note.
+// ----------------------------------------------------------
+//
+void CCertParser::ShowErrorNoteL( TInt aResourceID )
+    {
+     if ( !iEikEnv )
+        {
+        iEikEnv = CEikonEnv::Static();
+        }
+    HBufC* buffer = iEikEnv->AllocReadResourceLC( aResourceID );
+    CAknErrorNote* note = new (ELeave) CAknErrorNote( ETrue );
+    note->ExecuteLD(buffer->Des());
+    CleanupStack::PopAndDestroy( buffer );
+    }
+
+//  End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/Certificates/data/addclients.txt	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,82 @@
+<action>
+	<actionname>Creating a CertificateAppInfoManager</actionname>
+	<actiontype>initappmanager</actiontype>
+	<actionbody></actionbody>
+	<actionresult>
+		<return>KErrNone</return>
+	</actionresult>
+</action>
+
+<action>
+	<actionname>Adding SW Install applicability</actionname>
+	<actiontype>addclient</actiontype>
+	<actionbody>
+		<name>Application Controller</name>
+		<uid>268452523</uid>
+	</actionbody>
+	<actionresult>
+		<return>KErrNone</return>
+	</actionresult>
+</action>
+<action>
+	<actionname>Adding TLS applicability</actionname>
+	<actiontype>addclient</actiontype>
+	<actionbody>
+		<name>Internet</name>
+		<uid>268441661</uid>
+	</actionbody>
+	<actionresult>
+		<return>KErrNone</return>
+	</actionresult>
+</action>
+<action>
+	<actionname>Adding MIDlet Installation applicability</actionname>
+	<actiontype>addclient</actiontype>
+	<actionbody>
+		<name>Java installer</name>
+		<uid>270506792</uid>
+	</actionbody>
+	<actionresult>
+		<return>KErrNone</return>
+	</actionresult>
+</action>
+<action>
+	<actionname>Adding OCSP applicability</actionname>
+	<actiontype>addclient</actiontype>
+	<actionbody>
+		<name>OCSP</name>
+		<uid>268478646</uid>
+	</actionbody>
+	<actionresult>
+		<return>KErrNone</return>
+	</actionresult>
+</action>
+<action>
+	<actionname>Adding VPN applicability</actionname>
+	<actiontype>addclient</actiontype>
+	<actionbody>
+		<name>VPN</name>
+		<uid>270498195</uid>
+	</actionbody>
+	<actionresult>
+		<return>KErrNone</return>
+	</actionresult>
+</action>
+<action>
+	<actionname>Retrieving the clients</actionname>
+	<actiontype>getclients</actiontype>
+	<actionbody></actionbody>
+	<actionresult>
+		<return>KErrNone</return>
+		<uid>268452523 268441661 270506792 268478646 270498195</uid>
+	</actionresult>
+</action>
+
+<action>
+	<actionname>Deleting the CertificateAppInfoManager</actionname>
+	<actiontype>deleteappmanager</actiontype>
+	<actionbody></actionbody>
+	<actionresult>
+		<return>KErrNone</return>
+	</actionresult>
+</action>
Binary file pkiutilities/Certificates/data/certclients.dat has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/Certificates/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,31 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Common build information for the Certificates project
+*
+*/
+
+
+
+PRJ_PLATFORMS
+DEFAULT -ARMI
+
+PRJ_EXPORTS
+../data/certclients.dat  /epoc32/release/winscw/udeb/Z/Private/101f72a6/certclients.dat
+../data/certclients.dat  /epoc32/release/winscw/urel/Z/Private/101f72a6/certclients.dat
+../data/certclients.dat  /epoc32/data/z/private/101f72a6/certclients.dat
+
+
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/BMARM/CERTMANUIU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	E32Dll__F10TDllReason @ 1 NONAME R3UNUSED ; E32Dll(TDllReason)
+	NewLC__16CCertManUIKeeperRC5TRectG4TUid @ 2 NONAME R3UNUSED ; CCertManUIKeeper::NewLC(TRect const &, TUid)
+	NewL__16CCertManUIKeeperRC5TRectG4TUid @ 3 NONAME R3UNUSED ; CCertManUIKeeper::NewL(TRect const &, TUid)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/BWINS/CERTMANUIU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	?E32Dll@@YAHW4TDllReason@@@Z @ 1 NONAME ; int __cdecl E32Dll(enum TDllReason)
+	?NewL@CCertManUIKeeper@@SAPAV1@ABVTRect@@VTUid@@@Z @ 2 NONAME ; public: static class CCertManUIKeeper * __cdecl CCertManUIKeeper::NewL(class TRect const &,class TUid)
+	?NewLC@CCertManUIKeeper@@SAPAV1@ABVTRect@@VTUid@@@Z @ 3 NONAME ; public: static class CCertManUIKeeper * __cdecl CCertManUIKeeper::NewLC(class TRect const &,class TUid)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/BWINSCW/CERTMANUIU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	?E32Dll@@YAHW4TDllReason@@@Z @ 1 NONAME ; int E32Dll(enum TDllReason)
+	?NewL@CCertManUIKeeper@@SAPAV1@ABVTRect@@VTUid@@@Z @ 2 NONAME ; class CCertManUIKeeper * CCertManUIKeeper::NewL(class TRect const &, class TUid)
+	?NewLC@CCertManUIKeeper@@SAPAV1@ABVTRect@@VTUid@@@Z @ 3 NONAME ; class CCertManUIKeeper * CCertManUIKeeper::NewLC(class TRect const &, class TUid)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/BWINSCW/CERTMANUI_EKA2U.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,4 @@
+EXPORTS
+	?NewL@CCertManUIKeeper@@SAPAV1@ABVTRect@@VTUid@@@Z @ 1 NONAME ; class CCertManUIKeeper * CCertManUIKeeper::NewL(class TRect const &, class TUid)
+	?NewLC@CCertManUIKeeper@@SAPAV1@ABVTRect@@VTUid@@@Z @ 2 NONAME ; class CCertManUIKeeper * CCertManUIKeeper::NewLC(class TRect const &, class TUid)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/EABI/CertManUiU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	_Z6E32Dll10TDllReason @ 1 NONAME
+	_ZN16CCertManUIKeeper4NewLERK5TRect4TUid @ 2 NONAME
+	_ZN16CCertManUIKeeper5NewLCERK5TRect4TUid @ 3 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/EABI/CertManUi_EKA2U.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,4 @@
+EXPORTS
+	_ZN16CCertManUIKeeper4NewLERK5TRect4TUid @ 1 NONAME
+	_ZN16CCertManUIKeeper5NewLCERK5TRect4TUid @ 2 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/GROUP/CertmanuiPlugin.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,123 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Project definition file for Certificate Management UI
+*
+*/
+
+
+#include <platform_paths.hrh>
+#include <bldvariant.hrh>
+#include <data_caging_paths.hrh>
+
+// Build target
+
+TARGET            CertManUi.dll
+TARGETTYPE        PLUGIN
+UID  0x10009D8D   0x10008D3D
+
+CAPABILITY        CAP_ECOM_PLUGIN
+VENDORID          VID_DEFAULT
+
+// Resource file location
+SOURCEPATH    ../data
+
+START RESOURCE    10008D3D.rss
+TARGET            CertManUI.rsc
+END
+
+
+// Resource file
+START RESOURCE    certmanui.rss
+HEADER
+TARGETPATH        RESOURCE_FILES_DIR
+LANGUAGE_IDS
+END
+
+// Define the following lines to enable logging.
+
+//#define _CERTMANUI_LOG
+
+
+// Source files location
+SOURCEPATH    ../SRC
+
+// Source files
+SOURCE      CertmanuiKeeper.cpp
+SOURCE      CertmanuiviewAuthority.cpp
+SOURCE      CertmanuiviewPersonal.cpp
+SOURCE      CertmanuiviewTrust.cpp
+SOURCE      CertmanuicontainerAuthority.cpp
+SOURCE      CertmanuicontainerPersonal.cpp
+SOURCE      CertmanuicontainerTrust.cpp
+SOURCE      CertmanuiSyncWrapper.cpp
+SOURCE      CertmanuiCertificateHelper.cpp
+SOURCE      Certmanuidialogs.cpp
+SOURCE      CertmanuiPlugin.cpp
+SOURCE      CertmanuiPluginContainer.cpp
+SOURCE      CertmanuiPluginImplementationTable.cpp
+SOURCE      CertmanuiviewMain.cpp
+SOURCE      CertmanuiviewTrustedSite.cpp
+SOURCE      CertmanuiviewDevice.cpp
+SOURCE      CertmanuicontainerMain.cpp
+SOURCE      CertmanuicontainerTrustedSite.cpp
+SOURCE      CertmanuicontainerDevice.cpp
+
+// Include paths
+USERINCLUDE     . ../INC
+USERINCLUDE     ../../Include
+
+APP_LAYER_SYSTEMINCLUDE
+SYSTEMINCLUDE   ../../DeviceToken/Inc
+
+
+// Dependencies
+LIBRARY         euser.lib
+LIBRARY         cone.lib
+LIBRARY         eikcore.lib
+LIBRARY         eikcoctl.lib
+LIBRARY         avkon.lib
+LIBRARY         aknskins.lib
+LIBRARY         aknicon.lib
+LIBRARY         bafl.lib
+LIBRARY         crypto.lib
+LIBRARY         certstore.lib       // TCertManClientInfo::Id
+LIBRARY         commonengine.lib    // StringLoader.h
+LIBRARY         eikctl.lib          // markable icons
+LIBRARY         efsrv.lib           // needed by CertManUI debug logger
+LIBRARY         SysUtil.lib         // For FFS Space checking
+LIBRARY         commonui.lib        // for CErrorUI
+LIBRARY         CTFramework.lib     // CCertAttributeFilter
+LIBRARY         X509.lib
+LIBRARY         pkixcert.lib        // Validation
+LIBRARY         x509certnameparser.lib    // parsing of label
+LIBRARY         hash.lib
+LIBRARY         Featmgr.lib         // feature manager support
+LIBRARY         ecom.lib
+LIBRARY         GSFramework.lib
+LIBRARY         GSEcomPlugin.lib
+LIBRARY         DevTokenClient.lib
+LIBRARY         cryptography.lib    // Public key functions
+
+
+#ifdef _CERTMANUI_LOG
+MACRO   _CERTMANUI_LOG_
+LIBRARY         flogger.lib         // needed by CertManUI debug logger
+#else
+DEBUGLIBRARY    flogger.lib         // needed by CertManUI debug logger
+#endif
+
+LIBRARY         hlplch.lib          // for "Help" options menu
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/GROUP/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Build information file for Certificate Management UI
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT -ARMI
+
+#include "../help/group/bld.inf"        // Help exports
+
+PRJ_EXPORTS
+../loc/certmanui.loc  MW_LAYER_LOC_EXPORT_PATH(certmanui.loc)
+
+PRJ_MMPFILES
+CertmanuiPlugin.mmp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertManUILogger.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,170 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implements logger functionality of the module
+*
+*/
+
+
+#ifndef CERTMANUI_LOGGER_H
+#define CERTMANUI_LOGGER_H
+
+
+#if defined ( _DEBUG ) || defined ( _CERTMANUI_LOG_ )
+
+// INCLUDES
+#include <flogger.h>
+
+enum TLoggingSelectors
+  {
+  ECertManUILogEnter = 1,
+    ECertManUILogLeave,
+    ECertManUILogTimeStamp,
+    ECertManUILogWrite
+  };
+
+// CONSTANTS
+
+// Macros to be substituted
+_LIT( KCertManUILogMessageAppBanner,   "CertManUI: module (%d.%d.%d) started" );
+_LIT( KCertManUILogExit,               "CertManUI: module exit" );
+_LIT( KCertManUILogTimeFormatString,   "%H:%T:%S:%*C3" );
+_LIT8( KCertManUILogEnterFn,           "ENTRY " );
+_LIT8( KCertManUILogLeaveFn,           "EXIT " );
+
+// ATTENTION!!! We're depending on FLogger DLL, because it presumes the
+// existance of C:\LOGS directory.
+_LIT( KCertManUIFLoggerDependency,    "c:\\logs\\" );
+_LIT( KCertManUIDoubleBackSlash,    "\\" );
+_LIT( KCertManUILogDir,         "certmanui" );
+_LIT( KCertManUILogFile,        "certmanui.log" );
+
+/**
+* Use this macro in order to initialize logger :
+* - create log directory,
+* - write version information into the log file
+*/
+#define CERTMANUILOGGER_CREATE { \
+                              TFileName path( KCertManUIFLoggerDependency ); \
+                              path.Append( KCertManUILogDir ); \
+                              path.Append( KCertManUIDoubleBackSlash ); \
+                              RFs& fs = CEikonEnv::Static()->FsSession(); \
+                              fs.MkDirAll( path ); \
+                              RFileLogger::WriteFormat( \
+                                                      KCertManUILogDir, \
+                                                      KCertManUILogFile, \
+                                                      EFileLoggingModeOverwrite, \
+                                                      KCertManUILogMessageAppBanner \
+                                                      ); \
+                              }
+
+/**
+* Use this macro for writing information about exiting.
+*/
+#define CERTMANUILOGGER_DELETE { \
+                                RFileLogger::Write( \
+                                                  KCertManUILogDir, \
+                                                  KCertManUILogFile, \
+                                                  EFileLoggingModeAppend, \
+                                                  KCertManUILogExit \
+                                                  ); \
+                                }
+
+/**
+* Use this function at the entry point of any functions.
+* @param a Entry information of the method.
+*/
+#define CERTMANUILOGGER_ENTERFN( a ) write_log (ECertManUILogEnter, a)
+/**
+* Use this function right before you leave the method.
+* @param a Leaving information of the method.
+*/
+#define CERTMANUILOGGER_LEAVEFN( a ) write_log (ECertManUILogLeave, a)
+
+/**
+* Use this function at any points of a function for logging the current state.
+* @param a String to be written into logfile about the current state
+*/
+#define LOG_WRITE( a ) write_log (ECertManUILogWrite, a)
+/**
+* Use this function at any points of a function for logging the current state.
+* You can use printf-like formats, but with only one parameter to be substituted..
+* @param a Format string,
+* @param b Parameter to be substituted.
+*/
+#define LOG_WRITE_FORMAT( a, b ) write_log (ECertManUILogWrite, a, b)
+
+/**
+* Use this function at any points of a function for logging the current state.
+* The current date/time stamp is written besides the string you give.
+* @param a String to be written into logfile about the current state
+*/
+
+#define CERTMANUILOGGER_WRITE_TIMESTAMP( a ) write_log (ECertManUILogTimeStamp, a)
+
+inline void write_log (TInt aSelector, const char* aFmt,...) //lint !e960
+    {
+    TBuf8<256> buf;
+        {
+      VA_LIST ap;//lint !e960
+        TPtrC8 fmt((unsigned char *)aFmt);
+      VA_START(ap, aFmt);  //lint !e960
+      buf.FormatList(fmt, ap);
+      VA_END(ap);  //lint !e960
+        }
+    switch(aSelector)
+        {
+        case ECertManUILogEnter:
+            buf.Insert(0, KCertManUILogEnterFn);
+            break;
+        case ECertManUILogLeave:
+            buf.Insert(0, KCertManUILogLeaveFn);
+            break;
+        default:
+            break;
+        }
+
+    RFileLogger::Write( KCertManUILogDir, KCertManUILogFile, EFileLoggingModeAppend, buf);
+
+    TBuf<256> tempBuf;
+    tempBuf.Copy( buf );
+    RDebug::Print( tempBuf );
+    }
+
+#define LOG_HEXDUMP( aBuf ) { \
+                            RFileLogger::HexDump( \
+                                                  KCertManUILogDir, \
+                                                  KCertManUILogFile, \
+                                                  EFileLoggingModeAppend, \
+                                                  ((const TText *)" "), \
+                                                  ((const TText *)" "), \
+                                                  aBuf.Ptr(), aBuf.Size()); \
+                            }
+
+
+#else // _DEBUG || _CERTMANUI_LOG
+
+// Empty macros
+#define CERTMANUILOGGER_CREATE
+#define CERTMANUILOGGER_DELETE
+#define CERTMANUILOGGER_ENTERFN( a )
+#define CERTMANUILOGGER_LEAVEFN( a )
+#define LOG_WRITE( a )
+#define LOG_WRITE_FORMAT( a, b )
+#define CERTMANUILOGGER_WRITE_TIMESTAMP( a ) /**/
+
+#endif // _DEBUG || _CERTMANUI_LOG
+
+#endif  // CERTMANUI_LOGGER_H
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/Certmanui.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,79 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Application UI class
+*
+*/
+
+
+#ifndef     CERTMANUI_H
+#define     CERTMANUI_H
+
+//  INCLUDES
+#include <aknview.h>
+#include <ConeResLoader.h>
+
+// CLASS DECLARATION
+
+/**
+*  CertManUI application UI class.
+*
+*  @lib certmanui.lib
+*/
+NONSHARABLE_CLASS( CCertManUi ): public CCoeControl
+  {
+  public: // functions
+
+        /**
+        * Initializes CCertManUi resource file
+        */
+    static void InitializeLibL();
+
+        /**
+        * Uninitializes CCertManUi resource file
+        */
+        static void UnInitializeLib();
+
+  private: // functions
+
+        /**
+        * C++ default constructor
+        */
+    CCertManUi();
+
+        /**
+        * Destructor
+        */
+    ~CCertManUi();
+
+        /**
+        * EPOC default constructor
+        */
+    void ConstructL();
+
+        /**
+        * Used in ConstructL to get resource file
+        */
+    void AddResourceFileL();
+
+  private: // data
+
+        /**
+        * To get hold of iResourceLoader
+        */
+        RConeResourceLoader       iResourceLoader;
+  };
+
+#endif //   CERTMANUI_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/Certmanui.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This file contains declarations for resources of CertManUI
+*
+*/
+
+
+#ifndef CERTMANUI_HRH
+#define CERTMANUI_HRH
+
+// DATA TYPES
+enum TCertManUIMenuCommands
+    {
+    ECertManUICmdAppViewDtls = 1,
+    ECertManUICmdAppDelete,
+    ECertManUICmdAppTrustSet,
+    ECertManUICmdAppChangeTrust,
+    ECertManUICmdMarkUnmark,
+    ECertManUICmdMark,
+    ECertManUICmdUnmark,
+    ECertManUICmdMarkAll,
+    ECertManUICmdUnmarkAll,
+    ECertManUICmdAppOpen,
+    ECertManUICmdMoveToDevice,
+    ECertManUICmdMoveToPersonal
+    };
+
+enum TCertManUITabViewId
+    {
+    ECertManUIViewCATab = 0,
+    ECertManUIViewPETab
+    };
+
+enum TCertManUINotes
+    {
+    ECertManUIDeleteNote = 1,
+    ECertManUIWaitNote
+    };
+
+#endif      // CERTMANUI_HRH
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuiCertificateHelper.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,237 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUICertificateHelper class
+*
+*/
+
+
+#ifndef  CERTMANUICERTIFICATEHELPER_H
+#define  CERTMANUICERTIFICATEHELPER_H
+
+// INCLUDES
+#include <pkixcertchain.h>          // for validation
+#include <e32std.h>
+#include "CertmanuiKeeper.h"
+#include "CertmanuiCommon.h"
+// FORWARD DECLARATIONS
+
+class CCertManUIKeeper;
+
+// CLASS DECLARATION
+
+
+/**
+*
+*/
+NONSHARABLE_CLASS( CCertManUICertificateHelper )
+    {
+    public:
+        CCertManUICertificateHelper( CCertManUIKeeper& aKeeper );
+
+        ~CCertManUICertificateHelper();
+
+       /**
+        * If CertLabel, Issuer and Owner length is over 80 characters, cut it down to 80
+        * Returns the cut certificate field.
+        */
+        TPtrC CutCertificateField(TPtrC aField);
+
+       /**
+        * Check whether certificate is deletable
+        * @param aIndex Index to certificate array
+        * @param aIsCA Flag whether CA/User certificate is in use
+        * @return ETrue if certificate is deletable
+        */
+        TBool IsCertificateDeletable(TInt aIndex, TInt aType)const;
+
+       /**
+        * Check whether one marked certificate is deletable
+        * @param aListbox Pointer to active view's listbox
+        * @param aIsCA Flag whether CA/User certificate is in use
+        * @return ETrue if certificate is deletable
+        */
+        TBool IsOneMarkedCertificateDeletable(CEikColumnListBox* aListBox,
+                                                TInt aType) const;
+
+       /**
+        * Creates the whole of certificate details view
+        * Appends strings from both resources and CertManAPI to one
+        * message body text and displays it.
+        */
+        void MessageQueryViewDetailsL( TInt aIndex, TInt aType,
+                                        CEikonEnv* aEikonEnv );
+
+       /**
+        * Checks if the certificate is corrupted
+        * Checks the validity period of the certificate
+        */
+        void ValidateCertificateL(
+            TInt aIndex, CCertificate* aDetails, const CCTCertInfo& aCertInfo, TInt aType);
+
+       /**
+        * Reads line from resources
+        */
+        void DetailsResourceL(HBufC& aMessage, TInt aResourceOne);
+
+       /**
+        * Deletes either certificate in focus if there are no marked items,
+        * or deletes the marked items
+        * Shows read-only information notes if certificates are not deletable
+        * Returns ETrue if at least one certificate is deleted
+        */
+        TBool ConfirmationQueryDeleteCertL(TInt aType,
+                                       CEikColumnListBox* aListBox);
+
+       /**
+        * Handle markable list command. Does nothing
+        * if listbox is not markable or empty.
+        */
+        void HandleMarkableListCommandL( TInt aCommand, CEikColumnListBox* aListBox);
+
+       /**
+        * Displays Delete yes/no confirmation notes
+        */
+        TInt DisplayConfirmationLD(HBufC* aString);
+
+       /**
+        * Moves one key from one store to another
+        */
+        void MoveKeyL( const TCTKeyAttributeFilter& aFilter,
+                       const TUid aSourceStore,
+                       const TUid aTargetStore );
+
+       /**
+        * Moves one certificate from one store to another
+        */
+        void MoveCertL( CCTCertInfo& aEntry, TInt aPosition,
+                        CEikColumnListBox* aListBox,
+                        const TUid aSourceStore,
+                        const TUid aTargetStore );
+
+    private:
+       /**
+        * Appends a field that has string from resources and string from CertManAPI
+        * to the details view message body
+        */
+        void DetailsFieldDynamicL(HBufC& aMessage, TPtrC aValue,
+                                  TInt aResourceOne, TInt aResourceTwo);
+
+       /**
+        * Appends a field that has two strings from resources
+        * to the details view message body
+        */
+        void DetailsFieldResourceL(HBufC& aMessage, TInt aResourceOne, TInt aResourceTwo);
+
+       /**
+        * Devides string to four characters blocks
+        * and delimits them with space.
+        * @param aInput String to devide
+        * @param aOutput Descriptor where result is appended
+        * @return void
+        */
+        void DevideToBlocks( const TDesC8& aInput, TPtr aOutput );
+
+       /**
+        * Displays the warning note for corrupted/expired/not yet valid certificate
+        */
+        void DisplayWarningNoteLD(HBufC* aString);
+
+       /**
+        * Checks if the X509 certificate is corrupted and the validity period of
+        * the certificate. Display only one warning note, in the following order:
+        * 1) Expired/Not yet valid
+        * 2) Corrupted
+        * 3) Not trusted
+        * @param aDetails
+        * @return
+        */
+        CArrayFixFlat<TValidationError>* ValidateX509CertificateL( CX509Certificate* aDetails );
+
+       /**
+        * Reads dynamic text from CertManAPI, if the string is empty
+        * put a not defined text from the resource in its place
+        */
+        void DetailsDynamicL(HBufC& aMessage, TPtrC aValue, TInt aResourceOne);
+
+       /**
+        * Gets the certificate name (or No label/No subject) for the Confirmation note
+        */
+        TInt DeleteSingleItemQueryL(CCTCertInfo& aEntry);
+
+       /**
+        * Deletes one item from CertManAPI and from listbox
+        */
+        void DeleteSingleItemL(CCTCertInfo& aEntry,
+                               TInt aPosition,
+                               CEikColumnListBox* aListBox,
+                               TInt aType);
+
+       /**
+        * Gets the certificate name (or No label/No subject) for the read-only note
+        */
+        void ReadOnlySingleItemNoteL(CCTCertInfo& aEntry);
+
+
+       /**
+        * Displays read-only information notes
+        */
+        void DisplayNoteLD(HBufC* aString);
+
+       /**
+        * Check if Disk space goes below critical level if allocating
+        * more disk space.
+        * @param aShowErrorNote If ETrue, a warning note is shown.
+        * @param aBytesToWrite Amount of disk space to be allocated (use an
+        * estimate if exact amount is not known).
+        * @return ETrue if allocation would go below critical level.
+        */
+        static TBool FFSSpaceBelowCriticalLevelL
+            ( TBool aShowErrorNote, TInt aBytesToWrite = 0 );
+
+       /**
+        * Returns usage of key
+        * @param aCertEntry Certificate in handling.
+        * @param aKeyLocation Where is key is being stored
+        */
+
+        TKeyUsagePKCS15 GetKeyUsageAndLocationL(CCTCertInfo* aCertEntry, TUid* aKeyLocation);
+
+       /**
+        * Set certificate/key location info to certificate details view
+        * @param aMessage Certificate details string
+        * @param aCertificate flag whether handling certificate or key
+        * @param aLocUid The location UID of cert/key
+        */
+        void SetLocationInfoL(HBufC& aMessage, TBool aCertificate, TUid* aLocUid);
+
+        /**
+         * Helper function for MessageQueryViewDetailsL() member. Fills in
+         * message body text for certificate details dialog.
+         * @param aIndex Certificate index, from MessageQueryViewDetailsL().
+         * @param aType Certificate type, from MessageQueryViewDetailsL().
+         * @param aEikonEnv Pointer to EIKON environment, from MessageQueryViewDetailsL().
+         * @param aMessage Message body text to be filled in.
+         */
+        void CreateMessageBodyTextL(TInt aIndex, TInt aType, CEikonEnv* aEikonEnv,
+                HBufC& aMessage);
+
+    private:  //Data
+
+        CCertManUIKeeper&   iKeeper;
+
+    };
+
+#endif //   CERTMANUICERTIFICATEHELPER_H
+
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuiCommon.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,117 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Includes, classes, constants and strings used by CertManUI
+*
+*/
+
+
+#ifndef  CERTMANUICOMMON_H
+#define  CERTMANUICOMMON_H
+
+// INCLUDES
+#include <eikmenub.h>     // for menu and cba support
+#include <aknnavide.h>
+#include <akntabgrp.h>
+#include <akntitle.h>
+#include <aknlists.h>
+#include <aknViewAppUi.h>
+#include <barsread.h>     // for TResourceReader
+#include <StringLoader.h>
+#include <featmgr.h>
+
+// _LITS
+_LIT( KCertManUIInsertDescriptor, "\t" );
+_LIT( KCertManUIFormatDescriptorTrustSettings, "\t%S\t\t" );
+_LIT( KCertManUIDetailsViewEnter, "\n" );
+_LIT( KCertManUIDetailsViewEnterEnter, "\n\n" );
+_LIT( KCertManUIDetailsViewEnterHyphenEnter, " - " );
+_LIT( KCertManUIDetailsViewHexaFormat, "%02X" );
+_LIT( KCertManUICertDataIndexFormat, "%d" );
+
+// FORWARD DECLARATIONS
+class CCertManUIContainerAuthority;
+class CCertManUIContainerPersonal;
+
+// CONST TINTS
+
+const TInt KCertTypeAuthority = 1;
+const TInt KCertTypeTrustedSite = 2;
+const TInt KCertTypePersonal = 3;
+const TInt KCertTypeDevice = 4;
+
+// For setting the correct title for CertManUI
+const TInt KViewTitleCertManUI = 1;
+const TInt KViewTitleCertManUIAuthority = 2;
+const TInt KViewTitleCertManUITrustedSite = 3;
+const TInt KViewTitleCertManUIPersonal = 4;
+const TInt KViewTitleCertManUIDevice = 5;
+
+
+const TUid KCMFileCertStoreTokenUid = { 0x101F501A };
+const TUid KCMTrustedServerTokenUid = { 0x101FB66F };
+const TUid KCMDeviceCertStoreTokenUid = { 0x101FB668 };
+
+const TUid KCMFileKeyStoreTokenUid = { 0x101F7333 };
+const TUid KCMDeviceKeyStoreTokenUid = { 0x101FB66A };
+
+
+// Granularity of the created iconarrays
+LOCAL_D const TInt KGranularity = 4;
+
+// "dd/mm/yyyy0"
+const TInt KMaxLengthTextDateString = 11;
+// HH0
+const TInt KMaxLengthTextSerialNumberFormatting = 3;
+// CertLabel, Issuer, Owner max length 510 bytes
+const TInt KMaxLengthTextCertLabel = 510;
+// CertLabel, Issuer, Owner max visible length
+const TInt KMaxLengthTextCertLabelVisible = 200;
+// CertWimLabel, KeyLabel, KeyWimLabel max length 255 bytes
+const TInt KMaxLengthTextKeyWimLabel = 256;
+// Maximum length of dynamic strings is 4092,
+// plus 13 resource strings with average lenght of 50 makes 650
+// total 4742 rounded up to 5000
+const TInt KMaxLengthTextDetailsBody = 5000;
+// Max length for ave_list_setting_pane_1 is 52 and
+// for ave_list_setting_pane_2 51 (formatting 7) , total 103 + end mark
+const TInt KMaxLengthTextSettListOneTwo = 104;
+// Max length for ave_list_setting_pane_1 is 52
+const TInt KMaxLengthTextSettListOne = 52;
+// Maximum length of a certificate
+const TInt KMaxCertificateLength = 5000;
+const TInt KMaxKeyLength = 10000;
+
+const TInt KWIMCertStoreUid ( 0x101F79D9 );
+
+// FEATURE FLAGS
+
+#define WIM_ENABLED ( FeatureManager::FeatureSupported( KFeatureIdWim ) )
+
+// DATA TYPES
+
+enum TCertmanUiPanics
+    {
+    EBadDialogSelector,
+    EDoubleDialogClose
+    };
+
+enum TCertmanUiDialogs
+    {
+    ECertmanUiDeleteDialog,
+    ECertmanUiWaitDialog
+    };
+
+#endif //   CERTMANUICOMMON_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuiKeeper.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,353 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIKeeper class
+*
+*/
+
+
+#ifndef  CERTMANUIKEEPER_H
+#define  CERTMANUIKEEPER_H
+
+// INCLUDES
+#include <unifiedcertstore.h>
+#include <mctwritablecertstore.h>
+#include <unifiedkeystore.h>
+#include <AknProgressDialog.h>
+#include <ConeResLoader.h>
+
+// FORWARD DECLARATIONS
+class CCrCertEntry;
+class CCertManUISyncWrapper;
+class CCertManUICertData;
+class CCertManUiDialogs;
+class CEikColumnListBox;
+class CAknTabGroup;
+class CAknNavigationDecorator;
+class CAknNavigationControlContainer;
+class CCertManUICertificateHelper;
+class CCertManUIWaitDialog;
+
+// CLASS DECLARATION
+
+/**
+*  CCertManUIKeeper view control class.
+*
+*  @lib certmanui.lib
+*/
+NONSHARABLE_CLASS( CCertManUIKeeper ): public CCoeControl, public MCoeControlObserver
+    {
+    public: // functions
+
+        /**
+        * Default constructor
+        */
+        CCertManUIKeeper();
+
+        /**
+        * Destructor.
+        */
+        ~CCertManUIKeeper();
+
+        /**
+        * NewL
+        */
+        static class CCertManUIKeeper* NewL(const TRect& aRect, TUid aViewId);
+
+        /**
+        * NewLC
+        */
+        static class CCertManUIKeeper* NewLC(const TRect& aRect, TUid aViewId);
+
+        /**
+        * Activates the WimTitle and CertManUI Trust Settings title
+        */
+        void ActivateTitleL(TInt aCurrentTitle);
+
+        /**
+        * Returns *iCertStore
+        */
+        CUnifiedCertStore*& CertManager();
+
+
+        /**
+        * Initializes CertManUI Keeper
+        */
+        void InitializeL(const TRect& aRect, TUid aViewId);
+
+        /**
+        * Returns *iKeyStore
+        */
+        CUnifiedKeyStore*& KeyManager();
+
+        /**
+        * Added here because FocusChanged need to be included
+        * in every control derived from CCoeControl that can have listbox
+        */
+        void FocusChanged(TDrawNow aDrawNow);
+
+        /**
+        * Checks that cacerts.dat file is not corrupt
+        * and returns CA certificates from it.
+        */
+        void RefreshCAEntriesL();
+
+        /**
+        * Checks that cacerts.dat file is not corrupt
+        * and returns user certificates from it.
+        */
+        void RefreshUserCertEntriesL();
+
+        /**
+        * Returns peer certificates.
+        */
+        void RefreshPeerCertEntriesL();
+
+        /**
+        * Returns peer certificates.
+        */
+        void RefreshDeviceCertEntriesL();
+
+        /**
+        * Shows error note
+        */
+        void ShowErrorNoteL(TInt aError);
+
+        /**
+        * Displays wait dialog
+        */
+        void StartWaitDialogL(TInt aDialogSelector);
+
+        /**
+        * Closes wait dialog
+        */
+        void CloseWaitDialogL();
+
+        /**
+        * Check whether local feature is on
+        */
+        TBool IsLocalFeatureSupported( const TInt aFeature ) const;
+
+    public: //data
+
+        /**
+        * Added here because FocusChanged need to be included
+        * in every control derived from CCoeControl that can have listbox
+        */
+        CEikColumnListBox*    iListBox;
+
+
+        /**
+        * To store CA certificate entries for Authority and Trust view
+        * Includes label from x509certnameparser.
+        */
+        RMPointerArray<CCertManUICertData>     iCALabelEntries;
+
+        /**
+        * To store CA certificate entries for Authority and Trust view
+        * Includes label from x509certnameparser.
+        */
+        RMPointerArray<CCertManUICertData>     iUserLabelEntries;
+
+        /**
+        * To store Peer certificate entries for Trusted Site view
+        * Includes label from x509certnameparser.
+        */
+        RMPointerArray<CCertManUICertData>     iPeerLabelEntries;
+
+        /**
+        * To store Peer certificate entries for Device certificate view
+        * Includes label from x509certnameparser.
+        */
+        RMPointerArray<CCertManUICertData>     iDeviceLabelEntries;
+
+        /**
+        * Used to wrap asynchronous calls
+        */
+        CCertManUISyncWrapper*          iWrapper;
+
+        /**
+        * File session handle.
+        */
+        RFs                             iRfs;
+
+        /**
+        * To keep track of the currupted state of cacerts.dat
+        * ETrue = not corrupted
+        * EFalse = corrupted
+        */
+        TBool   iCertsDatOK;
+
+        /**
+        * To know when CertManUI is started the first time
+        * ETrue = startup
+        * EFalse = not startup
+        */
+        TBool   iStartup;
+
+         /**
+        * Certificate helper class
+        */
+        CCertManUICertificateHelper*    iCertificateHelper;
+
+    private: // functions
+
+        /**
+        * EPOC default constructor.
+        * @param aRect Frame rectangle for container.
+        */
+        void ConstructL(const TRect& aRect, TUid aViewId);
+
+        /**
+        * Opens resource file.
+        */
+        void AddResourceFileL();
+
+        /**
+        * Handles control events
+        * Cannot be changed to non-leaving function.
+        * L-function is required by the class definition, even if empty.
+        */
+        void HandleControlEventL( CCoeControl* aControl,TCoeEvent aEventType );
+
+        /**
+        * Called when a key is pressed
+        * Cannot be changed to non-leaving function.
+        * L-function is required by the class definition, even if empty.
+        */
+        TKeyResponse OfferKeyEventL(
+                const TKeyEvent& aKeyEvent, TEventCode aType);
+
+        /**
+        * Read local variation settings
+        */
+        void ReadLocalVariationL();
+
+
+    private: //data
+
+        /**
+        * To store the previous view id inside CertManUI
+        */
+        TUid    iPreviousViewId;
+
+        /**
+        * To store the previous view id outside CertManUI, KSettListSecurityViewId
+        */
+        TUid    iPreviousAppViewId;
+
+        /**
+        * To list certificates with criteria.
+        */
+        CCertAttributeFilter*   iFilter;
+
+        /**
+        * To list certificates with criteria.
+        */
+
+        TCTKeyAttributeFilter*    iKeyFilter;
+
+        /**
+        * UnifiedCertStore
+        */
+        CUnifiedCertStore*    iStore;
+
+        /**
+        * UnifiedCertStore
+        */
+        CUnifiedKeyStore*   iKeyStore;
+
+        /**
+        * To store CA certificate entries.
+        */
+        RMPointerArray<CCTCertInfo>     iCAEntries;
+
+        /**
+        * To store User certificate entries.
+        */
+        RMPointerArray<CCTCertInfo>     iUserEntries;
+
+        /**
+        * To store Peer certificate entries.
+        */
+        RMPointerArray<CCTCertInfo>     iPeerEntries;
+
+        /**
+        * To store Device certificate entries.
+        */
+        RMPointerArray<CCTCertInfo>     iDeviceEntries;
+
+        /**
+        * To store Key entries
+        */
+        RMPointerArray<CCTKeyInfo>      iKeyEntries;
+
+        /*
+        * Wait dialog
+        */
+        CCertManUIWaitDialog*           iCertmanUIDialog;
+
+        /**
+        * Local variantion mask
+        */
+        TInt    iLocalFeaturesMask;
+
+        /**
+        * Resource loader
+        */
+        RConeResourceLoader iResourceLoader;
+
+
+   };
+
+/**
+*  Small helper class to put label and certificate in same class.
+*
+*  @lib certmanui.lib
+*/
+NONSHARABLE_CLASS( CCertManUICertData ): public CBase
+    {
+    public:
+
+        CCertManUICertData();
+
+        void Release();
+
+        HBufC* iCAEntryLabel;
+        HBufC* iUserEntryLabel;
+        HBufC* iPeerEntryLabel;
+        HBufC* iDeviceEntryLabel;
+        CCTCertInfo* iCAEntry;
+        CCTCertInfo* iUserEntry;
+        CCTCertInfo* iPeerEntry;
+        CCTCertInfo* iDeviceEntry;
+
+    private:
+        ~CCertManUICertData();
+
+    };
+
+
+/**
+ * Helper function to close wait dialog if leave happens.
+ * CCertManUIKeeper::StartWaitDialogL() brings wait dialog visible.
+ * Wait dialog must be closed by calling CCertManUIKeeper::CloseWaitDialogL().
+ * If code leaves after StartWaitDialogL() and before CloseWaitDialogL(),
+ * the wait dialog is never closed.
+ */
+void CleanupCloseWaitDialogPushL( CCertManUIKeeper& aKeeper );
+
+
+#endif // __CERTMANUIKEEPER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuiPlugin.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,128 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIPlugin class
+*
+*/
+
+
+#ifndef   CERTMANUIPLUGIN_H
+#define   CERTMANUIPLUGIN_H
+
+// Includes
+#include <aknview.h>
+#include <eikclb.h>
+#include <ConeResLoader.h>
+
+#include <gsplugininterface.h>
+
+// Forward declarations
+class CCertManUIKeeper;
+class CCertManUIPluginContainer;
+class CAknViewAppUi;
+
+// Constants
+
+/**
+* Used for both the view UID and the ECOM plugin implementation UID.
+*/
+const TUid KCertManUIPluginUid = { 0x10008D3D };
+
+// CLASS DECLARATION
+
+/**
+* @since Series60_3.1
+*/
+class CCertManUIPlugin : public CGSPluginInterface
+    {
+
+    public: // Constructors and destructor
+
+        /**
+        * Symbian OS two-phased constructor
+        * @return
+        */
+        static CCertManUIPlugin* NewL( TAny* aInitParams );
+
+        /**
+        * Destructor.
+        */
+        ~CCertManUIPlugin();
+
+    public: // From CAknView
+
+        /**
+        * See base class.
+        *
+        */
+        TUid Id() const;
+
+        /**
+        * See base class.
+        */
+        void HandleClientRectChange();
+
+        /**
+        * See base class.
+        */
+        void DoActivateL( const TVwsViewId& aPrevViewId,
+                          TUid aCustomMessageId,
+                          const TDesC8& aCustomMessage );
+
+        /**
+        * See base class.
+        */
+        void DoDeactivate();
+
+        /**
+        * See base class.
+        */
+        void GetCaptionL( TDes& aCaption ) const;
+
+    private: // New
+
+        /**
+        * C++ default constructor.
+        */
+        CCertManUIPlugin();
+
+        /**
+        * Symbian OS default constructor.
+        */
+        void ConstructL();
+
+        /**
+        * Used in ConstructL to get resource file
+        */
+        void AddResourceFileL();
+
+    private: // Data
+
+        // Resouce loader.
+        RConeResourceLoader iResourceLoader;
+
+        CCertManUIKeeper* iCertManUIKeeper;
+
+        // Pointer to the container
+        CCertManUIPluginContainer* iContainer;
+
+        //Previous view (Security view)
+        TVwsViewId iPrevViewId;
+
+        // Indicates if CertManUI is initialized
+        TBool iCertManUIInitialized;
+    };
+
+#endif //   CERTMANUIPLUGIN_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuiPluginContainer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,72 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIPluginContainer class
+*
+*/
+
+
+#ifndef   CERTMANUIPLUGINCONTAINER_H
+#define   CERTMANUIPLUGINCONTAINER_H
+
+// INCLUDES
+#include    <coeccntx.h>
+#include    <eikclb.h>
+
+// CLASS DECLARATION
+
+/**
+*  CCertManUIPluginContainer container class
+*
+*  container class for CertMan UI view
+*/
+class CCertManUIPluginContainer : public CCoeControl
+    {
+    public: // Constructors and destructor
+
+        CCertManUIPluginContainer();
+
+        /**
+        * Symbian OS constructor.
+        *
+        * @param aRect Listbox's rect.
+        */
+        void ConstructL( const TRect& aRect );
+
+        /**
+        * Destructor.
+        */
+        ~CCertManUIPluginContainer();
+
+    public: // From CCoeControl
+
+        /**
+        * From CoeControl returns the amount of controls
+        */
+        TInt CountComponentControls() const;
+
+        /**
+        * From CCoeControl returns controls for CONE actions
+        */
+        CCoeControl* ComponentControl( TInt aIndex ) const;
+
+        /**
+        * From CCoeControl changes the size of the list box
+        */
+        void SizeChanged();
+
+    };
+
+#endif // CERTMANUIPLUGINCONTAINER_H
+
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuiSyncWrapper.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,352 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Wrapper class for Symbian's Security Framework's calls
+*
+*/
+
+
+#ifndef     CERTMANUISYNCWRAPPER_H
+#define     CERTMANUISYNCWRAPPER_H
+
+
+// INCLUDES
+#include <e32base.h>
+
+// FORWARD DECLERATIONS
+class CCertificate;
+class CPKIXValidationResult;
+class CPKIXCertChain;
+class CUnifiedCertStore;
+
+// CLASS DECLARATION
+
+/**
+*  Wrapper class for Symbian's Security Framework's calls.
+*  Shows error notes if an error happenes.
+*
+*  @lib certmanui.dll
+*  @since S60 2.0
+*/
+NONSHARABLE_CLASS( CCertManUISyncWrapper ): public CActive
+    {
+    public:
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCertManUISyncWrapper* NewLC();
+
+        /**
+        * Two-phased constructor.
+        */
+        static CCertManUISyncWrapper* NewL();
+
+        /**
+        * Destructor.
+        */
+        ~CCertManUISyncWrapper();
+
+    public: // New functions
+
+        /**
+        * TInt ListL
+        * @since S60 2.8
+        * @param aStore reference to store where operation is done.
+        * @param aArray Keys are stored here.
+        * @param aFilter Information on what kind keys are looked.
+        * @return TInt Status Symbian's API's call.
+        */
+
+        TInt ListL( CUnifiedKeyStore*& aStore,
+            RMPointerArray<CCTKeyInfo>* aArray,
+            const TCTKeyAttributeFilter& aFilter );
+
+        /**
+        * TInt ListL
+        * @since S60 3.2
+        * @param aStore reference to store where operation is done.
+        * @param aArray Keys are stored here.
+        * @param aFilter Information on what kind keys are looked.
+        * @param aTokenUid Token UID of key store
+        * @return TInt Status Symbian's API's call.
+        */
+
+        TInt ListL( CUnifiedKeyStore*& aStore,
+            RMPointerArray<CCTKeyInfo>* aArray,
+            const TCTKeyAttributeFilter& aFilter,
+            const TUid aTokenUid );
+
+        /**
+        * TInt ListL
+        * @since S60 2.0
+        * @param aStore reference to store where operation is done.
+        * @param aArray certificates are stored here.
+        * @param aFilter Information on what kind certificates are looked.
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt ListL( CUnifiedCertStore*& aStore,
+            RMPointerArray<CCTCertInfo>* aArray,
+            const CCertAttributeFilter& aFilter );
+
+        /**
+        * TInt ListL
+        * @since S60 3.2
+        * @param aStore reference to store where operation is done.
+        * @param aArray certificates are stored here.
+        * @param aFilter Information on what kind certificates are looked.
+        * @param aTokenUid Token UID of certificate store
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt ListL( CUnifiedCertStore*& aStore,
+            RMPointerArray<CCTCertInfo>* aArray,
+            const CCertAttributeFilter& aFilter,
+            const TUid aTokenUid );
+
+
+        /**
+        * TInt GetCertificateL
+        * @since S60 2.0
+        * @param aStore reference to store where operation is done.
+        * @param aCertInfo Certificate that's detailed information is fetched.
+        * @param aCert Fetched certificate.
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt GetCertificateL( CUnifiedCertStore*& aStore,
+            const CCTCertInfo& aCertInfo, CCertificate*& aCert );
+
+        /**
+        * TInt GetCertificateL
+        * @since S60 3.2
+        * @param aStore reference to store where operation is done.
+        * @param aCertInfo Certificate that's detailed information is fetched.
+        * @param aCert Fetched certificate.
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt GetCertificateL( CUnifiedCertStore*& aStore,
+            const CCTCertInfo& aCertInfo, CCertificate*& aCert, TUid aTokenUid );
+
+
+        /**
+        * TInt GetUrlCertificateL
+        * @since S60 3.0
+        * @param aStore reference to store where operation is done.
+        * @param aCertInfo Certificate that's detailed information is fetched.
+        * @param aUrl Fetched URL.
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt GetUrlCertificateL(
+            CUnifiedCertStore*& aStore,
+            const CCTCertInfo& aCertInfo,
+            TDes8& aUrl)            ;
+
+        /**
+        * TInt GetApplicationsL
+        * @since S60 2.0
+        * @param aStore reference to store where operation is done.
+        * @param aCertInfo Certificate that applications are fetched.
+        * @param Certificates applications are stoted here.
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt GetApplicationsL( CUnifiedCertStore*& aStore,
+            const CCTCertInfo& aCertInfo, RArray<TUid>& aApps );
+
+        /**
+        * TInt ValidateX509RootCertificateL
+        * @since S60 2.0
+        * @param aValidationResult Result of validation.
+        * @param aValidationTime Time of validation.
+        * @param aChain Chain to be validated.
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt ValidateX509RootCertificateL(
+            CPKIXValidationResult*& aValidationResult,
+            const TTime& aValidationTime, CPKIXCertChain* aChain );
+
+        /**
+        * TInt InitStoreL
+        * @since S60 2.0
+        * @param aStore reference to store to be initialized.
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt InitStoreL( CUnifiedCertStore*& aStore );
+
+        /**
+        * void InitStoreL
+        * @since S60 2.8
+        * @param aStore reference to store to be initialized.
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt InitStoreL( CUnifiedKeyStore*& aStore );
+
+        /**
+        * TInt DeleteCertL
+        * @since S60 2.0
+        * @param aStore reference to store where operation is done.
+        * @param aCertInfo Certificate to be deleted.
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt DeleteCertL( CUnifiedCertStore*& aStore,
+            const CCTCertInfo& aCertInfo );
+
+        /**
+        * TInt DeleteCertL
+        * @since S60 3.2
+        * @param aStore reference to store where operation is done.
+        * @param aCertInfo Certificate to be deleted.
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt DeleteCertL( CUnifiedCertStore*& aStore,
+            const CCTCertInfo& aCertInfo,
+            TUid aTokenUid );
+
+        /**
+        * TInt IsApplicableL
+        * @since S60 2.0
+        * @param aStore reference to store where operation is done.
+        * @param aCertInfo Certificate thats applicability is queried.
+        * @param aApplication Application that's status is queried.
+        * @param aIsApplicable ETrue if applcable.
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt IsApplicableL( CUnifiedCertStore*& aStore,
+            const CCTCertInfo& aCertInfo, TUid aApplication,
+        TBool& aIsApplicable );
+
+        /**
+        * TInt IsTrustedL
+        * @since S60 2.0
+        * @param aStore reference to store where operation is done.
+        * @param aCertInfo Certificate that's trust status is queried.
+        * @param aTrusted ETrue if trusted.
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt IsTrustedL( CUnifiedCertStore*& aStore,
+            const CCTCertInfo& aCertInfo, TBool& aTrusted );
+
+        /**
+        * TInt SetApplicabilityL
+        * @since S60 2.0
+        * @param aStore reference to store where operation is done.
+        * @param aCertInfo Certificate thats applicability is set.
+        * @param aApplications New applicability settings.
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt SetApplicabilityL( CUnifiedCertStore*& aStore,
+            const CCTCertInfo& aCertInfo,
+        RArray<TUid>& aApplications );
+
+      /**
+        * void MoveCertL
+        * @since S60 3.2
+        * @param aStore reference to store where operation is done
+        * @param aCertInfo Certificate info
+        * @param aSourceStore UID of source certificate store
+        * @param aTargetStore UID of source certificate store
+        * @return TInt Number of moved certificates
+        */
+        TInt MoveCertL( CUnifiedCertStore*& aStore,
+            const CCTCertInfo& aCertInfo,
+            const TUid aSourceTokenId,
+            const TUid aTargetTokenId );
+
+      /**
+        * void MoveKeyL
+        * @since S60 3.2
+        * @param aStore reference to store where operation is done
+        * @param CCTKeyInfo Key info
+        * @param aSourceStore UID of source key store
+        * @param aTargetStore UID of source key store
+        * @return none
+        */
+        void MoveKeyL( CUnifiedKeyStore*& aStore,
+            const TCTKeyAttributeFilter& aFilter,
+            const TUid aSourceTokenId,
+            const TUid aTargetTokenId );
+
+        /**
+        * TInt GetInterface
+        * @since S60 3.0
+        * @param aToken reference to token
+        * @param aTokenInterface Pointer to returned interface
+        * @return TInt Status Symbian's API's call.
+        */
+        TInt GetInterface( TUid aRequiredInterface,
+            MCTToken& aToken,
+            MCTTokenInterface*& aReturnedInterface );
+
+    protected:
+
+        void DoCancel();
+        void RunL();
+
+    private:
+
+        CCertManUISyncWrapper();
+        void ConstructL();
+
+        void HandleErrorL();
+
+    private:    //Data
+
+        // Internal operation states.
+        enum TOperation
+            {
+            EOperationNone,
+            EOperationInit,
+            EOperationList,
+            EGetCertificate,
+            EAddCertificate,
+            ERetriveURLCertificate,
+            EOperationDelete,
+            EOperationGetApps,
+            EOperationIsApplicable,
+            EOperationIsTrusted,
+            EOperationSetApplicability,
+            EOperationSetToTrusted,
+            EOperationValidateX509Root,
+            EShowErrorNote,
+            EOperationInitKeyStore,
+            EOperationKeyList,
+            EOperationGetInterface,
+            EOperationExportKey,
+            EOperationImportKey,
+            EOperationDeleteKey
+            };
+
+        // For wrapping asynchronous calls.
+        CActiveSchedulerWait    iWait;
+
+        // Internal state of operation.
+        TOperation              iOperation;
+
+        // Just for cancelling a operation. Does not own.
+        CUnifiedCertStore*      iStore;
+
+        // Just for cancelling a operation. Does not own.
+        CUnifiedKeyStore*       iKeyStore;
+
+        // Just for cancelling a operation. Does not own.
+        CPKIXCertChain*         iChain;
+
+        // For retrieving a certificate.
+        TPtr8                   iCertPtr;
+
+        // Token handle
+        MCTToken*               iToken;
+
+    };
+
+#endif // CERTMANUISYNCWRAPPER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuicontainerAuthority.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,200 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIContainerAuthority class
+*
+*/
+
+
+#ifndef  CERTMANUICONTAINERAUTHORITY_H
+#define  CERTMANUICONTAINERAUTHORITY_H
+
+// INCLUDES
+#include "CertmanuiviewAuthority.h"
+
+// CLASS DECLARATION
+
+class CAknIconArray;
+
+/**
+*  CCertManUIContainerAuthority container control class.
+*
+*  @lib certmanui.lib
+*/
+NONSHARABLE_CLASS( CCertManUIContainerAuthority ):
+    public CCoeControl, public MCoeControlObserver, public MEikListBoxObserver
+    {
+
+    /**
+    * Container authority needs to get access to CertManUIViewAuthority's DoActivateL
+    */
+    friend void CCertManUIViewAuthority::DoActivateL( const TVwsViewId&,
+                                                      TUid, const TDesC8& );
+
+    public: // functions
+
+        /**
+        * Overrided Default constructor
+        */
+        CCertManUIContainerAuthority( CCertManUIViewAuthority& aParent,
+                                      CCertManUIKeeper& aKeeper );
+
+        /**
+        * Destructor.
+        */
+        ~CCertManUIContainerAuthority();
+
+        /**
+        * Change focus
+        */
+        void FocusChanged( TDrawNow aDrawNow );
+
+        /**
+        * Draws listbox, fetches graphic icons for markable list
+        */
+        void DrawListBoxL( TInt aCurrentPosition, TInt aTopItem );
+
+        /**
+        * Gets list of certificates from CertManAPI, displays them,
+        * sets No label/No subject text to them if their names are empty
+        */
+        void UpdateListBoxL( TInt& aCurrentPosition, TInt& aTopItem );
+
+        /**
+        * Handles listbox events
+        */
+        void HandleListBoxEventL( CEikListBox* aListBox, TListBoxEvent aEventType );
+
+        /**
+        * Handles resource change
+        */
+        void HandleResourceChange( TInt aType );
+
+    public: // data
+
+        /**
+        * To handle listbox
+        * Type column for making the list markable
+        * Cannot be private because CertManUIViewTrust uses it
+        */
+        CEikColumnListBox*    iListBox;
+
+        /**
+        * To get hold of ViewAuthority
+        */
+        CCertManUIViewAuthority&    iParent;
+
+        /**
+        * To get hold of CertManUIKeeper
+        */
+        CCertManUIKeeper&   iKeeper;
+
+        /**
+        * To store the list item count
+        */
+        TInt    iListItemCount;
+
+    private: // functions
+
+        /**
+        * Default constructor
+        */
+        CCertManUIContainerAuthority();
+
+        /**
+        * EPOC default constructor.
+        * @param aRect Frame rectangle for container.
+        */
+        void ConstructL( const TRect& aRect, TInt& aCurrentPosition, TInt& aTopItem );
+
+        /**
+        * Creates listbox, sets empty listbox text
+        */
+        void CreateListBoxL();
+
+        /**
+        * From CoeControl,SizeChanged.
+        */
+        void SizeChanged();
+
+        /**
+        * From CoeControl,CountComponentControls.
+        */
+        TInt CountComponentControls() const;
+
+        /**
+        * From CCoeControl,ComponentControl.
+        */
+        CCoeControl* ComponentControl( TInt aIndex ) const;
+
+        /**
+        * From CCoeControl,Draw.
+        */
+        void Draw( const TRect& aRect ) const;
+
+        /**
+        * Handles control events
+        * Cannot be changed to non-leaving function.
+        * L-function is required by the class definition, even if empty.
+        */
+        void HandleControlEventL( CCoeControl* aControl,TCoeEvent aEventType );
+
+        /**
+        * Handles the key events OK button, arrow keys, delete key.
+        * OK button functionality is different depending on the number of marked items
+        * in the list; zero marked -> show details view, one or more marked -> show
+        * OKOptions list, list empty -> OK inactive.
+        * Delete active only if list not empty.
+        */
+        TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+        /**
+        * Create the iconarray. Derived classes please don't forget that the
+        * 0th icon must be the markable listbox's mark icon.
+        * @return The created iconarray. Owner is the caller.
+        */
+        CAknIconArray* CreateIconArrayL() const;
+
+        /**
+        * Get resource id for the iconarray.
+        * @return The resource id for the iconarray.
+        */
+        TInt IconArrayResourceId() const;
+
+
+        /**
+        * This function is called when Help application is launched.
+        * (other items were commented in a header).
+        */
+        void GetHelpContext( TCoeHelpContext& aContext ) const;
+
+    protected: //data
+
+       /**
+        * If ETrue, OK-Options menu is shown instead of normal Options menu.
+        */
+        TBool   iShowOkOptions;
+
+    private: //data
+
+        /**
+        * Icon handler (this creates icons and calculates icon indexes).
+        */
+        const CCertManUIContainerAuthority*   iIconHandler;
+ };
+
+#endif // CERTMANUICONTAINERAUTHORITY_H
+
+// End of File
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuicontainerDevice.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,196 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIContainerDevice class
+*
+*/
+
+
+#ifndef  CERTMANUICONTAINERDEVICE_H
+#define  CERTMANUICONTAINERDEVICE_H
+
+// INCLUDES
+#include "CertmanuiviewDevice.h"
+
+// CLASS DECLARATION
+
+class CAknIconArray;
+
+/**
+*  CCertManUIContainerDevice container control class.
+*
+*  @lib certmanui.lib
+*/
+NONSHARABLE_CLASS( CCertManUIContainerDevice ):
+    public CCoeControl, public MCoeControlObserver, public MEikListBoxObserver
+    {
+    /**
+    * Container device needs to get access to CCertManUIViewDevice's DoActivateL
+    */
+    friend void CCertManUIViewDevice::DoActivateL( const TVwsViewId&, TUid, const TDesC8& );
+
+    public: // functions
+
+        /**
+        * Overrided Default constructor
+        */
+        CCertManUIContainerDevice( CCertManUIViewDevice& aParent, CCertManUIKeeper& aKeeper );
+
+        /**
+        * Destructor.
+        */
+        ~CCertManUIContainerDevice();
+
+        /**
+        * Change focus
+        */
+        void FocusChanged( TDrawNow aDrawNow );
+
+        /**
+        * Draws listbox, fetches graphic icons for markable list
+        */
+        void DrawListBoxL( TInt aCurrentPosition, TInt aTopItem );
+
+        /**
+        * Gets list of certificates from CertManAPI, displays them,
+        * sets No label/No subject text to them if their names are empty
+        */
+        void UpdateListBoxL( TInt& aCurrentPosition, TInt& aTopItem );
+
+        /**
+        * Handles listbox events
+        */
+        void HandleListBoxEventL( CEikListBox* aListBox, TListBoxEvent aEventType );
+
+        /**
+        * Handles resource change
+        */
+        void HandleResourceChange( TInt aType );
+
+    public: // data
+
+        /**
+        * To handle listbox
+        * Type column for making the list markable
+        * Cannot be private because CertManUIViewTrust uses it
+        */
+        CEikColumnListBox*    iListBox;
+
+        /**
+        * To get hold of ViewAuthority
+        */
+        CCertManUIViewDevice&   iParent;
+
+        /**
+        * To get hold of CertManUIKeeper
+        */
+        CCertManUIKeeper&   iKeeper;
+
+        /**
+        * To store the list item count
+        */
+        TInt    iListItemCount;
+
+    private: // functions
+
+        /**
+        * Default constructor
+        */
+        CCertManUIContainerDevice();
+
+        /**
+        * EPOC default constructor.
+        * @param aRect Frame rectangle for container.
+        */
+    void ConstructL( const TRect& aRect, TInt& aCurrentPosition, TInt& aTopItem );
+
+       /**
+        * Creates listbox, sets empty listbox text
+        */
+    void CreateListBoxL();
+
+        /**
+        * From CoeControl,SizeChanged.
+        */
+        void SizeChanged();
+
+        /**
+        * From CoeControl,CountComponentControls.
+        */
+        TInt CountComponentControls() const;
+
+        /**
+        * From CCoeControl,ComponentControl.
+        */
+        CCoeControl* ComponentControl( TInt aIndex ) const;
+
+        /**
+        * From CCoeControl,Draw.
+        */
+        void Draw( const TRect& aRect ) const;
+
+        /**
+        * Handles control events
+        * Cannot be changed to non-leaving function.
+        * L-function is required by the class definition, even if empty.
+        */
+        void HandleControlEventL( CCoeControl* aControl, TCoeEvent aEventType );
+
+        /**
+        * Handles the key events OK button, arrow keys, delete key.
+        * OK button functionality is different depending on the number of marked items
+        * in the list; zero marked -> show details view, one or more marked -> show
+        * OKOptions list, list empty -> OK inactive.
+        * Delete active only if list not empty.
+        */
+        TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+        /**
+        * Create the iconarray. Derived classes please don't forget that the
+        * 0th icon must be the markable listbox's mark icon.
+        * @return The created iconarray. Owner is the caller.
+        */
+        CAknIconArray* CreateIconArrayL() const;
+
+        /**
+        * Get resource id for the iconarray.
+        * @return The resource id for the iconarray.
+        */
+    TInt IconArrayResourceId() const;
+
+        /**
+        * This function is called when Help application is launched.
+        * (other items were commented in a header).
+        */
+        void GetHelpContext(TCoeHelpContext& aContext) const;
+
+    protected: //data
+
+       /**
+        * If ETrue, OK-Options menu is shown instead of normal Options menu.
+        */
+        TBool   iShowOkOptions;
+
+    private: //data
+
+        /**
+        * Icon handler (this creates icons and calculates icon indexes).
+        */
+        const CCertManUIContainerDevice*    iIconHandler;
+ };
+
+#endif // CERTMANUICONTAINERDEVICE_H
+
+// End of File
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuicontainerMain.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,194 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIContainerMain class
+*
+*/
+
+
+#ifndef  CERTMANUICONTAINERMAIN_H
+#define  CERTMANUICONTAINERMAIN_H
+
+// INCLUDES
+#include "CertmanuiviewMain.h"
+
+// FORWARD DECLARATIONS
+class CAknIconArray;
+
+// CLASS DECLARATION
+/**
+*  CCertManUIContainerMain container control class.
+*
+*  @lib certmanui.lib
+*/
+NONSHARABLE_CLASS( CCertManUIContainerMain ):
+    public CCoeControl, public MCoeControlObserver, public MEikListBoxObserver
+    {
+
+    /**
+    * Container main needs to get access to CCertManUIViewMain's DoActivateL
+    */
+    friend void CCertManUIViewMain::DoActivateL( const TVwsViewId&, TUid, const TDesC8& );
+
+    public: // functions
+
+        /**
+        * Overrided Default constructor
+        */
+        CCertManUIContainerMain( CCertManUIViewMain& aParent, CCertManUIKeeper& aKeeper );
+
+        /**
+        * Destructor.
+        */
+        ~CCertManUIContainerMain();
+
+        /**
+        * Change focus
+        */
+        void FocusChanged( TDrawNow aDrawNow );
+
+        /**
+        * Draws listbox, fetches graphic icons for markable list
+        */
+        void DrawListBoxL( TInt aCurrentPosition, TInt aTopItem );
+
+        /**
+        * Handles listbox events
+        */
+        void HandleListBoxEventL( CEikListBox* aListBox, TListBoxEvent aEventType );
+
+        /**
+        * Handles resource change
+        */
+        void HandleResourceChange( TInt aType );
+
+    public: // data
+
+        /**
+        * To handle listbox
+        * Type column for making the list markable
+        * Cannot be private because CertManUIViewPersonal uses it
+        */
+        CAknSettingStyleListBox*    iListBox;
+
+        /**
+        * To get hold of ViewPersonal
+        */
+        CCertManUIViewMain&   iParent;
+
+        /**
+        * To get hold of CertManUIKeeper
+        */
+        CCertManUIKeeper&   iKeeper;
+
+        /**
+        * To store the list item count
+        */
+        TInt    ListItemCount;
+
+        /**
+        * To store certificate entries
+        */
+        CArrayPtrFlat<CCrCertEntry>*    iEntriesPersonal;
+
+    private: // functions
+
+        /**
+        * Default constructor
+        */
+        CCertManUIContainerMain();
+
+        /**
+        * EPOC default constructor.
+        * @param aRect Frame rectangle for container.
+        */
+        void ConstructL( const TRect& aRect, TInt aCurrentPosition, TInt aTopItem );
+
+        /**
+        * Creates listbox, sets empty listbox text
+        */
+        void CreateListBoxL();
+
+        /**
+        * From CoeControl,SizeChanged.
+        */
+        void SizeChanged();
+
+        /**
+        * From CoeControl,CountComponentControls.
+        */
+        TInt CountComponentControls() const;
+
+        /**
+        * From CCoeControl,ComponentControl.
+        */
+        CCoeControl* ComponentControl( TInt aIndex ) const;
+
+        /**
+        * From CCoeControl,Draw.
+        */
+        void Draw( const TRect& aRect ) const;
+
+        /**
+        * Handles control events
+        * Cannot be changed to non-leaving function.
+        * L-function is required by the class definition, even if empty.
+        */
+        void HandleControlEventL( CCoeControl* aControl, TCoeEvent aEventType );
+
+        /**
+        * Handles the key events OK button, arrow keys, delete key.
+        * OK button functionality is different depending on the number of marked items
+        * in the list; zero marked -> show details view, one or more marked -> show
+        * OKOptions list, list empty -> OK inactive.
+        * Delete active only if list not empty.
+        */
+        TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+        /**
+        * Create the iconarray. Derived classes please don't forget that the
+        * 0th icon must be the markable listbox's mark icon.
+        * @return The created iconarray. Owner is the caller.
+        */
+        CAknIconArray* CreateIconArrayL() const;
+
+        /**
+        * Get resource id for the iconarray.
+        * @return The resource id for the iconarray.
+        */
+        TInt IconArrayResourceId() const;
+
+        /**
+        * This function is called when Help application is launched.
+        * (other items were commented in a header).
+        */
+        void GetHelpContext( TCoeHelpContext& aContext ) const;
+
+  protected: //data
+
+        /**
+        * If ETrue, OK-Options menu is shown instead of normal Options menu.
+        */
+        TBool   iShowOkOptions;
+
+    private: //data
+
+        /**
+        * Icon handler (this creates icons and calculates icon indexes).
+        */
+        const CCertManUIContainerMain* iIconHandler;
+    };
+
+#endif // CERTMANUICONTAINERMAIN_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuicontainerPersonal.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,200 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIContainerPersonal class
+*
+*/
+
+
+#ifndef  CERTMANUICONTAINERPERSONAL_H
+#define  CERTMANUICONTAINERPERSONAL_H
+
+// INCLUDES
+#include "CertmanuiviewPersonal.h"
+
+// FORWARD DECLARATIONS
+class CAknIconArray;
+
+// CLASS DECLARATION
+/**
+*  CCertManUIContainerPersonal container control class.
+*
+*  @lib certmanui.lib
+*/
+NONSHARABLE_CLASS( CCertManUIContainerPersonal ):
+    public CCoeControl, public MCoeControlObserver, public MEikListBoxObserver
+    {
+
+    /**
+    * Container personal needs to get access to CertManUIViewPersonal's DoActivateL
+    */
+    friend void CCertManUIViewPersonal::DoActivateL( const TVwsViewId&, TUid, const TDesC8& );
+
+    public: // functions
+
+        /**
+        * Overrided Default constructor
+        */
+        CCertManUIContainerPersonal( CCertManUIViewPersonal& aParent, CCertManUIKeeper& aKeeper );
+
+        /**
+        * Destructor.
+        */
+        ~CCertManUIContainerPersonal();
+
+        /**
+        * Change focus
+        */
+        void FocusChanged( TDrawNow aDrawNow );
+
+        /**
+        * Draws listbox, fetches graphic icons for markable list
+        */
+        void DrawListBoxL( TInt aCurrentPosition, TInt aTopItem );
+
+        /**
+        * Gets list of certificates from CertManAPI, displays them,
+        * sets No label text to them if their names are empty
+        */
+        void UpdateListBoxL( TInt& aCurrentPosition, TInt& aTopItem );
+
+        /**
+        * Handles listbox events
+        */
+        void HandleListBoxEventL( CEikListBox* aListBox, TListBoxEvent aEventType );
+
+        /**
+        * Handles resource change
+        */
+        void HandleResourceChange(TInt aType);
+
+    public: // data
+
+        /**
+        * To handle listbox
+        * Type column for making the list markable
+        * Cannot be private because CertManUIViewPersonal uses it
+        */
+        CEikColumnListBox*  iListBox;
+
+        /**
+        * To get hold of ViewPersonal
+        */
+        CCertManUIViewPersonal&   iParent;
+
+        /**
+        * To get hold of CertManUIKeeper
+        */
+        CCertManUIKeeper&   iKeeper;
+
+        /**
+        * To store the list item count
+        */
+        TInt    iListItemCount;
+
+        /**
+        * To store certificate entries
+        */
+        CArrayPtrFlat<CCrCertEntry>*    iEntriesPersonal;
+
+    private: // functions
+
+        /**
+        * Default constructor
+        */
+        CCertManUIContainerPersonal();
+
+        /**
+        * EPOC default constructor.
+        * @param aRect Frame rectangle for container.
+        */
+        void ConstructL( const TRect& aRect, TInt aCurrentPosition, TInt aTopItem );
+
+        /**
+        * Creates listbox, sets empty listbox text
+        */
+        void CreateListBoxL();
+
+        /**
+        * From CoeControl,SizeChanged.
+        */
+        void SizeChanged();
+
+        /**
+        * From CoeControl,CountComponentControls.
+        */
+        TInt CountComponentControls() const;
+
+        /**
+        * From CCoeControl,ComponentControl.
+        */
+        CCoeControl* ComponentControl( TInt aIndex ) const;
+
+        /**
+        * From CCoeControl,Draw.
+        */
+        void Draw( const TRect& aRect ) const;
+
+        /**
+        * Handles control events
+        * Cannot be changed to non-leaving function.
+        * L-function is required by the class definition, even if empty.
+        */
+        void HandleControlEventL( CCoeControl* aControl,TCoeEvent aEventType );
+
+        /**
+        * Handles the key events OK button, arrow keys, delete key.
+        * OK button functionality is different depending on the number of marked items
+        * in the list; zero marked -> show details view, one or more marked -> show
+        * OKOptions list, list empty -> OK inactive.
+        * Delete active only if list not empty.
+        */
+        TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+        /**
+        * Create the iconarray. Derived classes please don't forget that the
+        * 0th icon must be the markable listbox's mark icon.
+        * @return The created iconarray. Owner is the caller.
+        */
+        CAknIconArray* CreateIconArrayL() const;
+
+        /**
+        * Get resource id for the iconarray.
+        * @return The resource id for the iconarray.
+        */
+        TInt IconArrayResourceId() const;
+
+        /**
+        * This function is called when Help application is launched.
+        * (other items were commented in a header).
+        */
+    void GetHelpContext( TCoeHelpContext& aContext ) const;
+
+  protected: //data
+
+        /**
+        * If ETrue, OK-Options menu is shown instead of normal Options menu.
+        */
+        TBool   iShowOkOptions;
+
+    private: //data
+
+        /**
+        * Icon handler (this creates icons and calculates icon indexes).
+        */
+        const CCertManUIContainerPersonal* iIconHandler;
+    };
+
+#endif // CERTMANUICONTAINERPERSONAL_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuicontainerTrust.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,274 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIContainerTrust class
+*                Maintains correct list of trusted clients depending
+*                on the certificate that was in focus in Authority
+*                certificates view when Trust Settings view was entered.
+*                Shows and changes correct Yes/No text for the Trusted client.
+*
+*/
+
+
+#ifndef  CERTMANUICONTAINERTRUST_H
+#define  CERTMANUICONTAINERTRUST_H
+
+// INCLUDES
+#include <aknradiobuttonsettingpage.h>
+
+// CONSTANTS
+const TInt KTrustSettingsResourceIndexWAP = 0;
+const TInt KTrustSettingsResourceIndexMailAndImageConn = 1;
+const TInt KTrustSettingsResourceIndexAppCtrl = 2;
+const TInt KTrustSettingsResourceIndexJavaInstall = 3;
+const TInt KTrustSettingsResourceIndexOCSPCheck = 4;
+const TInt KTrustSettingsResourceIndexVPN = 5;
+const TInt KTrustSettingsResourceIndexValueYes = 0;
+const TInt KTrustSettingsResourceIndexValueNo = 1;
+
+// FORWARD DECLARATIONS
+class CCertificateAppInfoManager;
+
+// CLASS DECLARATION
+
+/**
+*  CCertManUIContainerTrust container control class.
+*
+*  @lib certmanui.lib
+*/
+NONSHARABLE_CLASS( CCertManUIContainerTrust ):
+    public CCoeControl, public MCoeControlObserver, public MEikListBoxObserver
+    {
+
+    /**
+    * Container trust needs to get access to CertManUIViewTrust's DoActivateL
+    */
+    friend void CCertManUIViewTrust::DoActivateL( const TVwsViewId&, TUid, const TDesC8& );
+
+    public: // functions
+
+        /**
+        * Overrided Default constructor
+        */
+        CCertManUIContainerTrust( CCertManUIViewTrust& aParent, CCertManUIKeeper& aKeeper );
+
+        /**
+        * Destructor.
+        */
+        ~CCertManUIContainerTrust();
+
+        /**
+        * Change focus
+        */
+        void FocusChanged( TDrawNow aDrawNow );
+
+        /**
+        * Draws listbox
+        */
+        void DrawListBoxL( TInt aCurrentPosition, TInt aTopItem, TInt aCertificateIndex );
+
+        /**
+        * Puts correct Trust Settings text to listbox and correct value (yes/no) to the setting,
+        * asks the value from CheckCertificateClientTrustL
+        * For X509 certificates, only one Application is currently supported (Application controller),
+        * more applications maybe added later however, so one additional application has been left
+        * in comments as an example.
+        * WAP connection and Application installer have their names from resources and are thus localized,
+        * other additional application get their names from the CertMan API with Name() function
+        */
+        void UpdateListBoxL( TInt aCertificateIndex );
+
+        /**
+        * Handles listbox events
+        * Cannot be changed to non-leaving function.
+        * L-function is required by the class definition, even if empty.
+        */
+        void HandleListBoxEventL( CEikListBox* aListBox, TListBoxEvent aEventType );
+
+        /**
+        * Changes the Trust Settings text from Yes to No and Vice versa
+        * Updates the Trust Settings Listbox item value
+        * Can be called only for those certificates that are located in ECrCertLocationCertMan !!!
+        * Cannot be called for certificates located in ECrCertLocationWIMCard,
+        *                       ECrCertLocationWIMURL,
+        *                       ECrCertLocationPhoneMemory
+        *                       ECrCertLocationPhoneMemoryURL
+        * Certificate formats ECrX968Certificate ECrCertificateURL
+        * are not visible in the Trust View
+        */
+        void UpdateTrustListboxItemL( CCTCertInfo& aEntry, TInt aCurrentTruster );
+
+        /**
+        * Puts correct client name and trust state to radiobutton setting page
+        * Finds out which client was focused in Trust Settings view and calls ShowTrustChangeSettingPageL
+        * This is accessed only by X509 certificates, located in CertMan
+        * and having one or more clients
+        * Must be public so that viewTrust can access
+        */
+        void PopupTrustChangeSettingPageL( TInt aCertificateIndex );
+
+        /**
+        * Checks if a certificate trusts a client
+        * * Certificate format == ECrX509Certificate ECrX968Certificate ECrCertificateURL
+        * are not supported if certificate location == ECrCertLocationWIMCard
+        * * Certificate format == ECrX968Certificate ECrCertificateURL are not supported
+        * if certificate location == ECrCertLocationCertMan
+        * * Certificate location == ECrCertLocationWIMURL ECrCertLocationPhoneMemory
+        * ECrCertLocationPhoneMemoryURL are not supported
+        */
+        TBool CheckCertificateClientTrustL( const TUid aClientTUid, CCTCertInfo& aEntry ) const;
+
+        /**
+        * Changes the Trust state of client in the CertManAPI
+        */
+        void ChangeTrustValueL( CCTCertInfo& aEntry, const TUid aClientUid );
+
+        /**
+        * Handles resource change
+        */
+        void HandleResourceChange( TInt aType );
+
+    public: // data
+
+        /**
+        * To get hold of ViewTrust
+        */
+        CCertManUIViewTrust&    iParent;
+
+        /**
+        * To get hold of CertManUIKeeper
+        */
+        CCertManUIKeeper&   iKeeper;
+
+        /**
+        * To handle listbox
+        * Must be public so that viewTrust can access
+        */
+        CEikTextListBox*    iListBox;
+
+        /**
+        * To get the certificate location
+        * Must be public so that viewTrust can access
+        */
+        TInt  iCertificateLocation;
+
+        /**
+        * Application manager class, used to get applications in system.
+        */
+        CCertificateAppInfoManager*   iAppInfoManager;
+
+        /**
+        * Applications registered to system.
+        */
+        RArray<TCertificateAppInfo> iApps;
+
+        /**
+        * Client Uids of the certstore
+        */
+        RArray<TUid> iClientUids;
+
+    private: // functions
+
+        /**
+        * Default constructor
+        */
+        CCertManUIContainerTrust();
+
+        /**
+        * EPOC default constructor.
+        * @param aRect Frame rectangle for container.
+        */
+    void ConstructL(const TRect& aRect);
+
+        /**
+        * Creates listbox
+        */
+        void CreateListBoxL();
+
+        /**
+        * From CoeControl,SizeChanged.
+        */
+        void SizeChanged();
+
+        /**
+        * From CoeControl,CountComponentControls.
+        */
+        TInt CountComponentControls() const;
+
+        /**
+        * From CCoeControl,ComponentControl.
+        */
+        CCoeControl* ComponentControl( TInt aIndex ) const;
+
+        /**
+        * From CCoeControl,Draw.
+        */
+        void Draw( const TRect& aRect ) const;
+
+        /**
+        * Handles control events
+        * Cannot be changed to non-leaving function.
+        * L-function is required by the class definition, even if empty.
+        */
+        void HandleControlEventL( CCoeControl* aControl,TCoeEvent aEventType);
+
+        /**
+        * Handles the key events OK button, arrow keys.
+        */
+        TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+        /**
+        * Sets empty list for listbox.
+        */
+        void SetEmptyListL( CEikListBox* aListBox );
+
+        /**
+        * Puts correct client names and yes/no state to settings page
+        * Sets title text to a setting page
+        */
+        void ShowTrustChangeSettingPageL( const TUid aClientUid,
+            TDesC& aClientName, CCTCertInfo& aEntry );
+
+        void InsertItemToTrustListL( const TInt index, const TUid id,
+                                   CCTCertInfo& entry, CDesCArray* itemArray,
+                                   TInt position );
+
+        /**
+        * Sets empty list for listbox.
+        */
+        TInt GetTrusterResId( TUid aTrusterUid );
+
+        /**
+        * This function is called when Help application is launched.
+        * (other items were commented in a header).
+        */
+        void GetHelpContext( TCoeHelpContext& aContext ) const;
+
+
+    private: //data
+
+        /**
+        * To get the names of the trusted clients from the resources
+        */
+        CDesCArrayFlat*   iTrustedClients;
+
+        /**
+        * To get the yes/no trust texts from the resources
+        */
+        CDesCArrayFlat*   iTrustValues;
+
+    };
+
+#endif // __CERTMANUICONTAINERTRUST_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuicontainerTrustedSite.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,199 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIContainerTrustedSite class
+*
+*/
+
+
+#ifndef  CERTMANUICONTAINERTRUSTEDSITE_H
+#define  CERTMANUICONTAINERTRUSTEDSITE_H
+
+// INCLUDES
+#include "CertmanuiviewTrustedSite.h"
+
+// CLASS DECLARATION
+
+class CAknIconArray;
+
+/**
+*  CCertManUIContainerTrustedSite container control class.
+*
+*  @lib certmanui.lib
+*/
+NONSHARABLE_CLASS( CCertManUIContainerTrustedSite ):
+    public CCoeControl, public MCoeControlObserver, public MEikListBoxObserver
+    {
+
+      /**
+      * Container trusted site needs to get access to CCertManUIViewTrustedSite's DoActivateL
+      */
+      friend void CCertManUIViewTrustedSite::DoActivateL( const TVwsViewId&,
+                                                          TUid, const TDesC8& );
+
+    public: // functions
+
+        /**
+        * Overrided Default constructor
+        */
+        CCertManUIContainerTrustedSite( CCertManUIViewTrustedSite& aParent,
+                                        CCertManUIKeeper& aKeeper );
+
+        /**
+        * Destructor.
+        */
+        ~CCertManUIContainerTrustedSite();
+
+        /**
+        * Change focus
+        */
+        void FocusChanged( TDrawNow aDrawNow );
+
+        /**
+        * Draws listbox, fetches graphic icons for markable list
+        */
+        void DrawListBoxL( TInt aCurrentPosition, TInt aTopItem );
+
+        /**
+        * Gets list of certificates from CertManAPI, displays them,
+        * sets No label/No subject text to them if their names are empty
+        */
+        void UpdateListBoxL( TInt& aCurrentPosition, TInt& aTopItem );
+
+        /**
+        * Handles listbox events
+        */
+        void HandleListBoxEventL( CEikListBox* aListBox, TListBoxEvent aEventType );
+
+        /**
+        * Handles resource change
+        */
+        void HandleResourceChange( TInt aType );
+
+    public: // data
+
+        /**
+        * To handle listbox
+        * Type column for making the list markable
+        * Cannot be private because CertManUIViewTrust uses it
+        */
+        CEikColumnListBox*    iListBox;
+
+        /**
+        * To get hold of ViewAuthority
+        */
+        CCertManUIViewTrustedSite&    iParent;
+
+        /**
+        * To get hold of CertManUIKeeper
+        */
+        CCertManUIKeeper&   iKeeper;
+
+        /**
+        * To store the list item count
+        */
+        TInt    iListItemCount;
+
+    private: // functions
+
+        /**
+        * Default constructor
+        */
+        CCertManUIContainerTrustedSite();
+
+        /**
+        * EPOC default constructor.
+        * @param aRect Frame rectangle for container.
+        */
+        void ConstructL( const TRect& aRect, TInt& aCurrentPosition, TInt& aTopItem );
+
+        /**
+        * Creates listbox, sets empty listbox text
+        */
+        void CreateListBoxL();
+
+        /**
+        * From CoeControl,SizeChanged.
+        */
+        void SizeChanged();
+
+        /**
+        * From CoeControl,CountComponentControls.
+        */
+        TInt CountComponentControls() const;
+
+        /**
+        * From CCoeControl,ComponentControl.
+        */
+        CCoeControl* ComponentControl( TInt aIndex ) const;
+
+        /**
+        * From CCoeControl,Draw.
+        */
+        void Draw( const TRect& aRect ) const;
+
+        /**
+        * Handles control events
+        * Cannot be changed to non-leaving function.
+        * L-function is required by the class definition, even if empty.
+        */
+        void HandleControlEventL( CCoeControl* aControl, TCoeEvent aEventType );
+
+        /**
+        * Handles the key events OK button, arrow keys, delete key.
+        * OK button functionality is different depending on the number of marked items
+        * in the list; zero marked -> show details view, one or more marked -> show
+        * OKOptions list, list empty -> OK inactive.
+        * Delete active only if list not empty.
+        */
+        TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+        /**
+        * Create the iconarray. Derived classes please don't forget that the
+        * 0th icon must be the markable listbox's mark icon.
+        * @return The created iconarray. Owner is the caller.
+        */
+        CAknIconArray* CreateIconArrayL() const;
+
+        /**
+        * Get resource id for the iconarray.
+        * @return The resource id for the iconarray.
+        */
+        TInt IconArrayResourceId() const;
+
+        /**
+        * This function is called when Help application is launched.
+        * (other items were commented in a header).
+        */
+        void GetHelpContext(TCoeHelpContext& aContext) const;
+
+    protected: //data
+
+        /**
+        * If ETrue, OK-Options menu is shown instead of normal Options menu.
+        */
+        TBool   iShowOkOptions;
+
+    private: //data
+
+        /**
+        * Icon handler (this creates icons and calculates icon indexes).
+        */
+        const CCertManUIContainerTrustedSite*   iIconHandler;
+ };
+
+#endif // CERTMANUICONTAINERTRUSTEDSITE_H
+
+// End of File
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/Certmanuidialogs.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,87 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIWaitDialog class
+*
+*/
+
+
+#ifndef     CERTMANUIDIALOGS_H
+#define     CERTMANUIDIALOGS_H
+
+// INCLUDES
+#include <e32base.h>
+
+// FORWARD DECLARATIONS
+
+class CAknGlobalNote;
+class CAknGlobalConfirmationQuery;
+class CAknWaitDialog;
+
+// CLASS DECLARATION
+
+/**
+*  CCertManUIKeeper view control class.
+*
+*
+*/
+class CCertManUIWaitDialog: public CBase
+    {
+    public: // functions
+
+        /**
+        * Default Constructor
+        */
+        CCertManUIWaitDialog();
+
+        /**
+        * Destructor
+        */
+        ~CCertManUIWaitDialog();
+
+        /**
+        * Display dialog
+        * @param selector for progress or delete dialog
+        */
+        void StartWaitDialogL(TInt aDialogSelector);
+
+        /**
+        * Close dialog.
+        */
+
+        void CloseWaitDialogL();
+
+
+    private:    // Functions
+
+
+        static void CleanupWaitDialog(TAny* aAny);
+
+
+    private:    // Data
+
+        /**
+        * For wait note
+        */
+        CAknWaitDialog*     iDialog;
+
+        /**
+        *  Flag whether dialof is being displayed
+        */
+        TBool               iDisplayed;
+
+    };
+
+#endif //   CERTMANUIDIALOGS_H
+
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/Certmanuidll.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   CCertManUidll is an application class required help
+*
+*/
+
+
+#ifndef CERTMANUIDLL_H
+#define CERTMANUIDLL_H
+
+// INCLUDES
+
+// CONSTANTS
+
+// UID of app
+const TUid KUidCM = { 0x10008D3D };
+
+// CLASS DECLARATION
+
+#endif  // CERTMANUIDLL_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/Certmanuitrustids.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,34 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Contains the TUids of supported clients for CertManUI's
+*                Trust Setting View
+*
+*/
+
+
+#ifndef    CERTMANUITRUSTIDS_H
+#define    CERTMANUITRUSTIDS_H
+
+// CONSTANTS
+const TUid KCertManUINullId = {0};
+const TUid KCertManUIViewTrustWapConnectionId = {268479059};
+const TUid KCertManUIViewTrustApplicationControllerId = {268452523};
+const TUid KCertManUIViewTrustMailAndImageConnId = {268441661};
+const TUid KCertManUIViewTrustJavaInstallingId = {270506792};
+const TUid KCertManUIViewOCSPCheckInstallingId = {268478646};
+const TUid KCertManUIViewTrustVPNId = {270498195};
+
+#endif // __CERTMANUITRUSTIDS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuiviewAuthority.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,159 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIViewAuthority class
+*
+*/
+
+
+#ifndef  CERTMANUIVIEWAUTHORITY_H
+#define  CERTMANUIVIEWAUTHORITY_H
+
+// INCLUDES
+#include <aknview.h>
+#include <e32base.h>
+#include "Certmanuiviewid.h"
+
+// FORWARD DECLERATIONS
+class CCrCertificate;
+class CCertificate;
+class CX509Certificate;
+class CCertManUIContainerAuthority;
+
+// CLASS DECLARATION
+
+/**
+*  CCertManUIViewAuthority view class.
+*
+*  @lib certmanui.dll
+*/
+NONSHARABLE_CLASS( CCertManUIViewAuthority ): public CAknView
+    {
+    public: // functions
+
+        /**
+        * Destructor
+        */
+        ~CCertManUIViewAuthority();
+
+        /**
+        * NewL
+        */
+        static class CCertManUIViewAuthority* NewL(const TRect& aRect, CCertManUIKeeper& aKeeper);
+
+        /**
+        * NewLC
+        */
+        static class CCertManUIViewAuthority* NewLC(const TRect& aRect, CCertManUIKeeper& aKeeper);
+
+        /**
+        * Returns Authority view id
+        */
+        TUid Id() const;
+
+        /**
+        * Handles ClientRectChange
+        */
+        void HandleClientRectChange();
+
+        /**
+        * Returns iContainerAuthority to be used in CertManUIContainerAuthority
+        */
+        CCoeControl* Container();
+
+        /**
+        * Handles Softkey and Options list commands
+        */
+        void HandleCommandL(TInt aCommand);
+
+        /**
+        * Updates the view when opening it
+        */
+        void DoActivateL(const TVwsViewId& aPrevViewId,TUid aCustomMessageId,
+            const TDesC8& aCustomMessage);
+
+        /**
+        * Updates the menu bar
+        */
+        void UpdateMenuBar();
+
+        /**
+        * Updates cba
+        */
+        void UpdateCba(TInt aCbaResourceId);
+        
+  public: // data
+
+        /**
+        * To get hold of CertManUIKeeper
+        */
+        CCertManUIKeeper&   iKeeper;
+
+        /**
+        * To get access to certificate list in authority view
+        */
+        CCertManUIContainerAuthority* iContainerAuthority;
+
+        /**
+        * To store the position of the focus in the Authority view
+        */
+        TInt    iCurrentPosition;
+
+        /**
+        * Stores top item in the listbox
+        */
+        TInt    iTopItem;
+
+    private: // functions
+
+        /**
+        * Constructor.
+        */
+        CCertManUIViewAuthority(CCertManUIKeeper& aKeeper);
+
+        /**
+        * EPOC default constructor.
+        */
+        void ConstructL();
+
+
+        /**
+        * Saves focus position when closing view
+        */
+        void DoDeactivate();
+
+        /**
+        * Updates Options list with correct items depending on
+        * whether the listbox is empty or if it has any marked items
+        */
+        void DynInitMenuPaneL(TInt aResourceId,CEikMenuPane* aMenuPane);
+
+        /**
+        * Appends a field that has string from resources and string from CertManAPI
+        * to the details view message body
+        */
+        void DetailsFieldDynamicL(HBufC& aMessage, TPtrC aValue,
+                TInt aResourceOne, TInt aResourceTwo);
+
+
+    private: // Data
+
+        /**
+        * To get the certificate location
+        */
+        TInt    iCertificateLocation;
+    };
+
+#endif // CERTMANUIVIEWAUTHORITY_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuiviewDevice.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,152 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIViewDevice class
+*
+*/
+
+
+#ifndef  CERTMANUIVIEWDEVICE_H
+#define  CERTMANUIVIEWDEVICE_H
+
+// INCLUDES
+#include <aknview.h>
+#include <e32base.h>
+#include "Certmanuiviewid.h"
+
+// FORWARD DECLERATIONS
+class CCrCertificate;
+class CCertificate;
+class CX509Certificate;
+class CCertManUIContainerDevice;
+
+// CLASS DECLARATION
+
+/**
+*  CCertManUIViewDevice view class.
+*
+*  @lib certmanui.dll
+*/
+NONSHARABLE_CLASS( CCertManUIViewDevice ): public CAknView
+    {
+    public: // functions
+
+        /**
+        * Destructor
+        */
+        ~CCertManUIViewDevice();
+
+        /**
+        * NewL
+        */
+        static class CCertManUIViewDevice* NewL( const TRect& aRect, CCertManUIKeeper& aKeeper );
+
+        /**
+        * NewLC
+        */
+        static class CCertManUIViewDevice* NewLC( const TRect& aRect, CCertManUIKeeper& aKeeper );
+
+        /**
+        * Returns Authority view id
+        */
+        TUid Id() const;
+
+        /**
+        * Handles ClientRectChange
+        */
+        void HandleClientRectChange();
+
+        /**
+        * Returns iContainerTrustedSite to be used in CertManUIContainerTrustedSite
+        */
+        CCoeControl* Container();
+
+        /**
+        * Handles Softkey and Options list commands
+        */
+        void HandleCommandL( TInt aCommand );
+
+        /**
+        * Updates the view when opening it
+        */
+        void DoActivateL( const TVwsViewId& aPrevViewId,TUid aCustomMessageId,
+            const TDesC8& aCustomMessage );
+
+        /**
+        * Updates the menu bar
+        */
+        void UpdateMenuBar();
+
+        /**
+        * Updates cba
+        */
+        void UpdateCba(TInt aCbaResourceId);
+
+  public: // data
+
+        /**
+        * To get hold of CertManUIKeeper
+        */
+        CCertManUIKeeper&   iKeeper;
+
+        /**
+        * To get access to certificate list in authority view
+        */
+        CCertManUIContainerDevice*    iContainerDevice;
+
+        /**
+        * To store the position of the focus in the Authority view
+        */
+        TInt    iCurrentPosition;
+
+        /**
+        * Stores top item in the listbox
+        */
+        TInt    iTopItem;
+
+    private: // functions
+
+        /**
+        * Constructor.
+        */
+        CCertManUIViewDevice( CCertManUIKeeper& aKeeper );
+
+        /**
+        * EPOC default constructor.
+        */
+        void ConstructL();
+
+
+        /**
+        * Saves focus position when closing view
+        */
+        void DoDeactivate();
+
+        /**
+        * Updates Options list with correct items depending on
+        * whether the listbox is empty or if it has any marked items
+        */
+        void DynInitMenuPaneL( TInt aResourceId,CEikMenuPane* aMenuPane );
+
+
+    private: // Data
+
+        /**
+        * To get the certificate location
+        */
+        TInt    iCertificateLocation;
+    };
+
+#endif // CERTMANUIVIEWDEVICE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuiviewMain.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,149 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIViewMain class
+*
+*/
+
+
+#ifndef  CERTMANUIVIEWMAIN_H
+#define  CERTMANUIVIEWMAIN_H
+
+// INCLUDES
+#include <aknview.h>
+#include <e32base.h>
+#include "Certmanuiviewid.h"
+
+// FORWARD DECLERATIONS
+class CCrCertificate;
+class CCertificate;
+class CX509Certificate;
+class CCertManUIContainerMain;
+
+// CLASS DECLARATION
+
+/**
+*  CCertManUIViewMain view class.
+*
+*  @lib certmanui.dll
+*/
+NONSHARABLE_CLASS( CCertManUIViewMain ): public CAknView
+    {
+    public: // functions
+
+        /**
+        * Destructor
+        */
+        ~CCertManUIViewMain();
+
+        /**
+        * NewL
+        */
+        static class CCertManUIViewMain* NewL( const TRect& aRect, CCertManUIKeeper& aKeeper );
+
+        /**
+        * NewLC
+        */
+        static class CCertManUIViewMain* NewLC( const TRect& aRect, CCertManUIKeeper& aKeeper );
+
+        /**
+        * Returns Authority view id
+        */
+        TUid Id() const;
+
+        /**
+        * Handles ClientRectChange
+        */
+        void HandleClientRectChange();
+
+        /**
+        * Returns iContainerAuthority to be used in CertManUIContainerAuthority
+        */
+        CCoeControl* Container();
+
+        /**
+        * Handles Softkey and Options list commands
+        */
+        void HandleCommandL( TInt aCommand );
+
+        /**
+        * Updates the view when opening it
+        */
+        void DoActivateL( const TVwsViewId& aPrevViewId,TUid aCustomMessageId,
+            const TDesC8& aCustomMessage );
+
+  public: // data
+
+        /**
+        * To get hold of CertManUIKeeper
+        */
+        CCertManUIKeeper&   iKeeper;
+
+        /**
+        * To get access to certificate list in authority view
+        */
+        CCertManUIContainerMain* iContainerMain;
+
+        /**
+        * To store the position of the focus in the Authority view
+        */
+        TInt    iCurrentPosition;
+
+        /**
+        * Stores top item in the listbox
+        */
+        TInt  iTopItem;
+
+    private: // functions
+
+        /**
+        * Constructor.
+        */
+        CCertManUIViewMain( CCertManUIKeeper& aKeeper );
+
+        /**
+        * EPOC default constructor.
+        */
+        void ConstructL();
+
+
+        /**
+        * Saves focus position when closing view
+        */
+        void DoDeactivate();
+
+        /**
+        * Appends a field that has string from resources and string from CertManAPI
+        * to the details view message body
+        */
+        void DetailsFieldDynamicL( HBufC& aMessage, TPtrC aValue,
+                TInt aResourceOne, TInt aResourceTwo );
+                
+       /**
+        * Updates Options list with correct items depending on
+        * whether the listbox is empty or if it has any marked items
+        */
+        void DynInitMenuPaneL(TInt aResourceId,CEikMenuPane* aMenuPane);        
+
+
+    private: // Data
+
+        /**
+        * To get the certificate location
+        */
+        CCertManUIContainerMain*  iContainerPersonal;
+    };
+
+#endif // CERTMANUIVIEWMAIN_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuiviewPersonal.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,141 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIViewPersonal class.
+*
+*/
+
+
+#ifndef  CERTMANUIVIEWPERSONAL_H
+#define  CERTMANUIVIEWPERSONAL_H
+
+// INCLUDES
+#include <aknview.h>
+#include "Certmanuiviewid.h"
+
+// CLASS DECLARATION
+class CCertManUIContainerPersonal;
+
+/**
+*  CCertManUIViewPersonal view class.
+*
+*  @lib certmanui.dll
+*/
+NONSHARABLE_CLASS( CCertManUIViewPersonal ): public CAknView
+    {
+    public: // functions
+
+        /**
+        * Destructor
+        */
+        ~CCertManUIViewPersonal();
+
+        /**
+        * NewL
+        */
+        static class CCertManUIViewPersonal* NewL( const TRect& aRect, CCertManUIKeeper& aKeeper );
+
+        /**
+        * NewLC
+        */
+        static class CCertManUIViewPersonal* NewLC( const TRect& aRect, CCertManUIKeeper& aKeeper );
+
+        /**
+        * Returns Personal view id
+        */
+        TUid Id() const;
+
+        /**
+        * Handles ClientRectChange
+        */
+        void HandleClientRectChange();
+
+        /**
+        * Returns iContainerPersonal to be used in CertManUIContainerPersonal
+        */
+        CCoeControl* Container();
+
+        /**
+        * Handles Softkey and Options list commands
+        */
+        void HandleCommandL( TInt aCommand );
+
+        /**
+        * Updates the view when opening it
+        */
+        void DoActivateL( const TVwsViewId& aPrevViewId,TUid aCustomMessageId,
+              const TDesC8& aCustomMessage );
+
+        /**
+        * Updates the menu bar
+        */
+        void UpdateMenuBar();
+
+        /**
+        * Updates cba
+        */
+        void UpdateCba(TInt aCbaResourceId);
+
+  public: // data
+
+        /**
+        * To get hold of CertManUIKeeper
+        */
+        CCertManUIKeeper&   iKeeper;
+
+       /**
+        * Stores top item in the listbox
+        */
+        TInt    iTopItem;
+
+       /**
+        * To store the position of the focus in the Personal view
+        */
+        TInt    iCurrentPosition;
+
+    private: // functions
+
+        /**
+        * Constructor.
+        */
+        CCertManUIViewPersonal( CCertManUIKeeper& aKeeper );
+
+        /**
+        * EPOC default constructor.
+        */
+        void ConstructL();
+
+        /**
+        * Saves focus position when closing view
+        */
+        void DoDeactivate();
+
+        /**
+        * Updates Options list with correct items depending on
+        * whether the listbox is empty or if it has any marked items
+        */
+        void DynInitMenuPaneL( TInt aResourceId,CEikMenuPane* aMenuPane );
+
+
+    private: // Data
+
+       /**
+        * To get access to certificate list in Personal view
+        */
+        CCertManUIContainerPersonal*  iContainerPersonal;
+
+    };
+
+#endif // CERTMANUIVIEWPERSONAL_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuiviewTrust.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,174 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIViewTrust class.
+*                Updates Options list depending on the status of the
+*                trusted clients (unavailable, located in WIM).
+*                Handles Softkey and Options list commands.
+*                Calls ChangeTrust method in CertManUIContainerTrust.
+*
+*/
+
+
+#ifndef  CERTMANUIVIEWTRUST_H
+#define  CERTMANUIVIEWTRUST_H
+
+// INCLUDES
+#include <aknview.h>
+
+// FORWARD DECLERATIONS
+class CCertManUIContainerTrust;
+
+// CLASS DECLARATION
+
+/**
+*  CCertManUIViewTrust view class.
+*
+*  @lib certmanui.dll
+*/
+NONSHARABLE_CLASS( CCertManUIViewTrust ): public CAknView
+    {
+    public: // functions
+
+        /**
+        * Destructor
+        */
+        ~CCertManUIViewTrust();
+
+        /**
+        * NewL
+        */
+        static class CCertManUIViewTrust* NewL( const TRect& aRect, CCertManUIKeeper& aKeeper );
+
+        /**
+        * NewLC
+        */
+        static class CCertManUIViewTrust* NewLC( const TRect& aRect, CCertManUIKeeper& aKeeper );
+
+        /**
+        * Returns Trust view id
+        */
+        TUid Id() const;
+
+        /**
+        * Handles ClientRectChange
+        */
+        void HandleClientRectChange();
+
+        /**
+        * Returns iContainerTrust to be used in CertManUIContainerTrust
+        */
+        CCoeControl* Container();
+
+        /**
+        * Handles Softkey and Options list commands
+        */
+        void HandleCommandL( TInt aCommand );
+
+        /**
+        * Calls Change trust method UpdateTrustSettingsViewL in certmanuicontainertrust
+        * for not supported certificate formats ECrX968Certificate and ECrCertificateURL
+        * and for not supported certificate locations  ECrCertLocationWIMCard, ECrCertLocationWIMURL,
+        * ECrCertLocationPhoneMemory, ECrCertLocationPhoneMemoryURL UpdateTrustSettingsViewL is not called
+        * also UpdateTrustSettingsViewL is not called if there are no clients in Trust view
+        */
+        void ChangeTrustL();
+
+        /**
+        * Shows Trust Change Setting page
+        */        
+        void PopupTrustChangeSettingPageL();
+
+        /**
+        * Updates the view when opening it
+        */
+        void DoActivateL( const TVwsViewId& aPrevViewId,TUid aCustomMessageId,
+            const TDesC8& aCustomMessage );
+
+        /**
+        * Updates the menu bar
+        */
+        void UpdateMenuBar();
+
+        /**
+        * Updates navi pane
+        */
+        void UpdateNaviPaneL();
+        
+        /**
+        * Removes navi pane
+        */
+        void RemoveNaviPane();        
+        
+  public: // data
+
+        /**
+        * To get hold of CertManUIKeeper
+        */
+        CCertManUIKeeper&   iKeeper;
+
+        /**
+        * To get access to Trust container
+        * Changed from private to public so that Change Trust's CAknRadioButtonSettingPage can access it
+        */
+        CCertManUIContainerTrust*   iContainerTrust;
+
+    private: // functions
+
+        /**
+        * Constructor.
+        */
+        CCertManUIViewTrust( CCertManUIKeeper& aKeeper );
+
+        /**
+        * EPOC default constructor.
+        */
+        void ConstructL();
+
+
+        /**
+        * Closes the view
+        */
+        void DoDeactivate();
+
+        /**
+        * Updates Options list with correct items depending on
+        * whether the listbox is empty or if the trust can be changed
+        * Change trust is not shown if certificate location is not supported
+        * unsupported certificate locations are ECrCertLocationWIMCard,
+        *                   ECrCertLocationWIMURL,
+        *                   ECrCertLocationPhoneMemory,
+        *                   ECrCertLocationPhoneMemoryURL
+        * Change trust is not shown if certificate format is not supported
+        * unsupported certificate formats are ECrX968Certificate
+        *                   ECrCertificateURL
+        */
+        void DynInitMenuPaneL( TInt aResourceId,CEikMenuPane* aMenuPane );
+
+    private: // Data
+
+        /**
+        * For Navipane
+        */
+        CAknNavigationDecorator*		iTrustSettingsNaviPane;
+
+        /**
+        * For Navi container
+        */
+        CAknNavigationControlContainer* iNaviPane;
+
+    };
+
+#endif // CERTMANUIVIEWTRUST_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/CertmanuiviewTrustedSite.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,152 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CCertManUIViewTrustedSite class
+*
+*/
+
+
+#ifndef  CERTMANUIVIEWTRUSTEDSITE_H
+#define  CERTMANUIVIEWTRUSTEDSITE_H
+
+// INCLUDES
+#include <aknview.h>
+#include <e32base.h>
+#include "Certmanuiviewid.h"
+
+// FORWARD DECLERATIONS
+class CCrCertificate;
+class CCertificate;
+class CX509Certificate;
+class CCertManUIContainerTrustedSite;
+
+// CLASS DECLARATION
+
+/**
+*  CCertManUIViewTrustedSite view class.
+*
+*  @lib certmanui.dll
+*/
+NONSHARABLE_CLASS( CCertManUIViewTrustedSite ): public CAknView
+    {
+    public: // functions
+
+        /**
+        * Destructor
+        */
+        ~CCertManUIViewTrustedSite();
+
+        /**
+        * NewL
+        */
+        static class CCertManUIViewTrustedSite* NewL( const TRect& aRect, CCertManUIKeeper& aKeeper );
+
+        /**
+        * NewLC
+        */
+        static class CCertManUIViewTrustedSite* NewLC( const TRect& aRect, CCertManUIKeeper& aKeeper );
+
+        /**
+        * Returns Authority view id
+        */
+        TUid Id() const;
+
+        /**
+        * Handles ClientRectChange
+        */
+        void HandleClientRectChange();
+
+        /**
+        * Returns iContainerTrustedSite to be used in CertManUIContainerTrustedSite
+        */
+        CCoeControl* Container();
+
+        /**
+        * Handles Softkey and Options list commands
+        */
+        void HandleCommandL( TInt aCommand );
+
+        /**
+        * Updates the view when opening it
+        */
+        void DoActivateL( const TVwsViewId& aPrevViewId,TUid aCustomMessageId,
+            const TDesC8& aCustomMessage );
+
+        /**
+        * Updates the menu bar
+        */
+        void UpdateMenuBar();
+
+        /**
+        * Updates cba
+        */
+        void UpdateCba(TInt aCbaResourceId);
+
+  public: // data
+
+        /**
+        * To get hold of CertManUIKeeper
+        */
+        CCertManUIKeeper&   iKeeper;
+
+        /**
+        * To get access to certificate list in authority view
+        */
+        CCertManUIContainerTrustedSite* iContainerTrustedSite;
+
+        /**
+        * To store the position of the focus in the Authority view
+        */
+        TInt    iCurrentPosition;
+
+        /**
+        * Stores top item in the listbox
+        */
+        TInt    iTopItem;
+
+    private: // functions
+
+        /**
+        * Constructor.
+        */
+        CCertManUIViewTrustedSite(CCertManUIKeeper& aKeeper);
+
+        /**
+        * EPOC default constructor.
+        */
+        void ConstructL();
+
+
+        /**
+        * Saves focus position when closing view
+        */
+        void DoDeactivate();
+
+        /**
+        * Updates Options list with correct items depending on
+        * whether the listbox is empty or if it has any marked items
+        */
+        void DynInitMenuPaneL( TInt aResourceId, CEikMenuPane* aMenuPane );
+
+
+    private: // Data
+
+        /**
+        * To get the certificate location
+        */
+        TInt    iCertificateLocation;
+    };
+
+#endif // CERTMANUIVIEWTRUSTEDSITE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/INC/Certmanuiviewid.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Contains the TUids for CertManUI Views.
+*
+*/
+
+
+#ifndef     __CERTMANUIVIEWID_H
+#define     __CERTMANUIVIEWID_H
+
+// INCLUDES
+
+// CONST TUIDS
+
+// Changed the Id numbers accordingly to the GS
+const TUid KCertManUIViewAuthorityId = {0x2000B18E};
+const TUid KCertManUIViewPersonalId = {0x2000B18F};
+const TUid KCertManUIViewTrustId = {0x2000B190};
+const TUid KCertManUIViewMainId = {0x2000B191};
+const TUid KCertManUIViewTrustedSiteId = {0x2000B192};
+const TUid KCertManUIViewDeviceId = {0x2000B193};
+
+#endif // __CERTMANUIVIEWID_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuiCertificateHelper.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1619 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUICertificateHelper
+*
+*/
+
+
+#include <X509CertNameParser.h>
+#include <certmanui.rsg>
+#include <hash.h>                   // MD5 fingerprint
+#include <aknmessagequerydialog.h>
+#include <pkixcertchain.h>          // for validation
+#include <aknnotewrappers.h>        // for warning & information notes
+#include <sysutil.h>
+#include <ErrorUI.h>
+#include <unifiedkeystore.h>
+#include <TrustedSitesStore.h>
+#include <x509keys.h>               // TX509KeyFactory
+#include <e32math.h>                // Pow
+#include "Certmanui.hrh"
+#include "CertmanuiCertificateHelper.h"
+#include "CertmanuiCommon.h"
+#include "CertmanuiSyncWrapper.h"
+#include "CertManUILogger.h"
+
+const TInt KFileCertStoreUid( 0x101F501A );
+const TInt KTrustedServerCertStoreUid( 0x101FB66F );
+const TInt KDeviceCertStoreUid( 0x101FB668 );
+const TInt KDeviceKeyStoreUid( 0x101FB66A );
+
+_LIT( KBlockSeparator, " " );
+
+template <class T>
+class CleanupResetAndDestroy
+    {
+public:
+    inline static void PushL( T& aRef );
+private:
+    static void ResetAndDestroy( TAny *aPtr );
+    };
+
+template <class T>
+inline void CleanupResetAndDestroyPushL( T& aRef );
+
+template <class T>
+inline void CleanupResetAndDestroy<T>::PushL( T& aRef )
+    {
+    CleanupStack::PushL( TCleanupItem( &ResetAndDestroy, &aRef ) );
+    }
+
+template <class T>
+void CleanupResetAndDestroy<T>::ResetAndDestroy( TAny *aPtr )
+    {
+    if( aPtr )
+        {
+        static_cast<T*>( aPtr )->ResetAndDestroy();
+        }
+    }
+
+template <class T>
+inline void CleanupResetAndDestroyPushL( T& aRef )
+    {
+    CleanupResetAndDestroy<T>::PushL( aRef );
+    }
+
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::CCertManUICertificateHelper()
+// Default C++ Constructor
+// ---------------------------------------------------------
+//
+CCertManUICertificateHelper::CCertManUICertificateHelper( CCertManUIKeeper& aKeeper )
+: iKeeper(aKeeper)
+    {
+  }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::~CCertManUICertificateHelper()
+// Destructor
+// ---------------------------------------------------------
+//
+CCertManUICertificateHelper::~CCertManUICertificateHelper()
+    {
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::CutCertificateField(TPtrC aField)
+// If CertLabel, Issuer and Owner length is over 80 characters,
+// cut it down to 80
+// Returns the cut certificate field.
+// ---------------------------------------------------------
+//
+TPtrC CCertManUICertificateHelper::CutCertificateField( TPtrC aField )
+    {
+    CERTMANUILOGGER_ENTERFN(
+         "CCertManUICertificateHelper::CutCertificateField" );
+
+    TInt fieldLength = aField.Length();
+    if ( fieldLength >= KMaxLengthTextCertLabelVisible )
+        {
+        TPtrC cutCertLabel = aField.Mid( 0, KMaxLengthTextCertLabelVisible );
+
+        CERTMANUILOGGER_LEAVEFN(
+           "CCertManUICertificateHelper::CutCertificateField" );
+
+        return cutCertLabel;
+        }
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUICertificateHelper::CutCertificateField" );
+
+    return aField;
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::IsCertificateDeletable
+// Check whether certificate is deletable
+// ---------------------------------------------------------
+//
+TBool CCertManUICertificateHelper::IsCertificateDeletable( TInt aIndex,
+    TInt aType ) const
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::IsCertificateDeletable" );
+    TBool ret = ETrue;
+
+    // If wim has not been enabled and certificate resides in smart card
+    // we cannot delete it since we don't have smart card certificate
+    // delete functionality in non WIM builds. So in non WIM builds all
+    // smart card certificates are marked read-only.
+    if( aIndex > -1 )
+        {
+        CCTCertInfo* entry;
+        if ( aType == KCertTypeAuthority )
+            {
+            entry = iKeeper.iCALabelEntries[ aIndex ]->iCAEntry;
+            }
+        else if( aType == KCertTypeTrustedSite )
+            {
+            entry = iKeeper.iPeerLabelEntries[ aIndex ]->iPeerEntry;
+            }
+        else if( aType == KCertTypeDevice )
+            {
+            entry = iKeeper.iDeviceLabelEntries[ aIndex ]->iDeviceEntry;
+            }
+        else
+            {
+            entry = iKeeper.iUserLabelEntries[ aIndex ]->iUserEntry;
+            }
+        if ( !entry->IsDeletable() )
+            {
+            ret = EFalse;
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUICertificateHelper::IsCertificateDeletable" );
+    return ret;
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::IsOneMarkedCertificateDeletable
+// Check whether one marked certificate is deletable, or
+// if none certificate is marked, check if the highlighted
+// certificate is deletable
+// ---------------------------------------------------------
+//
+TBool CCertManUICertificateHelper::IsOneMarkedCertificateDeletable
+    ( CEikColumnListBox* aListBox, TInt aType ) const
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::IsOneMarkedCertificateDeletable" );
+
+    const CArrayFix<TInt>* array  = aListBox->SelectionIndexes();
+    TInt markedCount = array->Count();
+    TBool oneIsDeletable = EFalse;
+
+    if ( 0 == markedCount )
+        {
+        TInt currentItem = aListBox->CurrentItemIndex();
+        return IsCertificateDeletable( currentItem, aType );
+        }
+
+    for ( TInt i = 0; !oneIsDeletable && i < markedCount; i++ )
+        {
+        oneIsDeletable = IsCertificateDeletable( (*array)[i], aType );
+        }
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUICertificateHelper::IsOneMarkedCertificateDeletable" );
+
+    return oneIsDeletable;
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::MessageQueryViewDetailsL(TInt aIndex)
+// Creates the whole of certificate details view
+// Appends strings from both resources and CertManAPI to one
+// message body text and displays it.
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::MessageQueryViewDetailsL( TInt aIndex,
+    TInt aType,
+    CEikonEnv* aEikonEnv )
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::MessageQueryViewDetailsL" );
+     LOG_WRITE_FORMAT( "certificate index %i", aIndex );
+
+    iKeeper.StartWaitDialogL( ECertmanUiWaitDialog );
+
+    HBufC* message = HBufC::NewLC( KMaxLengthTextDetailsBody );
+    TRAPD( err, CreateMessageBodyTextL( aIndex, aType, aEikonEnv, *message ) );
+
+    iKeeper.CloseWaitDialogL();
+    User::LeaveIfError( err );
+
+    if( message->Length() )
+        {
+        HBufC* header = StringLoader::LoadLC( R_TEXT_RESOURCE_DETAILS_VIEW_HEADER );
+        CAknMessageQueryDialog* dlg = CAknMessageQueryDialog::NewL( *message );
+        dlg->PrepareLC( R_MESSAGE_QUERY_DETAILS_VIEW );
+        dlg->QueryHeading()->SetTextL( *header );
+        dlg->RunLD();
+        CleanupStack::PopAndDestroy( header );
+        }
+
+    CleanupStack::PopAndDestroy( message );
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUICertificateHelper::MessageQueryViewDetailsL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::ValidateCertificateL(
+// Checks if the certificate is corrupted
+// Checks the validity period of the certificate
+// Display only one warning note, in the following order:
+// 1) Expired/Not yet valid
+// 2) Corrupted
+// 3) Not trusted
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::ValidateCertificateL(
+    TInt aIndex, CCertificate* aDetails, const CCTCertInfo& aCertInfo, TInt aType )
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::ValidateCertificateL" );
+
+    TInt poppableItems = 0;
+    // Check allways first the validity period
+    // Show Expired/Not yet valid notes
+    const CValidityPeriod& validityPeriod = aDetails->ValidityPeriod();
+    const TTime& startValue = validityPeriod.Start();
+    const TTime& finishValue = validityPeriod.Finish();
+    TTime current;
+    current.UniversalTime();
+
+    if ( startValue > current )
+        {
+        // certificate is not valid yet
+        HBufC* string = StringLoader::LoadLC(
+            R_WARNING_NOTE_TEXT_CERTIFICATE_NOT_VALID_YET );
+        DisplayWarningNoteLD(string);
+        }
+    else if ( finishValue < current )
+        {
+        // certificate is expired
+        HBufC* string = StringLoader::LoadLC(
+            R_WARNING_NOTE_TEXT_CERTIFICATE_EXPIRED );
+        DisplayWarningNoteLD( string );
+        }
+    else
+        {
+        // put here check for certificate status, show warning notes if needed
+        TBool noValidationError = ETrue;
+        CArrayFixFlat<TValidationError>* status = NULL;
+        TCertificateFormat certificateFormat;
+
+        if ( aType == KCertTypeAuthority )
+            {
+            certificateFormat = iKeeper.iCALabelEntries[aIndex]->
+                                        iCAEntry->CertificateFormat();
+            }
+        else if ( aType == KCertTypeTrustedSite )
+            {
+            certificateFormat = iKeeper.iPeerLabelEntries[aIndex]->
+                                        iPeerEntry->CertificateFormat();
+            }
+        else if ( aType == KCertTypeDevice )
+            {
+            certificateFormat = iKeeper.iDeviceLabelEntries[aIndex]->
+                                        iDeviceEntry->CertificateFormat();
+            }
+        else
+            {
+            certificateFormat = iKeeper.iUserLabelEntries[aIndex]->
+                                        iUserEntry->CertificateFormat();
+            }
+
+        switch ( certificateFormat )
+            {
+            case EX509Certificate:
+                {
+                status = ValidateX509CertificateL(
+                    (CX509Certificate*)aDetails );
+                break;
+                }
+            default:
+                {
+                status = new ( ELeave) CArrayFixFlat<TValidationError>( 1 );
+                break;
+                }
+            }
+        CleanupStack::PushL( status );
+        poppableItems++;
+
+        TInt errorCount = status->Count();
+        TBool ready = EFalse;
+        for ( TInt i = 0; i < errorCount && !ready; i++ )
+            {
+            TValidationError errorType = status->At(i);
+
+            switch ( errorType )
+                {
+                case EValidatedOK:
+                case EChainHasNoRoot:
+                case EBadKeyUsage:
+                // Ignore these errors
+                    LOG_WRITE( "Ignored certificate validation error" );
+                    break;
+
+                default:
+                // certificate is corrupted
+                noValidationError = EFalse;
+                HBufC* string = StringLoader::LoadLC(
+                    R_WARNING_NOTE_TEXT_CERTIFICATE_CORRUPTED );
+                DisplayWarningNoteLD( string );
+                ready = ETrue;
+                    break;
+                }
+            }
+
+        if ( noValidationError  && (aType == KCertTypeAuthority ))
+        // Check for last if the CA certificate has no clients,
+        // ie. the trust state of every client is No
+        // For user certificates we don't do the check
+            {
+
+            RArray<TUid> trusterUids;
+            CleanupClosePushL( trusterUids );
+            poppableItems++;
+
+            iKeeper.iWrapper->GetApplicationsL(
+                iKeeper.CertManager(), aCertInfo, trusterUids );
+
+            if ( trusterUids.Count() == 0)
+                {
+                HBufC* string = StringLoader::LoadLC(
+                    R_WARNING_NOTE_TEXT_CERTIFICATE_NOT_TRUSTED );
+                DisplayWarningNoteLD( string );
+                }
+            }
+        }
+    CleanupStack::PopAndDestroy( poppableItems );
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUICertificateHelper::ValidateCertificateL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::DetailsFieldDynamicL(
+// Appends a field that has string from resources and string from CertManAPI
+// to the details view message body
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::DetailsFieldDynamicL(
+    HBufC& aMessage, TPtrC aValue, TInt aResourceOne, TInt aResourceTwo )
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::DetailsFieldDynamicL" );
+
+    DetailsResourceL( aMessage, aResourceOne );
+    DetailsDynamicL( aMessage, aValue, aResourceTwo );
+    aMessage.Des().Append( KCertManUIDetailsViewEnter );
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUICertificateHelper::DetailsFieldDynamicL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::DetailsResourceL(
+// Reads line from resources
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::DetailsResourceL(
+    HBufC& aMessage, TInt aResourceOne )
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::DetailsResourceL" );
+
+    HBufC* stringHolder = StringLoader::LoadLC( aResourceOne );
+    aMessage.Des().Append( stringHolder->Des() );
+    CleanupStack::PopAndDestroy();  // stringHolder
+    aMessage.Des().Append( KCertManUIDetailsViewEnter );
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUICertificateHelper::DetailsResourceL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::DetailsFieldResourceL(
+// Appends a field that has two strings from resources
+// to the details view message body
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::DetailsFieldResourceL(
+    HBufC& aMessage, TInt aResourceOne,
+    TInt aResourceTwo)
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::DetailsFieldResourceL" );
+
+    DetailsResourceL( aMessage, aResourceOne );
+    DetailsResourceL( aMessage, aResourceTwo );
+    aMessage.Des().Append( KCertManUIDetailsViewEnter );
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUICertificateHelper::DetailsFieldResourceL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::DevideToBlocks
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::DevideToBlocks( const TDesC8& aInput, TPtr aOutput )
+    {
+    const TInt KBlockLength = 2;
+    TInt blockIndex = 0;
+    for ( TInt j = 0 ; j < aInput.Length() ; j++ )
+        {
+        if ( blockIndex == KBlockLength )
+            {
+            aOutput.Append( KBlockSeparator );
+            blockIndex = 0;
+            }
+        aOutput.AppendNumFixedWidthUC( (TUint)(aInput[ j ]), EHex, 2 );
+        ++blockIndex;
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::DisplayWarningNoteLD(HBufC* aString)
+// Displays the warning note for corrupted/expired/not yet valid certificate
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::DisplayWarningNoteLD( HBufC* aString )
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::DisplayWarningNoteLD" );
+
+    CAknWarningNote* note = new ( ELeave ) CAknWarningNote( ETrue );
+    note->ExecuteLD( *aString );
+    CleanupStack::PopAndDestroy();  // aString
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUICertificateHelper::DisplayWarningNoteLD" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::ValidateX509CertificateL(CX509Certificate* aDetails)
+// Checks if the certificate is corrupted
+// Checks the validity period of the certificate
+// Display only one warning note, in the following order:
+// 1) Expired/Not yet valid
+// 2) Corrupted
+// 3) Not trusted
+// ---------------------------------------------------------
+//
+CArrayFixFlat<TValidationError>* CCertManUICertificateHelper::
+    ValidateX509CertificateL( CX509Certificate* aDetails )
+    {
+    TInt poppableItems = 0;
+    CArrayFixFlat<TValidationError>* status =
+        new ( ELeave ) CArrayFixFlat<TValidationError>( 1 );
+    CleanupStack::PushL( status ); //This is returned, so it isn't destroyed at the end.
+
+    TTime GMTTime;
+    GMTTime.UniversalTime(); // Get Universal Time
+    RPointerArray<CX509Certificate> certArray( &aDetails, 1 );
+
+    CPKIXCertChain* chain = CPKIXCertChain::NewLC(
+        iKeeper.iRfs, aDetails->Encoding(), certArray );
+    poppableItems++;
+
+    CPKIXValidationResult* result = CPKIXValidationResult::NewLC();
+    poppableItems++;
+    iKeeper.iWrapper->ValidateX509RootCertificateL( result, GMTTime, chain );
+
+    TValidationStatus validationStatus = result->Error();
+    //Set reserve space. One for error, other for warnings.
+    status->SetReserveL( 1 + result->Warnings().Count() );
+    status->AppendL(validationStatus.iReason);
+    for ( TUint8 i = 0; i < result->Warnings().Count(); i++ )
+        {
+        status->AppendL( result->Warnings().At(0).iReason );
+        }
+
+    CleanupStack::PopAndDestroy( poppableItems );    //  All but status.
+    CleanupStack::Pop();        //  status
+    return status;
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::DetailsDynamicL(
+// HBufC& aMessage, TPtrC aValue, TInt aResourceOne)
+// Reads dynamic text from CertManAPI, if the string is empty
+// put a not defined text from the resource in its place
+// KMaxLengthTextCertLabel = 510, used by CertLabel(), Issuer(), Owner()
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::DetailsDynamicL(
+    HBufC& aMessage, TPtrC aValue, TInt aResourceOne )
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::DetailsDynamicL" );
+
+    HBufC* buf = HBufC::NewLC( KMaxLengthTextCertLabel );
+    buf->Des() = aValue;
+    buf->Des().TrimLeft();
+    // Cut CertLabel after fourth semi colon
+    TPtrC trimmedCertLabel = CutCertificateField( buf->Des() );
+    buf->Des().Copy( trimmedCertLabel );
+    TInt length = buf->Des().Length();
+    if ( length == 0 )
+        {
+        DetailsResourceL( aMessage, aResourceOne );
+        }
+    else
+        {
+        //LRM (Left-to-Right mark 200E)
+        const TInt KLRMark = 0x200E;
+        aMessage.Des().Append( buf->Des() );
+        aMessage.Des().Append(KLRMark);
+        aMessage.Des().Append( KCertManUIDetailsViewEnter );
+        }
+    CleanupStack::PopAndDestroy();  // buf
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUICertificateHelper::DetailsDynamicL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::ConfirmationQueryDeleteCertL()
+// Deletes either certificate in focus if there are no marked items,
+// or deletes the marked items
+// Shows read-only information notes if certificates are not deletable
+// Returns ETrue if at least one certificate is deleted
+// ---------------------------------------------------------
+//
+TBool CCertManUICertificateHelper::ConfirmationQueryDeleteCertL(
+    TInt aType,
+    CEikColumnListBox* aListBox )
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::ConfirmationQueryDeleteCertL" );
+
+    TBool result = EFalse;
+
+    const CArrayFix<TInt>* array = aListBox->SelectionIndexes();
+    TInt focusPosition = aListBox->CurrentItemIndex();
+    CCTCertInfo* entry;
+    TInt queryOk = 0;
+    // comes here when there is no selection, can be read-only
+    // certificate if Clear key is pressed, must check
+    if ( array->Count() == 0 && IsCertificateDeletable( focusPosition, aType ) )
+        {
+        if( aType == KCertTypeAuthority )
+            {
+            entry = iKeeper.iCALabelEntries[ focusPosition ]->iCAEntry;
+            }
+        else if( aType == KCertTypeTrustedSite )
+            {
+            entry = iKeeper.iPeerLabelEntries[ focusPosition ]->iPeerEntry;
+            }
+        else if( aType == KCertTypeDevice )
+            {
+            entry = iKeeper.iDeviceLabelEntries[ focusPosition ]->iDeviceEntry;
+            }
+        else
+            {
+            entry = iKeeper.iUserLabelEntries[ focusPosition ]->iUserEntry;
+            }
+        queryOk = DeleteSingleItemQueryL( *entry );
+        if ( queryOk )
+            {
+            if (IsCertificateDeletable( focusPosition, aType ))
+                {
+                DeleteSingleItemL( *entry, focusPosition, aListBox, aType );
+
+
+                AknListBoxUtils::HandleItemRemovalAndPositionHighlightL(
+                    aListBox, focusPosition, ETrue );
+                result = ETrue;
+                }
+            else
+                {
+                ReadOnlySingleItemNoteL( *entry );
+                }
+            }
+        }
+    else if ( IsOneMarkedCertificateDeletable(aListBox, aType) ) //if (array->Count()=>1)
+        {
+        if ( aType == KCertTypeAuthority )
+            {
+            entry = iKeeper.iCALabelEntries[ array->At(0) ]->iCAEntry;
+            }
+        else if ( aType == KCertTypeTrustedSite )
+            {
+            entry = iKeeper.iPeerLabelEntries[ array->At(0) ]->iPeerEntry;
+            }
+        else if( aType == KCertTypeDevice )
+            {
+            entry = iKeeper.iDeviceLabelEntries[ array->At(0) ]->iDeviceEntry;
+            }
+        else
+            {
+            entry = iKeeper.iUserLabelEntries[ array->At(0) ]->iUserEntry;
+            }
+
+        if (array->Count()==1)
+            {
+            queryOk = DeleteSingleItemQueryL( *entry );
+            }
+        else
+            {
+            HBufC* prompt = StringLoader::LoadLC(
+                R_CONFIRMATION_QUERY_DELETE_CERT_PLURAL, array->Count() );
+            queryOk = DisplayConfirmationLD( prompt );
+            }
+        if ( queryOk )
+            {
+            TInt readonlyCount = 0;
+            TInt singleReadOnlyPosition = 0;
+            TInt markedPosition = 0;
+            TKeyArrayFix ownKey( 0, ECmpTInt );
+            CONST_CAST(CArrayFix<int>*, array)->Sort( ownKey ); //lint !e665 expression macro param ok
+            TInt markedCount = array->Count();
+            CArrayFixFlat<TInt>* deletedIndexes = new (ELeave)CArrayFixFlat<TInt>( 4 );
+            CleanupStack::PushL( deletedIndexes );
+
+            iKeeper.StartWaitDialogL( ECertmanUiDeleteDialog );
+            CleanupCloseWaitDialogPushL( iKeeper );
+
+            for ( TInt i = markedCount; i > 0; i-- )
+                {
+                markedPosition = array->At( i-1 );
+                // move focus up the list if marked items were
+                // between focus and the beginning of the list
+                if ( focusPosition > markedPosition )
+                    {
+                    focusPosition--;
+                    }
+
+                // Check whether certificate is deletable
+
+                if( aType == KCertTypeAuthority )
+                    {
+                    entry = iKeeper.iCALabelEntries[ markedPosition ]->iCAEntry;
+                    }
+                else if( aType == KCertTypeTrustedSite )
+                    {
+                    entry = iKeeper.iPeerLabelEntries[ markedPosition ]->iPeerEntry;
+                    }
+                else if( aType == KCertTypeDevice )
+                    {
+                    entry = iKeeper.iDeviceLabelEntries[ markedPosition ]->iDeviceEntry;
+                    }
+                else
+                    {
+                    entry = iKeeper.iUserLabelEntries[ markedPosition ]->iUserEntry;
+                    }
+
+                if (IsCertificateDeletable(markedPosition, aType))
+                    {
+                    DeleteSingleItemL( *entry, markedPosition, aListBox, aType );
+                    deletedIndexes->AppendL(markedPosition);
+                    result = ETrue;
+                    }
+                else // Cannot be deleted
+                    {
+                    readonlyCount++;
+                    singleReadOnlyPosition = markedPosition;
+                    }
+                }
+
+            CleanupStack::PopAndDestroy();    // closes wait dialog
+
+            if ( readonlyCount == 1 )
+                {
+                if( aType == KCertTypeAuthority  )
+                    {
+                    entry = iKeeper.iCALabelEntries[ singleReadOnlyPosition ]->iCAEntry;
+                    }
+                else if( aType == KCertTypeTrustedSite  )
+                    {
+                    entry = iKeeper.iPeerLabelEntries[ singleReadOnlyPosition ]->iPeerEntry;
+                    }
+                else if( aType == KCertTypeDevice )
+                    {
+                    entry = iKeeper.iDeviceLabelEntries[ singleReadOnlyPosition ]->iDeviceEntry;
+                    }
+                else
+                    {
+                    entry = iKeeper.iUserLabelEntries[ singleReadOnlyPosition ]->iUserEntry;
+                    }
+
+                ReadOnlySingleItemNoteL( *entry );
+                }
+            else if ( readonlyCount > 1 )
+                {
+                HBufC* string = StringLoader::LoadLC(
+                    R_INFO_NOTE_TEXT_CERTIFICATE_READ_ONLY_MULTIPLE,
+                    readonlyCount );
+                DisplayNoteLD( string );
+                }
+            else
+                { // For lint
+                }
+
+            aListBox->ClearSelection();
+            AknListBoxUtils::HandleItemRemovalAndPositionHighlightL(
+                aListBox, focusPosition, *deletedIndexes);
+            CleanupStack::PopAndDestroy(deletedIndexes);
+
+            }
+        }
+    else
+        {
+        result = EFalse;
+        }
+
+    aListBox->DrawNow();//lint !e539
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUICertificateHelper::ConfirmationQueryDeleteCertL" );
+
+
+    return result;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::DeleteSingleItemQueryL(CCTCertInfo& aEntry)
+// Gets the certificate name (or No label/No subject) for the Confirmation note
+// ---------------------------------------------------------
+//
+TInt CCertManUICertificateHelper::DeleteSingleItemQueryL( CCTCertInfo& aEntry )
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::DeleteSingleItemQueryL" );
+
+    TInt selection = 0;
+
+    HBufC* buf = HBufC::NewLC( KMaxLengthTextCertLabel );
+    buf->Des() = aEntry.Label();
+    buf->Des().TrimLeft();
+    // Cut CertLabel after fourth semi colon
+    TPtrC trimmedCertLabel = CutCertificateField( buf->Des() );
+    buf->Des().Copy(trimmedCertLabel);
+    TInt length = buf->Des().Length();
+    if ( length == 0 )
+        {
+        // here the resource name is _NO_LABEL, but it returns only "Delete certificate?"
+        // not any "No label" or "No subject" string
+        HBufC* prompt = StringLoader::LoadLC(
+            R_CONFIRMATION_QUERY_DELETE_CERT_NO_LABEL );
+        selection = DisplayConfirmationLD( prompt );
+        }
+    else
+        {
+        HBufC* prompt = StringLoader::LoadLC(
+            R_CONFIRMATION_QUERY_DELETE_CERT, buf->Des() );
+        selection = DisplayConfirmationLD(prompt);
+        }
+    CleanupStack::PopAndDestroy();  // buf
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUICertificateHelper::DeleteSingleItemQueryL" );
+
+    return selection;
+    }
+
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::DeleteSingleItemL(CCrCertEntry& aEntry, TInt aPosition, TInt aType)
+// Deletes one item from CertManAPI and from listbox
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::DeleteSingleItemL( CCTCertInfo& aEntry,
+    TInt aPosition,
+    CEikColumnListBox* aListBox,
+    TInt aType )
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::DeleteSingleItemL" );
+
+    TInt status( KErrNone );
+
+    if ( aType == KCertTypeTrustedSite )
+        {
+        status = iKeeper.iWrapper->DeleteCertL(
+                                              iKeeper.CertManager(),
+                                              aEntry,
+                                              KCMTrustedServerTokenUid
+                                              );
+        }
+    else if( aType == KCertTypeDevice )
+        {
+        status = iKeeper.iWrapper->DeleteCertL(
+                                              iKeeper.CertManager(),
+                                              aEntry,
+                                              KCMDeviceCertStoreTokenUid
+                                              );
+        }
+    else
+        {
+        status = iKeeper.iWrapper->DeleteCertL( iKeeper.CertManager(), aEntry );
+        }
+
+    // Update the list after delete. In case of a error, a note show inside DeleteCertL.
+    if ( status == KErrNone )
+        {
+        MDesCArray *itemList = aListBox->Model()->ItemTextArray();
+        CDesCArray* itemArray = STATIC_CAST( CDesCArray*, itemList );
+        itemArray->Delete( aPosition );
+        }
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUICertificateHelper::DeleteSingleItemL" ); //lint !e539
+    }
+
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::MoveKeyL(const TCTKeyAttributeFilter& aFilter,
+//                       TUid aSourceStore, TUid aSourceStore )
+// Moves a key from one store to another
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::MoveKeyL(
+    const TCTKeyAttributeFilter& aFilter,
+    const TUid aSourceStore,
+    const TUid aTargetStore )
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::MoveCertL" );
+
+    iKeeper.iWrapper->MoveKeyL( iKeeper.KeyManager(), aFilter, aSourceStore, aTargetStore );
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUICertificateHelper::MoveCertL" );
+    }
+
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::MoveCertL(CCrCertEntry& aEntry,
+//                        TInt aPosition, CEikColumnListBox* aListBox,
+//                        TUid aSourceStore, TUid aSourceStore )
+// Moves a certificate from one store to another
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::MoveCertL( CCTCertInfo& aEntry,
+    TInt aPosition,
+    CEikColumnListBox* aListBox,
+    const TUid aSourceStore,
+    const TUid aTargetStore )
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::MoveCertL" );
+
+    TInt certCount(0);
+
+    TRAPD( err, certCount = iKeeper.iWrapper->MoveCertL( iKeeper.CertManager(), aEntry, aSourceStore, aTargetStore ));
+
+    // Update the list after moving the certificate
+    if ( err == KErrNone )
+        {
+        MDesCArray *itemList = aListBox->Model()->ItemTextArray();
+        CDesCArray* itemArray = STATIC_CAST( CDesCArray*, itemList );
+        if ( certCount == 1  )
+            {
+            // Delete single item
+            itemArray->Delete( aPosition );
+            AknListBoxUtils::HandleItemRemovalAndPositionHighlightL(
+                          aListBox, aPosition, ETrue );
+            }
+         else
+            {
+            // More than one certificate moved. Empty listbox items.
+            // It will be updated later
+            itemArray->Reset();
+            }
+        }
+    else
+        {
+        User::Leave( err );
+        }
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUICertificateHelper::MoveCertL" );
+    }
+
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::ReadOnlySingleItemNoteL(CCTCertInfo& aEntry)
+// Gets the certificate name (or No label/No subject) for the read-only note
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::ReadOnlySingleItemNoteL(CCTCertInfo& aEntry )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUICertificateHelper::ReadOnlySingleItemNoteL" );
+
+    HBufC* buf = HBufC::NewLC( KMaxLengthTextCertLabel );
+    buf->Des() = aEntry.Label();
+    buf->Des().TrimLeft();
+    // Cut CertLabel after fourth semi colon
+    TPtrC trimmedCertLabel = CutCertificateField( buf->Des() );
+    buf->Des().Copy(trimmedCertLabel);
+    TInt length = buf->Des().Length();
+    if ( length == 0 )
+        {
+        // here the resource name is _NO_LABEL, but it returns only "Cannot delete certificate"
+        // not any "No label" or "No subject" string
+        HBufC* stringHolder = StringLoader::LoadLC(
+                                R_INFO_NOTE_TEXT_CERTIFICATE_READ_ONLY_NO_LABEL );
+        DisplayNoteLD( stringHolder );
+        }
+    else
+        {
+        HBufC* stringHolder = StringLoader::LoadLC(
+                                R_INFO_NOTE_TEXT_CERTIFICATE_READ_ONLY, buf->Des() );
+        DisplayNoteLD( stringHolder );
+        }
+    CleanupStack::PopAndDestroy();  // buf
+
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUICertificateHelper::ReadOnlySingleItemNoteL" );
+    }
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::DisplayConfirmationLD(HBufC* aString)
+// Displays Delete yes/no confirmation notes
+// ---------------------------------------------------------
+//
+TInt CCertManUICertificateHelper::DisplayConfirmationLD( HBufC* aString )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUICertificateHelper::DisplayConfirmationLD" );
+
+    CAknQueryDialog* dlg = CAknQueryDialog::NewL( CAknQueryDialog::ENoTone );
+    TInt selection = dlg->ExecuteLD( R_CERTMANUI_CONFIRMATION_QUERY_YES_NO, *aString );
+    // Takes ownership and destroys aString
+    CleanupStack::PopAndDestroy();  // aString
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUICertificateHelper::DisplayConfirmationLD" );
+
+    return selection;
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::DisplayNoteLD(HBufC* aString)
+// Displays read-only information notes
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::DisplayNoteLD(HBufC* aString)
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUICertificateHelper::DisplayNoteLD" );
+
+    CAknInformationNote* note = new ( ELeave ) CAknInformationNote( ETrue );
+    note->ExecuteLD( *aString );
+    CleanupStack::PopAndDestroy();  // aString
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUICertificateHelper::DisplayNoteLD" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::FFSSpaceBelowCriticalLevelL
+// Handle deleting when disk is getting full
+// ---------------------------------------------------------
+//
+TBool CCertManUICertificateHelper::FFSSpaceBelowCriticalLevelL(
+    TBool aShowErrorNote, TInt aBytesToWrite )
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::FFSSpaceBelowCriticalLevelL" );
+
+    TBool ret = EFalse;
+    if ( SysUtil::FFSSpaceBelowCriticalLevelL(
+        &(CCoeEnv::Static()->FsSession()), aBytesToWrite ) )
+        {
+        ret = ETrue;
+        if ( aShowErrorNote )
+            {
+            CErrorUI* errorUi = CErrorUI::NewLC( *(CCoeEnv::Static()) );
+            errorUi->ShowGlobalErrorNoteL( KErrDiskFull );
+            CleanupStack::PopAndDestroy();  // errorUi
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUICertificateHelper::FFSSpaceBelowCriticalLevelL" );
+
+    return ret;
+    }
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::HandleMarkableListCommandL( TInt aCommand )
+// Handles marking and unmarking of the list.
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::HandleMarkableListCommandL( TInt aCommand,
+                                                    CEikColumnListBox* aListBox )
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUICertificateHelper::HandleMarkableListCommandL" );
+
+    TInt index;
+    switch ( aCommand )
+        {
+        case ECertManUICmdMark:
+            {
+            index = aListBox->CurrentItemIndex();
+            if ( index >= 0 )
+                {
+                // This is done to make sure listbox updates its state
+                // to make shift+arrow work correctly after shift+ok
+                aListBox->View()->UpdateSelectionL( CListBoxView::EDisjointSelection );
+                aListBox->View()->SelectItemL( index );
+                }
+            break;
+            }
+        case ECertManUICmdUnmark:
+            {
+            index = aListBox->CurrentItemIndex();
+            if ( index >= 0 )
+                {
+                // This is done to make sure listbox updates its state
+                // to make shift+arrow work correctly after shift+ok
+                aListBox->View()->UpdateSelectionL(
+                      CListBoxView::EDisjointSelection );
+                aListBox->View()->DeselectItem( index );
+                }
+            break;
+            }
+        case ECertManUICmdMarkAll:
+            {
+            aListBox->ClearSelection();
+            TInt count = aListBox->Model()->NumberOfItems();
+            if ( count )
+                {
+                CArrayFixFlat<TInt>* selection =
+                    new( ELeave ) CArrayFixFlat<TInt>( 1 );
+                CleanupStack::PushL( selection );
+                selection->SetReserveL( count );
+                for( TInt i = 0; i < count; i++ )
+                    {
+                    selection->AppendL( i );
+                    }
+                aListBox->SetSelectionIndexesL( selection );
+                CleanupStack::PopAndDestroy();  // selection
+                }
+            break;
+            }
+        case ECertManUICmdUnmarkAll:
+            {
+            aListBox->ClearSelection();
+            break;
+            }
+        default:
+      break;
+      }
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUICertificateHelper::HandleMarkableListCommandL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::GetKeyUsageAndLocationL( CCTCertInfo* aCertEntry,
+//                                                      TUid* aKeyLocation)
+// Returns key usage and location.
+// ---------------------------------------------------------
+//
+TKeyUsagePKCS15 CCertManUICertificateHelper::GetKeyUsageAndLocationL( CCTCertInfo* aCertEntry,
+                                                                     TUid* aKeyLocation )
+    {
+    TKeyUsagePKCS15 keyUsage;
+
+    CERTMANUILOGGER_ENTERFN( "CCertManUICertificateHelper::GetKeyUsageAndLocationL" );
+
+    // Check whether we have key for this certificate
+    RMPointerArray<CCTKeyInfo> keyEntry;
+    TCTKeyAttributeFilter filter;
+    filter.iKeyId = aCertEntry->SubjectKeyId();
+
+    iKeeper.iWrapper->ListL( iKeeper.KeyManager(), &keyEntry, filter );
+
+    if (keyEntry.Count())
+        {
+        keyUsage = keyEntry[0]->Usage();
+        // Get Location
+        aKeyLocation->iUid = keyEntry[0]->Token().TokenType().Type().iUid ;
+        }
+    else
+        {
+        keyUsage = EPKCS15UsageNone;
+        }
+
+    keyEntry.Close();
+    LOG_WRITE_FORMAT( "Key usage : %X", keyUsage );
+    CERTMANUILOGGER_LEAVEFN( "CCertManUICertificateHelper::GetKeyUsageAndLocationL" );
+    return keyUsage;
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::SetLocationInfoL( (HBufC& aMessage,
+//                                               TBool aCertificate,
+//                                               TUid* aLocUid)
+// Adds certificate/private key's location info to certificate details
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::SetLocationInfoL(
+    HBufC& aMessage,
+    TBool aCertificate,
+    TUid* aLocUid)
+    {
+    TInt location = 0;
+    TInt locationRes = 0;
+
+    CERTMANUILOGGER_ENTERFN( "CCertManUICertificateHelper::SetLocationInfo" );
+
+    switch ( aLocUid->iUid )
+        {
+        case KFileCertStoreUid:
+        case KTrustedServerCertStoreUid:
+        case KDeviceCertStoreUid:
+        case KDeviceKeyStoreUid:
+        case KTokenTypeFileKeystore:
+            location = R_TEXT_RESOURCE_DETAILS_VIEW_LOCATION_PHONE_MEMORY;
+            break;
+
+        case KWIMCertStoreUid:
+            location = R_TEXT_RESOURCE_DETAILS_VIEW_LOCATION_SMART_CARD;
+            break;
+
+        default:
+            if ( aCertificate )
+                {
+                location = R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED;
+                }
+            else
+                {
+                location = R_TEXT_RESOURCE_DETAILS_VIEW_NO_PRIVATE_KEY;
+                }
+            break;
+        }
+
+    if ( aCertificate )
+        {
+        locationRes = R_TEXT_RESOURCE_DETAILS_VIEW_CERTIFICATE_LOCATION;
+        }
+    else
+        {
+        locationRes = R_TEXT_RESOURCE_DETAILS_VIEW_PRIVATE_KEY_LOCATION;
+        }
+
+    DetailsFieldResourceL( aMessage, locationRes, location );
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUICertificateHelper::SetLocationInfo" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUICertificateHelper::CreateMessageBodyTextL()
+// ---------------------------------------------------------
+//
+void CCertManUICertificateHelper::CreateMessageBodyTextL( TInt aIndex, TInt aType,
+        CEikonEnv* aEikonEnv, HBufC& aMessage )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUICertificateHelper::CreateMessageBodyTextL" );
+
+    // Use certificate index from previous view
+    HBufC8* urlBuf = NULL;
+    CCTCertInfo* entry = NULL;
+    CCertificate* details = NULL;
+    CUnifiedCertStore*& store = iKeeper.CertManager();
+
+    if( aType == KCertTypeAuthority )
+        {
+        entry = ( iKeeper.iCALabelEntries )[ aIndex ]->iCAEntry;
+        }
+    else if( aType == KCertTypeTrustedSite )
+        {
+        entry = ( iKeeper.iPeerLabelEntries )[ aIndex ]->iPeerEntry;
+        }
+    else if( aType == KCertTypeDevice )
+        {
+        entry = ( iKeeper.iDeviceLabelEntries )[ aIndex ]->iDeviceEntry;
+        }
+    else
+        {
+        entry = ( iKeeper.iUserLabelEntries )[ aIndex ]->iUserEntry;
+        }
+
+    TCertificateFormat certiticateFormat = entry->CertificateFormat();
+
+    if( certiticateFormat != EX509CertificateUrl )
+        {
+        TInt err = iKeeper.iWrapper->GetCertificateL( store, *entry, details );
+        CleanupStack::PushL( details );
+        User::LeaveIfError( err );
+
+        ValidateCertificateL( aIndex, details, *entry, aType );
+        }
+    else
+        {
+        urlBuf = HBufC8::NewLC( entry->Size() );
+        TPtr8 urlPtr = urlBuf->Des();
+        TInt err = iKeeper.iWrapper->GetUrlCertificateL( store, *entry, urlPtr );
+        User::LeaveIfError( err );
+        }
+
+    if( aType == KCertTypeTrustedSite )
+        {
+        CTrustSitesStore* trustedSitesStore = CTrustSitesStore::NewL();
+        CleanupStack::PushL( trustedSitesStore );
+
+        RPointerArray<HBufC> trustedSites;
+        CleanupResetAndDestroyPushL( trustedSites );
+        trustedSitesStore->GetTrustedSitesL( details->Encoding(), trustedSites );
+
+        if( trustedSites.Count() > 0 )
+            {
+            if( trustedSites.Count() == 1 )
+                {
+                DetailsResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_SITE );
+                }
+            else
+                {
+                DetailsResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_SITES );
+                }
+
+            for( TInt i = 0; i < trustedSites.Count(); i++ )
+                {
+                aMessage.Des().Append( *trustedSites[ i ] );
+                aMessage.Des().Append( KCertManUIDetailsViewEnter );
+                }
+            aMessage.Des().Append( KCertManUIDetailsViewEnter );
+            }
+
+        CleanupStack::PopAndDestroy( &trustedSites );
+        CleanupStack::PopAndDestroy( trustedSitesStore );
+        }
+    else
+        {
+        DetailsFieldDynamicL( aMessage, entry->Label(),
+                R_TEXT_RESOURCE_DETAILS_VIEW_LABEL,
+                R_TEXT_RESOURCE_VIEW_NO_LABEL_DETAILS );
+        }
+
+    // certificate issuer and owner
+    if( certiticateFormat == EX509Certificate )
+        {
+        HBufC* owner = NULL;
+        X509CertNameParser::SubjectFullNameL( *(CX509Certificate*)details, owner );
+        CleanupStack::PushL( owner );
+
+        HBufC* issuer = NULL;
+        X509CertNameParser::IssuerFullNameL( *(CX509Certificate*)details, issuer );
+        CleanupStack::PushL( issuer );
+
+        DetailsFieldDynamicL( aMessage, issuer->Des(),
+            R_TEXT_RESOURCE_DETAILS_VIEW_ISSUER,
+            R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED );
+        CleanupStack::PopAndDestroy( issuer );
+
+        // certificate subject
+        DetailsFieldDynamicL( aMessage, owner->Des(),
+            R_TEXT_RESOURCE_DETAILS_VIEW_SUBJECT,
+            R_TEXT_RESOURCE_VIEW_NO_SUBJECT_DETAILS );
+        CleanupStack::PopAndDestroy( owner );
+        }
+
+    // Get key usage and location. This is done only client certificates.
+    const TInt KLocationUnknown = 0;
+    TUid keyLocation = { KLocationUnknown };
+
+    if(( aType == KCertTypePersonal ) || ( aType == KCertTypeDevice ))
+        {
+        TInt usage;
+        switch( GetKeyUsageAndLocationL( entry, &keyLocation ) )
+            {
+            case EPKCS15UsageSignSignRecover:
+            case EPKCS15UsageSignDecrypt:
+            case EPKCS15UsageSign:
+                usage = R_TEXT_RESOURCE_DETAILS_VIEW_CLIENT_AUTHENTICATION;
+                break;
+            case EPKCS15UsageNonRepudiation:
+                usage = R_TEXT_RESOURCE_DETAILS_VIEW_DIGITAL_SIGNING;
+                break;
+            default:
+                usage = R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED;
+                break;
+            }
+        DetailsFieldResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_KEY_USAGE, usage );
+        }
+
+    if( certiticateFormat == EX509Certificate )
+        {
+        // Certificate validity period
+        // Hometime's offset to UTC
+        TLocale locale;
+        TTimeIntervalSeconds offSet = locale.UniversalTimeOffset();
+
+        DetailsResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_VALID_FROM );
+        const CValidityPeriod& validityPeriod = details->ValidityPeriod();
+        TTime startValue = validityPeriod.Start();
+        startValue += offSet;
+
+        HBufC* dateFormatString = aEikonEnv->AllocReadResourceLC( R_QTN_DATE_USUAL_WITH_ZERO );
+
+        TBuf<KMaxLengthTextDateString> startString;
+        startValue.FormatL( startString, *dateFormatString );
+        AknTextUtils::DisplayTextLanguageSpecificNumberConversion( startString );
+        aMessage.Des().Append( startString );
+        aMessage.Des().Append( KCertManUIDetailsViewEnterEnter );
+
+        DetailsResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_VALID_UNTIL );
+        TTime finishValue = validityPeriod.Finish();
+        finishValue += offSet;
+        TBuf<KMaxLengthTextDateString> finishString;
+
+        finishValue.FormatL( finishString, *dateFormatString );
+        AknTextUtils::DisplayTextLanguageSpecificNumberConversion( finishString );
+        aMessage.Des().Append( finishString );
+        aMessage.Des().Append( KCertManUIDetailsViewEnterEnter );
+
+        CleanupStack::PopAndDestroy( dateFormatString );
+
+        TUid certLoc;
+        certLoc.iUid = entry->Token().TokenType().Type().iUid;
+        SetLocationInfoL( aMessage, ETrue, &certLoc );
+        }
+    else if( certiticateFormat == EX509CertificateUrl )
+        {
+        HBufC* urlBuf16 = HBufC::NewLC( urlBuf->Length() );
+        TPtr urlPtr = urlBuf16->Des();
+        urlPtr.Copy(*urlBuf);
+        DetailsFieldDynamicL( aMessage, urlBuf16->Des(),
+                R_TEXT_RESOURCE_DETAILS_VIEW_CERTIFICATE_LOCATION,
+                R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED );
+        CleanupStack::PopAndDestroy( urlBuf16 );
+        }
+    else
+        {
+        // nothing
+        }
+
+    // certificate format
+    TInt fieldType = 0;
+    TInt fieldType2 = 0;
+    switch( certiticateFormat )
+        {
+        case EX509Certificate:
+        case EX509CertificateUrl:
+            {
+            fieldType = R_TEXT_RESOURCE_DETAILS_VIEW_CERT_FORMAT_X509;
+            break;
+            }
+         default:
+            {
+            fieldType = R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED;
+            break;
+            }
+        }
+    DetailsFieldResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_CERT_FORMAT, fieldType );
+
+    // Private key location, only for user and device certicates
+    if(( aType == KCertTypePersonal ) || ( aType == KCertTypeDevice ))
+        {
+        SetLocationInfoL( aMessage, EFalse, &keyLocation );
+        }
+
+    if( certiticateFormat == EX509Certificate )
+        {
+        __UHEAP_MARK;
+
+        // certificate algorithms
+
+        // digest algorithm
+        TAlgorithmId algorithmId = details->SigningAlgorithm().DigestAlgorithm().Algorithm();
+        switch( algorithmId )
+            {
+            case EMD2:
+                {
+                fieldType = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_MD2;
+                break;
+                }
+            case EMD5:
+                {
+                fieldType = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_MD5;
+                break;
+                }
+            case ESHA1:
+                {
+                fieldType = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_SHA1;
+                break;
+                }
+            default:
+                {
+                fieldType = R_TEXT_RESOURCE_DETAILS_VIEW_UNKNOWN;
+                break;
+                }
+            }
+
+        // public-key algorithm
+        algorithmId = details->SigningAlgorithm().AsymmetricAlgorithm().Algorithm();
+        switch( algorithmId )
+            {
+            case ERSA:
+                {
+                fieldType2 = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_RSA;
+                break;
+                }
+            case EDSA:
+                {
+                fieldType2 = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_DSA;
+                break;
+                }
+            case EDH:
+                {
+                fieldType2 = R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM_DH;
+                break;
+                }
+            default:
+                {
+                fieldType2 = R_TEXT_RESOURCE_DETAILS_VIEW_UNKNOWN;
+                }
+            }
+
+        // If other algorithm is unknown
+        if( fieldType == R_TEXT_RESOURCE_DETAILS_VIEW_UNKNOWN ||
+                fieldType2 == R_TEXT_RESOURCE_DETAILS_VIEW_UNKNOWN )
+            {
+            DetailsFieldResourceL( aMessage,
+                    R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM,
+                    R_TEXT_RESOURCE_DETAILS_VIEW_UNKNOWN );
+            }
+        else // Both are known.
+            {
+            DetailsResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_ALGORITHM );
+            HBufC* stringHolder = StringLoader::LoadLC( fieldType );
+            aMessage.Des().Append( stringHolder->Des() );
+            CleanupStack::PopAndDestroy( stringHolder );
+            stringHolder = StringLoader::LoadLC( fieldType2 );
+            aMessage.Des().Append( stringHolder->Des() );
+            CleanupStack::PopAndDestroy( stringHolder );
+            aMessage.Des().Append( KCertManUIDetailsViewEnterEnter );
+            }
+
+        // certificate serial number
+        DetailsResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_SERIAL_NUMBER );
+        TPtrC8 serialNumber = details->SerialNumber();
+        TBuf<KMaxLengthTextSerialNumberFormatting> buf2;
+
+        for( TInt i = 0; i < serialNumber.Length(); i++ )
+           {
+           buf2.Format( KCertManUIDetailsViewHexaFormat, serialNumber[i] );
+           aMessage.Des().Append( buf2 );
+           }
+
+        aMessage.Des().Append( KCertManUIDetailsViewEnterEnter );
+
+        // certificate fingerprint SHA-1
+        DetailsResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_FINGERPRINT );
+        TPtrC8 sha1_fingerprint = details->Fingerprint();
+        DevideToBlocks( sha1_fingerprint, aMessage.Des() );
+        aMessage.Des().Append( KCertManUIDetailsViewEnterEnter );
+
+        // certificate fingerprint MD5
+        DetailsResourceL( aMessage, R_TEXT_RESOURCE_DETAILS_VIEW_FINGERPRINT_MD5 );
+
+        CMD5* md5 = CMD5::NewL();
+        CleanupStack::PushL( md5 );
+        TBuf8<20> fingerprint = md5->Hash( details->Encoding() );
+        CleanupStack::PopAndDestroy( md5 );
+
+        DevideToBlocks( fingerprint, aMessage.Des() );
+        aMessage.Des().Append( KCertManUIDetailsViewEnterEnter );
+
+        // Public key
+        // qtn_cm_public_key looks like this "Public key (%0U %1N bit):"
+        // so DetailsResource cannot be used to get it.
+
+        // We already know the public key algorithm, it has been put into fieldType2 above.
+        HBufC* pubkeyHolder = StringLoader::LoadLC( fieldType2 );  // %0U
+
+        CDesCArrayFlat* strArray = new (ELeave) CDesCArrayFlat( 1 );
+        CleanupStack::PushL( strArray );
+
+        strArray->InsertL( 0, *pubkeyHolder );
+
+        // Get public key already here to get length of it for string loader.
+        const CSubjectPublicKeyInfo& publicKey = details->PublicKey();
+        TPtrC8 keyData = publicKey.KeyData();
+        TInt size = keyData.Size();  // %1N
+
+        // To get key size decode DER encoded key got from the certificate.
+        TX509KeyFactory key;
+
+        // There doesn't seem to be definition of MAX_INT anywhere so calculate it.
+        TReal maxInt;
+        TReal intBits = sizeof( TInt ) * 8;
+        Math::Pow( maxInt, 2, intBits );
+        maxInt = ( maxInt / 2 ) - 1;
+
+        switch( algorithmId )
+            {
+            case ERSA:
+                {
+                const CRSAPublicKey* keyRSA = key.RSAPublicKeyL( keyData );
+
+                const TInteger& n = keyRSA->N();
+
+                TUint keySizeN = n.BitCount();
+
+                // Play it safe.
+                if( keySizeN < maxInt )
+                    {
+                    size = keySizeN;
+                    }
+
+                delete keyRSA;
+
+                break;
+                }
+            case EDSA:
+                {
+                TPtrC8 params = publicKey.EncodedParams();
+                const CDSAPublicKey* keyDSA = key.DSAPublicKeyL( params, keyData );
+
+                const TInteger& y = keyDSA->Y();
+
+                TUint keySizeY = y.BitCount();
+
+                // Play it safe.
+                if( keySizeY < maxInt )
+                    {
+                    size = keySizeY;
+                    }
+
+                delete keyDSA;
+
+                break;
+                }
+            // There doesn't seem to be TX509KeyFactory function for DH keys.
+            // If the key is DH or unknown, just multiply length of the key
+            // in bytes with 8. It is not correct but at least gives an idea.
+            // Without setting something to size 'unknown' text should be used
+            // below for the string which is much more error prone than setting
+            // at least something.
+            case EDH:
+            default:
+                {
+                size = 8 * keyData.Size();
+                }
+            }
+
+        CArrayFixFlat<TInt>* intArr = new (ELeave) CArrayFixFlat<TInt>( 1 );
+        CleanupStack::PushL( intArr );
+        intArr->AppendL( size );
+
+        // Load string and set algorithm and key length strings.
+        HBufC* stringHolder = StringLoader::LoadLC( R_TEXT_RESOURCE_DETAILS_VIEW_PUBLIC_KEY,
+                *strArray, *intArr );
+        aMessage.Des().Append( stringHolder->Des() );
+        aMessage.Des().Append( KCertManUIDetailsViewEnter );
+
+        // Finally append the public key.
+        DevideToBlocks( keyData, aMessage.Des() );
+
+        const TInt KItemsInCleanupStack = 4; // stringHolder, intArr, strArray, pubkeyHolder
+        CleanupStack::PopAndDestroy( KItemsInCleanupStack, pubkeyHolder );
+
+        __UHEAP_MARKEND;
+        }
+    else
+        {
+        // SetUrlCertAlgorihm()
+        }
+
+    if( certiticateFormat != EX509CertificateUrl )
+        {
+        CleanupStack::PopAndDestroy( details );
+        }
+    else
+        {
+        CleanupStack::PopAndDestroy( urlBuf );
+        }
+
+    aMessage.Des().Append( KCertManUIDetailsViewEnter );
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUICertificateHelper::CreateMessageBodyTextL" );
+    }
+
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuiKeeper.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1050 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIKeeper
+*                Creates and destroys all the views CertManUI uses.
+*                Handles changing CertManUI views.
+*
+*/
+
+
+// INCLUDE FILES
+#include <aknnotewrappers.h>            // for warning & information notes
+#include <unifiedcertstore.h>
+#include <unifiedkeystore.h>
+#include <mctwritablecertstore.h>
+#include <X509CertNameParser.h>
+#include <certmanui.rsg>
+#include <data_caging_path_literals.hrh>
+#include "CertmanuiSyncWrapper.h"
+#include "CertmanuiCertificateHelper.h"
+#include "Certmanuidialogs.h"
+#include "CertmanuiKeeper.h"
+#include "CertmanuiviewTrust.h"
+#include "CertmanuiviewPersonal.h"
+#include "CertmanuicontainerAuthority.h"
+#include "CertmanuiCommon.h"
+#include "CertManUILogger.h"
+#include "securityuisvariant.hrh"
+
+// CONSTANTS
+_LIT( KNameSeparator, " " );
+_LIT( KResourceFile, "z:CertManUi.rsc" );
+
+
+// ============================= GLOBAL FUNCTIONS ==============================
+
+//---------------------------------------------------------------
+// CloseWaitDialogOnLeave( TAny* aPtr )
+// Closes wait dialog when leave happens.
+//---------------------------------------------------------------
+void CloseWaitDialogOnLeave( TAny* aPtr )
+    {
+    CCertManUIKeeper* keeper = reinterpret_cast< CCertManUIKeeper* >( aPtr );
+    if( keeper )
+        {
+        TRAP_IGNORE( keeper->CloseWaitDialogL() );
+        }
+    }
+
+//---------------------------------------------------------------
+// CleanupCloseWaitDialogPushL( CCertManUIKeeper& aKeeper )
+// Helper function for to close wait dialog if leave happens.
+//---------------------------------------------------------------
+void CleanupCloseWaitDialogPushL( CCertManUIKeeper& aKeeper )
+    {
+    CleanupStack::PushL( TCleanupItem( CloseWaitDialogOnLeave, &aKeeper ) );
+    }
+
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// TInt CompareCALabels( const CCTCertInfo& cert1, const CCTCertInfo& cert2 )
+// Compares two labels.
+// -----------------------------------------------------------------------------
+//
+TInt CompareCALabels(
+    const CCertManUICertData& cert1,
+    const CCertManUICertData& cert2 )
+    {
+    return ( (cert1.iCAEntryLabel->Des()).
+        CompareF( cert2.iCAEntryLabel->Des() ) );
+    }
+
+// -----------------------------------------------------------------------------
+// TInt CompareUserLabels( const CCTCertInfo& cert1, const CCTCertInfo& cert2 )
+// Compares two labels.
+// -----------------------------------------------------------------------------
+//
+TInt CompareUserLabels(
+    const CCertManUICertData& cert1,
+    const CCertManUICertData& cert2 )
+    {
+    return ( (cert1.iUserEntryLabel->Des()).
+        CompareF( cert2.iUserEntryLabel->Des() ) );
+    }
+
+// -----------------------------------------------------------------------------
+// TInt ComparePeerLabels( const CCTCertInfo& cert1, const CCTCertInfo& cert2 )
+// Compares two labels.
+// -----------------------------------------------------------------------------
+//
+TInt ComparePeerLabels(
+    const CCertManUICertData& cert1,
+    const CCertManUICertData& cert2 )
+    {
+    return ( (cert1.iPeerEntryLabel->Des()).
+        CompareF( cert2.iPeerEntryLabel->Des() ) );
+    }
+
+// -----------------------------------------------------------------------------
+// TInt CompareDeviceLabels( const CCTCertInfo& cert1, const CCTCertInfo& cert2 )
+// Compares two labels.
+// -----------------------------------------------------------------------------
+//
+TInt CompareDeviceLabels(
+    const CCertManUICertData& cert1,
+    const CCertManUICertData& cert2 )
+    {
+    return ( (cert1.iDeviceEntryLabel->Des()).
+        CompareF( cert2.iDeviceEntryLabel->Des() ) );
+    }
+
+// ================= HELPER CLASS ===========================
+
+// Constructor.
+CCertManUICertData::CCertManUICertData()
+    {
+    }
+
+// Destructor.
+CCertManUICertData::~CCertManUICertData()
+    {
+    delete iCAEntryLabel;
+    delete iUserEntryLabel;
+    delete iPeerEntryLabel;
+    delete iDeviceEntryLabel;
+    }
+
+// Releases Certificate entries.
+void CCertManUICertData::Release()
+    {
+    if ( iCAEntry )
+        {
+        iCAEntry->Release();
+        }
+
+    if ( iUserEntry )
+        {
+        iUserEntry->Release();
+        }
+
+    if ( iPeerEntry )
+        {
+        iPeerEntry->Release();
+        }
+
+    if ( iDeviceEntry )
+        {
+        iDeviceEntry->Release();
+        }
+
+    delete this;
+    }
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::CCertManUIKeeper()
+// Constructor with parent
+// ---------------------------------------------------------
+//
+CCertManUIKeeper::CCertManUIKeeper(): iResourceLoader( *iCoeEnv )
+    {
+    CERTMANUILOGGER_CREATE; //lint !e960
+    CERTMANUILOGGER_WRITE_TIMESTAMP( "CCertManUIKeeper::CCertManUIKeeper" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::~CCertManUIKeeper()
+// Destructor
+// ---------------------------------------------------------
+//
+CCertManUIKeeper::~CCertManUIKeeper()
+    {
+    CERTMANUILOGGER_WRITE_TIMESTAMP( "CCertManUIKeeper::~CCertManUIKeeper" );
+    if ( iWrapper )
+        {
+        iWrapper->Cancel();
+        }
+    delete iFilter;
+    delete iKeyFilter;
+    delete iStore;
+    delete iKeyStore;
+    delete iWrapper;
+    delete iCertificateHelper;
+    delete iCertmanUIDialog;
+
+    iCAEntries.Close();
+    iCALabelEntries.Close();
+
+    iUserEntries.Close();
+    iUserLabelEntries.Close();
+
+    iPeerEntries.Close();
+    iPeerLabelEntries.Close();
+
+    iDeviceEntries.Close();
+    iDeviceLabelEntries.Close();
+
+    iKeyEntries.Close();
+
+    iRfs.Close();
+
+    CERTMANUILOGGER_DELETE; //lint !e960
+    }
+
+// ---------------------------------------------------------
+// CCertManUIKeeper* CCertManUIKeeper::NewL(const TRect& aRect, TUid aViewId)
+// ---------------------------------------------------------
+//
+
+CCertManUIKeeper* CCertManUIKeeper::NewL(
+    const TRect& aRect, TUid aViewId )
+    {
+    CCertManUIKeeper* self = new ( ELeave ) CCertManUIKeeper;
+    CleanupStack::PushL( self );
+    self->ConstructL( aRect, aViewId );
+    CleanupStack::Pop();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIKeeper* CCertManUIKeeper::NewLC(
+//      const TRect& aRect, TUid aViewId)
+// ---------------------------------------------------------
+//
+CCertManUIKeeper* CCertManUIKeeper::NewLC(
+    const TRect& aRect, TUid aViewId )
+    {
+    CCertManUIKeeper* self = new ( ELeave ) CCertManUIKeeper;
+    CleanupStack::PushL( self );
+    self->ConstructL( aRect, aViewId );
+    return self;
+    }
+
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::ConstructL(
+ //     const TRect& aRect, TUid aViewId
+//
+// ---------------------------------------------------------
+//
+void CCertManUIKeeper::ConstructL( const TRect& aRect, TUid aViewId )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIKeeper::ConstructL" );
+
+    AddResourceFileL();
+
+    InitializeL( aRect, aViewId );
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIKeeper::ConstructL" );
+    }
+
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::InitializeL(
+ //     const TRect& aRect, TUid aViewId
+//
+// ---------------------------------------------------------
+//
+void CCertManUIKeeper::InitializeL( const TRect& /*aRect*/, TUid /*aViewId*/)
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIKeeper::InitializeL" );
+    iCertmanUIDialog = new ( ELeave ) CCertManUIWaitDialog();
+
+    // Ensure that file server session is succesfully created
+    User::LeaveIfError( iRfs.Connect() );
+
+    iCertsDatOK = EFalse;
+
+    // Is this the place where these errors can be handled?
+    // iCertsDatOK is set when cert entries are refreshed.
+    // Create a R/W interface. Symbian has promised to support
+    // up to two simultaneous R/W interfaces.
+    TRAPD ( error, iStore = CUnifiedCertStore::NewL( iRfs, ETrue ) );
+    if ( error != KErrNone )
+        {
+        if ( error == KErrNotSupported
+           || error == KErrNotReady
+           || error == KErrArgument
+           || error == KErrNotFound )
+            {
+            // Something may be wrong with the databases
+            iCertsDatOK = EFalse;
+            ShowErrorNoteL( error );
+            User::Leave( KErrNone );
+            }
+        else
+            {
+            User::Leave( error );
+            }
+        }
+    else
+        {
+        // cacerts.dat file is ok
+        iCertsDatOK = ETrue;
+        }
+
+    iCertificateHelper = new ( ELeave ) CCertManUICertificateHelper( *this );
+
+    iWrapper = CCertManUISyncWrapper::NewL();
+    error = iWrapper->InitStoreL( iStore );
+
+    if ( error )
+        {
+        LOG_WRITE_FORMAT("InitStoreL returned %i", error);
+        }
+
+
+    iFilter = CCertAttributeFilter::NewL();
+
+    TRAP( error, iKeyStore = CUnifiedKeyStore::NewL( iRfs ) );
+    if ( error != KErrNone )
+        {
+        if (error == KErrNotSupported
+            || error == KErrNotReady
+            || error == KErrArgument
+            || error == KErrNotFound)
+            {
+            // Something is wrong with key stores
+            LOG_WRITE( "Keystore corrupt" );
+
+            ShowErrorNoteL( error );
+            User::Leave( KErrNone );
+            }
+        else
+            {
+            User::Leave( error );
+            }
+          }
+
+    LOG_WRITE("Init keystore");
+    iWrapper->InitStoreL( iKeyStore );
+    iKeyEntries.Close();
+    LOG_WRITE_FORMAT("Keys available : %i", iKeyEntries.Count());
+
+    if ( iCertsDatOK ) // == ETrue
+        {
+        iStartup = ETrue;
+        }
+
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIKeeper::InitializeL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::AddResourceFileL()
+//
+// ---------------------------------------------------------
+//
+void CCertManUIKeeper::AddResourceFileL()
+    {
+    TFileName fileName;
+    TParse parse;
+    parse.Set( KResourceFile, &KDC_RESOURCE_FILES_DIR, NULL );
+
+    fileName = parse.FullName();
+    iResourceLoader.OpenL( fileName );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::FocusChanged(TDrawNow aDrawNow)
+// Added here because FocusChanged need to be included
+// in every control derived from CCoeControl that can have listbox
+// ---------------------------------------------------------
+//
+void CCertManUIKeeper::FocusChanged(TDrawNow aDrawNow)
+    {
+    if (iListBox)
+        {
+        iListBox->SetFocus( IsFocused(), aDrawNow );
+        }
+     }
+
+
+// ----------------------------------------------------
+// CCertManUIKeeper::ActivateTitleL(TInt aCurrentTitle)
+// Activates the WimTitle and CertManUI Trust Settings title
+// ----------------------------------------------------
+//
+void CCertManUIKeeper::ActivateTitleL( TInt aCurrentTitle )
+    {
+    CERTMANUILOGGER_ENTERFN("CCertManUIKeeper::ActivateTitleL" );
+
+    CEikStatusPane* sp = STATIC_CAST(
+        CAknAppUi*, iEikonEnv->EikAppUi())->StatusPane();
+    // Fetch pointer to the default title pane control
+    CAknTitlePane* title = STATIC_CAST(
+        CAknTitlePane*, sp->ControlL( TUid::Uid( EEikStatusPaneUidTitle ) ));
+    TResourceReader reader;
+
+    if ( aCurrentTitle == KViewTitleCertManUI )
+        {
+        iCoeEnv->CreateResourceReaderLC( reader, R_CERTMANUI_VIEW_TITLE );
+        }
+    else if ( aCurrentTitle == KViewTitleCertManUIAuthority )
+        {
+        iCoeEnv->CreateResourceReaderLC( reader, R_CERTMANUI_VIEW_TITLE_AUTHORITY );
+        }
+    else if ( aCurrentTitle == KViewTitleCertManUITrustedSite )
+        {
+        iCoeEnv->CreateResourceReaderLC( reader, R_CERTMANUI_VIEW_TITLE_TRUSTED_SITE );
+        }
+    else if ( aCurrentTitle == KViewTitleCertManUIPersonal )
+        {
+        iCoeEnv->CreateResourceReaderLC( reader, R_CERTMANUI_VIEW_TITLE_PERSONAL );
+        }
+    else if ( aCurrentTitle == KViewTitleCertManUIDevice )
+        {
+        iCoeEnv->CreateResourceReaderLC( reader, R_CERTMANUI_VIEW_TITLE_DEVICE );
+        }
+    else  // for lint
+        {
+        }
+
+    title->SetFromResourceL( reader );
+    CleanupStack::PopAndDestroy();  // reader
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIKeeper::ActivateTitleL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::HandleControlEventL(
+//      CCoeControl* /*aControl*/,TCoeEvent /*aEventType*/)
+// Cannot be changed to non-leaving function.
+// L-function is required by the class definition, even if empty.
+// ---------------------------------------------------------
+//
+void CCertManUIKeeper::HandleControlEventL(
+    CCoeControl* /*aControl*/,TCoeEvent /*aEventType*/)
+    {
+    }
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::OfferKeyEventL(
+//      const TKeyEvent& /*aKeyEvent*/, TEventCode /*aType*/)
+// Called when a key is pressed.
+// Cannot be changed to non-leaving function.
+// L-function is required by the class definition, even if empty.
+// ---------------------------------------------------------
+//
+TKeyResponse CCertManUIKeeper::OfferKeyEventL(
+    const TKeyEvent& /*aKeyEvent*/, TEventCode /*aType*/)
+    {
+    // Listbox takes all event even if it doesn't use them
+    return EKeyWasNotConsumed;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::CertManager()
+// ---------------------------------------------------------
+//
+CUnifiedCertStore*& CCertManUIKeeper::CertManager()
+    {
+    return iStore;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::KeyManager()
+// ---------------------------------------------------------
+//
+CUnifiedKeyStore*& CCertManUIKeeper::KeyManager()
+    {
+    return iKeyStore;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::RefreshCAEntriesL()
+// Checks that cacerts.dat file is not corrupted and
+// returns CA certificates from it
+// ---------------------------------------------------------
+//
+void CCertManUIKeeper::RefreshCAEntriesL()
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIKeeper::RefreshCAEntriesL" );
+    iFilter->SetOwnerType( ECACertificate );
+    iCAEntries.Close();
+    CUnifiedCertStore*& store = CertManager();
+    iWrapper->ListL( store, &iCAEntries, *iFilter );
+
+    iCALabelEntries.Close();
+    LOG_WRITE_FORMAT("CA entries found: %i", iCAEntries.Count());
+    for ( TInt ii = 0; ii < iCAEntries.Count(); ii++ )
+        {
+        switch ( iCAEntries[ii]->CertificateFormat() )
+            {
+            case EX509Certificate:
+                {
+                CCertManUICertData* data = new ( ELeave ) CCertManUICertData();
+                data->iCAEntry = CCTCertInfo::NewL( *iCAEntries[ii] );
+                CleanupStack::PushL( data );
+                HBufC* pri = NULL;
+                HBufC* sec = NULL;
+
+                CCertificate* cert;
+
+                TRAPD(err, iWrapper->GetCertificateL( CertManager(), *iCAEntries[ii], cert ));
+                if (( err == KErrArgument ) || ( err == KErrCorrupt ))
+                    {
+                    // This indicates that certificate is not according to X509
+                    // specification or it is corrupted. Ignore certificate
+                    if(data->iCAEntry)
+                       {
+                       data->iCAEntry->Release();
+                       }
+                    CleanupStack::PopAndDestroy( data ); // data
+                    continue;
+                    }
+                else
+                    {
+                    User::LeaveIfError( err );
+                    }
+
+                CleanupStack::PushL( cert );
+
+                X509CertNameParser::PrimaryAndSecondaryNameL
+                    ( *((CX509Certificate*)cert), pri, sec, iCAEntries[ii]->Label());
+
+                CleanupStack::PushL( pri );
+                CleanupStack::PushL( sec );
+
+                TInt lenght = 0;
+
+                lenght += iCAEntries[ii]->Label().Length();
+
+                if ( pri )
+                    {
+                    lenght += pri->Length();
+                    }
+                if ( sec && !(iCAEntries[ii]->Label().Length()) )
+                    {
+                    lenght += sec->Length();
+                    }
+                lenght += KNameSeparator.iTypeLength;
+
+                HBufC* label = HBufC::NewL( lenght );
+                label->Des().Append( iCAEntries[ii]->Label() );
+
+                if ( pri )
+                    {
+                    label->Des().Append( KNameSeparator );
+                    label->Des().Append( pri->Des() );
+                    }
+                if ( sec && !(iCAEntries[ii]->Label().Length()) )
+                    {
+                    label->Des().Append( sec->Des() );
+                    }
+
+                data->iCAEntryLabel = label;
+                iCALabelEntries.Append( data );
+
+                CleanupStack::PopAndDestroy( 3 ); // cert, pri, sec
+                CleanupStack::Pop( data ); // data
+                break;
+                } // EX509Certificate
+
+            case EWTLSCertificate:
+                // Do nothing for wtls certificates
+                break;
+            default:
+                {
+                User::Leave( KErrNotSupported );
+                }
+            }   // switch
+
+        }   // for
+
+    // Sort the certificates.
+    TLinearOrder<CCertManUICertData> order( CompareCALabels );
+    iCALabelEntries.Sort( order );
+
+    CERTMANUILOGGER_LEAVEFN("CCertManUIKeeper::RefreshCAEntriesL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::RefreshUserCertEntriesL()
+// Checks that cacerts.dat file is not corrupted and
+// returns User certificates from it
+// ---------------------------------------------------------
+//
+void CCertManUIKeeper::RefreshUserCertEntriesL()
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUIKeeper::RefreshUserCertEntriesL" );
+
+    iFilter->SetOwnerType( EUserCertificate );
+    iUserEntries.Close();
+    CUnifiedCertStore*& store = CertManager();
+    iWrapper->ListL( store, &iUserEntries, *iFilter );
+
+    iUserLabelEntries.Close();
+    LOG_WRITE_FORMAT(" Userentries found %i", iUserEntries.Count());
+    for ( TInt i = 0; i < iUserEntries.Count(); i++ )
+        {
+
+       if ( iUserEntries[i]->Handle().iTokenHandle.iTokenTypeUid == KCMDeviceCertStoreTokenUid )
+            {
+            // User certificates from DeviceCertStore are not
+            // shown in Personal certificate view. Ignore this certificate.
+            break;
+            }
+
+        switch ( iUserEntries[i]->CertificateFormat() )
+            {
+            case EX509Certificate:
+                {
+                LOG_WRITE_FORMAT(" User X509 certificate, index %i", i);
+                CCertManUICertData* data = new (ELeave) CCertManUICertData();
+                data->iUserEntry = CCTCertInfo::NewL( *iUserEntries[i] );
+                CleanupStack::PushL( data );
+                HBufC* pri = NULL;
+                HBufC* sec = NULL;
+
+                CCertificate* cert = NULL;
+                TRAPD(error, iWrapper->GetCertificateL( CertManager(), *iUserEntries[i], cert ));
+
+                if( error == KErrArgument)
+                    {
+                    LOG_WRITE("Corrupted user certificate detected");
+                    CleanupStack::PopAndDestroy( data );
+                    break;
+                    }
+                else if ( error != KErrNone )
+                    {
+                    LOG_WRITE_FORMAT( " GetCertificateL leaves, error code %i", error );
+                    User::Leave( error );
+                    }
+                else
+                    {
+                    CleanupStack::PushL( cert );
+                    }
+
+                X509CertNameParser::PrimaryAndSecondaryNameL
+                    ( *((CX509Certificate*)cert), pri, sec, iUserEntries[i]->Label());
+
+                CleanupStack::PushL( pri );
+                CleanupStack::PushL( sec );
+
+                TInt lenght = 0;
+
+                lenght += iUserEntries[i]->Label().Length();
+
+                if ( pri )
+                    {
+                    lenght += pri->Length();
+                    }
+                if ( sec && !(iUserEntries[i]->Label().Length()) )
+                    {
+                    lenght += sec->Length();
+                    }
+                lenght += KNameSeparator.iTypeLength;
+
+                HBufC* label = HBufC::NewL( lenght );
+                label->Des().Append( iUserEntries[i]->Label() );
+
+                if ( pri )
+                    {
+                    label->Des().Append( KNameSeparator );
+                    label->Des().Append( pri->Des() );
+                    }
+                if ( sec && !(iUserEntries[i]->Label().Length()) )
+                    {
+                    label->Des().Append( sec->Des() );
+                    }
+
+                data->iUserEntryLabel = label;
+                iUserLabelEntries.Append( data );
+
+                CleanupStack::PopAndDestroy( 3 ); // cert, pri, sec
+                CleanupStack::Pop( data ); // data
+                break;
+                } // EX509Certificate
+
+            case EX509CertificateUrl:
+                {
+                LOG_WRITE_FORMAT(" User X509URL certificate, index %i", i);
+                CCertManUICertData* urlCertData = new (ELeave) CCertManUICertData();
+                urlCertData->iUserEntry = CCTCertInfo::NewL( *iUserEntries[i] );
+                CleanupStack::PushL( urlCertData );
+
+                CCertificate* cert = NULL;
+                TRAPD(error, iWrapper->GetCertificateL( CertManager(), *iUserEntries[i], cert ));
+                if( error == KErrArgument )
+                    {
+                    LOG_WRITE("Corrupted user certificate detected");
+                    CleanupStack::PopAndDestroy( urlCertData ); // urlCertData
+                    break;
+                    }
+                else if ( error != KErrNone )
+                    {
+                    LOG_WRITE_FORMAT( " GetCertificateL leaves, error code %i", error );
+                    User::Leave(error);
+                    }
+                else
+                    {
+                    CleanupStack::PushL( cert );
+                    }
+
+
+                HBufC* UrlLabel = HBufC::NewL( 20 );
+                UrlLabel->Des().Append( _L("URL UserCert"));
+
+                urlCertData->iUserEntryLabel = UrlLabel;
+                iUserLabelEntries.Append( urlCertData );
+
+                CleanupStack::PopAndDestroy( cert ); // cert
+                CleanupStack::Pop( urlCertData ); // data
+                break;
+                }
+            default:
+                {
+                LOG_WRITE_FORMAT( "Unsupported certificate format 0x%x",
+                                        iUserEntries[i]->CertificateFormat() );
+                }
+            }   // switch
+
+        }   // for
+
+    // Sort the certificates.
+    TLinearOrder<CCertManUICertData> order( CompareUserLabels );
+    iUserLabelEntries.Sort( order );
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUIKeeper::RefreshUserCertEntriesL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::RefreshPeerCertEntriesL()
+// Checks that Trusted site certificate store is
+// not corrupted and returns Peer certificates from it
+// ---------------------------------------------------------
+//
+void CCertManUIKeeper::RefreshPeerCertEntriesL()
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIKeeper::RefreshPeerEntriesL" );
+
+
+
+    iFilter->SetOwnerType( EPeerCertificate );
+    iPeerEntries.Close();
+    CUnifiedCertStore*& store = CertManager();
+
+    iWrapper->ListL( store, &iPeerEntries, *iFilter, KCMTrustedServerTokenUid );
+
+    iPeerLabelEntries.Close();
+    LOG_WRITE_FORMAT("Peer entries found: %i", iPeerEntries.Count());
+    for ( TInt ii = 0; ii < iPeerEntries.Count(); ii++ )
+        {
+        switch ( iPeerEntries[ii]->CertificateFormat() )
+            {
+            case EX509Certificate:
+                {
+                CCertManUICertData* data = new (ELeave) CCertManUICertData();
+                data->iPeerEntry = CCTCertInfo::NewL( *iPeerEntries[ii] );
+                CleanupStack::PushL( data );
+
+                CCertificate* cert;
+
+                TRAPD( err, iWrapper->GetCertificateL( CertManager(), *iPeerEntries[ii], cert, KCMTrustedServerTokenUid ));
+                if (( err == KErrArgument ) || ( err == KErrCorrupt ))
+                    {
+                    // This indicates that certificate is not according to X509
+                    // specification or it is corrupted. Ignore certificate
+                    if( data->iPeerEntry )
+                       {
+                       data->iPeerEntry->Release();
+                       }
+                    CleanupStack::PopAndDestroy( data ); // data
+                    continue;
+                    }
+                else
+                    {
+                    User::LeaveIfError( err );
+                    }
+
+                CleanupStack::PushL( cert );
+
+                TInt lenght = 0;
+
+                lenght += iPeerEntries[ii]->Label().Length();
+
+                HBufC* label = HBufC::NewL( lenght );
+                label->Des().Append( iPeerEntries[ii]->Label() );
+
+                data->iPeerEntryLabel = label;
+                iPeerLabelEntries.Append( data );
+
+                CleanupStack::PopAndDestroy( cert ); // cert
+                CleanupStack::Pop( data ); // data
+                break;
+                } // EX509Certificate
+
+            case EWTLSCertificate:
+                // Do nothing for wtls certificates
+                break;
+            default:
+                {
+                User::Leave( KErrNotSupported );
+                }
+            }   // switch
+
+        }   // for
+
+    // Sort the certificates.
+    TLinearOrder<CCertManUICertData> order( ComparePeerLabels );
+    iPeerLabelEntries.Sort( order );
+
+    CERTMANUILOGGER_LEAVEFN("CCertManUIKeeper::RefreshPeerEntriesL" );
+    }
+
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::RefreshDeviceCertEntriesL()
+// returns device certificates
+// ---------------------------------------------------------
+//
+void CCertManUIKeeper::RefreshDeviceCertEntriesL()
+    {
+    CERTMANUILOGGER_ENTERFN(
+        "CCertManUIKeeper::RefreshUserCertEntriesL" );
+
+    iFilter->SetOwnerType( EUserCertificate );
+    iDeviceEntries.Close();
+    CUnifiedCertStore*& store = CertManager();
+
+    iWrapper->ListL( store, &iDeviceEntries, *iFilter, KCMDeviceCertStoreTokenUid );
+
+    iDeviceLabelEntries.Close();
+    LOG_WRITE_FORMAT(" Device entries found %i", iDeviceEntries.Count());
+    for ( TInt i = 0; i < iDeviceEntries.Count(); i++ )
+        {
+        switch ( iDeviceEntries[i]->CertificateFormat() )
+            {
+            case EX509Certificate:
+                {
+                LOG_WRITE_FORMAT(" User X509 certificate, index %i", i);
+                CCertManUICertData* data = new (ELeave) CCertManUICertData();
+                data->iDeviceEntry = CCTCertInfo::NewL( *iDeviceEntries[i] );
+                CleanupStack::PushL( data );
+                HBufC* pri = NULL;
+                HBufC* sec = NULL;
+
+                CCertificate* cert = NULL;
+                TRAPD(error, iWrapper->GetCertificateL( CertManager(), *iDeviceEntries[i], cert, KCMDeviceCertStoreTokenUid ));
+
+                if( error == KErrArgument)
+                    {
+                    LOG_WRITE("Corrupted Device certificate detected");
+                    CleanupStack::PopAndDestroy( data );
+                    break;
+                    }
+                else if ( error != KErrNone )
+                    {
+                    LOG_WRITE_FORMAT(" GetCertificateL leaves, error code %i", error);
+                    User::Leave( error );
+                    }
+                else
+                    {
+                    CleanupStack::PushL( cert );
+                    }
+
+                X509CertNameParser::PrimaryAndSecondaryNameL
+                    ( *((CX509Certificate*)cert), pri, sec, iDeviceEntries[i]->Label());
+
+                CleanupStack::PushL( pri );
+                CleanupStack::PushL( sec );
+
+                TInt lenght = 0;
+
+                lenght += iDeviceEntries[i]->Label().Length();
+
+                if ( pri )
+                    {
+                    lenght += pri->Length();
+                    }
+                if ( sec && !(iDeviceEntries[i]->Label().Length()) )
+                    {
+                    lenght += sec->Length();
+                    }
+                lenght += KNameSeparator.iTypeLength;
+
+                HBufC* label = HBufC::NewL( lenght );
+                label->Des().Append( iDeviceEntries[i]->Label() );
+
+                if ( pri )
+                    {
+                    label->Des().Append( KNameSeparator );
+                    label->Des().Append( pri->Des() );
+                    }
+                if ( sec && !(iDeviceEntries[i]->Label().Length()) )
+                    {
+                    label->Des().Append( sec->Des() );
+                    }
+
+                data->iDeviceEntryLabel = label;
+                iDeviceLabelEntries.Append( data );
+
+                CleanupStack::PopAndDestroy( 3 ); // cert, pri, sec
+                CleanupStack::Pop( data ); // data
+                break;
+                } // EX509Certificate
+
+            case EX509CertificateUrl:
+                {
+                LOG_WRITE_FORMAT(" User X509URL certificate, index %i", i);
+                CCertManUICertData* urlCertData = new (ELeave) CCertManUICertData();
+                urlCertData->iDeviceEntry = CCTCertInfo::NewL( *iDeviceEntries[i] );
+                CleanupStack::PushL( urlCertData );
+
+                CCertificate* cert = NULL;
+                TRAPD(error, iWrapper->GetCertificateL( CertManager(), *iDeviceEntries[i], cert, KCMDeviceCertStoreTokenUid ));
+                if( error == KErrArgument)
+                    {
+                    LOG_WRITE("Corrupted user certificate detected");
+                    CleanupStack::PopAndDestroy( urlCertData ); // urlCertData
+                    break;
+                    }
+                else if ( error != KErrNone )
+                    {
+                    LOG_WRITE_FORMAT(" GetCertificateL leaves, error code %i", error);
+                    User::Leave(error);
+                    }
+                else
+                    {
+                    CleanupStack::PushL( cert );
+                    }
+
+
+                HBufC* UrlLabel = HBufC::NewL( 20 );
+                UrlLabel->Des().Append( _L("URL UserCert"));
+
+                urlCertData->iDeviceEntryLabel = UrlLabel;
+                iDeviceLabelEntries.Append( urlCertData );
+
+                CleanupStack::PopAndDestroy( cert ); // cert
+                CleanupStack::Pop( urlCertData ); // data
+                break;
+                }
+            default:
+                {
+                LOG_WRITE_FORMAT( "Unsupported certificate format 0x%x",
+                                        iDeviceEntries[i]->CertificateFormat() );
+                }
+            }   // switch
+
+        }   // for
+
+    // Sort the certificates.
+    TLinearOrder<CCertManUICertData> order( CompareDeviceLabels );
+    iDeviceLabelEntries.Sort( order );
+
+    CERTMANUILOGGER_LEAVEFN(
+        "CCertManUIKeeper::RefreshDeviceCertEntriesL" );
+    }
+
+
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::ShowErrorNoteL( TInt aError )
+// Shows error note
+// ---------------------------------------------------------
+//
+void CCertManUIKeeper::ShowErrorNoteL( TInt aError )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIKeeper::ShowErrorNoteL" );
+    // Make sure wait dialog isn't running
+    CloseWaitDialogL();
+    // Display error note
+    TInt resourceid(0);
+
+    switch ( aError )
+        {
+        case KErrCorrupt:
+            {
+            resourceid = R_ERROR_NOTE_TEXT_CACERTS_DB_CORRUPTED;
+            break;
+            }
+        case KErrCancel:
+            {
+            // Show nothing
+            break;
+            }
+         default:
+            {
+            resourceid = R_ERROR_NOTE_TEXT_INTERNAL_ERROR;
+            break;
+            }
+        }
+
+    if ( resourceid != 0 )
+        {
+        HBufC* string = StringLoader::LoadLC( resourceid );
+        CAknErrorNote* note = new ( ELeave ) CAknErrorNote( ETrue );
+        note->ExecuteLD( *string );
+        CleanupStack::PopAndDestroy();  // string
+        }
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIKeeper::ShowErrorNoteL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::StartWaitDialogL( TInt aDialogSelector )
+// Displays wait dialog
+// ---------------------------------------------------------
+//
+void CCertManUIKeeper::StartWaitDialogL( TInt aDialogSelector )
+    {
+    iCertmanUIDialog->StartWaitDialogL( aDialogSelector );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::CloseWaitDialogL( TInt aDialogSelector )
+// Closes wait dialog
+// ---------------------------------------------------------
+//
+void CCertManUIKeeper::CloseWaitDialogL()
+    {
+    iCertmanUIDialog->CloseWaitDialogL();
+    }
+
+//---------------------------------------------------------------
+// CCertManUIKeeper::ReadLocalVariationL
+// Reads local variation settings
+//---------------------------------------------------------------
+void CCertManUIKeeper::ReadLocalVariationL()
+    {
+    iLocalFeaturesMask |= KSecurityUIsNoNativeAppTrustSettingChange;
+    }
+
+//---------------------------------------------------------------
+// CCertManUIKeeper::IsLocalFeatureSupported
+// Check whether local variation setting is defined
+//---------------------------------------------------------------
+TBool CCertManUIKeeper::IsLocalFeatureSupported( const TInt aFeature ) const
+  {
+    return ( iLocalFeaturesMask & aFeature );
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuiPlugin.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,250 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIPlugin
+*
+*/
+
+
+// INCLUDE FILES
+#include <aknViewAppUi.h>
+#include <bautils.h>
+
+#include <certmanui.rsg>
+
+#include "CertmanuiKeeper.h"
+#include "Certmanuiviewid.h"
+#include "CertmanuiPlugin.h"
+#include "CertmanuiviewMain.h"
+#include "CertmanuiviewTrust.h"
+#include "CertmanuiviewPersonal.h"
+#include "CertmanuiviewDevice.h"
+#include "CertmanuiviewTrustedSite.h"
+#include "CertmanuicontainerAuthority.h"
+#include "CertmanuiPluginContainer.h"
+#include "StringLoader.h"
+
+
+// Constants
+_LIT( KResourceFile, "z:CertManUi.rsc" );
+
+// ========================= MEMBER FUNCTIONS ================================
+
+
+// ---------------------------------------------------------------------------
+// CCertManUIPlugin::CCertManUIPlugin()
+// Constructor
+//
+// ---------------------------------------------------------------------------
+//
+CCertManUIPlugin::CCertManUIPlugin():
+    iResourceLoader( *CCoeEnv::Static() ),
+    iPrevViewId()
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CCertManUIPlugin::~CCertManUIPlugin()
+// Destructor
+//
+// ---------------------------------------------------------------------------
+//
+CCertManUIPlugin::~CCertManUIPlugin()
+    {
+    iResourceLoader.Close();
+
+    if ( iContainer != NULL )
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainer );
+        }
+
+    delete iContainer;
+    delete iCertManUIKeeper;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CCertManUIPlugin::ConstructL(const TRect& aRect)
+// Symbian OS two-phased constructor
+//
+// ---------------------------------------------------------------------------
+//
+void CCertManUIPlugin::ConstructL()
+    {
+    BaseConstructL();
+
+    AddResourceFileL();
+
+    iCertManUIKeeper = new ( ELeave )CCertManUIKeeper();
+
+    iCertManUIInitialized = EFalse;
+
+    CCertManUIViewMain* viewMain =
+        CCertManUIViewMain::NewLC( ClientRect(), *iCertManUIKeeper );
+    AppUi()->AddViewL(viewMain);
+
+    CCertManUIViewAuthority* viewAuthority =
+        CCertManUIViewAuthority::NewLC( ClientRect(), *iCertManUIKeeper );
+    AppUi()->AddViewL(viewAuthority);
+
+    CCertManUIViewTrustedSite* viewTrustedSite =
+        CCertManUIViewTrustedSite::NewLC( ClientRect(), *iCertManUIKeeper );
+    AppUi()->AddViewL(viewTrustedSite);
+
+    CCertManUIViewPersonal* viewPersonal =
+        CCertManUIViewPersonal::NewLC( ClientRect(), *iCertManUIKeeper );
+    AppUi()->AddViewL(viewPersonal);
+
+    CCertManUIViewDevice* viewDevice =
+        CCertManUIViewDevice::NewLC( ClientRect(), *iCertManUIKeeper );
+    AppUi()->AddViewL(viewDevice);
+
+    CCertManUIViewTrust* viewTrust =
+        CCertManUIViewTrust::NewLC( ClientRect(), *iCertManUIKeeper );
+    AppUi()->AddViewL( viewTrust );
+
+    CleanupStack::Pop( 6 ); // viewMain, viewAuthority, viewTrustedSite, viewPersonal, viewDevice, viewTrust
+    }
+// ---------------------------------------------------------------------------
+// CCertManUIPlugin::NewL()
+// Static constructor
+//
+// ---------------------------------------------------------------------------
+//
+CCertManUIPlugin* CCertManUIPlugin::NewL( TAny* /*aInitParams*/ )
+    {
+    CCertManUIPlugin* self = new( ELeave ) CCertManUIPlugin();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CCertManUIPlugin::Id()
+//
+//
+// ---------------------------------------------------------------------------
+//
+TUid CCertManUIPlugin::Id() const
+    {
+    return KCertManUIPluginUid;
+    }
+
+
+// ---------------------------------------------------------
+// CCertManUIKeeper::AddResourceFileL()
+//
+// ---------------------------------------------------------
+//
+void CCertManUIPlugin::AddResourceFileL()
+    {
+    TFileName fileName;
+    TParse parse;
+    parse.Set( KResourceFile, &KDC_RESOURCE_FILES_DIR, NULL );
+
+    fileName = parse.FullName();
+    iResourceLoader.OpenL( fileName );
+    }
+
+
+// ---------------------------------------------------------
+// CApSettingsPlugin::HandleClientRectChange
+// ---------------------------------------------------------
+void CCertManUIPlugin::HandleClientRectChange()
+    {
+    if ( iContainer )
+        {
+        iContainer->SetRect( ClientRect() );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CCertManUIPlugin::DoActivateL()
+//
+//
+// ---------------------------------------------------------------------------
+//
+void CCertManUIPlugin::DoActivateL( const TVwsViewId& aPrevViewId,
+                                   TUid /*aCustomMessageId*/,
+                                   const TDesC8& /*aCustomMessage*/ )
+    {
+    if (iPrevViewId.iViewUid.iUid == 0)
+      {
+      // This is Security View
+      iPrevViewId = aPrevViewId;
+      }
+
+    if( iContainer )
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainer );
+        delete iContainer;
+        iContainer=NULL;
+        }
+
+    iContainer = new( ELeave ) CCertManUIPluginContainer;
+    iContainer->SetMopParent( this );
+    iContainer->ConstructL( ClientRect() );
+
+    AppUi()->AddToViewStackL( *this, iContainer );
+
+    if ( iPrevViewId != aPrevViewId )
+        {
+        // Activate parent view Security View
+        AppUi()->ActivateLocalViewL( iPrevViewId.iViewUid );
+        }
+    else
+        {
+        if (( iCertManUIKeeper != NULL ) && ( !iCertManUIInitialized ))
+            {
+            iCertManUIKeeper->InitializeL( ClientRect(), KCertManUIPluginUid );
+            iCertManUIInitialized = ETrue;
+            }
+
+        // Activate CertMan Authority view
+        AppUi()->ActivateLocalViewL( KCertManUIViewMainId );
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CCertManUIPlugin::DoDeactivate()
+//
+//
+// ---------------------------------------------------------------------------
+//
+void CCertManUIPlugin::DoDeactivate()
+    {
+    if( iContainer )
+       {
+       AppUi()->RemoveFromViewStack( *this, iContainer );
+       delete iContainer;
+       iContainer = NULL;
+       }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CCertManUIPlugin::GetCaptionL()
+//
+//
+// ---------------------------------------------------------------------------
+//
+void CCertManUIPlugin::GetCaptionL( TDes& aCaption ) const
+    {
+    StringLoader::Load( aCaption, R_GS_CERTMANUI_CAPTION  );
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuiPluginContainer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,83 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIPluginContainer
+*
+*/
+
+
+// INCLUDE FILES
+#include    "CertmanuiPluginContainer.h"
+
+// CONSTANTS
+
+// ========================= MEMBER FUNCTIONS ================================
+
+CCertManUIPluginContainer::CCertManUIPluginContainer()
+    {
+
+    }
+
+// ---------------------------------------------------------------------------
+// CCertManUIPluginContainer::ConstructL(const TRect& aRect)
+// Symbian OS two phased constructor
+//
+// ---------------------------------------------------------------------------
+//
+void CCertManUIPluginContainer::ConstructL( const TRect& aRect )
+    {
+    CreateWindowL();
+    SetRect( aRect );
+    ActivateL();
+    }
+
+// ---------------------------------------------------------------------------
+// CCertManUIPluginContainer::~CCertManUIPluginContainer()
+// Destructor
+//
+// ---------------------------------------------------------------------------
+//
+CCertManUIPluginContainer::~CCertManUIPluginContainer()
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// CCertManUIPluginContainer::SizeChanged
+//
+// ---------------------------------------------------------------------------
+//
+void CCertManUIPluginContainer::SizeChanged()
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// CCertManUIPluginContainer::CountComponentControls
+//
+// ---------------------------------------------------------------------------
+//
+TInt CCertManUIPluginContainer::CountComponentControls() const
+    {
+    return 0;
+    }
+
+// ---------------------------------------------------------------------------
+// CCertManUIPluginContainer::ComponentControl
+//
+// ---------------------------------------------------------------------------
+//
+CCoeControl* CCertManUIPluginContainer::ComponentControl( TInt /*aIndex*/ ) const
+    {
+    return NULL;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuiPluginImplementationTable.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   ECOM proxy table for CertManUI plugin
+*
+*/
+
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <ecom/implementationproxy.h>
+
+#include "CertmanuiPlugin.h"
+
+// Constants
+const TImplementationProxy KCertManUIPluginImplementationTable[] =
+    {
+    IMPLEMENTATION_PROXY_ENTRY( 0x10008D3D, CCertManUIPlugin::NewL )
+    };
+
+
+// ---------------------------------------------------------------------------
+// ImplementationGroupProxy
+// Gate/factory function
+//
+// ---------------------------------------------------------------------------
+//
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt& aTableCount )
+    {
+    aTableCount = sizeof( KCertManUIPluginImplementationTable )
+          / sizeof( TImplementationProxy );
+    return KCertManUIPluginImplementationTable;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuiSyncWrapper.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1012 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implements a synchronous wrapper for easier use of Symbian's
+*                Security Frameworks's API's.
+*
+*/
+
+
+// INCLUDE FILES
+#include <unifiedcertstore.h>
+#include <unifiedkeystore.h>
+#include <mctwritablecertstore.h>
+#include <x509cert.h>
+#include <pkixcertchain.h>
+#include "CertmanuiSyncWrapper.h"
+#include "CertmanuiCommon.h"
+#include "CertManUILogger.h"
+
+// CONSTANTS
+_LIT_SECURITY_POLICY_C1( KKeyStoreUsePolicy, ECapabilityReadUserData );
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::CCertManUISyncWrapper()
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CCertManUISyncWrapper::CCertManUISyncWrapper() : CActive( EPriorityStandard ), iCertPtr(0,0)
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::ConstructL()
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CCertManUISyncWrapper::ConstructL()
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CCertManUISyncWrapper* CCertManUISyncWrapper::NewLC()
+    {
+    CCertManUISyncWrapper* wrap = new ( ELeave ) CCertManUISyncWrapper();
+    CleanupStack::PushL( wrap );
+    wrap->ConstructL();
+    return wrap;
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CCertManUISyncWrapper* CCertManUISyncWrapper::NewL()
+    {
+    CCertManUISyncWrapper* wrap = CCertManUISyncWrapper::NewLC();
+    CleanupStack::Pop();
+    return wrap;
+    }
+
+// Destructor
+CCertManUISyncWrapper::~CCertManUISyncWrapper()
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::~CCertManUISyncWrapper()" );
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::~CCertManUISyncWrapper()" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::DoCancel
+// Cancels the ongoing operation if possible.
+// -----------------------------------------------------------------------------
+//
+void CCertManUISyncWrapper::DoCancel()
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::DoCancel" );
+
+    switch ( iOperation )
+        {
+        case EOperationInit:
+            {
+            LOG_WRITE( "CCertManUISyncWrapper::DoCancel EOperationInit" );
+            iStore->CancelInitialize();
+            break;
+            }
+        case EOperationList:
+            {
+            LOG_WRITE( "CCertManUISyncWrapper::DoCancel EOperationList" );
+            iStore->CancelList();
+            break;
+            }
+        case EGetCertificate:
+            {
+            LOG_WRITE( "CCertManUISyncWrapper::DoCancel EGetCertificate" );
+            iStore->CancelRetrieve();
+            break;
+            }
+        case EAddCertificate:
+            {
+            LOG_WRITE( "CCertManUISyncWrapper::DoCancel EAddCertificate" );
+            iStore->Cancel();
+            break;
+            }
+        case ERetriveURLCertificate:
+            {
+            LOG_WRITE(" CCertManUISyncWrapper::DoCancel ERetriveURLCertificate ");
+            iStore->CancelRetrieve();
+            break;
+            }
+        case EOperationDelete:
+            {
+            LOG_WRITE( "CCertManUISyncWrapper::DoCancel EOperationDelete" );
+            iStore->CancelRemove();
+            break;
+            }
+        case EOperationGetApps:
+            {
+            LOG_WRITE( "CCertManUISyncWrapper::DoCancel EOperationGetApps" );
+            iStore->CancelApplications();
+            break;
+            }
+        case EOperationValidateX509Root:
+            {
+            LOG_WRITE( "CCertManUISyncWrapper::DoCancel EOperationValidateX509Root" );
+            iChain->CancelValidate();
+            break;
+            }
+        case EShowErrorNote:
+            {
+            LOG_WRITE( "CCertManUISyncWrapper::DoCancel EShowErrorNote" );
+            break;
+            }
+        case EOperationInitKeyStore:
+            {
+            LOG_WRITE( "CCertManUISyncWrapper::DoCancel EOperationInitKeyStore" );
+            iKeyStore->CancelInitialize();
+            break;
+            }
+        case EOperationKeyList:
+            {
+            LOG_WRITE( "CCertManUISyncWrapper::DoCancel EOperationKeyList" );
+            iKeyStore->CancelList();
+            break;
+            }
+        case EOperationGetInterface:
+            {
+            LOG_WRITE( "CCertManUISyncWrapper::DoCancel EOperationGetInterface" );
+            iToken->CancelGetInterface();
+            break;
+            }
+        case EOperationExportKey:
+            {
+            LOG_WRITE( "CCertManUISyncWrapper::DoCancel EOperationExportKey" );
+            iKeyStore->CancelExportKey();
+            break;
+            }
+        case EOperationImportKey:
+            {
+            LOG_WRITE( "CCertManUISyncWrapper::DoCancel EOperationImportKey" );
+            iKeyStore->CancelImportKey();
+            break;
+            }
+        case EOperationDeleteKey:
+            {
+            LOG_WRITE( "CCertManUISyncWrapper::DoCancel EOperationDeleteKey" );
+            iKeyStore->CancelDeleteKey();
+            break;
+            }
+        default:
+            {
+            break;
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::DoCancel" );
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::InitStoreL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::InitStoreL( CUnifiedCertStore*& aStore )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::InitStoreL Certstore" );
+
+    aStore->Initialize( iStatus );
+    iOperation = EOperationInit;
+    iStore = aStore;
+    SetActive();
+    iWait.Start();
+    HandleErrorL();
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::InitStoreL Certstore" );
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::InitStoreL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::InitStoreL( CUnifiedKeyStore*& aStore  )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::InitStoreL Keystore" );
+
+    aStore->Initialize( iStatus );
+    iOperation = EOperationInitKeyStore;
+    iKeyStore = aStore;
+    SetActive();
+    iWait.Start();
+    HandleErrorL();
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::InitStoreL Keystore" );
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::ListL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::ListL(
+    CUnifiedCertStore*& aStore,
+    RMPointerArray<CCTCertInfo>* aArray,
+    const CCertAttributeFilter& aFilter )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::ListL 1" );
+
+    if ( IsActive() )
+        {
+        // Wrapper is active. Don't go further
+        return KErrGeneral;
+        }
+
+    aStore->List( *aArray, aFilter, iStatus );
+    iOperation = EOperationList;
+    iStore = aStore;
+    SetActive();
+    iWait.Start();
+    HandleErrorL();
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::ListL 1" );
+    return iStatus.Int();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::ListL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::ListL(
+    CUnifiedCertStore*& aStore,
+    RMPointerArray<CCTCertInfo>* aArray,
+    const CCertAttributeFilter& aFilter,
+    const TUid aTokenUid )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::ListL 2" );
+
+    TInt status( KErrNone );
+
+    if ( IsActive() )
+        {
+        // Wrapper is active. Don't go further
+        return KErrGeneral;
+        }
+
+    TInt count = aStore->CertStoreCount();
+    for ( TInt ii = 0; ii < count; ii++ )
+        {
+        MCTCertStore& certstore = aStore->CertStore( ii );
+        MCTToken& token = certstore.Token();
+        TUid tokenuid = token.Handle().iTokenTypeUid;
+        if ( tokenuid == aTokenUid )
+            {
+            certstore.List( *aArray, aFilter, iStatus );
+            iOperation = EOperationList;
+            iStore = aStore;
+            SetActive();
+            iWait.Start();
+            HandleErrorL();
+            status = iStatus.Int();
+            break;
+            }
+        }
+
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::ListL 2" );
+    return status;
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::ListL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::ListL(
+    CUnifiedKeyStore*& aStore,
+    RMPointerArray<CCTKeyInfo>* aArray,
+    const TCTKeyAttributeFilter& aFilter )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::ListL 3" );
+
+    if ( IsActive() )
+        {
+        // Wrapper is active. Don't go further
+        return KErrGeneral;
+        }
+
+    aStore->List( *aArray, aFilter, iStatus );
+    iOperation = EOperationKeyList;
+    iKeyStore = aStore;
+    SetActive();
+    iWait.Start();
+    HandleErrorL();
+
+    iOperation = EOperationNone;
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::ListL 3" );
+    return iStatus.Int();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::ListL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::ListL(
+    CUnifiedKeyStore*& aStore,
+    RMPointerArray<CCTKeyInfo>* aArray,
+    const TCTKeyAttributeFilter& aFilter,
+    const TUid aTokenUid )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::ListL 4" );
+
+    TInt status( KErrNone );
+
+    if ( IsActive() )
+        {
+        // Wrapper is active. Don't go further
+        return KErrGeneral;
+        }
+
+    TInt count = aStore->KeyStoreManagerCount();
+    for ( TInt ii = 0; ii < count; ii++ )
+        {
+        MCTKeyStoreManager& keystoremanager = aStore->KeyStoreManager( ii );
+        MCTToken& token = keystoremanager.Token();
+        TUid tokenuid = token.Handle().iTokenTypeUid;
+        if ( tokenuid == aTokenUid )
+            {
+            keystoremanager.List( *aArray, aFilter, iStatus );
+            iOperation = EOperationKeyList;
+            iKeyStore = aStore;
+            SetActive();
+            iWait.Start();
+            HandleErrorL();
+            status = iStatus.Int();
+            break;
+            }
+        }
+
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::ListL 4" );
+    return status;
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::GetCertificateL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::GetCertificateL(
+    CUnifiedCertStore*& aStore,
+    const CCTCertInfo& aCertInfo,
+    CCertificate*& aCert )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::GetCertificateL 1" );
+
+    aCert = NULL;
+    HBufC8* buf = HBufC8::NewLC( KMaxCertificateLength );
+    iCertPtr.Set( buf->Des() );
+    aStore->Retrieve( aCertInfo, iCertPtr, iStatus);
+    iOperation = EGetCertificate;
+    iStore = aStore;
+    SetActive();
+    iWait.Start();
+
+    if ( iStatus.Int() == KErrNone )
+        {
+        switch ( aCertInfo.CertificateFormat() )
+            {
+            case EX509Certificate:
+                {
+                aCert = CX509Certificate::NewL( iCertPtr );
+                break;
+                }
+            case EX509CertificateUrl:
+                {
+#ifdef  _CERTMANUI_LOG_
+                TPtrC8 dump = buf->Des();
+                LOG_HEXDUMP(dump);
+#endif
+                break;
+                }
+            default:
+                {
+                break;
+                }
+            }
+        }
+
+    CleanupStack::PopAndDestroy();  // buf
+    HandleErrorL();
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::GetCertificateL 1" );
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::GetUrlCertificateL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::GetUrlCertificateL(
+    CUnifiedCertStore*& aStore,
+    const CCTCertInfo& aCertInfo,
+    TDes8& aUrl )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::GetUrlCertificateL" );
+
+    aStore->Retrieve( aCertInfo, aUrl, iStatus);
+    iOperation = ERetriveURLCertificate;
+    iStore = aStore;
+    SetActive();
+    iWait.Start();
+    HandleErrorL();
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::GetUrlCertificateL" );
+    return iStatus.Int();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::GetCertificateL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::GetCertificateL( CUnifiedCertStore*& aStore,
+    const CCTCertInfo& aCertInfo,
+    CCertificate*& aCert,
+    TUid aTokenUid )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::GetCertificateL 2 " );
+
+    aCert = NULL;
+    TInt status( KErrNone );
+
+    HBufC8* buf = HBufC8::NewLC( KMaxCertificateLength );
+    iCertPtr.Set( buf->Des() );
+
+    TInt count = aStore->CertStoreCount();
+    for (TInt i = 0; i < count; i++)
+        {
+        MCTCertStore& certstore = aStore->CertStore( i );
+        MCTToken& token = certstore.Token();
+        TUid tokenuid = token.Handle().iTokenTypeUid;
+        if ( tokenuid == aTokenUid )
+            {
+            certstore.Retrieve( aCertInfo, iCertPtr, iStatus );
+            iOperation = EGetCertificate;
+            iStore = aStore;
+            SetActive();
+            iWait.Start();
+            HandleErrorL();
+            status = iStatus.Int();
+            break;
+            }
+        }
+
+    if ( status == KErrNone )
+        {
+        switch ( aCertInfo.CertificateFormat() )
+            {
+            case EX509Certificate:
+                {
+                aCert = CX509Certificate::NewL( iCertPtr );
+                break;
+                }
+            case EX509CertificateUrl:
+                {
+#ifdef  _CERTMANUI_LOG_
+                TPtrC8 dump = buf->Des();
+                LOG_HEXDUMP( dump );
+#endif
+                break;
+                }
+            default:
+                {
+                break;
+                }
+            }
+        }
+
+    CleanupStack::PopAndDestroy();  // buf
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::GetCertificateL 2" );
+    return status;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::DeleteCertL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::DeleteCertL( CUnifiedCertStore*& aStore,
+    const CCTCertInfo& aCertInfo )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::DeleteCertL 1" );
+
+    aStore->Remove( aCertInfo, iStatus );
+    iOperation = EOperationDelete;
+    iStore = aStore;
+    SetActive();
+    iWait.Start();
+    HandleErrorL();
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::DeleteCertL 1" );
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::DeleteCertL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::DeleteCertL( CUnifiedCertStore*& aStore,
+    const CCTCertInfo& aCertInfo,
+    TUid aTokenUid )
+    {
+    TInt status( KErrNone );
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::DeleteCertL 2" );
+
+    TInt count = aStore->WritableCertStoreCount();
+    for (TInt i = 0; i < count; i++)
+        {
+        MCTWritableCertStore& writablestore = aStore->WritableCertStore( i );
+        MCTToken& token = writablestore.Token();
+        TUid tokenuid = token.Handle().iTokenTypeUid;
+        if ( tokenuid == aTokenUid )
+            {
+            writablestore.Remove( aCertInfo, iStatus );
+            iOperation = EOperationDelete;
+            iStore = aStore;
+            SetActive();
+            iWait.Start();
+            HandleErrorL();
+            status = iStatus.Int();
+            break;
+            }
+        }
+
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::DeleteCertL 2" );
+    return status;
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::GetApplicationsL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::GetApplicationsL( CUnifiedCertStore*& aStore,
+    const CCTCertInfo& aCertInfo, RArray<TUid>& aApps )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::GetApplicationsL" );
+
+    aStore->Applications( aCertInfo, aApps, iStatus );
+    iOperation = EOperationGetApps;
+    iStore = aStore;
+    SetActive();
+    iWait.Start();
+    HandleErrorL();
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::GetApplicationsL" );
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::IsApplicableL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::IsApplicableL( CUnifiedCertStore*& aStore,
+    const CCTCertInfo& aCertInfo, TUid aApplication,
+    TBool& aIsApplicable )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::IsApplicableL" );
+
+    aStore->IsApplicable( aCertInfo, aApplication, aIsApplicable, iStatus );
+    iOperation = EOperationIsApplicable;
+    iStore = aStore;
+    SetActive();
+    iWait.Start();
+    HandleErrorL();
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::IsApplicableL" );
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::IsTrustedL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::IsTrustedL( CUnifiedCertStore*& aStore,
+    const CCTCertInfo& aCertInfo, TBool& aTrusted )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::IsTrustedL" );
+
+    aStore->Trusted( aCertInfo, aTrusted, iStatus );
+    iOperation = EOperationIsTrusted;
+    iStore = aStore;
+    SetActive();
+    iWait.Start();
+    HandleErrorL();
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::IsTrustedL" );
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::SetApplicabilityL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::SetApplicabilityL( CUnifiedCertStore*& aStore,
+    const CCTCertInfo& aCertInfo,
+    RArray<TUid>& aApplications )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::SetApplicabilityL" );
+
+    aStore->SetApplicability( aCertInfo, aApplications, iStatus );
+    iOperation = EOperationSetApplicability;
+    iStore = aStore;
+    SetActive();
+    iWait.Start();
+
+    if ( !(iStatus.Int()) )
+        {
+        aStore->SetTrust( aCertInfo, ETrue, iStatus );
+        iOperation = EOperationSetToTrusted;
+        SetActive();
+        iWait.Start();
+        }
+    HandleErrorL();
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::SetApplicabilityL" );
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::MoveKeyL
+// -----------------------------------------------------------------------------
+//
+void CCertManUISyncWrapper::MoveKeyL(
+    CUnifiedKeyStore*& aStore,
+    const TCTKeyAttributeFilter& aFilter,
+    const TUid aSourceTokenId,
+    const TUid aTargetTokenId )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::MoveKeyL" );
+
+    TInt sourceIndex(-1);
+    TInt targetIndex(-1);
+
+    // Find the index of key stores
+    TInt count = aStore->KeyStoreManagerCount();
+
+    for (TInt ii = 0; ii < count; ii++)
+        {
+        MCTKeyStoreManager& keystoremanager = aStore->KeyStoreManager( ii );
+        MCTToken& token = keystoremanager.Token();
+        TUid tokenuid = token.Handle().iTokenTypeUid;
+
+        if ( tokenuid == aSourceTokenId )
+            {
+            sourceIndex = ii;
+            }
+
+        if ( tokenuid == aTargetTokenId )
+            {
+            targetIndex = ii;
+            }
+        }
+
+    if (( sourceIndex == -1 ) || ( targetIndex == -1 ))
+        {
+        // Key store(s) doesn't exist
+        User::Leave( KErrNotFound );
+        }
+
+    RMPointerArray<CCTKeyInfo> keyEntries;
+
+    MCTKeyStoreManager& sourcekeystore =
+                            aStore->KeyStoreManager( sourceIndex );
+
+    MCTKeyStoreManager& targetkeystore =
+                            aStore->KeyStoreManager( targetIndex );
+
+
+    ListL( aStore, &keyEntries, aFilter, aSourceTokenId );
+
+    // Go through all matching keys and move them to
+    // target store
+    for ( TInt ii = 0; ii < keyEntries.Count(); ii++ )
+        {
+        HBufC8* keyData = HBufC8::NewLC( KMaxKeyLength );
+
+        // Retrieve key from source key store
+        sourcekeystore.ExportKey( (*keyEntries[ii]).Handle(), keyData, iStatus );
+        iOperation = EOperationExportKey;
+        SetActive();
+        iWait.Start();
+        User::LeaveIfError( iStatus.Int() );
+
+        TCTTokenObjectHandle sourceKeyHandle = (*keyEntries[ii]).Handle();
+
+        // Import key to target key store
+
+        // If key info access type indicates that key is local, then importing is
+        // not possible. The following is the workarround. Almost identical
+        // copy of keyinfo is created without CCTKeyInfo::ELocal access type flag.
+        // UsePolicy is also updated
+        TInt accessType = (*keyEntries[ii]).AccessType();
+        if ( accessType & CCTKeyInfo::ELocal )
+            {
+            // CCTKeyInfo::ELocal is set in key info
+            HBufC* label = (*keyEntries[ii]).Label().AllocLC();
+
+            // The following XOR operation will clear local bit if it is on.
+            accessType ^= CCTKeyInfo::ELocal;
+
+            CCTKeyInfo* keyInfo = CCTKeyInfo::NewL( (*keyEntries[ii]).ID(),
+                                (*keyEntries[ii]).Usage(),
+                                (*keyEntries[ii]).Size(),
+                                NULL,
+                                label,
+                                (*keyEntries[ii]).Token(),
+                                (*keyEntries[ii]).HandleID(),
+                                KKeyStoreUsePolicy,
+                                (*keyEntries[ii]).ManagementPolicy(),
+                                (*keyEntries[ii]).Algorithm(),
+                                accessType,
+                                (*keyEntries[ii]).Native(),
+                                (*keyEntries[ii]).StartDate(),
+                                (*keyEntries[ii]).EndDate() );
+
+            CleanupStack::Pop(label);
+            targetkeystore.ImportKey( *keyData, keyInfo, iStatus );
+            }
+        else
+            {
+            targetkeystore.ImportKey( *keyData, keyEntries[ii], iStatus );
+            }
+
+        iOperation = EOperationImportKey;
+        SetActive();
+        iWait.Start();
+        User::LeaveIfError( iStatus.Int() );
+
+        // Delete key from source key store
+        sourcekeystore.DeleteKey( sourceKeyHandle, iStatus );
+        iOperation = EOperationDeleteKey;
+        SetActive();
+        iWait.Start();
+        User::LeaveIfError( iStatus.Int() );
+
+        CleanupStack::PopAndDestroy();  // keyData
+        }
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::MoveKeyL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::MoveCertL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::MoveCertL(
+    CUnifiedCertStore*& aStore,
+    const CCTCertInfo& aCertInfo,
+    const TUid aSourceTokenId,
+    const TUid aTargetTokenId )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::MoveCertL" );
+
+    TInt sourceIndex(-1);
+    TInt targetIndex(-1);
+    TInt certCount (0);
+
+    // Find the index of certificate stores
+    TInt count = aStore->WritableCertStoreCount();
+    for (TInt ii = 0; ii < count; ii++)
+        {
+        MCTWritableCertStore& writablestore = aStore->WritableCertStore( ii );
+        MCTToken& token = writablestore.Token();
+        TUid tokenuid = token.Handle().iTokenTypeUid;
+
+        if ( tokenuid == aSourceTokenId )
+            {
+            sourceIndex = ii;
+            }
+
+        if ( tokenuid == aTargetTokenId )
+            {
+            targetIndex = ii;
+            }
+        }
+
+    if (( sourceIndex == -1 ) || ( targetIndex == -1 ))
+        {
+        // Certificate store(s) doesn't exist
+        User::Leave( KErrNotFound );
+        }
+
+
+    MCTWritableCertStore& sourcewritablestore =
+                    aStore->WritableCertStore( sourceIndex );
+
+    // All of the certificates that are associated with same
+    // private key will be moved to target certificate store.
+    CCertAttributeFilter* filter = CCertAttributeFilter::NewL();
+    filter->SetOwnerType( EUserCertificate );
+    filter->SetSubjectKeyId( aCertInfo.SubjectKeyId() );
+    RMPointerArray<CCTCertInfo> certEntries;
+
+    // List certificates from source certificate store
+    ListL( aStore, &certEntries, *filter, aSourceTokenId );
+
+    delete filter;
+
+    for ( TInt ii = 0; ii < certEntries.Count(); ii++ )
+        {
+        // Retrieve certificate from source certificate store
+        HBufC8* buf = HBufC8::NewLC( KMaxCertificateLength );
+        iCertPtr.Set( buf->Des() );
+        sourcewritablestore.Retrieve( *certEntries[ii], iCertPtr, iStatus );
+        iOperation = EGetCertificate;
+        SetActive();
+        iWait.Start();
+        User::LeaveIfError( iStatus.Int() );
+
+        // Add certificate to target certificate store
+        MCTWritableCertStore& targetwritablestore =
+                        aStore->WritableCertStore( targetIndex );
+
+        targetwritablestore.Add( (*certEntries[ii]).Label(), EX509Certificate,
+                      EUserCertificate, &((*certEntries[ii]).SubjectKeyId()),
+                      &((*certEntries[ii]).IssuerKeyId()), *buf, iStatus );
+
+        iOperation = EAddCertificate;
+        SetActive();
+        iWait.Start();
+        User::LeaveIfError( iStatus.Int() );
+
+        // Delete certificate from source certificate store
+        sourcewritablestore.Remove( *certEntries[ii], iStatus );
+        iOperation = EOperationDelete;
+        iStore = aStore;
+        SetActive();
+        iWait.Start();
+        HandleErrorL();
+        iOperation = EOperationNone;
+        User::LeaveIfError( iStatus.Int() );
+        certCount++;
+
+        CleanupStack::PopAndDestroy();  // buf
+        }
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::MoveCertL" );
+    return certCount;
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::ValidateX509RootCertificateL
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::ValidateX509RootCertificateL(
+    CPKIXValidationResult*& aValidationResult,
+    const TTime& aValidationTime, CPKIXCertChain* aChain )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::ValidateX509RootCertificateL" );
+
+    aChain->ValidateL( *aValidationResult, aValidationTime, iStatus );
+    iOperation = EOperationValidateX509Root;
+    iChain = aChain;
+    SetActive();
+    iWait.Start();
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::ValidateX509RootCertificateL" );
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::GetInterface
+// -----------------------------------------------------------------------------
+//
+TInt CCertManUISyncWrapper::GetInterface(
+    TUid aRequiredInterface, MCTToken& aToken,
+    MCTTokenInterface*& aReturnedInterface)
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::GetInterface" );
+
+    iToken = &aToken;
+    aToken.GetInterface( aRequiredInterface, aReturnedInterface, iStatus );
+    iOperation = EOperationGetInterface;
+    SetActive();
+    iWait.Start();
+    iOperation = EOperationNone;
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::GetInterface" );
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::RunL
+// If no errors happened, stop. Show an error note if needed.
+// -----------------------------------------------------------------------------
+//
+
+void CCertManUISyncWrapper::RunL()
+    {
+    CERTMANUILOGGER_ENTERFN("CCertManUISyncWrapper::RunL");
+
+    if ( iWait.IsStarted() )
+        {
+        iWait.AsyncStop();
+        }
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::RunL" );
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUISyncWrapper::HandleErrorL
+// Shows an error note according to status of operation,
+// -----------------------------------------------------------------------------
+//
+void CCertManUISyncWrapper::HandleErrorL()
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUISyncWrapper::HandleErrorL" );
+
+    TInt status = iStatus.Int();
+    switch ( status )
+        {
+        case KErrNone:
+            {
+            LOG_WRITE( "No error" );
+            break;
+            }
+        case KErrCancel:
+            {
+            LOG_WRITE( "HandleErrorL : KErrCancel" );
+            // Up to caller decide if note is needed. No error note shown.
+            break;
+            }
+        case KErrNoMemory:
+        case KErrBadHandle:
+        case KErrAlreadyExists:
+        case KErrNotSupported:
+        case EShowErrorNote:
+            {
+            LOG_WRITE_FORMAT( "HandleErrorL LEAVE : error code %i", status );
+            User::Leave( iStatus.Int() );
+            break;
+            }
+        default:
+            {
+            LOG_WRITE_FORMAT( "HandleErrorL LEAVE (default) : error code %i", status );
+            break;
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUISyncWrapper::HandleErrorL" );
+    }
+
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuicontainerAuthority.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,480 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIContainerAuthority
+*                Reads & updates certificate list
+*                Handles markable list for certificates
+*
+*/
+
+
+// INCLUDE FILES
+#include <eikclbd.h>
+#include <AknIconArray.h>
+#include <certmanui.rsg>
+#include <csxhelp/cm.hlp.hrh>    // for help context of CertManUI
+
+#include "CertmanuiCertificateHelper.h"
+#include "CertmanuiKeeper.h"
+#include "CertmanuicontainerAuthority.h"
+#include "CertmanuiSyncWrapper.h"
+#include "Certmanui.hrh"
+#include "CertManUILogger.h"
+#include "CertmanuiCommon.h"
+#include "Certmanuidll.h"        // for applicationUID
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::CCertManUIContainerAuthority(
+// CCertManUIViewAuthority& aParent, CCertManUIKeeper& aKeeper )
+// Constructor with parent
+// ---------------------------------------------------------
+//
+CCertManUIContainerAuthority::CCertManUIContainerAuthority(
+    CCertManUIViewAuthority& aParent, CCertManUIKeeper& aKeeper ) :
+    iParent ( aParent ), iKeeper ( aKeeper )
+    {
+    CERTMANUILOGGER_WRITE_TIMESTAMP(
+        "CCertManUIContainerAuthority::CCertManUIContainerAuthority" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::~CCertManUIContainerAuthority()
+// Destructor
+// ---------------------------------------------------------
+//
+CCertManUIContainerAuthority::~CCertManUIContainerAuthority()
+    {
+    CERTMANUILOGGER_ENTERFN(
+        " CCertManUIContainerAuthority::~CCertManUIContainerAuthority" );
+
+    delete iListBox;
+
+    CERTMANUILOGGER_LEAVEFN(
+        " CCertManUIContainerAuthority::~CCertManUIContainerAuthority" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::ConstructL(
+// const TRect& aRect, TInt& aCurrentPosition, TInt& aTopItem)
+// EPOC two phased constructor
+// ---------------------------------------------------------
+//
+void CCertManUIContainerAuthority::ConstructL(
+    const TRect& aRect, TInt& aCurrentPosition, TInt& aTopItem )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerAuthority::ConstructL" );
+
+    CreateWindowL();
+    CreateListBoxL();
+    UpdateListBoxL( aCurrentPosition, aTopItem );
+    if ( iListBox )
+        {
+        // Creates graphic.
+        iListBox->ItemDrawer()->ColumnData()->
+            SetIconArray( iIconHandler->CreateIconArrayL() );
+        }
+    SetRect( aRect );
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerAuthority::ConstructL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::SizeChanged()
+// Called by framework when the view size is changed
+// ---------------------------------------------------------
+//
+void CCertManUIContainerAuthority::SizeChanged()
+    {
+    iListBox->SetRect( Rect() );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::FocusChanged( TDrawNow aDrawNow )
+// ---------------------------------------------------------
+//
+void CCertManUIContainerAuthority::FocusChanged( TDrawNow aDrawNow )
+    {
+    if ( iListBox )
+        {
+        iListBox->SetFocus( IsFocused(), aDrawNow );
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::HandleListBoxEventL(
+// CEikListBox* /*aListBox*/, TListBoxEvent aEventType)
+// ---------------------------------------------------------
+//
+void CCertManUIContainerAuthority::HandleListBoxEventL(
+    CEikListBox* /*aListBox*/, TListBoxEvent aEventType )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerAuthority::HandleListBoxEventL" );
+
+    switch  ( aEventType )
+        {
+        case EEventItemDoubleClicked:
+        case EEventItemSingleClicked:
+        case EEventEnterKeyPressed:
+            {
+            const CListBoxView::CSelectionIndexArray* selections = iListBox->SelectionIndexes();
+            if ( iListItemCount > 0 )
+                {
+                TInt currentItemIndex = iListBox->CurrentItemIndex();
+                if ( selections->Count() == 0 )
+                    {
+                    iKeeper.iCertificateHelper->MessageQueryViewDetailsL(
+                          currentItemIndex, KCertTypeAuthority, iEikonEnv );
+                    }
+                else
+                    {
+                    CEikMenuBar* menuBar = iParent.MenuBar();
+                    menuBar->SetContextMenuTitleResourceId( R_CERTMANUI_MENUBAR_OPTIONS_MARKED );
+                    menuBar->TryDisplayContextMenuBarL();
+                    }
+                }
+              break;
+              }
+
+        default:
+              {
+              break;
+              }
+          }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerAuthority::HandleListBoxEventL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::CountComponentControls() const
+// ---------------------------------------------------------
+//
+TInt CCertManUIContainerAuthority::CountComponentControls() const
+    {
+    // return number of controls inside this container
+    return 1;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::ComponentControl(
+// TInt /*aIndex*/) const
+// ---------------------------------------------------------
+//
+CCoeControl* CCertManUIContainerAuthority::ComponentControl(
+    TInt /*aIndex*/) const
+    {
+    return iListBox;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::Draw(const TRect& aRect) const
+// ---------------------------------------------------------
+//
+void CCertManUIContainerAuthority::Draw( const TRect& aRect ) const
+    {
+    CWindowGc& gc = SystemGc();
+    gc.SetPenStyle( CGraphicsContext::ENullPen );
+    gc.SetBrushColor( KRgbGray );
+    gc.SetBrushStyle( CGraphicsContext::ESolidBrush );
+    gc.DrawRect( aRect );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::HandleControlEventL(
+//    CCoeControl* /*aControl*/,TCoeEvent /*aEventType*/)
+// Cannot be changed to non-leaving function.
+// L-function is required by the class definition, even if empty.
+// ---------------------------------------------------------
+//
+void CCertManUIContainerAuthority::HandleControlEventL(
+    CCoeControl* /*aControl*/,TCoeEvent /*aEventType*/)
+    {
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::OfferKeyEventL(
+// const TKeyEvent& aKeyEvent, TEventCode aType)
+// Handles the key events arrow keys, delete key.
+// ---------------------------------------------------------
+//
+TKeyResponse CCertManUIContainerAuthority::OfferKeyEventL(
+    const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerAuthority::OfferKeyEventL" );
+
+    // If operation is currenly onway, do not continue.
+    if ( iKeeper.iWrapper->IsActive() )
+        {
+        return EKeyWasNotConsumed;
+        }
+
+    TKeyResponse retval = EKeyWasNotConsumed;
+    if ( aType==EEventKey )
+        {
+        if ( aKeyEvent.iCode == EKeyRightArrow )
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL(
+                                      KCertManUIViewTrustedSiteId );
+            retval = EKeyWasConsumed;
+            }
+      else if ( aKeyEvent.iCode == EKeyLeftArrow )
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL(
+                                            KCertManUIViewDeviceId );
+            retval = EKeyWasConsumed;
+            }
+      else if ( aKeyEvent.iCode == EKeyDelete
+                  || aKeyEvent.iCode == EKeyBackspace )
+            {
+            TInt currentItemAuthority = iListBox->CurrentItemIndex();
+
+            if ( ( currentItemAuthority >= 0 ) &&
+                ( currentItemAuthority < iKeeper.iCALabelEntries.Count()))
+                {
+                // list is not empty
+                if ( iKeeper.iCertificateHelper->ConfirmationQueryDeleteCertL(
+                                               KCertTypeAuthority, iListBox ) ) // == ETrue
+                    {
+
+                    iParent.iCurrentPosition = iListBox->CurrentItemIndex();
+                    iParent.iTopItem = iListBox->TopItemIndex();
+
+                    DrawListBoxL(iParent.iCurrentPosition, iParent.iTopItem );
+                    // goes here if at least one certificate is deleted
+                    TRAPD( error, iKeeper.RefreshCAEntriesL() );
+                    if ( error != KErrNone )
+                        {
+                        if ( error == KErrCorrupt )
+                            {
+                            iKeeper.ShowErrorNoteL( error );
+                            User::Exit( KErrNone );
+                            }
+                        else
+                            {
+                            // have to call straight away the Exit
+                            // showing any error notes would corrupt the display
+                            User::Exit( error );
+                            }
+                        }
+                      iParent.UpdateMenuBar();
+                      }
+                    }
+                // Listbox takes all event even if it doesn't use them
+                retval = EKeyWasConsumed;
+            }
+      else
+          {
+          retval = iListBox->OfferKeyEventL( aKeyEvent, aType );
+          }
+
+        }
+    else
+        {
+        retval = iListBox->OfferKeyEventL( aKeyEvent, aType );
+        }
+
+    if ( iListBox->SelectionIndexes()->Count() > 0 )
+        {
+        iParent.MenuBar()->SetContextMenuTitleResourceId(
+                                          R_CERTMANUI_MENUBAR_OPTIONS_MARKED );
+        iParent.UpdateCba( R_CERTMANUI_OPTIONS_CONTEXT_BACK );
+        }
+    else
+        {
+        iParent.MenuBar()->SetMenuTitleResourceId( R_CERTMANUI_MENUBAR_VIEW_AUTHORITY );
+        iParent.UpdateCba( R_CERTMANUI_OPTIONS_OPEN_BACK );
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerAuthority::OfferKeyEventL" );
+
+    return retval;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::CreateListBoxL()
+// Creates listbox, sets empty listbox text.
+// ---------------------------------------------------------
+//
+void CCertManUIContainerAuthority::CreateListBoxL()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerAuthority::CreateListBoxL()" );
+
+    iListBox = new( ELeave ) CAknSingleStyleListBox;
+    iListBox->SetContainerWindowL( *this );
+    iListBox->ConstructL( this, EAknListBoxMarkableList );
+    iListBox->CreateScrollBarFrameL( ETrue );
+    iListBox->ScrollBarFrame()->
+        SetScrollBarVisibilityL( CEikScrollBarFrame::EOff,CEikScrollBarFrame::EAuto );
+    iListBox->SetListBoxObserver( this );
+
+    HBufC* stringHolder = StringLoader::LoadLC(
+        R_TEXT_RESOURCE_VIEW_AUTHORITY_EMPTY_LIST );
+    iListBox->View()->SetListEmptyTextL( *stringHolder );
+    CleanupStack::PopAndDestroy();  // stringHolder
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerAuthority::CreateListBoxL()" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::DrawListBoxL(TInt aCurrentPosition, TInt aTopItem)
+// Draws listbox, fetches graphic icons for markable list
+// ---------------------------------------------------------
+//
+void CCertManUIContainerAuthority::DrawListBoxL(
+    TInt aCurrentPosition, TInt aTopItem )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerAuthority::DrawListBoxL" );
+
+    if ( aCurrentPosition >= 0 )
+        {
+        iListBox->SetTopItemIndex( aTopItem );
+        iListBox->SetCurrentItemIndex( aCurrentPosition );
+        }
+
+    ActivateL();
+    DrawNow();
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerAuthority::DrawListBoxL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::UpdateListBoxL(TInt& aCurrentPosition, TInt& aTopItem)
+// Gets list of certificates from CertManAPI, displays them,
+// sets No label/No subject text to them if their names are empty
+// ---------------------------------------------------------
+//
+void CCertManUIContainerAuthority::UpdateListBoxL(
+    TInt& aCurrentPosition, TInt& aTopItem )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerAuthority::UpdateListBoxL()" );
+
+    iKeeper.StartWaitDialogL( ECertmanUiWaitDialog );
+    CleanupCloseWaitDialogPushL( iKeeper );
+
+    MDesCArray* itemList = iListBox->Model()->ItemTextArray();
+    CDesCArray* itemArray = ( CDesCArray* )itemList;
+
+    // List CA certificates
+    if ( iKeeper.iCertsDatOK )  // == ETrue
+        {
+        // cacerts.dat is not corrupted, get count
+        iListItemCount = iKeeper.iCALabelEntries.Count();
+        }
+    else
+        {
+        iListItemCount = 0;
+        }
+    if (iListItemCount == 0 ) //list is empty, disable the scroll bar 
+        {
+    	iListBox->ScrollBarFrame()->SetScrollBarVisibilityL(
+	        CEikScrollBarFrame::EOff,CEikScrollBarFrame::EOff);
+        }
+    if ( iListItemCount > 0 )
+        {
+        if ( ( aCurrentPosition == -1 )
+            || ( aCurrentPosition > iListItemCount-1 ) )
+            {
+            aCurrentPosition = 0;
+            aTopItem = 0;
+            }
+
+        HBufC* buf = HBufC::NewLC( KMaxLengthTextCertLabel );
+        for ( TInt i = 0; i < iListItemCount; i++ )
+              {
+              buf->Des() = ( iKeeper.iCALabelEntries )[i]->iCAEntryLabel->Des();
+
+              TPtrC trimmedCertLabel = iKeeper.iCertificateHelper->CutCertificateField( buf->Des() );
+              buf->Des().Copy( trimmedCertLabel );
+              TInt length = buf->Des().Length();
+              if ( length == 0 )
+                  {
+                  HBufC* stringHolder = NULL;
+
+                  stringHolder = StringLoader::LoadLC(
+                           R_TEXT_RESOURCE_VIEW_NO_SUBJECT_LIST );
+
+                  itemArray->AppendL( *stringHolder );
+                  CleanupStack::PopAndDestroy();  // stringHolder
+                  }
+              else
+                  {
+                  buf->Des().Insert(0, KCertManUIInsertDescriptor);
+                  itemArray->AppendL(buf->Des());
+                  }
+              iListBox->HandleItemAdditionL();
+              }
+              CleanupStack::PopAndDestroy();  // buf
+          }
+
+    CleanupStack::PopAndDestroy();    // closes wait dialog
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerAuthority::UpdateListBoxL()" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::HandleResourceChange
+//
+// ---------------------------------------------------------
+//
+void CCertManUIContainerAuthority::HandleResourceChange( TInt aType )
+    {
+    CCoeControl::HandleResourceChange( aType );
+
+    if ( aType == KEikDynamicLayoutVariantSwitch )
+        {
+        TRect mainPaneRect;
+        AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::EMainPane, mainPaneRect );
+        SetRect( mainPaneRect );
+        DrawNow();
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::IconArrayResourceId
+// Loads Mark/Unmark icons from resource
+// ---------------------------------------------------------
+//
+TInt CCertManUIContainerAuthority::IconArrayResourceId() const
+    {
+    return R_CERTMANUI_CERTIFICATE_LISTBOX_MARK_ICONS;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::CreateIconArrayL
+// Creates Icon Array
+// ---------------------------------------------------------
+//
+CAknIconArray* CCertManUIContainerAuthority::CreateIconArrayL() const
+    {
+    CAknIconArray* icons = new (ELeave) CAknIconArray( KGranularity );
+    CleanupStack::PushL( icons );
+    icons->ConstructFromResourceL( IconArrayResourceId() );
+    CleanupStack::Pop(); // icons
+    return icons;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::GetHelpContext
+// This function is called when Help application is launched.
+// (other items were commented in a header).
+// ---------------------------------------------------------
+//
+void CCertManUIContainerAuthority::GetHelpContext(
+    TCoeHelpContext& aContext ) const
+    {
+    aContext.iMajor = KUidCM;
+    aContext.iContext = KCM_HLP_AUTHORITY;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuicontainerDevice.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,474 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIContainerDevice
+*                Reads & updates certificate list
+*                Handles markable list for certificates
+*
+*/
+
+
+// INCLUDE FILES
+#include <eikclbd.h>
+#include <AknIconArray.h>
+#include <certmanui.rsg>
+#include <csxhelp/cm.hlp.hrh>   // for help context of CertManUI
+
+#include "CertmanuiCertificateHelper.h"
+#include "CertmanuiKeeper.h"
+#include "CertmanuicontainerDevice.h"
+#include "CertmanuiSyncWrapper.h"
+#include "Certmanui.hrh"
+#include "CertManUILogger.h"
+#include "CertmanuiCommon.h"
+
+#include "Certmanuidll.h"       // for applicationUID
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::CCertManUIContainerDevice(
+// CCertManUIViewAuthority& aParent, CCertManUIKeeper& aKeeper)
+// Constructor with parent
+// ---------------------------------------------------------
+//
+CCertManUIContainerDevice::CCertManUIContainerDevice(
+    CCertManUIViewDevice& aParent, CCertManUIKeeper& aKeeper ) :
+    iParent ( aParent ), iKeeper ( aKeeper )
+    {
+    CERTMANUILOGGER_WRITE_TIMESTAMP(
+        "CCertManUIContainerDevice::CCertManUIContainerDevice" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::~CCertManUIContainerDevice()
+// Destructor
+// ---------------------------------------------------------
+//
+CCertManUIContainerDevice::~CCertManUIContainerDevice()
+    {
+    CERTMANUILOGGER_ENTERFN(
+        " CCertManUIContainerDevice::~CCertManUIContainerDevice" );
+
+    delete iListBox;
+
+    CERTMANUILOGGER_LEAVEFN(
+        " CCertManUIContainerDevice::~CCertManUIContainerDevice" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::ConstructL(
+// const TRect& aRect, TInt& aCurrentPosition, TInt& aTopItem)
+// EPOC two phased constructor
+// ---------------------------------------------------------
+//
+void CCertManUIContainerDevice::ConstructL(
+    const TRect& aRect, TInt& aCurrentPosition, TInt& aTopItem )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerDevice::ConstructL" );
+
+    CreateWindowL();
+    CreateListBoxL();
+    UpdateListBoxL( aCurrentPosition, aTopItem );
+
+    if ( iListBox )
+        {
+        // Creates graphic.
+        iListBox->ItemDrawer()->ColumnData()->
+        SetIconArray( iIconHandler->CreateIconArrayL() );
+    }
+
+    SetRect( aRect );
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerDevice::ConstructL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::SizeChanged()
+// Called by framework when the view size is changed
+// ---------------------------------------------------------
+//
+void CCertManUIContainerDevice::SizeChanged()
+    {
+    iListBox->SetRect( Rect() );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::FocusChanged(TDrawNow aDrawNow)
+// ---------------------------------------------------------
+//
+void CCertManUIContainerDevice::FocusChanged( TDrawNow aDrawNow )
+    {
+    if ( iListBox )
+        {
+        iListBox->SetFocus( IsFocused(), aDrawNow );
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::HandleListBoxEventL(
+// CEikListBox* /*aListBox*/, TListBoxEvent aEventType)
+// ---------------------------------------------------------
+//
+void CCertManUIContainerDevice::HandleListBoxEventL(
+    CEikListBox* /*aListBox*/, TListBoxEvent aEventType )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerDevice::HandleListBoxEventL" );
+
+    switch ( aEventType )
+         {
+         case EEventItemSingleClicked:
+         case EEventEnterKeyPressed:
+             {
+             const CListBoxView::CSelectionIndexArray* selections = iListBox->SelectionIndexes();
+             if ( iListItemCount > 0 )
+                 {
+                 if ( selections->Count() == 0 )
+                     {
+                     iKeeper.iCertificateHelper->MessageQueryViewDetailsL(
+                             iListBox->CurrentItemIndex(), KCertTypeDevice, iEikonEnv );
+                     }
+                 else
+                     {
+                     CEikMenuBar* menuBar = iParent.MenuBar();
+                     menuBar->SetContextMenuTitleResourceId( R_CERTMANUI_MENUBAR_OPTIONS_MARKED );
+                     menuBar->TryDisplayContextMenuBarL();
+                     }
+                 }
+             break;
+             }
+
+        default:
+             {
+             break;
+             }
+         }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerDevice::HandleListBoxEventL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::CountComponentControls() const
+// ---------------------------------------------------------
+//
+TInt CCertManUIContainerDevice::CountComponentControls() const
+    {
+    // return number of controls inside this container
+    return 1;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::ComponentControl(
+// TInt /*aIndex*/) const
+// ---------------------------------------------------------
+//
+CCoeControl* CCertManUIContainerDevice::ComponentControl(
+    TInt /*aIndex*/) const
+    {
+    return iListBox;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::Draw(const TRect& aRect) const
+// ---------------------------------------------------------
+//
+void CCertManUIContainerDevice::Draw( const TRect& aRect ) const
+    {
+    CWindowGc& gc = SystemGc();
+    gc.SetPenStyle( CGraphicsContext::ENullPen );
+    gc.SetBrushColor( KRgbGray );
+    gc.SetBrushStyle( CGraphicsContext::ESolidBrush );
+    gc.DrawRect( aRect );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::HandleControlEventL(
+//    CCoeControl* /*aControl*/,TCoeEvent /*aEventType*/)
+// Cannot be changed to non-leaving function.
+// L-function is required by the class definition, even if empty.
+// ---------------------------------------------------------
+//
+void CCertManUIContainerDevice::HandleControlEventL(
+    CCoeControl* /*aControl*/,TCoeEvent /*aEventType*/)
+    {
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::OfferKeyEventL(
+// const TKeyEvent& aKeyEvent, TEventCode aType)
+// Handles the key events arrow keys, delete key.
+// ---------------------------------------------------------
+//
+TKeyResponse CCertManUIContainerDevice::OfferKeyEventL(
+    const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerDevice::OfferKeyEventL" );
+
+    // If operation is currenly onway, do not continue.
+    if ( iKeeper.iWrapper->IsActive() )
+        {
+        return EKeyWasNotConsumed;
+        }
+
+    TKeyResponse retval = EKeyWasNotConsumed;
+    if ( aType==EEventKey )
+        {
+        if ( aKeyEvent.iCode == EKeyRightArrow )
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL( KCertManUIViewAuthorityId );
+            retval = EKeyWasConsumed;
+            }
+        else if ( aKeyEvent.iCode == EKeyLeftArrow )
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL( KCertManUIViewPersonalId );
+            retval = EKeyWasConsumed;
+            }
+        else if ( aKeyEvent.iCode == EKeyDelete
+                  || aKeyEvent.iCode == EKeyBackspace )
+            {
+            TInt currentItemAuthority = iListBox->CurrentItemIndex();
+
+            if ((currentItemAuthority >= 0) &&
+                ( currentItemAuthority < iKeeper.iDeviceLabelEntries.Count()))
+                {
+                // list is not empty
+                if ( iKeeper.iCertificateHelper->ConfirmationQueryDeleteCertL(
+                                               KCertTypeDevice, iListBox ) ) // == ETrue
+                    {
+                    iParent.iCurrentPosition = iListBox->CurrentItemIndex();
+                    iParent.iTopItem = iListBox->TopItemIndex();
+
+                    DrawListBoxL(iParent.iCurrentPosition, iParent.iTopItem );
+                    // goes here if at least one certificate is deleted
+                    TRAPD( error, iKeeper.RefreshDeviceCertEntriesL() );
+                    if ( error != KErrNone )
+                        {
+                        if ( error == KErrCorrupt )
+                            {
+                            iKeeper.ShowErrorNoteL( error );
+                            User::Exit( KErrNone );
+                            }
+                        else
+                            {
+                            // have to call straight away the Exit
+                            // showing any error notes would corrupt the display
+                            User::Exit( error );
+                            }
+                        }
+                    iParent.UpdateMenuBar();
+                    }
+                }
+            // Listbox takes all event even if it doesn't use them
+            retval = EKeyWasConsumed;
+            }
+        else
+            {
+            retval = iListBox->OfferKeyEventL( aKeyEvent, aType );
+            }
+        }
+    else
+        {
+        retval = iListBox->OfferKeyEventL( aKeyEvent, aType );
+        }
+
+    if ( iListBox->SelectionIndexes()->Count() > 0 )
+        {
+        iParent.MenuBar()->SetContextMenuTitleResourceId( R_CERTMANUI_MENUBAR_OPTIONS_MARKED );
+        iParent.UpdateCba( R_CERTMANUI_OPTIONS_CONTEXT_BACK );
+        }
+    else
+        {
+        iParent.MenuBar()->SetMenuTitleResourceId( R_CERTMANUI_MENUBAR_VIEW_DEVICE );
+        iParent.UpdateCba( R_CERTMANUI_OPTIONS_OPEN_BACK );
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerDevice::OfferKeyEventL" );
+
+    return retval;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::CreateListBoxL()
+// Creates listbox, sets empty listbox text.
+// ---------------------------------------------------------
+//
+void CCertManUIContainerDevice::CreateListBoxL()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerDevice::CreateListBoxL()" );
+
+    iListBox = new( ELeave ) CAknSingleStyleListBox;
+    iListBox->SetContainerWindowL( *this );
+    iListBox->ConstructL( this, EAknListBoxMarkableList );
+    iListBox->CreateScrollBarFrameL( ETrue );
+    iListBox->ScrollBarFrame()->
+    SetScrollBarVisibilityL( CEikScrollBarFrame::EOff,CEikScrollBarFrame::EAuto );
+    iListBox->SetListBoxObserver( this );
+
+    HBufC* stringHolder = StringLoader::LoadLC(
+            R_TEXT_RESOURCE_VIEW_DEVICE_EMPTY_LIST );
+    iListBox->View()->SetListEmptyTextL( *stringHolder );
+    CleanupStack::PopAndDestroy();  // stringHolder
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerDevice::CreateListBoxL()" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::DrawListBoxL(TInt aCurrentPosition, TInt aTopItem)
+// Draws listbox, fetches graphic icons for markable list
+// ---------------------------------------------------------
+//
+void CCertManUIContainerDevice::DrawListBoxL(
+    TInt aCurrentPosition, TInt aTopItem )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerDevice::DrawListBoxL" );
+
+    if ( aCurrentPosition >= 0 )
+        {
+        iListBox->SetTopItemIndex( aTopItem );
+        iListBox->SetCurrentItemIndex( aCurrentPosition );
+        }
+    ActivateL();
+    DrawNow();
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerDevice::DrawListBoxL" );
+  }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::UpdateListBoxL(TInt& aCurrentPosition, TInt& aTopItem)
+// Gets list of certificates from CertManAPI, displays them,
+// sets No label/No subject text to them if their names are empty
+// ---------------------------------------------------------
+//
+void CCertManUIContainerDevice::UpdateListBoxL(
+    TInt& aCurrentPosition, TInt& aTopItem )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerDevice::UpdateListBoxL()" );
+
+    iKeeper.StartWaitDialogL( ECertmanUiWaitDialog );
+    CleanupCloseWaitDialogPushL( iKeeper );
+
+    MDesCArray* itemList = iListBox->Model()->ItemTextArray();
+    CDesCArray* itemArray = ( CDesCArray* )itemList;
+
+    if ( iKeeper.iCertsDatOK )  // == ETrue
+        {
+        // database is not corrupted, get count
+        iListItemCount = iKeeper.iDeviceLabelEntries.Count();
+        }
+    else
+        {
+        iListItemCount = 0;
+        }
+    if (iListItemCount == 0 ) //list is empty, disable the scroll bar 
+        {
+    	iListBox->ScrollBarFrame()->SetScrollBarVisibilityL(
+	        CEikScrollBarFrame::EOff,CEikScrollBarFrame::EOff);
+        }
+    if ( iListItemCount > 0 )
+        {
+        if ( ( aCurrentPosition == -1 )
+            || ( aCurrentPosition > iListItemCount-1 ) )
+            {
+            aCurrentPosition = 0;
+            aTopItem = 0;
+            }
+
+    HBufC* buf = HBufC::NewLC( KMaxLengthTextCertLabel );
+    for ( TInt i = 0; i < iListItemCount; i++ )
+          {
+          buf->Des() = ( iKeeper.iDeviceLabelEntries )[i]->iDeviceEntryLabel->Des();
+
+          TPtrC trimmedCertLabel = iKeeper.iCertificateHelper->CutCertificateField( buf->Des() );
+          buf->Des().Copy( trimmedCertLabel );
+          TInt length = buf->Des().Length();
+          if ( length == 0 )
+              {
+              HBufC* stringHolder = NULL;
+
+              stringHolder = StringLoader::LoadLC(
+                       R_TEXT_RESOURCE_VIEW_NO_SUBJECT_LIST );
+
+              itemArray->AppendL( *stringHolder );
+              CleanupStack::PopAndDestroy();  // stringHolder
+              }
+          else
+              {
+              buf->Des().Insert(0, KCertManUIInsertDescriptor);
+              itemArray->AppendL(buf->Des());
+              }
+              iListBox->HandleItemAdditionL();
+          }
+          CleanupStack::PopAndDestroy();  // buf
+    }
+
+    CleanupStack::PopAndDestroy();    // closes wait dialog
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerDevice::UpdateListBoxL()" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::HandleResourceChange
+//
+// ---------------------------------------------------------
+//
+void CCertManUIContainerDevice::HandleResourceChange( TInt aType )
+    {
+    CCoeControl::HandleResourceChange( aType );
+
+    if ( aType == KEikDynamicLayoutVariantSwitch )
+        {
+        TRect mainPaneRect;
+        AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::EMainPane, mainPaneRect );
+        SetRect( mainPaneRect );
+        DrawNow();
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::IconArrayResourceId
+// Loads Mark/Unmark icons from resource
+// ---------------------------------------------------------
+//
+TInt CCertManUIContainerDevice::IconArrayResourceId() const
+    {
+    return R_CERTMANUI_CERTIFICATE_LISTBOX_MARK_ICONS;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::CreateIconArrayL
+// Creates Icon Array
+// ---------------------------------------------------------
+//
+CAknIconArray* CCertManUIContainerDevice::CreateIconArrayL() const
+    {
+    CAknIconArray* icons = new (ELeave) CAknIconArray( KGranularity );
+    CleanupStack::PushL( icons );
+    icons->ConstructFromResourceL( IconArrayResourceId() );
+    CleanupStack::Pop(); // icons
+    return icons;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerDevice::GetHelpContext
+// This function is called when Help application is launched.
+// (other items were commented in a header).
+// ---------------------------------------------------------
+//
+void CCertManUIContainerDevice::GetHelpContext(
+    TCoeHelpContext& aContext ) const
+    {
+    aContext.iMajor = KUidCM;
+    aContext.iContext = KCM_HLP_DEVICE;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuicontainerMain.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,353 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIContainerMain
+*
+*/
+
+
+// INCLUDE FILES
+#include <eikclbd.h>
+#include <AknIconArray.h>
+#include <certmanui.rsg>
+#include <csxhelp/cm.hlp.hrh>   // for help context of CertManUI
+
+#include "CertmanuiCertificateHelper.h"
+#include "CertmanuiKeeper.h"
+#include "CertmanuicontainerMain.h"
+#include "CertmanuiSyncWrapper.h"
+#include "Certmanui.hrh"
+#include "CertManUILogger.h"
+#include "CertmanuiCommon.h"
+
+#include "Certmanuidll.h"       // for applicationUID
+
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::CCertManUIContainerMain(
+// CCertManUIViewPersonal& aParent, CCertManUIKeeper& aKeeper)
+// Constructor with parent
+// ---------------------------------------------------------
+//
+CCertManUIContainerMain::CCertManUIContainerMain(
+    CCertManUIViewMain& aParent, CCertManUIKeeper& aKeeper )
+    : iParent( aParent ), iKeeper( aKeeper )
+    {
+    CERTMANUILOGGER_WRITE_TIMESTAMP(
+        "CCertManUIContainerMain::CCertManUIContainerMain" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::~CCertManUIContainerMain()
+// Destructor
+// ---------------------------------------------------------
+//
+CCertManUIContainerMain::~CCertManUIContainerMain()
+    {
+    CERTMANUILOGGER_ENTERFN(
+    		" CCertManUIContainerMain::~CCertManUIContainerMain" );
+
+    delete iListBox;
+
+    CERTMANUILOGGER_LEAVEFN(
+    		" CCertManUIContainerMain::~CCertManUIContainerMain" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::ConstructL(
+// const TRect& aRect, TInt aCurrentPosition, TInt aTopItem)
+// EPOC two phased constructor
+// ---------------------------------------------------------
+//
+void CCertManUIContainerMain::ConstructL(
+    const TRect& aRect, TInt /*aCurrentPosition*/, TInt /*aTopItem*/ )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerMain::ConstructL" );
+
+    CreateWindowL();
+    CreateListBoxL();
+
+    if ( iListBox )
+        {
+        // Creates graphic.
+        iListBox->ItemDrawer()->ColumnData()->
+            SetIconArray( iIconHandler->CreateIconArrayL() );
+        }
+
+    SetRect( aRect );
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerMain::ConstructL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::SizeChanged()
+// Called by framework when the view size is changed
+// ---------------------------------------------------------
+//
+void CCertManUIContainerMain::SizeChanged()
+    {
+    iListBox->SetRect( Rect() );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::FocusChanged(TDrawNow aDrawNow)
+// ---------------------------------------------------------
+//
+void CCertManUIContainerMain::FocusChanged( TDrawNow aDrawNow )
+    {
+    if ( iListBox )
+        {
+        iListBox->SetFocus( IsFocused(), aDrawNow );
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::HandleListBoxEventL(
+// CEikListBox* /*aListBox*/, TListBoxEvent aEventType)
+// ---------------------------------------------------------
+//
+void CCertManUIContainerMain::HandleListBoxEventL(
+    CEikListBox* /*aListBox*/, TListBoxEvent aEventType )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerMain::HandleListBoxEventL" );
+
+    switch( aEventType )
+        {
+        case EEventItemDoubleClicked:
+        case EEventItemSingleClicked:
+        case EEventEnterKeyPressed:
+            {
+            TInt index = iListBox->CurrentItemIndex();
+
+            if ( index == 0 )
+                {
+                ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL( KCertManUIViewAuthorityId );
+                }
+            else if ( index == 1 )
+                {
+                ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL( KCertManUIViewTrustedSiteId );
+                }
+            else if ( index == 2 )
+                {
+                ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL( KCertManUIViewPersonalId );
+                }
+            else if ( index == 3 )
+                {
+                ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL( KCertManUIViewDeviceId );
+                }
+
+            break;
+            }
+        default:
+            {
+            break;
+            }
+    		}
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerMain::HandleListBoxEventL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::CountComponentControls() const
+// ---------------------------------------------------------
+//
+TInt CCertManUIContainerMain::CountComponentControls() const
+    {
+    // return number of controls inside this container
+    return 1;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::ComponentControl(TInt /*aIndex*/) const
+// ---------------------------------------------------------
+//
+CCoeControl* CCertManUIContainerMain::ComponentControl( TInt /*aIndex*/ ) const
+    {
+    return iListBox;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::Draw(const TRect& aRect) const
+// ---------------------------------------------------------
+//
+void CCertManUIContainerMain::Draw( const TRect& aRect ) const
+    {
+    CWindowGc& gc = SystemGc();
+    gc.SetPenStyle( CGraphicsContext::ENullPen );
+    gc.SetBrushColor( KRgbGray );
+    gc.SetBrushStyle( CGraphicsContext::ESolidBrush );
+    gc.DrawRect( aRect );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::HandleControlEventL(
+//    CCoeControl* /*aControl*/,TCoeEvent /*aEventType*/)
+// Cannot be changed to non-leaving function.
+// L-function is required by the class definition, even if empty.
+// ---------------------------------------------------------
+//
+void CCertManUIContainerMain::HandleControlEventL(
+    CCoeControl* /*aControl*/, TCoeEvent /*aEventType*/ )
+    {
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::OfferKeyEventL(
+// const TKeyEvent& aKeyEvent, TEventCode aType)
+// Handles the key events OK button, arrow keys, delete key.
+// OK button functionality is different depending on the number of marked items
+// in the list; zero marked -> show details view, one or more marked -> show
+// OKOptions list, list empty -> OK inactive.
+// Delete active only if list not empty.
+// ---------------------------------------------------------
+//
+TKeyResponse CCertManUIContainerMain::OfferKeyEventL(
+    const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerMain::OfferKeyEventL" );
+    TKeyResponse retval = EKeyWasNotConsumed;
+
+    retval = iListBox->OfferKeyEventL( aKeyEvent, aType );
+
+		CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerMain::OfferKeyEventL" );
+
+    return retval;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::CreateListBoxL()
+// Creates listbox, sets empty listbox text.
+// ---------------------------------------------------------
+//
+void CCertManUIContainerMain::CreateListBoxL()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerMain::CreateListBoxL" );
+
+    iKeeper.ActivateTitleL( KViewTitleCertManUI );
+
+    iListBox = new( ELeave ) CAknSettingStyleListBox;
+    iListBox->SetContainerWindowL( *this );
+    iListBox->ConstructL( this, EAknListBoxMarkableList );
+    iListBox->CreateScrollBarFrameL( ETrue );
+    iListBox->ScrollBarFrame()->SetScrollBarVisibilityL(
+          CEikScrollBarFrame::EOff,CEikScrollBarFrame::EAuto );
+    iListBox->SetListBoxObserver( this );
+
+
+    MDesCArray* itemList = iListBox->Model()->ItemTextArray();
+    CDesCArray* itemArray = ( CDesCArray* )itemList;
+
+    HBufC*  stringHolder = StringLoader::LoadLC(
+                       R_TEXT_RESOURCE_MAIN_VIEW_AUTHORITY );
+    itemArray->AppendL( *stringHolder );
+    CleanupStack::PopAndDestroy();  // stringHolder
+
+    stringHolder = StringLoader::LoadLC(
+                       R_TEXT_RESOURCE_MAIN_VIEW_TRUSTED );
+    itemArray->AppendL( *stringHolder );
+    CleanupStack::PopAndDestroy();  // stringHolder
+
+    stringHolder = StringLoader::LoadLC(
+                       R_TEXT_RESOURCE_MAIN_VIEW_PERSONAL );
+    itemArray->AppendL( *stringHolder );
+    CleanupStack::PopAndDestroy();  // stringHolder
+
+    stringHolder = StringLoader::LoadLC(
+                       R_TEXT_RESOURCE_MAIN_VIEW_DEVICE );
+    itemArray->AppendL( *stringHolder );
+    CleanupStack::PopAndDestroy();  // stringHolder
+
+    iListBox->HandleItemAdditionL();
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerMain::CreateListBoxL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::DrawListBoxL(TInt aCurrentPosition, TInt aTopItem)
+// Draws listbox, fetches graphic icons for markable list
+// ---------------------------------------------------------
+//
+void CCertManUIContainerMain::DrawListBoxL( TInt aCurrentPosition, TInt aTopItem )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerMain::DrawListBoxL" );
+
+    if ( aCurrentPosition >= 0 )
+        {
+        iListBox->SetTopItemIndex( aTopItem );
+        iListBox->SetCurrentItemIndex( aCurrentPosition );
+        }
+    ActivateL();
+    DrawNow();
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerMain::DrawListBoxL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::HandleResourceChange
+//
+// ---------------------------------------------------------
+//
+void CCertManUIContainerMain::HandleResourceChange(TInt aType)
+    {
+    CCoeControl::HandleResourceChange(aType);
+
+    if ( aType == KEikDynamicLayoutVariantSwitch )
+        {
+        TRect mainPaneRect;
+        AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::EMainPane, mainPaneRect );
+        SetRect( mainPaneRect );
+        DrawNow();
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::IconArrayResourceId
+// Loads Mark/Unmark icons from resource
+// ---------------------------------------------------------
+//
+TInt CCertManUIContainerMain::IconArrayResourceId() const
+    {
+    return R_CERTMANUI_CERTIFICATE_LISTBOX_MARK_ICONS;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::CreateIconArrayL
+// Creates Icon Array
+// ---------------------------------------------------------
+//
+CAknIconArray* CCertManUIContainerMain::CreateIconArrayL() const
+    {
+    CAknIconArray* icons = new ( ELeave ) CAknIconArray( KGranularity );
+    CleanupStack::PushL( icons );
+    icons->ConstructFromResourceL( IconArrayResourceId() );
+    CleanupStack::Pop(); // icons
+    return icons;
+    }
+
+
+// ---------------------------------------------------------
+// CCertManUIContainerMain::GetHelpContext
+// This function is called when Help application is launched.
+// (other items were commented in a header).
+// ---------------------------------------------------------
+//
+
+void CCertManUIContainerMain::GetHelpContext( TCoeHelpContext& aContext ) const
+    {
+    aContext.iMajor = KUidCM;
+    aContext.iContext = KCM_HLP_MAIN;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuicontainerPersonal.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,468 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIContainerPersonal
+*                Reads & updates certificate list.
+*                Handles markable list for certificates.
+*
+*/
+
+
+// INCLUDE FILES
+#include <eikclbd.h>
+#include <AknIconArray.h>
+#include <csxhelp/cm.hlp.hrh>   // for help context of CertManUI
+#include <certmanui.rsg>
+
+#include "CertmanuiCertificateHelper.h"
+#include "CertmanuiKeeper.h"
+#include "CertmanuicontainerPersonal.h"
+#include "CertmanuiSyncWrapper.h"
+#include "Certmanui.hrh"
+#include "CertManUILogger.h"
+#include "CertmanuiCommon.h"
+#include "Certmanuidll.h"       // for applicationUID
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::CCertManUIContainerPersonal(
+// CCertManUIViewPersonal& aParent, CCertManUIKeeper& aKeeper)
+// Constructor with parent
+// ---------------------------------------------------------
+//
+CCertManUIContainerPersonal::CCertManUIContainerPersonal(
+    CCertManUIViewPersonal& aParent, CCertManUIKeeper& aKeeper )
+: iParent( aParent ), iKeeper( aKeeper )
+    {
+    CERTMANUILOGGER_WRITE_TIMESTAMP(
+        "CCertManUIContainerPersonal::CCertManUIContainerPersonal" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::~CCertManUIContainerPersonal()
+// Destructor
+// ---------------------------------------------------------
+//
+CCertManUIContainerPersonal::~CCertManUIContainerPersonal()
+    {
+    CERTMANUILOGGER_ENTERFN(
+        " CCertManUIContainerPersonal::~CCertManUIContainerPersonal" );
+
+    delete iListBox;
+
+    CERTMANUILOGGER_LEAVEFN(
+        " CCertManUIContainerPersonal::~CCertManUIContainerPersonal" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::ConstructL(
+// const TRect& aRect, TInt aCurrentPosition, TInt aTopItem)
+// EPOC two phased constructor
+// ---------------------------------------------------------
+//
+void CCertManUIContainerPersonal::ConstructL(
+    const TRect& aRect, TInt aCurrentPosition, TInt aTopItem )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerPersonal::ConstructL" );
+
+    CreateWindowL();
+    CreateListBoxL();
+    UpdateListBoxL( aCurrentPosition, aTopItem );
+    if ( iListBox )
+        {
+        // Creates graphic.
+        iListBox->ItemDrawer()->ColumnData()->
+            SetIconArray( iIconHandler->CreateIconArrayL() );
+        }
+    SetRect( aRect );
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerPersonal::ConstructL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::SizeChanged()
+// Called by framework when the view size is changed
+// ---------------------------------------------------------
+//
+void CCertManUIContainerPersonal::SizeChanged()
+    {
+    iListBox->SetRect( Rect() );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::FocusChanged(TDrawNow aDrawNow)
+// ---------------------------------------------------------
+//
+void CCertManUIContainerPersonal::FocusChanged( TDrawNow aDrawNow )
+    {
+    if ( iListBox )
+        {
+        iListBox->SetFocus( IsFocused(), aDrawNow );
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::HandleListBoxEventL(
+// CEikListBox* /*aListBox*/, TListBoxEvent aEventType)
+// ---------------------------------------------------------
+//
+void CCertManUIContainerPersonal::HandleListBoxEventL(
+    CEikListBox* /*aListBox*/, TListBoxEvent aEventType )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerPersonal::HandleListBoxEventL" );
+
+    switch( aEventType )
+        {
+        case EEventItemSingleClicked:
+        case EEventEnterKeyPressed:
+            {
+            const CListBoxView::CSelectionIndexArray* selections = iListBox->SelectionIndexes();
+            if ( iListItemCount > 0 )
+                {
+                if ( selections->Count() == 0 )
+                    {
+                    iKeeper.iCertificateHelper->MessageQueryViewDetailsL(
+                        iListBox->CurrentItemIndex(), KCertTypePersonal, iEikonEnv );
+                    }
+                else
+                    {
+                    CEikMenuBar* menuBar = iParent.MenuBar();
+                    menuBar->SetContextMenuTitleResourceId( R_CERTMANUI_MENUBAR_OPTIONS_MARKED );
+                    menuBar->TryDisplayContextMenuBarL();
+                    }
+                }
+            break;
+            }
+
+        default:
+            {
+            break;
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerPersonal::HandleListBoxEventL" );
+    }
+
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::CountComponentControls() const
+// ---------------------------------------------------------
+//
+TInt CCertManUIContainerPersonal::CountComponentControls() const
+    {
+    // return number of controls inside this container
+    return 1;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::ComponentControl(TInt /*aIndex*/) const
+// ---------------------------------------------------------
+//
+CCoeControl* CCertManUIContainerPersonal::ComponentControl( TInt /*aIndex*/ ) const
+    {
+    return iListBox;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::Draw(const TRect& aRect) const
+// ---------------------------------------------------------
+//
+void CCertManUIContainerPersonal::Draw( const TRect& aRect ) const
+    {
+    CWindowGc& gc = SystemGc();
+    gc.SetPenStyle( CGraphicsContext::ENullPen );
+    gc.SetBrushColor( KRgbGray );
+    gc.SetBrushStyle( CGraphicsContext::ESolidBrush );
+    gc.DrawRect( aRect );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::HandleControlEventL(
+//    CCoeControl* /*aControl*/,TCoeEvent /*aEventType*/)
+// Cannot be changed to non-leaving function.
+// L-function is required by the class definition, even if empty.
+// ---------------------------------------------------------
+//
+void CCertManUIContainerPersonal::HandleControlEventL(
+    CCoeControl* /*aControl*/, TCoeEvent /*aEventType*/ )
+    {
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::OfferKeyEventL(
+// const TKeyEvent& aKeyEvent, TEventCode aType)
+// Handles the key events arrow keys, delete key.
+// ---------------------------------------------------------
+//
+TKeyResponse CCertManUIContainerPersonal::OfferKeyEventL(
+    const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerPersonal::OfferKeyEventL" );
+
+    // If operation is currenly onway, do not continue.
+    if ( iKeeper.iWrapper->IsActive() )
+        {
+        return EKeyWasNotConsumed;
+        }
+
+    TKeyResponse retval = EKeyWasNotConsumed;
+    if ( aType == EEventKey )
+        {
+        if ( aKeyEvent.iCode == EKeyRightArrow )
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL( KCertManUIViewDeviceId );
+            retval = EKeyWasConsumed;
+            }
+          else if ( aKeyEvent.iCode == EKeyLeftArrow )
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL( KCertManUIViewTrustedSiteId );
+            retval = EKeyWasConsumed;
+            }
+          else if ( aKeyEvent.iCode == EKeyDelete
+                  || aKeyEvent.iCode == EKeyBackspace )
+            {
+            TInt currentItemPersonal = iListBox->CurrentItemIndex();
+
+            if ( ( currentItemPersonal >= 0 ) &&
+                ( currentItemPersonal < iKeeper.iUserLabelEntries.Count() ))
+              {
+              // list is not empty
+              if ( iKeeper.iCertificateHelper->ConfirmationQueryDeleteCertL(
+                     KCertTypePersonal, iListBox ) ) // == ETrue
+                  {
+                  iParent.iCurrentPosition = iListBox->CurrentItemIndex();
+                  iParent.iTopItem = iListBox->TopItemIndex();
+
+                  DrawListBoxL( iParent.iCurrentPosition, iParent.iTopItem );
+                  // goes here if at least one certificate is deleted
+                  TRAPD( error, iKeeper.RefreshUserCertEntriesL() );
+                  if ( error != KErrNone )
+                      {
+                      if ( error == KErrCorrupt )
+                          {
+                          iKeeper.ShowErrorNoteL( error );
+                          User::Exit( KErrNone );
+                          }
+                      else
+                          {
+                          // have to call straight away the Exit
+                          // showing any error notes would corrupt the display
+                          User::Exit( error );
+                          }
+                      }
+                  iParent.UpdateMenuBar();
+                  }
+              }
+          // Listbox takes all event even if it doesn't use them
+          retval = EKeyWasConsumed;
+          }
+        else
+          {
+          retval = iListBox->OfferKeyEventL( aKeyEvent, aType );
+          }
+        }
+    else
+        {
+        retval = iListBox->OfferKeyEventL( aKeyEvent, aType );
+        }
+
+    if ( iListBox->SelectionIndexes()->Count() > 0 )
+        {
+        iParent.MenuBar()->SetContextMenuTitleResourceId( R_CERTMANUI_MENUBAR_OPTIONS_MARKED );
+        iParent.UpdateCba( R_CERTMANUI_OPTIONS_CONTEXT_BACK );
+        }
+    else
+        {
+        iParent.MenuBar()->SetMenuTitleResourceId( R_CERTMANUI_MENUBAR_VIEW_PERSONAL );
+        iParent.UpdateCba( R_CERTMANUI_OPTIONS_OPEN_BACK );
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerPersonal::OfferKeyEventL" );
+
+    return retval;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::CreateListBoxL()
+// Creates listbox, sets empty listbox text.
+// ---------------------------------------------------------
+//
+void CCertManUIContainerPersonal::CreateListBoxL()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerPersonal::CreateListBoxL" );
+
+    iListBox = new( ELeave ) CAknSingleStyleListBox;
+    iListBox->SetContainerWindowL( *this );
+    iListBox->ConstructL( this, EAknListBoxMarkableList );
+    iListBox->CreateScrollBarFrameL( ETrue );
+    iListBox->ScrollBarFrame()->SetScrollBarVisibilityL(
+        CEikScrollBarFrame::EOff,CEikScrollBarFrame::EAuto );
+    iListBox->SetListBoxObserver( this );
+
+    HBufC* stringHolder = StringLoader::LoadLC( R_TEXT_RESOURCE_VIEW_PERSONAL_EMPTY_LIST );
+    iListBox->View()->SetListEmptyTextL( *stringHolder );
+    CleanupStack::PopAndDestroy();  // stringHolder
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerPersonal::CreateListBoxL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::DrawListBoxL(TInt aCurrentPosition, TInt aTopItem)
+// Draws listbox, fetches graphic icons for markable list
+// ---------------------------------------------------------
+//
+void CCertManUIContainerPersonal::DrawListBoxL( TInt aCurrentPosition, TInt aTopItem )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerPersonal::DrawListBoxL" );
+
+    if ( aCurrentPosition >= 0 )
+        {
+        iListBox->SetTopItemIndex( aTopItem );
+        iListBox->SetCurrentItemIndex( aCurrentPosition );
+        }
+    ActivateL();
+    DrawNow();
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerPersonal::DrawListBoxL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::UpdateListBoxL(TInt& aCurrentPosition, TInt& aTopItem)
+// Gets list of certificates from CertManAPI, displays them,
+// sets No label text to them if their names are empty
+// ---------------------------------------------------------
+//
+void CCertManUIContainerPersonal::UpdateListBoxL( TInt& aCurrentPosition, TInt& aTopItem )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerPersonal::UpdateListBoxL" );
+
+    iKeeper.StartWaitDialogL( ECertmanUiWaitDialog );
+    CleanupCloseWaitDialogPushL( iKeeper );
+
+    MDesCArray* itemList = iListBox->Model()->ItemTextArray();
+    CDesCArray* itemArray = ( CDesCArray* )itemList;
+
+    // List certificates
+    if ( iKeeper.iCertsDatOK )  // == ETrue
+        {
+        // cacerts.dat is not corrupted, get count
+        iListItemCount = iKeeper.iUserLabelEntries.Count();
+        }
+    else
+        {
+        iListItemCount = 0;
+        }
+    if (iListItemCount == 0 ) //list is empty, disable the scroll bar 
+        {
+    	iListBox->ScrollBarFrame()->SetScrollBarVisibilityL(
+	        CEikScrollBarFrame::EOff,CEikScrollBarFrame::EOff);
+        }
+    if ( iListItemCount > 0 )
+        {
+        if ( ( aCurrentPosition == -1 )
+              || ( aCurrentPosition > iListItemCount-1 ) )
+            {
+            aCurrentPosition = 0;
+            aTopItem = 0;
+            }
+
+      HBufC* buf = HBufC::NewLC( KMaxLengthTextCertLabel );
+      for ( TInt i = 0; i < iListItemCount; i++ )
+          {
+          buf->Des() = ( iKeeper.iUserLabelEntries )[i]->iUserEntryLabel->Des();
+
+          TPtrC trimmedCertLabel = iKeeper.iCertificateHelper->CutCertificateField( buf->Des() );
+          buf->Des().Copy( trimmedCertLabel );
+          TInt length = buf->Des().Length();
+          if ( length == 0 )
+              {
+              HBufC* stringHolder = NULL;
+
+              stringHolder = StringLoader::LoadLC(
+                       R_TEXT_RESOURCE_VIEW_NO_SUBJECT_LIST );
+
+              itemArray->AppendL( *stringHolder );
+              CleanupStack::PopAndDestroy();  // stringHolder
+              }
+          else
+              {
+              buf->Des().Insert( 0, KCertManUIInsertDescriptor );
+              itemArray->AppendL( buf->Des() );
+              }
+          iListBox->HandleItemAdditionL();
+          }
+        CleanupStack::PopAndDestroy();  // buf
+        }
+
+    CleanupStack::PopAndDestroy();    // closes wait dialog
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerPersonal::UpdateListBoxL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::HandleResourceChange
+//
+// ---------------------------------------------------------
+//
+void CCertManUIContainerPersonal::HandleResourceChange( TInt aType )
+    {
+    CCoeControl::HandleResourceChange(aType);
+
+    if ( aType == KEikDynamicLayoutVariantSwitch )
+        {
+        TRect mainPaneRect;
+        AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::EMainPane, mainPaneRect );
+        SetRect( mainPaneRect );
+        DrawNow();
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::IconArrayResourceId
+// Loads Mark/Unmark icons from resource
+// ---------------------------------------------------------
+//
+TInt CCertManUIContainerPersonal::IconArrayResourceId() const
+    {
+    return R_CERTMANUI_CERTIFICATE_LISTBOX_MARK_ICONS;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::CreateIconArrayL
+// Creates Icon Array
+// ---------------------------------------------------------
+//
+CAknIconArray* CCertManUIContainerPersonal::CreateIconArrayL() const
+    {
+    CAknIconArray* icons = new ( ELeave ) CAknIconArray( KGranularity );
+    CleanupStack::PushL( icons );
+    icons->ConstructFromResourceL( IconArrayResourceId() );
+    CleanupStack::Pop(); // icons
+    return icons;
+    }
+
+
+// ---------------------------------------------------------
+// CCertManUIContainerPersonal::GetHelpContext
+// This function is called when Help application is launched.
+// (other items were commented in a header).
+// ---------------------------------------------------------
+//
+void CCertManUIContainerPersonal::GetHelpContext( TCoeHelpContext& aContext ) const
+    {
+    aContext.iMajor = KUidCM;
+    aContext.iContext = KCM_HLP_PERSONAL;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuicontainerTrust.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,879 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIContainerTrust.
+*                Maintains correct list of trusted clients depending
+*                on the certificate that was in focus in Authority
+*                certificates view when Trust Settings view was entered.
+*                Shows and changes correct Yes/No text for the Trusted client.
+*
+*/
+
+
+// INCLUDE FILES
+#include <certificateapps.h>
+#include <mctcertapps.h>
+#include <mctcertstore.h>
+#include <csxhelp/cm.hlp.hrh>   // for help context of CertManUI
+#include <certmanui.rsg>
+
+#include "CertmanuiKeeper.h"
+#include "CertmanuiviewTrust.h"
+#include "CertmanuicontainerTrust.h"
+#include "Certmanuitrustids.h"
+#include "CertmanuiSyncWrapper.h"
+#include "CertManUILogger.h"
+#include "CertmanuiCommon.h"
+#include "CertManUILogger.h"
+
+#include "Certmanuidll.h"     // for applicationUID
+
+
+const TInt KMidpCertStoreUid = 0x101F5B71;
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// void CloseAndDeleteRArray( TAny* aPointer )
+// Function frees resources of a RArray.
+// Returns: void
+// -----------------------------------------------------------------------------
+//
+void CloseAndDeleteRArray( TAny* aPointer )
+    {
+    ((RArray<TUid>*)aPointer)->Close();
+    delete ( (RArray<TUid>*)aPointer );
+    }
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::CCertManUIContainerTrust(
+//                              CCertManUIViewTrust& aParent,
+//                              CCertManUIKeeper& aKeeper)
+// Constructor with parent
+// ---------------------------------------------------------
+//
+CCertManUIContainerTrust::CCertManUIContainerTrust(
+    CCertManUIViewTrust& aParent,
+    CCertManUIKeeper& aKeeper )
+    : iParent ( aParent ), iKeeper ( aKeeper )
+    {
+    CERTMANUILOGGER_WRITE_TIMESTAMP(
+        "CCertManUIContainerTrust::CCertManUIContainerTrust" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::~CCertManUIContainerTrust()
+// Destructor
+// ---------------------------------------------------------
+//
+CCertManUIContainerTrust::~CCertManUIContainerTrust()
+    {
+    CERTMANUILOGGER_ENTERFN(
+        " CCertManUIContainerTrust::~CCertManUIContainerTrust" );
+
+    delete iListBox;
+    delete iTrustedClients;
+    delete iTrustValues;
+    delete iAppInfoManager;
+    iClientUids.Close();
+
+    CERTMANUILOGGER_LEAVEFN(
+        " CCertManUIContainerTrust::~CCertManUIContainerTrust" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::ConstructL(const TRect& aRect)
+// EPOC two phased constructor
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrust::ConstructL(const TRect& aRect)
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrust::ConstructL" );
+
+    CreateWindowL();
+    CreateListBoxL();
+    SetRect(aRect);
+    iTrustedClients = iCoeEnv->ReadDesC16ArrayResourceL(
+          R_CERTMANUI_VIEW_TRUST_SETTINGS_LISTBOX );
+    iTrustValues = iCoeEnv->ReadDesC16ArrayResourceL(
+          R_CERTMANUI_TRUST_SETTINGS_VALUES );
+
+    TRAPD( error, iAppInfoManager =
+        CCertificateAppInfoManager::NewL( iKeeper.iRfs, EFalse ) );
+    if ( error != KErrNone )
+        {
+        if ( error == KErrNotSupported
+            || error == KErrCorrupt
+            || error == KErrNotReady
+            || error == KErrArgument
+            || error == KErrNotFound )
+            {
+            iKeeper.ShowErrorNoteL( error );
+            User::Exit( KErrNone );
+            }
+        else
+            {
+            User::Leave( error );
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrust::ConstructL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::SizeChanged()
+// Called by framework when the view size is changed
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrust::SizeChanged()
+    {
+    iListBox->SetRect( Rect() );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::FocusChanged(TDrawNow aDrawNow)
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrust::FocusChanged( TDrawNow aDrawNow )
+    {
+    if ( iListBox )
+        {
+        iListBox->SetFocus( IsFocused(), aDrawNow );
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::HandleListBoxEventL(
+//      CEikListBox* /*aListBox*/, TListBoxEvent /*aEventType*/)
+// Cannot be changed to non-leaving function.
+// L-function is required by the class definition, even if empty.
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrust::HandleListBoxEventL(
+    CEikListBox* /*aListBox*/, TListBoxEvent aEventType )
+    {
+    CERTMANUILOGGER_ENTERFN(
+      " CCertManUIContainerTrust::HandleListBoxEventL" );
+
+    switch( aEventType )
+        {
+        case EEventItemSingleClicked:
+            if ( !iKeeper.iWrapper->IsActive() )
+                {
+                iParent.ChangeTrustL();
+                }
+            break;
+        default:
+            {
+            break;
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN(
+      " CCertManUIContainerTrust::HandleListBoxEventL" );
+    }
+
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::CountComponentControls() const
+// ---------------------------------------------------------
+//
+TInt CCertManUIContainerTrust::CountComponentControls() const
+    {
+    // return number of controls inside this container
+    return 1;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::ComponentControl(TInt /*aIndex*/) const
+// ---------------------------------------------------------
+//
+CCoeControl* CCertManUIContainerTrust::ComponentControl(
+    TInt /*aIndex*/ ) const
+    {
+    return iListBox;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::Draw(const TRect& aRect) const
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrust::Draw( const TRect& aRect ) const
+    {
+    CWindowGc& gc = SystemGc();
+    gc.SetPenStyle( CGraphicsContext::ENullPen );
+    gc.SetBrushColor( KRgbGray );
+    gc.SetBrushStyle( CGraphicsContext::ESolidBrush );
+    gc.DrawRect( aRect );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::HandleControlEventL(
+//    CCoeControl* /*aControl*/,TCoeEvent /*aEventType*/)
+// Cannot be changed to non-leaving function.
+// L-function is required by the class definition, even if empty.
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrust::HandleControlEventL(
+    CCoeControl* /*aControl*/,TCoeEvent /*aEventType*/ )
+    {
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::OfferKeyEventL(const TKeyEvent& aKeyEvent,
+//      TEventCode aType)
+// Handles the key events OK button, arrow keys.
+// ---------------------------------------------------------
+//
+TKeyResponse CCertManUIContainerTrust::OfferKeyEventL(
+    const TKeyEvent& aKeyEvent,
+    TEventCode aType )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrust::OfferKeyEventL" );
+
+    TBool doRet = EFalse;
+
+    switch ( aKeyEvent.iCode )
+        {
+        case EKeyOK:
+            {
+            if ( !iKeeper.iWrapper->IsActive() )
+                {
+                iParent.ChangeTrustL();
+                }
+            break;
+            }
+        case EKeyLeftArrow:
+        case EKeyRightArrow:
+            {
+            // Listbox takes all event even if it doesn't use them
+            doRet = ETrue;
+            break;
+            }
+        default:
+            {
+            break;
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrust::OfferKeyEventL" );
+
+    if ( doRet )
+        {
+        return EKeyWasConsumed;
+        }
+
+    return iListBox->OfferKeyEventL( aKeyEvent, aType );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::CreateListBoxL()
+// Creates listbox
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrust::CreateListBoxL()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrust::CreateListBoxL" );
+
+    iListBox = new ( ELeave ) CAknSettingStyleListBox;
+    iListBox->SetContainerWindowL( *this );
+    iListBox->ConstructL( this, EAknListBoxSelectionList );
+    iListBox->CreateScrollBarFrameL( ETrue );
+    iListBox->ScrollBarFrame()->SetScrollBarVisibilityL(
+          CEikScrollBarFrame::EOff,CEikScrollBarFrame::EAuto );
+    iListBox->SetListBoxObserver( this );
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrust::CreateListBoxL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::DrawListBoxL(
+//      TInt aCurrentPosition, TInt aTopItem, TInt aCertificateIndex)
+// Draws listbox
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrust::DrawListBoxL(
+    TInt aCurrentPosition, TInt aTopItem, TInt aCertificateIndex)
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrust::DrawListBoxL" );
+
+    iListBox->SetTopItemIndex( aTopItem );
+    iListBox->SetCurrentItemIndex( aCurrentPosition );
+    UpdateListBoxL( aCertificateIndex );
+    ActivateL();
+    DrawNow();
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrust::DrawListBoxL" );
+    }
+
+// ---------------------------------------------------------------------------
+// CCertManUIContainerTrust::UpdateListBoxL(TInt aCertificateIndex)
+// Puts correct Trust Settings text to listbox and correct value (yes/no)
+// to the setting, asks the value from CheckCertificateClientTrust
+// For X509 certificates, only one Application is currently supported
+// (Application controller), more applications maybe added later however,
+// so one additional application has been left in comments as an example.
+// WAP connection and Application installer have their names from resources
+// and thus localized,  other additional application get their names from
+// TCertificateAppInfo's Name() function.
+// ---------------------------------------------------------------------------
+//
+void CCertManUIContainerTrust::UpdateListBoxL( TInt aCertificateIndex )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrust::UpdateListBoxL" );
+
+    SetEmptyListL( iListBox );
+
+    iApps.Reset();
+    iClientUids.Reset();
+
+    TInt clientCount = 0;
+
+    // Use certificate index from previous view
+    CCTCertInfo* entry = iKeeper.iCALabelEntries[ aCertificateIndex ]->iCAEntry;
+
+    // Here MCTCertApps should be used to get client options, but it is not properly
+    // supported in any cert store. It should be possible to get the MCTCertApps
+    // through token's GetInterface function.
+    if ( entry->Token().TokenType().Type() == TUid::Uid( KTokenTypeFileCertstore ) )
+        {
+        if ( !iAppInfoManager )
+            {
+            User::Leave( KErrArgument );
+            }
+        iApps = iAppInfoManager->Applications();
+        for ( TInt i = 0; i < iApps.Count(); i++ )
+            {
+            if ( iApps[i].Id() != KCertManUIViewTrustJavaInstallingId &&
+                 iApps[i].Id() != KCertManUIViewTrustApplicationControllerId )
+                {
+                iClientUids.Append( iApps[i].Id() );
+                }
+            }
+        }
+    else
+        {
+        iKeeper.iWrapper->GetApplicationsL(
+                iKeeper.CertManager(), *entry, iClientUids );
+        }
+
+    // This is needed because MIDPCertStore does not support MCTCertApps
+    if ( iClientUids.Count() == 0 &&
+        entry->Token().TokenType().Type() == TUid::Uid( KMidpCertStoreUid ) )
+        {
+        iClientUids.Append( KCertManUIViewTrustJavaInstallingId );
+        }
+
+    clientCount = iClientUids.Count();
+
+
+    MDesCArray* itemList = iListBox->Model()->ItemTextArray();
+    CDesCArray* itemArray = STATIC_CAST( CDesCArray*, itemList );
+    if ( EX509Certificate == entry->CertificateFormat() )
+        {
+        TInt resIndex = KErrNotFound;
+        TInt position = 0;
+        if ( iClientUids.Count() > 0 )
+            {
+            for ( TInt k = 0; k < clientCount; k++ )
+                {
+                resIndex = GetTrusterResId( iClientUids[k] );
+                if ( resIndex != KErrNotFound )
+                    {
+                    InsertItemToTrustListL(
+                        resIndex, iClientUids[k], *entry, itemArray, position );
+                    position++;
+                    }
+                }
+            }
+        }
+    else
+        {
+        return;
+        }
+
+    iListBox->HandleItemAdditionL();
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrust::UpdateListBoxL" );
+    }
+
+// ---------------------------------------------------------------------------
+// CCertManUIContainerTrust::GetTrusterResId( TUid aTrusterUid )
+// ---------------------------------------------------------------------------
+//
+TInt CCertManUIContainerTrust::GetTrusterResId( TUid aTrusterUid )
+    {
+    TInt resIndex = 0;
+    if ( aTrusterUid == KCertManUIViewTrustApplicationControllerId )
+        {
+        resIndex = KTrustSettingsResourceIndexAppCtrl;
+        }
+    else if ( aTrusterUid == KCertManUIViewTrustMailAndImageConnId )
+        {
+        resIndex = KTrustSettingsResourceIndexMailAndImageConn;
+        }
+    else if ( aTrusterUid == KCertManUIViewTrustJavaInstallingId )
+        {
+        resIndex = KTrustSettingsResourceIndexJavaInstall;
+        }
+    else if ( aTrusterUid == KCertManUIViewOCSPCheckInstallingId )
+        {
+        resIndex = KTrustSettingsResourceIndexOCSPCheck;
+        }
+    else if ( aTrusterUid == KCertManUIViewTrustVPNId )
+        {
+        resIndex = KTrustSettingsResourceIndexVPN;
+        }
+    else
+        {
+        resIndex = KErrNotFound;
+        }
+
+    return resIndex;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CCertManUIContainerTrust::InsertItemToTrustListL(const TInt aIndex,
+//                                              const TUid aId,
+//                                              CCTCertInfo& aEntry,
+//                                              CDesCArray* aItemArray,
+//                                              TInt aPosition)
+// This is helper function for UpdateListBoxL. Inserts trustsetting item to
+// listbox.
+// ---------------------------------------------------------------------------
+//
+void CCertManUIContainerTrust::InsertItemToTrustListL(
+    const TInt aIndex, const TUid aId,
+    CCTCertInfo& aEntry, CDesCArray* aItemArray,
+    TInt aPosition )
+    {
+    TBuf<KMaxLengthTextSettListOneTwo> item;
+    TBool trustState = EFalse;
+
+    item = (*iTrustedClients)[ aIndex ];
+    trustState = CheckCertificateClientTrustL( aId, aEntry );
+    if ( trustState )
+        {
+        // item gets its beginning and end
+        // from the resources using indexes
+        item += (*iTrustValues)
+                  [ KTrustSettingsResourceIndexValueYes ];
+        }
+    else
+        {
+        item += (*iTrustValues)
+                  [ KTrustSettingsResourceIndexValueNo ];
+        }
+    aItemArray->InsertL( aPosition, item );
+    }
+
+// ---------------------------------------------------------------------------
+// CCertManUIContainerTrust::CheckCertificateClientTrustL(const TUid aClientTUid,
+// CCTCertInfo& aEntry) const
+// Checks if a certificate trusts a client
+// * Certificate format == ECrX509Certificate ECrX968Certificate ECrCertificateURL
+// are not supported if certificate location == ECrCertLocationWIMCard
+// * Certificate format == ECrX968Certificate ECrCertificateURL are not supported
+// if certificate location == ECrCertLocationCertMan
+// * Certificate location == ECrCertLocationWIMURL ECrCertLocationPhoneMemory
+// ECrCertLocationPhoneMemoryURL are not supported
+// ---------------------------------------------------------------------------
+//
+TBool CCertManUIContainerTrust::CheckCertificateClientTrustL(
+    const TUid aClientTUid, CCTCertInfo& aEntry ) const
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrust::CheckCertificateClientTrust" );
+
+    TBool trustSettingTrusted = EFalse;
+    TCertificateFormat format = aEntry.CertificateFormat();
+
+    if ( format == EX509Certificate )
+        {
+
+        RArray<TUid> trusterUids;
+        CleanupClosePushL( trusterUids );
+
+        //Owned by iKeeper.
+        CUnifiedCertStore*& store = iKeeper.CertManager();
+        // Get trusting applications' Uids for the one selected
+        // certificate entry
+        iKeeper.iWrapper->GetApplicationsL( store, aEntry, trusterUids );
+
+
+        // get the number of trusting applications for one
+        // selected certificate entry
+        TInt trusterCount = trusterUids.Count();
+        // in this loop, for every trusting application in one
+        // selected certificate entry
+        for ( TInt i = 0; i < trusterCount && !trustSettingTrusted; i++ )
+            {
+            // put the trusting application's Uid to TUid truster
+            if ( aClientTUid == trusterUids[i] )
+                {
+                trustSettingTrusted = ETrue;
+                }
+            }
+        CleanupStack::PopAndDestroy();  // close trusterUids
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrust::CheckCertificateClientTrust" );
+
+    return trustSettingTrusted;
+    }
+
+// ---------------------------------------------------------------------------
+// CCertManUIContainerTrust::SetEmptyListL(CEikListBox* aListBox)
+// Sets empty list for listbox.
+// ---------------------------------------------------------------------------
+//
+void CCertManUIContainerTrust::SetEmptyListL( CEikListBox* aListBox )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrust::SetEmptyListL" );
+
+    // Sets empty list.
+    HBufC* emptyListText = iCoeEnv->AllocReadResourceLC(
+        R_TEXT_RESOURCE_VIEW_TRUST_SETTINGS_EMPTY_LIST );
+    aListBox->View()->SetListEmptyTextL( *emptyListText );
+    CleanupStack::PopAndDestroy();  // emptyListText
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrust::SetEmptyListL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::UpdateTrustListboxItemL(CCrCertEntry& aEntry,
+//                                              TInt aCurrentTruster)
+// Updates the Trust Settings Listbox item value
+// Can be called only for those certificates that are
+// located in ECrCertLocationCertMan !!!
+// Cannot be called for certificates located in ECrCertLocationWIMCard,
+//                        ECrCertLocationWIMURL,
+//                        ECrCertLocationPhoneMemory
+//                        ECrCertLocationPhoneMemoryURL
+// Certificate formats ECrX968Certificate ECrCertificateURL
+// are not visible in the Trust View
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrust::UpdateTrustListboxItemL(CCTCertInfo& aEntry,
+                                                       TInt aCurrentTruster)
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrust::UpdateTrustListboxItemL" );
+
+    MDesCArray* itemList = iListBox->Model()->ItemTextArray();
+    CDesCArray* itemArray = STATIC_CAST( CDesCArray*, itemList );
+    TCertificateFormat format = aEntry.CertificateFormat();
+    TUid id = KCertManUINullId;
+
+    TInt poppableItems = 0;
+
+    TInt index = 0;
+
+    if ( format == EX509Certificate )
+        {
+        id = iClientUids[ aCurrentTruster ];
+        index = aCurrentTruster;
+        }
+
+    if ( id != KCertManUINullId )
+        {
+        TBuf<KMaxLengthTextSettListOneTwo> item;
+
+        if ( id == KCertManUIViewTrustApplicationControllerId )
+            {
+            item = (*iTrustedClients)[ KTrustSettingsResourceIndexAppCtrl ];
+            }
+        else if ( id == KCertManUIViewTrustMailAndImageConnId )
+            {
+            item =
+             (*iTrustedClients)[ KTrustSettingsResourceIndexMailAndImageConn ];
+            }
+        else if ( id == KCertManUIViewTrustJavaInstallingId )
+            {
+            item =
+             (*iTrustedClients)[ KTrustSettingsResourceIndexJavaInstall ];
+            }
+        else if ( id == KCertManUIViewOCSPCheckInstallingId )
+            {
+            item =
+             (*iTrustedClients)[ KTrustSettingsResourceIndexOCSPCheck ];
+            }
+        else if ( id == KCertManUIViewTrustVPNId )
+            {
+            item =
+             (*iTrustedClients)[ KTrustSettingsResourceIndexVPN ];
+            }
+        else
+            {
+            if ( iApps.Count() > 0 )
+                {
+                const TName& name = iApps[index].Name();
+                TInt fieldLength = name.Length();
+                TBuf<KMaxLengthTextSettListOneTwo> item2;
+                if ( fieldLength >= KMaxLengthTextSettListOne )
+                    {
+                    item2 = name.Mid( 0, KMaxLengthTextSettListOne );
+                    }
+                else
+                    {
+                    item2 = name;
+                    }
+                item.Format( KCertManUIFormatDescriptorTrustSettings, &item2 );
+                }
+            }
+
+        if ( item.Length() )
+            {
+            if ( CheckCertificateClientTrustL(id, aEntry) )
+                {
+                item += (*iTrustValues)[ KTrustSettingsResourceIndexValueYes ];
+                }
+            else
+                {
+                item += (*iTrustValues)[ KTrustSettingsResourceIndexValueNo ];
+                }
+            // need to Delete first the old Yes/No entry
+            itemArray->Delete( aCurrentTruster );
+            itemArray->InsertL( aCurrentTruster, item );
+            }
+        }
+
+    CleanupStack::PopAndDestroy( poppableItems );
+
+    iListBox->HandleItemAdditionL();
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrust::UpdateTrustListboxItemL" );
+    }
+
+// ---------------------------------------------------------------------------
+// CCertManUIContainerTrust::ShowTrustChangeSettingPageL(const TUid aClientUid,
+//                            TDesC& aClientName,
+//                            CCTCertInfo& aEntry)
+// Puts correct client names and yes/no state to settings page
+// Sets title text to a setting page
+// ---------------------------------------------------------------------------
+//
+void CCertManUIContainerTrust::ShowTrustChangeSettingPageL(
+    const TUid aClientUid, TDesC& aClientName, CCTCertInfo& aEntry )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrust::ShowTrustChangeSettingPageL" );
+
+    TBool trustState = CheckCertificateClientTrustL( aClientUid, aEntry );
+    TInt oldTrustStatus = 1; // Trust set to No value
+    if ( trustState )
+        {
+        oldTrustStatus = 0; // Trust set to Yes value
+        }
+    TInt newTrustStatus = oldTrustStatus;
+    CDesCArrayFlat* items = iCoeEnv->ReadDesC16ArrayResourceL(
+            R_CERTMANUI_VIEW_TRUST_YES_NO_SETTING_PAGE_LBX );
+    CleanupStack::PushL( items );
+
+    CAknRadioButtonSettingPage* dlg = new(ELeave) CAknRadioButtonSettingPage(
+            R_CERTMANUI_VIEW_TRUST_YES_NO_SETTING_PAGE, newTrustStatus, items );
+
+    dlg->SetSettingTextL( aClientName );
+    dlg->ExecuteLD( CAknSettingPage::EUpdateWhenChanged );
+    CleanupStack::PopAndDestroy( items );
+
+    if ( newTrustStatus != oldTrustStatus )
+        {
+        TInt currentTruster = iListBox->CurrentItemIndex();
+        ChangeTrustValueL( aEntry, aClientUid );
+        UpdateTrustListboxItemL( aEntry, currentTruster );
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrust::ShowTrustChangeSettingPageL" );
+    }
+
+// ---------------------------------------------------------------------------
+// CCertManUIContainerTrust::PopupTrustChangeSettingPageL(
+//      TInt aCertificateIndex)
+// Finds out which client was focused in Trust Settings view and calls
+// ShowTrustChangeSettingPageL This is accessed only by X509S
+// certificates, located in CertMan and having one or more clients
+// Must be public so that viewTrust can access
+// ---------------------------------------------------------------------------
+//
+void CCertManUIContainerTrust::PopupTrustChangeSettingPageL(
+    TInt aCertificateIndex )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrust::PopupTrustChangeSettingPageL" );
+
+    // Use certificate index from previous view
+    CCTCertInfo* entry =
+        iKeeper.iCALabelEntries[ aCertificateIndex ]->iCAEntry;
+
+    // if the certificate is read-only, trust settings cannot be changed
+    if( !entry->IsDeletable() )
+    	{
+        CERTMANUILOGGER_LEAVEFN( "- PopupTrustChangeSettingPageL - read-only" );
+    	return;
+    	}
+    
+    TUid id = KCertManUINullId;
+    TInt poppableItems = 0;
+
+    TBuf<KMaxLengthTextSettListOne> clientName;
+
+    // get position of the focus in the Trust Settings view
+    TInt currentPosition = iListBox->CurrentItemIndex();
+    id = iClientUids[ currentPosition ];
+
+    if ( id != KCertManUINullId )
+        {
+        // Native installation
+        if ( id == KCertManUIViewTrustApplicationControllerId )
+            {
+            clientName =
+                    (*iTrustedClients)[ KTrustSettingsResourceIndexAppCtrl ];
+            }
+        // TLS
+        else if ( id == KCertManUIViewTrustMailAndImageConnId )
+            {
+            clientName =
+                  (*iTrustedClients)[
+                  KTrustSettingsResourceIndexMailAndImageConn ];
+            }
+        // Midlet installation
+        else if ( id == KCertManUIViewTrustJavaInstallingId )
+            {
+            clientName =
+                  (*iTrustedClients)[
+                  KTrustSettingsResourceIndexJavaInstall ];
+            }
+        // OCSP
+        else if ( id == KCertManUIViewOCSPCheckInstallingId )
+            {
+            clientName =
+                  (*iTrustedClients)[
+                  KTrustSettingsResourceIndexOCSPCheck ];
+            }
+        // VPN
+        else if ( id == KCertManUIViewTrustVPNId )
+            {
+            clientName =
+                  (*iTrustedClients)[
+                  KTrustSettingsResourceIndexVPN ];
+            }
+        else
+            {
+            if ( iApps.Count() > 0 )
+                {
+                const TName& name = iApps[currentPosition].Name();
+                TInt fieldLength = name.Length();
+                if ( fieldLength >= KMaxLengthTextSettListOne )
+                    {
+                    clientName = name.Mid(0, KMaxLengthTextSettListOne);
+                    }
+                else
+                    {
+                    clientName = name;
+                    }
+                }
+            }
+        }
+
+    if ( id != KCertManUINullId )
+        {
+        clientName.TrimLeft();
+        clientName.TrimRight();
+        ShowTrustChangeSettingPageL( id, clientName, *entry );
+        }
+
+    CleanupStack::PopAndDestroy( poppableItems );  // clients
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrust::PopupTrustChangeSettingPageL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::ChangeTrustValueL(CCTCertInfo& aEntry)
+// Changes the Trust state of client in the CertManAPI
+// ChangeTrustValueL is called only for certificates located
+// in certman.
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrust::ChangeTrustValueL(
+    CCTCertInfo& aEntry, const TUid aClientUid )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrust::ChangeTrustValueL" );
+
+    RArray<TUid> trusterUids;
+    CleanupClosePushL( trusterUids );
+
+    iKeeper.iWrapper->GetApplicationsL(
+        iKeeper.CertManager(), aEntry, trusterUids );
+
+    RArray<TUid> newUids;
+    CleanupClosePushL( newUids );
+
+    // Go through all applications and if aClientId does not exist, add it and
+    // update certificates data.
+    TBool add = ETrue;
+    for ( TInt i = 0; i < trusterUids.Count(); i++ )
+        {
+        if ( aClientUid == trusterUids[i] )
+            {
+            add = EFalse;
+            }
+        else
+            {
+            newUids.Append( trusterUids[i] );
+            }
+        }
+
+    if ( add )
+        {
+        newUids.Append( aClientUid );
+        }
+
+    iKeeper.iWrapper->SetApplicabilityL(
+        iKeeper.CertManager(), aEntry, newUids );
+
+    CleanupStack::PopAndDestroy(2);  // trusterUids, newUids
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrust::ChangeTrustValueL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::HandleResourceChange
+//
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrust::HandleResourceChange(TInt aType)
+    {
+    CCoeControl::HandleResourceChange(aType);
+
+    if (aType == KEikDynamicLayoutVariantSwitch)
+        {
+        TRect mainPaneRect;
+        AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EMainPane, mainPaneRect);
+        SetRect(mainPaneRect);
+        DrawNow();
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrust::GetHelpContext
+// This function is called when Help application is launched.
+// (other items were commented in a header).
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrust::GetHelpContext( TCoeHelpContext& aContext ) const
+    {
+    aContext.iMajor = KUidCM;
+    aContext.iContext = KCM_HLP_TRUST_SETTINGS;
+    }
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuicontainerTrustedSite.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,474 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIContainerTrustedSite
+*                Reads & updates certificate list.
+*                Handles markable list for certificates.
+*
+*/
+
+
+// INCLUDE FILES
+#include <eikclbd.h>
+#include <AknIconArray.h>
+#include <csxhelp/cm.hlp.hrh>   // for help context of CertManUI
+#include <certmanui.rsg>
+
+#include "CertmanuiCertificateHelper.h"
+#include "CertmanuiKeeper.h"
+#include "CertmanuicontainerTrustedSite.h"
+#include "CertmanuiSyncWrapper.h"
+#include "Certmanui.hrh"
+#include "CertManUILogger.h"
+#include "CertmanuiCommon.h"
+
+#include "Certmanuidll.h"       // for applicationUID
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::CCertManUIContainerTrustedSite(
+// CCertManUIViewAuthority& aParent, CCertManUIKeeper& aKeeper)
+// Constructor with parent
+// ---------------------------------------------------------
+//
+CCertManUIContainerTrustedSite::CCertManUIContainerTrustedSite(
+    CCertManUIViewTrustedSite& aParent, CCertManUIKeeper& aKeeper ) :
+    iParent ( aParent ), iKeeper ( aKeeper )
+    {
+    CERTMANUILOGGER_WRITE_TIMESTAMP(
+        "CCertManUIContainerTrustedSite::CCertManUIContainerTrustedSite" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::~CCertManUIContainerTrustedSite()
+// Destructor
+// ---------------------------------------------------------
+//
+CCertManUIContainerTrustedSite::~CCertManUIContainerTrustedSite()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrustedSite::~CCertManUIContainerTrustedSite" );
+
+    delete iListBox;
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrustedSite::~CCertManUIContainerTrustedSite" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::ConstructL(
+// const TRect& aRect, TInt& aCurrentPosition, TInt& aTopItem)
+// EPOC two phased constructor
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrustedSite::ConstructL(
+    const TRect& aRect, TInt& aCurrentPosition, TInt& aTopItem )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrustedSite::ConstructL" );
+
+    CreateWindowL();
+    CreateListBoxL();
+    UpdateListBoxL( aCurrentPosition, aTopItem );
+    if ( iListBox )
+        {
+        // Creates graphic.
+        iListBox->ItemDrawer()->ColumnData()->
+             SetIconArray( iIconHandler->CreateIconArrayL() );
+    }
+    SetRect( aRect );
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrustedSite::ConstructL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::SizeChanged()
+// Called by framework when the view size is changed
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrustedSite::SizeChanged()
+    {
+    iListBox->SetRect( Rect() );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::FocusChanged(TDrawNow aDrawNow)
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrustedSite::FocusChanged( TDrawNow aDrawNow )
+    {
+    if ( iListBox )
+        {
+        iListBox->SetFocus( IsFocused(), aDrawNow );
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::HandleListBoxEventL(
+// CEikListBox* /*aListBox*/, TListBoxEvent aEventType)
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrustedSite::HandleListBoxEventL(
+    CEikListBox* /*aListBox*/, TListBoxEvent aEventType )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrustedSite::HandleListBoxEventL" );
+
+    switch( aEventType )
+        {
+        case EEventItemSingleClicked:
+        case EEventEnterKeyPressed:
+            {
+            const CListBoxView::CSelectionIndexArray* selections = iListBox->SelectionIndexes();
+            if ( iListItemCount > 0 )
+                {
+                if ( selections->Count() == 0 )
+                    {
+                    iKeeper.iCertificateHelper->MessageQueryViewDetailsL(
+                            iListBox->CurrentItemIndex(), KCertTypeTrustedSite, iEikonEnv );
+                    }
+                else
+                    {
+                    CEikMenuBar* menuBar = iParent.MenuBar();
+                    menuBar->SetContextMenuTitleResourceId( R_CERTMANUI_MENUBAR_OPTIONS_MARKED );
+                    menuBar->TryDisplayContextMenuBarL();
+                    }
+                }
+            break;
+            }
+
+        default:
+            {
+            break;
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrustedSite::HandleListBoxEventL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::CountComponentControls() const
+// ---------------------------------------------------------
+//
+TInt CCertManUIContainerTrustedSite::CountComponentControls() const
+    {
+    // return number of controls inside this container
+    return 1;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::ComponentControl(
+// TInt /*aIndex*/) const
+// ---------------------------------------------------------
+//
+CCoeControl* CCertManUIContainerTrustedSite::ComponentControl(
+    TInt /*aIndex*/) const
+    {
+    return iListBox;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::Draw(const TRect& aRect) const
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrustedSite::Draw( const TRect& aRect ) const
+    {
+    CWindowGc& gc = SystemGc();
+    gc.SetPenStyle( CGraphicsContext::ENullPen );
+    gc.SetBrushColor( KRgbGray );
+    gc.SetBrushStyle( CGraphicsContext::ESolidBrush );
+    gc.DrawRect( aRect );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::HandleControlEventL(
+//    CCoeControl* /*aControl*/,TCoeEvent /*aEventType*/)
+// Cannot be changed to non-leaving function.
+// L-function is required by the class definition, even if empty.
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrustedSite::HandleControlEventL(
+    CCoeControl* /*aControl*/,TCoeEvent /*aEventType*/)
+    {
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::OfferKeyEventL(
+// const TKeyEvent& aKeyEvent, TEventCode aType)
+// Handles the key events arrow keys, delete key.
+// ---------------------------------------------------------
+//
+TKeyResponse CCertManUIContainerTrustedSite::OfferKeyEventL(
+    const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrustedSite::OfferKeyEventL" );
+
+    // If operation is currenly onway, do not continue.
+    if ( iKeeper.iWrapper->IsActive() )
+        {
+        return EKeyWasNotConsumed;
+        }
+
+    TKeyResponse retval = EKeyWasNotConsumed;
+    if ( aType == EEventKey )
+        {
+        if ( aKeyEvent.iCode == EKeyRightArrow )
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL( KCertManUIViewPersonalId );
+            retval = EKeyWasConsumed;
+            }
+        else if ( aKeyEvent.iCode == EKeyLeftArrow )
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL( KCertManUIViewAuthorityId );
+            retval = EKeyWasConsumed;
+            }
+        else if ( aKeyEvent.iCode == EKeyDelete
+                  || aKeyEvent.iCode == EKeyBackspace )
+            {
+            TInt currentItemAuthority = iListBox->CurrentItemIndex();
+
+            if ( ( currentItemAuthority >= 0) &&
+                ( currentItemAuthority < iKeeper.iPeerLabelEntries.Count()))
+                {
+                // list is not empty
+                if ( iKeeper.iCertificateHelper->
+                              ConfirmationQueryDeleteCertL(
+                                                    KCertTypeTrustedSite,
+                                               iListBox ) ) // == ETrue
+                    {
+
+                    iParent.iCurrentPosition = iListBox->CurrentItemIndex();
+                    iParent.iTopItem = iListBox->TopItemIndex();
+
+                    DrawListBoxL(iParent.iCurrentPosition, iParent.iTopItem );
+                    // goes here if at least one certificate is deleted
+                    TRAPD( error, iKeeper.RefreshPeerCertEntriesL() );
+                    if ( error != KErrNone )
+                        {
+                        if ( error == KErrCorrupt )
+                            {
+                            iKeeper.ShowErrorNoteL( error );
+                            User::Exit( KErrNone );
+                            }
+                        else
+                            {
+                            // have to call straight away the Exit
+                            // showing any error notes would corrupt the display
+                            User::Exit( error );
+                            }
+                        }
+                    iParent.UpdateMenuBar();
+                    }
+                  }
+                // Listbox takes all event even if it doesn't use them
+                retval = EKeyWasConsumed;
+          }
+        else
+          {
+          retval = iListBox->OfferKeyEventL( aKeyEvent, aType );
+          }
+        }
+    else
+        {
+        retval = iListBox->OfferKeyEventL( aKeyEvent, aType );
+        }
+
+    if ( iListBox->SelectionIndexes()->Count() > 0 )
+        {
+        iParent.MenuBar()->SetContextMenuTitleResourceId( R_CERTMANUI_MENUBAR_OPTIONS_MARKED );
+        iParent.UpdateCba( R_CERTMANUI_OPTIONS_CONTEXT_BACK );
+        }
+    else
+        {
+        iParent.MenuBar()->SetMenuTitleResourceId( R_CERTMANUI_MENUBAR_VIEW_TRUSTED_SITES );
+        iParent.UpdateCba( R_CERTMANUI_OPTIONS_OPEN_BACK );
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrustedSite::OfferKeyEventL" );
+
+    return retval;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::CreateListBoxL()
+// Creates listbox, sets empty listbox text.
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrustedSite::CreateListBoxL()
+  {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrustedSite::CreateListBoxL()" );
+
+    iListBox = new( ELeave ) CAknSingleStyleListBox;
+    iListBox->SetContainerWindowL( *this );
+    iListBox->ConstructL( this, EAknListBoxMarkableList );
+    iListBox->CreateScrollBarFrameL( ETrue );
+    iListBox->ScrollBarFrame()->
+        SetScrollBarVisibilityL( CEikScrollBarFrame::EOff,CEikScrollBarFrame::EAuto );
+    iListBox->SetListBoxObserver( this );
+
+    HBufC* stringHolder = StringLoader::LoadLC(
+        R_TEXT_RESOURCE_VIEW_TRUSTED_EMPTY_LIST );
+    iListBox->View()->SetListEmptyTextL( *stringHolder );
+    CleanupStack::PopAndDestroy();  // stringHolder
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrustedSite::CreateListBoxL()" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::DrawListBoxL(TInt aCurrentPosition, TInt aTopItem)
+// Draws listbox, fetches graphic icons for markable list
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrustedSite::DrawListBoxL(
+    TInt aCurrentPosition, TInt aTopItem )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrustedSite::DrawListBoxL" );
+
+    if ( aCurrentPosition >= 0 )
+        {
+        iListBox->SetTopItemIndex( aTopItem );
+        iListBox->SetCurrentItemIndex( aCurrentPosition );
+        }
+    ActivateL();
+    DrawNow();
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrustedSite::DrawListBoxL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::UpdateListBoxL(TInt& aCurrentPosition, TInt& aTopItem)
+// Gets list of certificates from CertManAPI, displays them,
+// sets No label/No subject text to them if their names are empty
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrustedSite::UpdateListBoxL(
+    TInt& aCurrentPosition, TInt& aTopItem )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIContainerTrustedSite::UpdateListBoxL()" );
+
+    iKeeper.StartWaitDialogL( ECertmanUiWaitDialog );
+    CleanupCloseWaitDialogPushL( iKeeper );
+
+    MDesCArray* itemList = iListBox->Model()->ItemTextArray();
+    CDesCArray* itemArray = ( CDesCArray* )itemList;
+
+    if ( iKeeper.iCertsDatOK )  // == ETrue
+        {
+        // database is not corrupted, get count
+        iListItemCount = iKeeper.iPeerLabelEntries.Count();
+        }
+    else
+        {
+        iListItemCount = 0;
+        }
+
+    if (iListItemCount == 0 ) //list is empty, disable the scroll bar 
+        {
+    	iListBox->ScrollBarFrame()->SetScrollBarVisibilityL(
+	        CEikScrollBarFrame::EOff,CEikScrollBarFrame::EOff);
+        }
+    if ( iListItemCount > 0 )
+        {
+        if ( ( aCurrentPosition == -1 )
+            || ( aCurrentPosition > iListItemCount-1 ) )
+            {
+            aCurrentPosition = 0;
+            aTopItem = 0;
+            }
+
+        HBufC* buf = HBufC::NewLC( KMaxLengthTextCertLabel );
+        for ( TInt i = 0; i < iListItemCount; i++ )
+            {
+            buf->Des() = ( iKeeper.iPeerLabelEntries )[i]->iPeerEntryLabel->Des();
+
+            TPtrC trimmedCertLabel = iKeeper.iCertificateHelper->CutCertificateField( buf->Des() );
+            buf->Des().Copy( trimmedCertLabel );
+            TInt length = buf->Des().Length();
+            if ( length == 0 )
+                {
+                HBufC* stringHolder = NULL;
+
+                stringHolder = StringLoader::LoadLC(
+                           R_TEXT_RESOURCE_VIEW_NO_SUBJECT_LIST );
+
+                itemArray->AppendL( *stringHolder );
+                CleanupStack::PopAndDestroy();  // stringHolder
+                }
+            else
+                {
+                buf->Des().Insert( 0, KCertManUIInsertDescriptor );
+                itemArray->AppendL( buf->Des() );
+                }
+          iListBox->HandleItemAdditionL();
+          }
+      CleanupStack::PopAndDestroy();  // buf
+    }
+
+    CleanupStack::PopAndDestroy();    // closes wait dialog
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIContainerTrustedSite::UpdateListBoxL()" );
+  }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::HandleResourceChange
+//
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrustedSite::HandleResourceChange( TInt aType )
+    {
+    CCoeControl::HandleResourceChange( aType );
+
+    if ( aType == KEikDynamicLayoutVariantSwitch )
+        {
+        TRect mainPaneRect;
+        AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::EMainPane, mainPaneRect );
+        SetRect( mainPaneRect );
+        DrawNow();
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::IconArrayResourceId
+// Loads Mark/Unmark icons from resource
+// ---------------------------------------------------------
+//
+TInt CCertManUIContainerTrustedSite::IconArrayResourceId() const
+    {
+    return R_CERTMANUI_CERTIFICATE_LISTBOX_MARK_ICONS;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::CreateIconArrayL
+// Creates Icon Array
+// ---------------------------------------------------------
+//
+CAknIconArray* CCertManUIContainerTrustedSite::CreateIconArrayL() const
+    {
+    CAknIconArray* icons = new (ELeave) CAknIconArray( KGranularity );
+    CleanupStack::PushL( icons );
+    icons->ConstructFromResourceL( IconArrayResourceId() );
+    CleanupStack::Pop(); // icons
+    return icons;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIContainerTrustedSite::GetHelpContext
+// This function is called when Help application is launched.
+// (other items were commented in a header).
+// ---------------------------------------------------------
+//
+void CCertManUIContainerTrustedSite::GetHelpContext(
+    TCoeHelpContext& aContext ) const
+    {
+    aContext.iMajor = KUidCM;
+    aContext.iContext = KCM_HLP_TRUSTED_SITE;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/Certmanuidialogs.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,141 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CertManUIDialogs
+*
+*/
+
+
+// INCLUDE FILES
+
+#include <AknWaitDialog.h>
+#include <certmanui.rsg>
+#include "Certmanuidialogs.h"
+#include "CertManUILogger.h"
+#include "CertmanuiCommon.h"
+
+
+#ifdef _DEBUG
+_LIT( KDesCertmanUiFault, "CertmanUi" );
+#endif
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertManUiDialog::CCertManUiDialogs()
+// Default c++ constructor
+// ---------------------------------------------------------
+CCertManUIWaitDialog::CCertManUIWaitDialog()
+    {
+    iDialog = NULL;
+    }
+
+// ---------------------------------------------------------
+// CCertManUiDialog::~CCertManUiDialogs()
+// Destructor
+// ---------------------------------------------------------
+CCertManUIWaitDialog::~CCertManUIWaitDialog()
+    {
+    if ( iDialog )
+        {
+        delete iDialog;
+        }
+    }
+
+//---------------------------------------------------------------
+// CCertManUiDialog::StartWaitDialogL
+// Displays wait dialog
+//---------------------------------------------------------------
+void CCertManUIWaitDialog::StartWaitDialogL( TInt aDialogSelector )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIWaitDialog::StartWaitDialogL" );
+    TInt dialog = 0;
+
+    // If iDisplayed flag is true, but iDialog is NULL we have had leave.
+    // Reset iDisplayed to normalize situation
+    if(iDisplayed && iDialog == NULL)
+        {
+        iDisplayed = EFalse;
+        }
+
+    if(!iDisplayed)
+        {
+        if( !iDialog )
+           {
+            iDialog = new ( ELeave )CAknWaitDialog( REINTERPRET_CAST(CEikDialog**,
+                &iDialog), ETrue );	
+           } 
+
+
+        //CleanupStack::PushL(TCleanupItem(CleanupWaitDialog, (TAny**)&iDialog));
+
+        switch(aDialogSelector)
+            {
+            case ECertmanUiDeleteDialog:
+                LOG_WRITE("Show delete note");
+                dialog = R_CERTMANUI_DELETE_WAIT_NOTE;
+                break;
+
+            case ECertmanUiWaitDialog:
+                LOG_WRITE("Show wait note");
+                dialog = R_CERTMANUI_WAIT_NOTE;
+                break;
+            default:
+                __ASSERT_DEBUG( EFalse, User::Panic(KDesCertmanUiFault,
+                    EBadDialogSelector));
+                break;
+            }
+
+        iDialog->ExecuteLD(dialog);
+        iDisplayed = ETrue;
+        }
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIWaitDialog::StartWaitDialogL" );
+    }
+
+//---------------------------------------------------------------
+// CCertManUiDialog::CloseWaitDialogL
+// Close wait dialog
+//---------------------------------------------------------------
+void CCertManUIWaitDialog::CloseWaitDialogL()
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIWaitDialog::CloseWaitDialogL" );
+
+    if( iDialog )
+        {
+        iDialog->ProcessFinishedL();
+        //CleanupStack::PopAndDestroy();
+        }
+
+    iDisplayed = EFalse;
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIWaitDialog::CloseWaitDialogL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIWaitDialog::CleanupWaitDialog
+//
+// ---------------------------------------------------------
+void CCertManUIWaitDialog::CleanupWaitDialog(TAny* aAny)
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIWaitDialog::CleanupWaitDialog" );
+
+    CAknWaitDialog** dialog = (CAknWaitDialog**) aAny;
+    if ( dialog && *dialog )
+        {
+        delete *dialog;
+        }
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIWaitDialog::CleanupWaitDialog" );
+    }
+
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuiviewAuthority.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,572 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIViewAuthority
+*                Updates Options list depending of the number of
+*                marked and unmarked certificates in the listbox.
+*                Handles softkey and Option list commands.
+*                Handles certificate deletion including confirmation and
+*                read-only notes.
+*                Shows certificate details view with appropriate
+*                warning notes if certificate is corrupted/expired/not valid.
+*
+*/
+
+
+// INCLUDE FILES
+#include <aknmessagequerydialog.h>
+#include <aknnotewrappers.h>            // for warning & information notes
+#include <X509CertNameParser.h>
+#include <hash.h>                       // SHA-1 fingerprint
+#include <sysutil.h>
+#include <ErrorUI.h>
+#include <x509cert.h>
+#include <pkixcertchain.h>              //for validation
+#include <certmanui.rsg>
+#include "CertmanuiCertificateHelper.h"
+#include "CertmanuiKeeper.h"
+#include "CertmanuiviewAuthority.h"
+#include "CertmanuicontainerAuthority.h"
+#include "Certmanui.hrh"
+#include "Certmanuitrustids.h"
+#include "CertmanuiSyncWrapper.h"
+#include "CertmanuiCommon.h"
+#include "CertManUILogger.h"
+#include    <hlplch.h>                   // For HlpLauncher
+#include    <featmgr.h>                  // For HlpLauncher
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::CCertManUIViewAuthority(CCertManUIKeeper& aKeeper)
+// : iKeeper(aKeeper), iCrMgr(iKeeper.CertManager())
+// Constructor
+// ---------------------------------------------------------
+//
+CCertManUIViewAuthority::CCertManUIViewAuthority( CCertManUIKeeper& aKeeper )
+    : iKeeper( aKeeper )
+    {
+    CERTMANUILOGGER_WRITE_TIMESTAMP(
+        "CCertManUIViewAuthority::CCertManUIViewAuthority" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::~CCertManUIViewAuthority()
+// Destructor
+// ---------------------------------------------------------
+//
+CCertManUIViewAuthority::~CCertManUIViewAuthority()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewAuthority::~CCertManUIViewAuthority" );
+
+    if ( iContainerAuthority )
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainerAuthority );
+        delete iContainerAuthority;
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewAuthority::~CCertManUIViewAuthority" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority* CCertManUIViewAuthority::NewL(
+//      const TRect& /*aRect*/, CCertManUIKeeper& aKeeper)
+// ---------------------------------------------------------
+//
+CCertManUIViewAuthority* CCertManUIViewAuthority::NewL(
+    const TRect& /*aRect*/, CCertManUIKeeper& aKeeper )
+    {
+    CCertManUIViewAuthority* self =
+        new ( ELeave ) CCertManUIViewAuthority( aKeeper );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority* CCertManUIViewAuthority::NewLC(
+//  const TRect& /*aRect*/, CCertManUIKeeper& aKeeper)
+// ---------------------------------------------------------
+//
+CCertManUIViewAuthority* CCertManUIViewAuthority::NewLC(
+    const TRect& /*aRect*/, CCertManUIKeeper& aKeeper )
+    {
+    CCertManUIViewAuthority* self =
+        new ( ELeave ) CCertManUIViewAuthority( aKeeper );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::ConstructL()
+// EPOC two-phased constructor
+// ---------------------------------------------------------
+//
+void CCertManUIViewAuthority::ConstructL()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewAuthority::ConstructL" );
+
+    BaseConstructL( R_CERTMANUI_VIEW_MAIN_AUTHORITY );
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewAuthority::ConstructL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::DynInitMenuPaneL(
+//      TInt aResourceId,CEikMenuPane* aMenuPane)
+// Updates Options list with correct items depending on
+// whether the listbox is empty or if it has any marked items
+// ---------------------------------------------------------
+//
+void CCertManUIViewAuthority::DynInitMenuPaneL(
+    TInt aResourceId, CEikMenuPane* aMenuPane )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewAuthority::DynInitMenuPaneL" );
+
+    if (( iKeeper.iWrapper->IsActive()) ||
+        ( iContainerAuthority->iListBox->CurrentItemIndex() >= iKeeper.iCALabelEntries.Count()) )
+        {
+        return;
+        }
+
+    const CListBoxView::CSelectionIndexArray* selections =
+            iContainerAuthority->iListBox->SelectionIndexes();
+    const TInt markedCount = selections->Count();
+    const TInt currentItemIndex = iContainerAuthority->iListBox->CurrentItemIndex();
+
+    switch ( aResourceId )
+        {
+        case R_CERTMANUI_VIEW_MENU_AUTHORITY:
+            {
+            if( !FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+               {
+               aMenuPane->DeleteMenuItem( EAknCmdHelp );
+               }
+
+            // the certificate list is empty, all except Exit are dimmed
+            if ( currentItemIndex == -1 )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdAppViewDtls, ETrue );
+                aMenuPane->SetItemDimmed( ECertManUICmdAppDelete, ETrue );
+                aMenuPane->SetItemDimmed( ECertManUICmdAppTrustSet, ETrue );
+                aMenuPane->SetItemDimmed( ECertManUICmdMarkUnmark, ETrue );
+                }
+            else
+                {
+                if ( markedCount == 1 )
+                    {
+                    aMenuPane->SetItemDimmed( ECertManUICmdAppViewDtls, ETrue );
+                    }
+
+                if ( markedCount > 0 )
+                    {
+                    aMenuPane->SetItemDimmed( ECertManUICmdAppViewDtls, ETrue );
+                    aMenuPane->SetItemDimmed( ECertManUICmdAppTrustSet, ETrue );
+                    }
+
+                if ( !iKeeper.iCertificateHelper->IsOneMarkedCertificateDeletable(
+                        iContainerAuthority->iListBox, KCertTypeAuthority ) )
+                    {
+                    aMenuPane->SetItemDimmed( ECertManUICmdAppDelete, ETrue );
+                    }
+                }
+            break;
+            }
+
+        case R_CERTMANUI_MENUPANE_OPTIONS_MARKED:
+            {
+            if ( !iKeeper.iCertificateHelper->IsOneMarkedCertificateDeletable(
+                    iContainerAuthority->iListBox, KCertTypeAuthority ) )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdAppDelete, ETrue );
+                }
+
+            // not available for authority certificates
+            aMenuPane->SetItemDimmed( ECertManUICmdMoveToDevice, ETrue );
+            aMenuPane->SetItemDimmed( ECertManUICmdMoveToPersonal, ETrue );
+            }
+            // FALLTHROUGH
+
+        case R_CERTMANUI_MENU_PANE_MARK_UNMARK:
+            {
+            TInt index = 0;
+            TKeyArrayFix key( 0, ECmpTInt );
+            if ( selections->Find( currentItemIndex, key, index ) )
+                {   // focus is on unmarked item
+                aMenuPane->SetItemDimmed( ECertManUICmdUnmark, ETrue );
+                }
+            else
+                {   // focus is on marked item
+                aMenuPane->SetItemDimmed( ECertManUICmdMark, ETrue );
+                }
+
+            // if all items are marked, dim "mark all" option
+            if ( markedCount == iContainerAuthority->iListBox->Model()->NumberOfItems() )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdMarkAll, ETrue );
+                }
+
+            // if no items are marked, dim "unmark all" option
+            if ( markedCount == 0 )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdUnmarkAll, ETrue );
+                }
+            break;
+            }
+
+        default:
+            break;
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewAuthority::DynInitMenuPaneL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::Id() const
+// Returns Authority view id
+// ---------------------------------------------------------
+//
+TUid CCertManUIViewAuthority::Id() const
+    {
+    return KCertManUIViewAuthorityId;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::HandleCommandL(TInt aCommand)
+// Handles Softkey and Options list commands
+// ---------------------------------------------------------
+//
+void CCertManUIViewAuthority::HandleCommandL( TInt aCommand )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewAuthority::HandleCommandL" );
+
+    if (( iKeeper.iWrapper->IsActive() ) ||
+        ( iContainerAuthority->iListBox->CurrentItemIndex() >= iKeeper.iCALabelEntries.Count() ))
+        {
+        return;
+        }
+
+    switch ( aCommand )
+        {
+        case EAknSoftkeyBack:
+            {
+            // Activate main view
+            AppUi()->ActivateLocalViewL( KCertManUIViewMainId );
+            break;
+            }
+        // put the view specific menu commands here
+        case EAknCmdExit:
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->HandleCommandL( EAknCmdExit );
+            break;
+            }
+        case ECertManUICmdAppViewDtls:
+            {
+            iKeeper.iCertificateHelper->MessageQueryViewDetailsL(
+                iContainerAuthority->iListBox->CurrentItemIndex(),
+                KCertTypeAuthority, iEikonEnv );
+            break;
+            }
+        case ECertManUICmdAppDelete:
+            {
+            if ( iKeeper.iCertificateHelper->ConfirmationQueryDeleteCertL( KCertTypeAuthority,
+                                                    iContainerAuthority->iListBox ) )
+                {
+                // goes here if at least one certificate is deleted
+                iCurrentPosition = iContainerAuthority->iListBox->CurrentItemIndex();
+                iTopItem = iContainerAuthority->iListBox->TopItemIndex();
+
+                iContainerAuthority->DrawListBoxL(iCurrentPosition, iTopItem );
+                TRAPD( error, iKeeper.RefreshCAEntriesL() );
+                if ( error != KErrNone )
+                    {
+                    if ( error == KErrCorrupt )
+                        {
+                        iKeeper.ShowErrorNoteL( error);
+                        User::Exit( KErrNone );
+                        }
+                    else
+                        {
+                        // have to call straight away the Exit
+                        // showing any error notes would corrupt the display
+                        User::Exit( error );
+                        }
+                    }
+                UpdateMenuBar();
+                }
+            break;
+            }
+        case ECertManUICmdMark:
+        case ECertManUICmdUnmark:
+        case ECertManUICmdMarkAll:
+        case ECertManUICmdUnmarkAll:
+            {
+            // Gets pointer of current listbox.
+            CEikListBox* listbox = iContainerAuthority->iListBox;
+            if ( listbox )
+                {
+                AknSelectionService::HandleMarkableListProcessCommandL(
+                    aCommand, listbox );
+
+                iKeeper.iCertificateHelper->HandleMarkableListCommandL(
+                                      aCommand, iContainerAuthority->iListBox );
+
+                UpdateMenuBar();
+                }
+            break;
+            }
+        case ECertManUICmdAppTrustSet:
+            {
+            TInt helpIndex3 = iContainerAuthority->iListBox->CurrentItemIndex();
+            CEikStatusPane* sp = STATIC_CAST(
+                CAknAppUi*, iEikonEnv->EikAppUi())->StatusPane();
+            // Fetch pointer to the default title pane control
+            CAknTitlePane* title = STATIC_CAST(
+                CAknTitlePane*,
+                sp->ControlL( TUid::Uid( EEikStatusPaneUidTitle ) ));
+
+            // Creating the correct title text for Trust Settings view
+            HBufC* buf = HBufC::NewLC( KMaxLengthTextCertLabel );
+
+            // Get Cert entries
+            buf->Des() =
+                (iKeeper.iCALabelEntries)[helpIndex3]->iCAEntryLabel->Des();
+            buf->Des().TrimLeft();
+            // Cut CertLabel after fourth semi colon
+            TPtrC trimmedCertLabel = iKeeper.iCertificateHelper->CutCertificateField( buf->Des() );
+            buf->Des().Copy( trimmedCertLabel );
+            TInt length = buf->Des().Length();
+            if (length == 0)
+                {
+                HBufC* stringHolder = NULL;
+
+                stringHolder = StringLoader::LoadLC(
+                       R_TEXT_RESOURCE_VIEW_NO_SUBJECT_TITLE );
+
+                title->SetTextL(stringHolder->Des());
+                CleanupStack::PopAndDestroy();  // stringHolder
+                }
+            else
+                {
+                title->SetTextL( buf->Des() );
+                }
+            CleanupStack::PopAndDestroy();  // buf
+
+            ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL(
+                KCertManUIViewTrustId, TUid::Uid( helpIndex3), KNullDesC8 );
+            break;
+            }
+        case EAknCmdHelp:
+            {
+            if( FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+                {
+                HlpLauncher::LaunchHelpApplicationL(
+                    iEikonEnv->WsSession(), AppUi()->AppHelpContextL() );
+                }
+            break;
+            }
+
+        default:
+            {
+            AppUi()->HandleCommandL( aCommand );
+            break;
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewAuthority::HandleCommandL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::HandleClientRectChange()
+// ---------------------------------------------------------
+//
+void CCertManUIViewAuthority::HandleClientRectChange()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewAuthority::HandleClientRectChange" );
+
+    if ( iContainerAuthority )
+        {
+        iContainerAuthority->SetRect( ClientRect() );
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewAuthority::HandleClientRectChange" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::DoActivateL(const TVwsViewId& /*aPrevViewId*/,
+//      TUid /*aCustomMessageId*/, const TDesC8& /*aCustomMessage*/)
+// Updates the view when opening it
+// ---------------------------------------------------------
+//
+void CCertManUIViewAuthority::DoActivateL(
+    const TVwsViewId& aPrevViewId,
+    TUid /*aCustomMessageId*/, const TDesC8& /*aCustomMessage*/)
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewAuthority::DoActivateL" );
+
+    iKeeper.StartWaitDialogL( ECertmanUiWaitDialog );
+    CleanupCloseWaitDialogPushL( iKeeper );
+
+    TRAPD ( error, iKeeper.RefreshCAEntriesL() );
+    if ( error != KErrNone )
+        {
+        if ( error == KErrCorrupt )
+            {
+            iKeeper.ShowErrorNoteL( error );
+            User::Exit( KErrNone );
+            }
+        else
+            {
+            // have to call straight away the Exit
+            // showing any error notes would corrupt the display
+            User::Exit( error );
+            }
+        }
+
+    // If this view is being activated from main view,
+    // current position is 0. The declaration of KCertManUIViewMainId is
+    // located in certmanuiviewid.h which is not public header --> constant
+    // is being used.
+    if( aPrevViewId.iViewUid == KCertManUIViewMainId )
+        {
+        iCurrentPosition = 0;
+        }
+
+    if ( iContainerAuthority )
+        {
+        ((CAknViewAppUi*)iAvkonAppUi)->RemoveFromViewStack(
+            *this, iContainerAuthority );
+
+        delete iContainerAuthority;
+        iContainerAuthority = NULL;
+        }
+    iContainerAuthority = new (ELeave) CCertManUIContainerAuthority(
+        *this, iKeeper );
+
+    iContainerAuthority->SetMopParent( this );
+    iContainerAuthority->ConstructL(
+        ClientRect(), iCurrentPosition, iTopItem );
+
+    if ( !iKeeper.iCertsDatOK )
+        {
+        iCurrentPosition = 0;
+        iTopItem = 0;
+        }
+
+    iKeeper.ActivateTitleL( KViewTitleCertManUIAuthority );
+
+    iContainerAuthority->DrawListBoxL( iCurrentPosition, iTopItem );
+    ((CAknViewAppUi*)iAvkonAppUi)->AddToStackL( *this, iContainerAuthority );
+
+    UpdateMenuBar();
+
+    CleanupStack::PopAndDestroy();    // closes wait dialog
+
+    iKeeper.iStartup = EFalse;
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewAuthority::DoActivateL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::DoDeactivate()
+// Saves focus position when closing view
+// ---------------------------------------------------------
+//
+void CCertManUIViewAuthority::DoDeactivate()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewAuthority::DoDeactivate" );
+
+    if ( iKeeper.iCertsDatOK )
+        {
+        iCurrentPosition = iContainerAuthority->iListBox->CurrentItemIndex();
+        iTopItem = iContainerAuthority->iListBox->TopItemIndex();
+        // do not destroy iContainerAuthority here because
+        // TrustSettings view needs it !
+        }
+    else
+        {
+        iCurrentPosition = 0;
+        iTopItem = 0;
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewAuthority::DoDeactivate" ); //lint !e539
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::Container()
+// Returns iContainerAuthority to be used in CertManUIContainerAuthority
+// ---------------------------------------------------------
+//
+CCoeControl* CCertManUIViewAuthority::Container()
+    {
+    return iContainerAuthority;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::UpdateMenuBar()
+// Updates the menu bar
+// ---------------------------------------------------------
+//
+void CCertManUIViewAuthority::UpdateMenuBar()
+    {
+    CEikButtonGroupContainer*  cba = Cba();
+
+    if ( cba == NULL )
+        {
+        return;
+        }
+
+    if ( iKeeper.iCALabelEntries.Count() == 0 )
+        {
+        // No certificate. Don't show MSK
+        UpdateCba( R_CERTMANUI_OPTIONS_OPEN_BACK );
+        cba->MakeCommandVisible( ECertManUICmdAppViewDtls, EFalse );
+        }
+    else
+        {
+        if ( iContainerAuthority->iListBox->SelectionIndexes()->Count() > 0 )
+            {
+            MenuBar()->SetContextMenuTitleResourceId( R_CERTMANUI_MENUBAR_OPTIONS_MARKED );
+            UpdateCba( R_CERTMANUI_OPTIONS_CONTEXT_BACK );
+            }
+        else
+            {
+            MenuBar()->SetMenuTitleResourceId( R_CERTMANUI_MENUBAR_VIEW_AUTHORITY );
+            UpdateCba( R_CERTMANUI_OPTIONS_OPEN_BACK );
+            }
+         }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewAuthority::UpdateCba( TInt aCbaResourceId )
+// Updates cba
+// ---------------------------------------------------------
+//
+void CCertManUIViewAuthority::UpdateCba( TInt aCbaResourceId )
+    {
+    CEikButtonGroupContainer*  cba = Cba();
+
+    if ( cba )
+        {
+        cba->SetCommandSetL( aCbaResourceId );
+        cba->DrawNow();
+        }
+    }
+
+
+// End of File
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuiviewDevice.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,612 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIViewDevice
+*                Updates Options list depending of the number of
+*                marked and unmarked certificates in the listbox.
+*                Handles softkey and Option list commands.
+*                Handles certificate deletion including confirmation and
+*                read-only notes.
+*                Shows certificate details view with appropriate
+*                warning notes if certificate is corrupted/expired/not valid.
+*
+*/
+
+
+// INCLUDE FILES
+#include <aknmessagequerydialog.h>
+#include <aknnotewrappers.h>            // for warning & information notes
+#include <X509CertNameParser.h>
+#include <ErrorUI.h>
+#include <x509cert.h>
+#include <pkixcertchain.h>              //for validation
+#include <certmanui.rsg>
+#include "CertmanuiCertificateHelper.h"
+#include "CertmanuiKeeper.h"
+#include "CertmanuiviewDevice.h"
+#include "CertmanuicontainerDevice.h"
+#include "Certmanui.hrh"
+#include "Certmanuitrustids.h"
+#include "CertmanuiSyncWrapper.h"
+#include "CertmanuiCommon.h"
+#include "CertManUILogger.h"
+
+#include    <hlplch.h>                  // For HlpLauncher
+#include    <featmgr.h>                 // For FeatureManager
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertManUIViewDevice::CCertManUIViewDevice(CCertManUIKeeper& aKeeper)
+// : iKeeper(aKeeper), iCrMgr(iKeeper.CertManager())
+// Constructor
+// ---------------------------------------------------------
+//
+CCertManUIViewDevice::CCertManUIViewDevice( CCertManUIKeeper& aKeeper )
+    : iKeeper( aKeeper )
+    {
+    CERTMANUILOGGER_WRITE_TIMESTAMP(
+        "CCertManUIViewDevice::CCertManUIViewDevice" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewDevice::~CCertManUIViewDevice()
+// Destructor
+// ---------------------------------------------------------
+//
+CCertManUIViewDevice::~CCertManUIViewDevice()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewDevice::~CCertManUIViewDevice" );
+
+    if ( iContainerDevice )
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainerDevice );
+        delete iContainerDevice;
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewDevice::~CCertManUIViewDevice" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewDevice* CCertManUIViewDevice::NewL(
+//      const TRect& /*aRect*/, CCertManUIKeeper& aKeeper)
+// ---------------------------------------------------------
+//
+CCertManUIViewDevice* CCertManUIViewDevice::NewL(
+    const TRect& /*aRect*/, CCertManUIKeeper& aKeeper )
+    {
+    CCertManUIViewDevice* self =
+        new ( ELeave ) CCertManUIViewDevice( aKeeper );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewDevice* CCertManUIViewDevice::NewLC(
+//  const TRect& /*aRect*/, CCertManUIKeeper& aKeeper)
+// ---------------------------------------------------------
+//
+CCertManUIViewDevice* CCertManUIViewDevice::NewLC(
+    const TRect& /*aRect*/, CCertManUIKeeper& aKeeper )
+    {
+    CCertManUIViewDevice* self =
+        new ( ELeave ) CCertManUIViewDevice( aKeeper );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewDevice::ConstructL()
+// EPOC two-phased constructor
+// ---------------------------------------------------------
+//
+void CCertManUIViewDevice::ConstructL()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewDevice::ConstructL" );
+
+    BaseConstructL( R_CERTMANUI_VIEW_MAIN_DEVICE );
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewDevice::ConstructL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewDevice::DynInitMenuPaneL(
+//      TInt aResourceId,CEikMenuPane* aMenuPane)
+// Updates Options list with correct items depending on
+// whether the listbox is empty or if it has any marked items
+// ---------------------------------------------------------
+//
+void CCertManUIViewDevice::DynInitMenuPaneL(
+    TInt aResourceId, CEikMenuPane* aMenuPane )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewDevice::DynInitMenuPaneL" );
+
+    if (( iKeeper.iWrapper->IsActive()) ||
+        ( iContainerDevice->iListBox->CurrentItemIndex() >= iKeeper.iDeviceLabelEntries.Count()))
+        {
+        return;
+        }
+
+    const CListBoxView::CSelectionIndexArray* selections =
+            iContainerDevice->iListBox->SelectionIndexes();
+    const TInt markedCount = selections->Count();
+    const TInt currentItemIndex = iContainerDevice->iListBox->CurrentItemIndex();
+
+    switch ( aResourceId )
+        {
+        case R_CERTMANUI_VIEW_MENU_DEVICE:
+            {
+            if( !FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+                {
+                aMenuPane->DeleteMenuItem( EAknCmdHelp );
+                }
+
+            // the certificate list is empty, all except Exit are dimmed
+            if ( currentItemIndex == -1 )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdAppViewDtls, ETrue );
+                aMenuPane->SetItemDimmed( ECertManUICmdAppDelete, ETrue );
+                aMenuPane->SetItemDimmed( ECertManUICmdMoveToPersonal, ETrue );
+                aMenuPane->SetItemDimmed( ECertManUICmdMarkUnmark, ETrue );
+                }
+            else
+                {
+                if ( markedCount == 1 )
+                    {
+                    aMenuPane->SetItemDimmed( ECertManUICmdAppViewDtls, ETrue );
+                    }
+
+                if ( markedCount > 1 )
+                    {
+                    aMenuPane->SetItemDimmed( ECertManUICmdAppViewDtls, ETrue );
+                    aMenuPane->SetItemDimmed( ECertManUICmdMoveToPersonal, ETrue );
+                    }
+
+                if ( !iKeeper.iCertificateHelper->IsOneMarkedCertificateDeletable(
+                        iContainerDevice->iListBox, KCertTypeDevice ) )
+                    {
+                    aMenuPane->SetItemDimmed( ECertManUICmdAppDelete, ETrue );
+                    aMenuPane->SetItemDimmed( ECertManUICmdMoveToPersonal, ETrue );
+                    }
+                }
+            break;
+            }
+
+        case R_CERTMANUI_MENUPANE_OPTIONS_MARKED:
+            {
+            if ( markedCount > 1 )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdMoveToPersonal, ETrue );
+                }
+
+            if ( !iKeeper.iCertificateHelper->IsOneMarkedCertificateDeletable(
+                    iContainerDevice->iListBox, KCertTypeDevice ) )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdAppDelete, ETrue );
+                }
+
+            // not available for device certificates
+            aMenuPane->SetItemDimmed( ECertManUICmdMoveToDevice, ETrue );
+            }
+            // FALLTHROUGH
+
+        case R_CERTMANUI_MENU_PANE_MARK_UNMARK:
+            {
+            TInt index = 0;
+            TKeyArrayFix key( 0, ECmpTInt );
+            if ( selections->Find( currentItemIndex, key, index ) )
+                {   // focus is on unmarked item
+                aMenuPane->SetItemDimmed( ECertManUICmdUnmark, ETrue );
+                }
+            else
+                {   // focus is on marked item
+                aMenuPane->SetItemDimmed( ECertManUICmdMark, ETrue );
+                }
+
+            // if all items are marked, dim "mark all" option
+            if ( markedCount == iContainerDevice->iListBox->Model()->NumberOfItems() )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdMarkAll, ETrue );
+                }
+
+            // if no items are marked, dim "unmark all" option
+            if ( markedCount == 0 )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdUnmarkAll, ETrue );
+                }
+            break;
+            }
+
+        default:
+            break;
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewDevice::DynInitMenuPaneL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewDevice::Id() const
+// Returns Authority view id
+// ---------------------------------------------------------
+//
+TUid CCertManUIViewDevice::Id() const
+    {
+    return KCertManUIViewDeviceId;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewDevice::HandleCommandL(TInt aCommand)
+// Handles Softkey and Options list commands
+// ---------------------------------------------------------
+//
+void CCertManUIViewDevice::HandleCommandL( TInt aCommand )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewDevice::HandleCommandL" );
+
+    if (( iKeeper.iWrapper->IsActive() ) ||
+        ( iContainerDevice->iListBox->CurrentItemIndex() >= iKeeper.iDeviceLabelEntries.Count() ))
+        {
+        return;
+        }
+
+    switch ( aCommand )
+        {
+        case EAknSoftkeyBack:
+            {
+            // Activate main view
+            AppUi()->ActivateLocalViewL( KCertManUIViewMainId );
+            break;
+            }
+        // put the view specific menu commands here
+        case EAknCmdExit:
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->HandleCommandL( EAknCmdExit );
+            break;
+            }
+        case ECertManUICmdAppViewDtls:
+            {
+            iKeeper.iCertificateHelper->MessageQueryViewDetailsL(
+                iContainerDevice->iListBox->CurrentItemIndex(),
+                KCertTypeDevice, iEikonEnv );
+            break;
+            }
+        case ECertManUICmdAppDelete:
+            {
+            if ( iKeeper.iCertificateHelper->ConfirmationQueryDeleteCertL( KCertTypeDevice,
+                                                    iContainerDevice->iListBox) )
+                {
+                // goes here if at least one certificate is deleted
+                iCurrentPosition = iContainerDevice->iListBox->CurrentItemIndex();
+                iTopItem = iContainerDevice->iListBox->TopItemIndex();
+
+                iContainerDevice->DrawListBoxL(iCurrentPosition, iTopItem );
+                TRAPD( error, iKeeper.RefreshDeviceCertEntriesL() );
+                if ( error != KErrNone )
+                    {
+                    if ( error == KErrCorrupt )
+                        {
+                        iKeeper.ShowErrorNoteL( error );
+                        User::Exit( KErrNone );
+                        }
+                    else
+                        {
+                        // have to call straight away the Exit
+                        // showing any error notes would corrupt the display
+                        User::Exit( error );
+                        }
+                    }
+                UpdateMenuBar();
+                }
+            break;
+            }
+       case ECertManUICmdMoveToPersonal:
+            {
+            HBufC* prompt = StringLoader::LoadLC(
+                        R_QTN_CM_CONF_MOVE_TO_PERSONAL );
+            TInt selection = iKeeper.iCertificateHelper->DisplayConfirmationLD(prompt);
+            if ( selection )
+                {
+                TInt focusPosition = 0;
+                
+                const CArrayFix<TInt>* array = iContainerDevice->iListBox->SelectionIndexes();
+                
+                if ( array->Count() == 1 )
+                    {
+                    // item is marked
+                    focusPosition = array->At( 0 );
+                    }
+                else
+                    {
+                    // There is no marked item. Select higlighted item 
+                    focusPosition = iContainerDevice->iListBox->CurrentItemIndex();
+                    }
+                                                        
+                CCTCertInfo* entry = iKeeper.iDeviceLabelEntries[ focusPosition ]->iDeviceEntry;
+
+                // Move key first
+                TCTKeyAttributeFilter keyFilter;
+                keyFilter.iKeyId = entry->SubjectKeyId();
+                keyFilter.iPolicyFilter =  TCTKeyAttributeFilter::EAllKeys;
+
+                TRAPD( error, iKeeper.iCertificateHelper->MoveKeyL( keyFilter,
+                                KCMDeviceKeyStoreTokenUid, KCMFileKeyStoreTokenUid ));
+
+                if ( error == KErrNone )
+                    {
+                    iKeeper.iCertificateHelper->MoveCertL(
+                                                      *entry,
+                                                      focusPosition,
+                                                      iContainerDevice->iListBox,
+                                                      KCMDeviceCertStoreTokenUid,
+                                                      KCMFileCertStoreTokenUid );
+
+                    TRAP( error, iKeeper.RefreshDeviceCertEntriesL() );
+                    if ( error != KErrNone )
+                        {
+                        if ( error == KErrCorrupt )
+                            {
+                            iKeeper.ShowErrorNoteL( error );
+                            User::Exit( KErrNone );
+                            }
+                        else
+                            {
+                            // have to call straight away the Exit
+                            // showing any error notes would corrupt the display
+                            User::Exit( error );
+                            }
+                        }
+
+                    MDesCArray* itemList = iContainerDevice->iListBox->Model()->ItemTextArray();
+                    CDesCArray* itemArray = ( CDesCArray* )itemList;
+                    if (( itemArray != NULL ) && ( itemArray->Count() == 0 ))
+                        {
+                        iCurrentPosition = 0;
+                        iTopItem = 0;
+                        iContainerDevice->UpdateListBoxL( iCurrentPosition, iTopItem );
+                        }
+                     else
+                        {
+                        iCurrentPosition = iContainerDevice->iListBox->CurrentItemIndex();
+                        iTopItem = iContainerDevice->iListBox->TopItemIndex();
+                        }
+
+                    iContainerDevice->DrawListBoxL(iCurrentPosition, iTopItem );
+
+                    UpdateMenuBar();
+                    }
+                }
+            break;
+            }
+        case ECertManUICmdMark:
+        case ECertManUICmdUnmark:
+        case ECertManUICmdMarkAll:
+        case ECertManUICmdUnmarkAll:
+            {
+            // Gets pointer of current listbox.
+            CEikListBox* listbox = iContainerDevice->iListBox;
+            if ( listbox )
+                {
+                AknSelectionService::HandleMarkableListProcessCommandL(
+                    aCommand, listbox );
+
+                iKeeper.iCertificateHelper->
+                                    HandleMarkableListCommandL(
+                                                              aCommand,
+                                                              iContainerDevice->iListBox
+                                                              );
+
+                UpdateMenuBar();
+                }
+            break;
+            }
+        case EAknCmdHelp:
+            {
+            if( FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+                {
+                HlpLauncher::LaunchHelpApplicationL(
+                   iEikonEnv->WsSession(), AppUi()->AppHelpContextL() );
+                }
+
+            break;
+            }
+
+        default:
+            {
+            AppUi()->HandleCommandL( aCommand );
+            break;
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewDevice::HandleCommandL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewDevice::HandleClientRectChange()
+// ---------------------------------------------------------
+//
+void CCertManUIViewDevice::HandleClientRectChange()
+    {
+    if ( iContainerDevice )
+        {
+        iContainerDevice->SetRect( ClientRect() );
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewDevice::DoActivateL(const TVwsViewId& /*aPrevViewId*/,
+//      TUid /*aCustomMessageId*/, const TDesC8& /*aCustomMessage*/)
+// Updates the view when opening it
+// ---------------------------------------------------------
+//
+void CCertManUIViewDevice::DoActivateL(
+    const TVwsViewId& aPrevViewId,
+    TUid /*aCustomMessageId*/, const TDesC8& /*aCustomMessage*/)
+    {
+     CERTMANUILOGGER_ENTERFN( " CCertManUIViewDevice::DoActivateL" );
+
+     iKeeper.StartWaitDialogL( ECertmanUiWaitDialog );
+     CleanupCloseWaitDialogPushL( iKeeper );
+
+     TRAPD ( error, iKeeper.RefreshDeviceCertEntriesL() );
+     if ( error != KErrNone )
+         {
+         if ( error == KErrCorrupt )
+             {
+             iKeeper.ShowErrorNoteL( error );
+             User::Exit( KErrNone );
+             }
+         else
+             {
+             // have to call straight away the Exit
+             // showing any error notes would corrupt the display
+             User::Exit( error );
+             }
+         }
+
+    // If this view is being activated from main view,
+    // current position is 0. The declaration of KCertManUIViewMainId is
+    // located in certmanuiviewid.h which is not public header --> constant
+    // is being used.
+    if( aPrevViewId.iViewUid == KCertManUIViewMainId )
+        {
+        iCurrentPosition = 0;
+        }
+
+    if ( iContainerDevice )
+        {
+        ((CAknViewAppUi*)iAvkonAppUi)->RemoveFromViewStack(
+            *this, iContainerDevice );
+
+        delete iContainerDevice;
+        iContainerDevice = NULL;
+        }
+
+    iContainerDevice = new (ELeave) CCertManUIContainerDevice(
+        *this, iKeeper );
+
+    iContainerDevice->SetMopParent( this );
+    iContainerDevice->ConstructL(
+        ClientRect(), iCurrentPosition, iTopItem );
+
+    if ( !iKeeper.iCertsDatOK )
+        {
+        iCurrentPosition = 0;
+        iTopItem = 0;
+        }
+
+    iKeeper.ActivateTitleL( KViewTitleCertManUIDevice );
+
+    iContainerDevice->DrawListBoxL( iCurrentPosition, iTopItem );
+    ((CAknViewAppUi*)iAvkonAppUi)->AddToStackL( *this, iContainerDevice );
+
+    UpdateMenuBar();
+
+    CleanupStack::PopAndDestroy();    // closes wait dialog
+
+    iKeeper.iStartup = EFalse;
+
+     CERTMANUILOGGER_LEAVEFN( " CCertManUIViewDevice::DoActivateL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewDevice::DoDeactivate()
+// Saves focus position when closing view
+// ---------------------------------------------------------
+//
+void CCertManUIViewDevice::DoDeactivate()
+    {
+     CERTMANUILOGGER_ENTERFN( " CCertManUIViewDevice::DoDeactivate" );
+
+    if ( iKeeper.iCertsDatOK )
+        {
+        iCurrentPosition = iContainerDevice->iListBox->CurrentItemIndex();
+        iTopItem = iContainerDevice->iListBox->TopItemIndex();
+        }
+    else
+        {
+        iCurrentPosition = 0;
+        iTopItem = 0;
+        }
+
+     CERTMANUILOGGER_LEAVEFN( " CCertManUIViewDevice::DoDeactivate" ); //lint !e539
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewDevice::Container()
+// Returns iContainerDevice to be used in CertManUiContainerDevice
+// ---------------------------------------------------------
+//
+CCoeControl* CCertManUIViewDevice::Container()
+    {
+    return iContainerDevice;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewDevice::UpdateMenuBar()
+// Updates the menu bar
+// ---------------------------------------------------------
+//
+void CCertManUIViewDevice::UpdateMenuBar()
+    {
+    CEikButtonGroupContainer*  cba = Cba();
+
+    if ( cba == NULL )
+        {
+        return;
+        }
+
+    if ( iKeeper.iDeviceLabelEntries.Count() == 0 )
+        {
+        // No certificate. Don't show MSK
+        UpdateCba( R_CERTMANUI_OPTIONS_OPEN_BACK );
+        cba->MakeCommandVisible( ECertManUICmdAppViewDtls, EFalse );
+        }
+    else
+        {
+        if ( iContainerDevice->iListBox->SelectionIndexes()->Count() > 0 )
+            {
+            MenuBar()->SetContextMenuTitleResourceId( R_CERTMANUI_MENUBAR_OPTIONS_MARKED );
+            UpdateCba( R_CERTMANUI_OPTIONS_CONTEXT_BACK );
+            }
+        else
+            {
+            MenuBar()->SetMenuTitleResourceId( R_CERTMANUI_MENUBAR_VIEW_DEVICE );
+            UpdateCba( R_CERTMANUI_OPTIONS_OPEN_BACK );
+            }
+         cba->MakeCommandVisible( ECertManUICmdAppViewDtls, ETrue );
+         }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewDevice::UpdateCba( TInt aCbaResourceId )
+// Updates cba
+// ---------------------------------------------------------
+//
+void CCertManUIViewDevice::UpdateCba( TInt aCbaResourceId )
+    {
+    CEikButtonGroupContainer*  cba = Cba();
+
+    if ( cba )
+        {
+        cba->SetCommandSetL( aCbaResourceId );
+        cba->DrawNow();
+        }
+    }
+
+// End of File
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuiviewMain.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,290 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIViewMain
+*
+*/
+
+
+// INCLUDE FILES
+
+#include <aknmessagequerydialog.h>
+#include <aknnotewrappers.h>            // for warning & information notes
+#include <certmanui.rsg>
+#include <ErrorUI.h>
+#include "CertmanuiCertificateHelper.h"
+#include "CertmanuiKeeper.h"
+#include "CertmanuicontainerMain.h"
+#include "CertmanuiSyncWrapper.h"
+#include "Certmanui.hrh"
+#include "CertmanuiCommon.h"
+#include "CertManUILogger.h"
+#include "CertmanuiPlugin.h"            // for KCertManUIPluginUid
+
+#include    <hlplch.h>                  // For HlpLauncher
+
+const TUid KGSSecurityViewUid = { 0x1020743A };
+
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertManUIViewMain::CCertManUIViewMain(CCertManUIKeeper& aKeeper)
+// : iKeeper(aKeeper), iCrMgr(iKeeper.CertManager())
+// Constructor
+// ---------------------------------------------------------
+//
+CCertManUIViewMain::CCertManUIViewMain(CCertManUIKeeper& aKeeper)
+    : iKeeper( aKeeper )
+    {
+    CERTMANUILOGGER_WRITE_TIMESTAMP( "CCertManUIViewMain::CCertManUIViewMain" );
+    }
+
+// -----------------------------------------------------------------------------
+// CCertManUIViewMain::~CCertManUIViewMain()
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CCertManUIViewMain::~CCertManUIViewMain()
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIViewMain::~CCertManUIViewMain" );
+
+    if ( iContainerMain )
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainerMain );
+        delete iContainerMain;
+        }
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIViewMain::~CCertManUIViewMain" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewMain* CCertManUIViewMain::NewL(const TRect& /*aRect*/,
+//                                CCertManUIKeeper& aKeeper)
+// ---------------------------------------------------------
+//
+CCertManUIViewMain* CCertManUIViewMain::NewL( const TRect& /*aRect*/,
+                                CCertManUIKeeper& aKeeper )
+    {
+    CCertManUIViewMain* self = new ( ELeave ) CCertManUIViewMain( aKeeper );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewMain* CCertManUIViewMain::NewLC(const TRect& /*aRect*/,
+//                                 CCertManUIKeeper& aKeeper)
+// ---------------------------------------------------------
+//
+CCertManUIViewMain* CCertManUIViewMain::NewLC(const TRect& /*aRect*/,
+                                 CCertManUIKeeper& aKeeper)
+    {
+    CCertManUIViewMain* self = new ( ELeave ) CCertManUIViewMain( aKeeper );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewMain::ConstructL()
+// EPOC two-phased constructor
+// ---------------------------------------------------------
+//
+void CCertManUIViewMain::ConstructL()
+    {
+  CERTMANUILOGGER_ENTERFN( "CCertManUIViewMain::ConstructL" );
+
+  BaseConstructL( R_CERTMANUI_VIEW_MAIN );
+
+  CERTMANUILOGGER_LEAVEFN( "CCertManUIViewMain::ConstructL" );
+  }
+
+// ---------------------------------------------------------
+// CCertManUIViewMain::Id() const
+// Returns Personal view id
+// ---------------------------------------------------------
+//
+TUid CCertManUIViewMain::Id() const
+    {
+    return KCertManUIViewMainId;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewMain::HandleCommandL(TInt aCommand)
+// Handles Softkey and Options list commands
+// ---------------------------------------------------------
+//
+void CCertManUIViewMain::HandleCommandL( TInt aCommand )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIViewMain::HandleCommandL" );
+
+    switch ( aCommand )
+        {
+        case EAknSoftkeyBack:
+            {
+            // Activate Security view
+            AppUi()->ActivateLocalViewL( KGSSecurityViewUid );
+            break;
+            }
+        case EAknCmdExit:
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->HandleCommandL( EAknCmdExit );
+            break;
+            }
+        case ECertManUICmdAppViewDtls:
+        case ECertManUICmdAppOpen:
+            {
+            TInt index = iContainerMain->iListBox->CurrentItemIndex();
+
+            if ( index == 0)
+                {
+                AppUi()->ActivateLocalViewL( KCertManUIViewAuthorityId );
+                }
+            else if ( index == 1)
+                {
+                AppUi()->ActivateLocalViewL( KCertManUIViewTrustedSiteId );
+                }
+            else if ( index == 2)
+                {
+                AppUi()->ActivateLocalViewL( KCertManUIViewPersonalId );
+                }
+            else if ( index == 3)
+                {
+                AppUi()->ActivateLocalViewL( KCertManUIViewDeviceId );
+                }
+            else  // For lint
+                {
+                }
+
+            break;
+            }
+
+        case EAknCmdHelp:
+            {
+             if( FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+                 {
+                 HlpLauncher::LaunchHelpApplicationL(
+                    iEikonEnv->WsSession(), AppUi()->AppHelpContextL() );
+                 }
+            break;
+            }
+
+        default:
+            {
+            AppUi()->HandleCommandL( aCommand );
+            break;
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIViewMain::HandleCommandL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewMain::HandleClientRectChange()
+// ---------------------------------------------------------
+//
+void CCertManUIViewMain::HandleClientRectChange()
+    {
+    if ( iContainerMain )
+        {
+        iContainerMain->SetRect( ClientRect() );
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewMain::DoActivateL(const TVwsViewId& aPrevViewId,
+//                                 TUid /*aCustomMessageId*/,
+//                                 const TDesC8& /*aCustomMessage*/)
+// Updates the view when opening it
+// ---------------------------------------------------------
+//
+void CCertManUIViewMain::DoActivateL( const TVwsViewId& aPrevViewId,
+                                      TUid /*aCustomMessageId*/,
+                                      const TDesC8& /*aCustomMessage*/ )
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIViewMain::DoActivateL" );
+
+    if ( iContainerMain )
+        {
+        ((CAknViewAppUi*)iAvkonAppUi)->RemoveFromViewStack(
+            *this, iContainerMain );
+
+        delete iContainerMain;
+        iContainerMain = NULL;
+        }
+
+    if( aPrevViewId.iViewUid == KCertManUIPluginUid )
+        {
+        iCurrentPosition = 0;
+        }
+
+    iContainerMain = new (ELeave) CCertManUIContainerMain(
+        *this, iKeeper );
+
+    iContainerMain->SetMopParent( this );
+    iContainerMain->ConstructL(
+        ClientRect(), iCurrentPosition, iTopItem );
+
+
+    iContainerMain->DrawListBoxL( iCurrentPosition, iTopItem );
+    ((CAknViewAppUi*)iAvkonAppUi)->AddToStackL( *this, iContainerMain );
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIViewMain::DoActivateL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewMain::DoDeactivate()
+// Saves focus position when closing view
+// ---------------------------------------------------------
+//
+void CCertManUIViewMain::DoDeactivate()
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIViewMain::DoDeactivate" );
+
+    iCurrentPosition = iContainerMain->iListBox->CurrentItemIndex();
+    iTopItem = iContainerMain->iListBox->TopItemIndex();
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIViewMain::DoDeactivate" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewMain::Container()
+// Returns iContainerMain to be used in CertManUIContainerMain
+// ---------------------------------------------------------
+//
+CCoeControl* CCertManUIViewMain::Container()
+    {
+    return iContainerMain;
+    }
+
+
+// ---------------------------------------------------------
+// CCertManUIViewMain::DynInitMenuPaneL()
+// ---------------------------------------------------------
+//
+void CCertManUIViewMain::DynInitMenuPaneL(
+    TInt aResourceId, CEikMenuPane* aMenuPane )
+    {
+    if ( aResourceId == R_CERTMANUI_VIEW_MENU_MAIN )
+        {
+        if( !FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+            {
+            aMenuPane->DeleteMenuItem( EAknCmdHelp ); //remove help
+            }
+        }
+    }
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuiviewPersonal.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,574 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIViewPersonal
+*                Updates Options list depending of the number of
+*                marked and unmarked certificates in the listbox.
+*                Handles softkey and Option list commands.
+*                Handles certificate deletion including confirmation and
+*                read-only notes.
+*                Shows certificate details view with appropriate
+*                warning notes if certificate is corrupted/expired/not valid.
+*
+*/
+
+
+// INCLUDE FILES
+
+#include <aknmessagequerydialog.h>
+#include <aknnotewrappers.h>            // for warning & information notes
+#include <certmanui.rsg>
+#include <ErrorUI.h>
+#include "CertmanuiCertificateHelper.h"
+#include "CertmanuiKeeper.h"
+#include "CertmanuicontainerPersonal.h"
+#include "CertmanuiSyncWrapper.h"
+#include "Certmanui.hrh"
+#include "CertmanuiCommon.h"
+#include "CertManUILogger.h"
+
+#include    <hlplch.h>                  // For HlpLauncher
+#include    <featmgr.h>                 // For FeatureManager
+
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertManUIViewPersonal::CCertManUIViewPersonal(CCertManUIKeeper& aKeeper)
+// : iKeeper(aKeeper), iCrMgr(iKeeper.CertManager())
+// Constructor
+// ---------------------------------------------------------
+//
+CCertManUIViewPersonal::CCertManUIViewPersonal( CCertManUIKeeper& aKeeper )
+: iKeeper( aKeeper )
+    {
+    CERTMANUILOGGER_WRITE_TIMESTAMP( "CCertManUIViewPersonal::CCertManUIViewPersonal" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewPersonal::~CCertManUIViewPersonal()
+// Destructor
+// ---------------------------------------------------------
+//
+CCertManUIViewPersonal::~CCertManUIViewPersonal()
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIViewPersonal::~CCertManUIViewPersonal" );
+
+    if ( iContainerPersonal )
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainerPersonal );
+        delete iContainerPersonal;
+        }
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIViewPersonal::~CCertManUIViewPersonal" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewPersonal* CCertManUIViewPersonal::NewL(const TRect& /*aRect*/,
+//                                CCertManUIKeeper& aKeeper)
+// ---------------------------------------------------------
+//
+CCertManUIViewPersonal* CCertManUIViewPersonal::NewL( const TRect& /*aRect*/,
+                                CCertManUIKeeper& aKeeper )
+    {
+    CCertManUIViewPersonal* self = new ( ELeave ) CCertManUIViewPersonal( aKeeper );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewPersonal* CCertManUIViewPersonal::NewLC(const TRect& /*aRect*/,
+//                                 CCertManUIKeeper& aKeeper)
+// ---------------------------------------------------------
+//
+CCertManUIViewPersonal* CCertManUIViewPersonal::NewLC( const TRect& /*aRect*/,
+                                 CCertManUIKeeper& aKeeper )
+    {
+    CCertManUIViewPersonal* self = new ( ELeave ) CCertManUIViewPersonal( aKeeper );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewPersonal::ConstructL()
+// EPOC two-phased constructor
+// ---------------------------------------------------------
+//
+void CCertManUIViewPersonal::ConstructL()
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIViewPersonal::ConstructL" );
+
+    BaseConstructL( R_CERTMANUI_VIEW_MAIN_PERSONAL );
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIViewPersonal::ConstructL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewPersonal::DynInitMenuPaneL(TInt aResourceId,CEikMenuPane* aMenuPane)
+// Updates Options list with correct items depending on
+// whether the listbox is empty or if it has any marked items
+// ---------------------------------------------------------
+//
+void CCertManUIViewPersonal::DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane)
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIViewPersonal::DynInitMenuPaneL" );
+
+    if (( iKeeper.iWrapper->IsActive() ) ||
+        ( iContainerPersonal->iListBox->CurrentItemIndex() >= iKeeper.iUserLabelEntries.Count() ))
+        {
+        return;
+        }
+
+    const CListBoxView::CSelectionIndexArray* selections =
+            iContainerPersonal->iListBox->SelectionIndexes();
+    const TInt markedCount = selections->Count();
+    const TInt currentItemIndex = iContainerPersonal->iListBox->CurrentItemIndex();
+
+    switch ( aResourceId )
+        {
+        case R_CERTMANUI_VIEW_MENU_PERSONAL:
+            {
+            if( !FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+                {
+                aMenuPane->DeleteMenuItem( EAknCmdHelp );
+                }
+
+            // the certificate list is empty, all except Exit are dimmed
+            if ( currentItemIndex == -1 )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdAppViewDtls, ETrue );
+                aMenuPane->SetItemDimmed( ECertManUICmdAppDelete, ETrue );
+                aMenuPane->SetItemDimmed( ECertManUICmdMoveToDevice, ETrue );
+                aMenuPane->SetItemDimmed( ECertManUICmdMarkUnmark, ETrue );
+                }
+            else
+                {
+                if ( markedCount == 1 )
+                    {
+                    aMenuPane->SetItemDimmed( ECertManUICmdAppViewDtls, ETrue );
+                    }
+
+                if ( markedCount > 1 )
+                    {
+                    aMenuPane->SetItemDimmed( ECertManUICmdAppViewDtls, ETrue );
+                    aMenuPane->SetItemDimmed( ECertManUICmdMoveToDevice, ETrue );
+                    }
+
+                if ( !iKeeper.iCertificateHelper->IsOneMarkedCertificateDeletable(
+                        iContainerPersonal->iListBox, KCertTypePersonal ) )
+                    {
+                    aMenuPane->SetItemDimmed( ECertManUICmdAppDelete, ETrue );
+                    aMenuPane->SetItemDimmed( ECertManUICmdMoveToDevice, ETrue );
+                    }
+                }
+            break;
+            }
+
+        case R_CERTMANUI_MENUPANE_OPTIONS_MARKED:
+            {
+            if ( markedCount > 1 )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdMoveToDevice, ETrue );
+                }
+
+            if ( !iKeeper.iCertificateHelper->IsOneMarkedCertificateDeletable(
+                    iContainerPersonal->iListBox, KCertTypePersonal ) )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdAppDelete, ETrue );
+                }
+
+            // not available for personal certificates
+            aMenuPane->SetItemDimmed( ECertManUICmdMoveToPersonal, ETrue );
+            }
+            // FALLTHROUGH
+
+        case R_CERTMANUI_MENU_PANE_MARK_UNMARK:
+            {
+            TInt index = 0;
+            TKeyArrayFix key( 0, ECmpTInt );
+            if ( selections->Find( currentItemIndex, key, index ) )
+                {   // focus is on unmarked item
+                aMenuPane->SetItemDimmed( ECertManUICmdUnmark, ETrue );
+                }
+            else
+                {   // focus is on marked item
+                aMenuPane->SetItemDimmed( ECertManUICmdMark, ETrue );
+                }
+
+            // if all items are marked, dim "mark all" option
+            if ( markedCount == iContainerPersonal->iListBox->Model()->NumberOfItems() )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdMarkAll, ETrue );
+                }
+
+            // if no items are marked, dim "unmark all" option
+            if ( markedCount == 0 )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdUnmarkAll, ETrue );
+                }
+            break;
+            }
+
+        default:
+            break;
+        }
+
+  CERTMANUILOGGER_LEAVEFN( "CCertManUIViewPersonal::DynInitMenuPaneL" );
+  }
+
+// ---------------------------------------------------------
+// CCertManUIViewPersonal::Id() const
+// Returns Personal view id
+// ---------------------------------------------------------
+//
+TUid CCertManUIViewPersonal::Id() const
+    {
+    return KCertManUIViewPersonalId;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewPersonal::HandleCommandL(TInt aCommand)
+// Handles Softkey and Options list commands
+// ---------------------------------------------------------
+//
+void CCertManUIViewPersonal::HandleCommandL(TInt aCommand)
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIViewPersonal::HandleCommandL" );
+
+    if (( iKeeper.iWrapper->IsActive() ) ||
+        ( iContainerPersonal->iListBox->CurrentItemIndex() >= iKeeper.iUserLabelEntries.Count() ))
+        {
+        return;
+        }
+
+    switch ( aCommand )
+        {
+        case EAknSoftkeyBack:
+            {
+            // Activate main view
+            AppUi()->ActivateLocalViewL( KCertManUIViewMainId );
+            break;
+            }
+        // put the view specific menu commands here
+        case EAknCmdExit:
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->HandleCommandL( EAknCmdExit );
+            break;
+            }
+        case ECertManUICmdAppViewDtls:
+            {
+            iKeeper.iCertificateHelper->MessageQueryViewDetailsL(
+                iContainerPersonal->iListBox->CurrentItemIndex(), KCertTypePersonal, iEikonEnv );
+            break;
+            }
+        case ECertManUICmdAppDelete:
+            {
+            if ( iKeeper.iCertificateHelper->ConfirmationQueryDeleteCertL( KCertTypePersonal,
+                                                      iContainerPersonal->iListBox ))
+                {
+                // goes here if at least one certificate is deleted
+                iCurrentPosition = iContainerPersonal->iListBox->CurrentItemIndex();
+                iTopItem = iContainerPersonal->iListBox->TopItemIndex();
+
+                iContainerPersonal->DrawListBoxL(iCurrentPosition, iTopItem );
+                TRAPD( error, iKeeper.RefreshUserCertEntriesL() );
+                if ( error != KErrNone )
+                    {
+                    if ( error == KErrCorrupt )
+                        {
+                        iKeeper.ShowErrorNoteL( error );
+                        User::Exit( KErrNone );
+                        }
+                    else
+                        {
+                        // have to call straight away the Exit
+                        // showing any error notes would corrupt the display
+                        User::Exit( error );
+                        }
+                    }
+                UpdateMenuBar();
+                }
+            break;
+            }
+       case ECertManUICmdMoveToDevice:
+            {
+            HBufC* prompt = StringLoader::LoadLC(
+                        R_QTN_CM_CONF_MOVE_TO_DEVICE );
+            TInt selection = iKeeper.iCertificateHelper->DisplayConfirmationLD(prompt);
+            if ( selection )
+                {                
+                TInt focusPosition = 0;
+                
+                const CArrayFix<TInt>* array = iContainerPersonal->iListBox->SelectionIndexes();
+                
+                if ( array->Count() == 1 )
+                    {
+                    // item is marked
+                    focusPosition = array->At( 0 );
+                    }
+                else
+                    {
+                    // There is no marked item. Select higlighted item 
+                    focusPosition = iContainerPersonal->iListBox->CurrentItemIndex();
+                    }
+                                                
+                CCTCertInfo* entry = iKeeper.iUserLabelEntries[ focusPosition ]->iUserEntry;
+
+                // Move key first
+                TCTKeyAttributeFilter keyFilter;
+                keyFilter.iKeyId = entry->SubjectKeyId();
+                keyFilter.iPolicyFilter =  TCTKeyAttributeFilter::EAllKeys;
+
+                TRAPD( error, iKeeper.iCertificateHelper->MoveKeyL( keyFilter,
+                                KCMFileKeyStoreTokenUid, KCMDeviceKeyStoreTokenUid ));
+
+                if ( error == KErrNone )
+                    {
+                    // Move certificate
+                    iKeeper.iCertificateHelper->MoveCertL( *entry, focusPosition, iContainerPersonal->iListBox,
+                                    KCMFileCertStoreTokenUid, KCMDeviceCertStoreTokenUid );
+
+                    TRAP( error, iKeeper.RefreshUserCertEntriesL() );
+                    if ( error != KErrNone )
+                        {
+                        if ( error == KErrCorrupt )
+                            {
+                            iKeeper.ShowErrorNoteL( error );
+                            User::Exit( KErrNone );
+                            }
+                        else
+                            {
+                            // have to call straight away the Exit
+                            // showing any error notes would corrupt the display
+                            User::Exit( error );
+                            }
+                        }
+
+                    MDesCArray* itemList = iContainerPersonal->iListBox->Model()->ItemTextArray();
+                    CDesCArray* itemArray = ( CDesCArray* )itemList;
+                    if (( itemArray != NULL ) && ( itemArray->Count() == 0 ))
+                        {
+                        iCurrentPosition = 0;
+                        iTopItem = 0;
+                        iContainerPersonal->UpdateListBoxL( iCurrentPosition, iTopItem );
+                        }
+                     else
+                        {
+                        iCurrentPosition = iContainerPersonal->iListBox->CurrentItemIndex();
+                        iTopItem = iContainerPersonal->iListBox->TopItemIndex();
+                        }
+
+                    iContainerPersonal->DrawListBoxL(iCurrentPosition, iTopItem );
+
+                    UpdateMenuBar();
+                    }
+                }
+            break;
+            }
+        case ECertManUICmdMark:
+        case ECertManUICmdUnmark:
+        case ECertManUICmdMarkAll:
+        case ECertManUICmdUnmarkAll:
+            {
+            // Gets pointer of current listbox.
+            CEikListBox* listbox = iContainerPersonal->iListBox;
+            if ( listbox )
+                {
+                AknSelectionService::HandleMarkableListProcessCommandL(
+                    aCommand, listbox );
+                iKeeper.iCertificateHelper->HandleMarkableListCommandL( aCommand,
+                                                iContainerPersonal->iListBox  );
+
+                UpdateMenuBar();
+                }
+            break;
+            }
+
+        case EAknCmdHelp:
+            {
+            if( FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+                {
+                HlpLauncher::LaunchHelpApplicationL( iEikonEnv->WsSession(), AppUi()->AppHelpContextL() );
+                }
+            break;
+            }
+
+        default:
+            {
+            AppUi()->HandleCommandL( aCommand );
+            break;
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIViewPersonal::HandleCommandL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewPersonal::HandleClientRectChange()
+// ---------------------------------------------------------
+//
+void CCertManUIViewPersonal::HandleClientRectChange()
+    {
+    if ( iContainerPersonal )
+        {
+        iContainerPersonal->SetRect( ClientRect() );
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewPersonal::DoActivateL(const TVwsViewId& /*aPrevViewId*/,TUid /*aCustomMessageId*/, const TDesC8& /*aCustomMessage*/)
+// Updates the view when opening it
+// ---------------------------------------------------------
+//
+void CCertManUIViewPersonal::DoActivateL(const TVwsViewId& aPrevViewId, TUid /*aCustomMessageId*/, const TDesC8& /*aCustomMessage*/)
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIViewPersonal::DoActivateL" );
+
+    iKeeper.StartWaitDialogL( ECertmanUiWaitDialog );
+    CleanupCloseWaitDialogPushL( iKeeper );
+
+    TRAPD ( error, iKeeper.RefreshUserCertEntriesL() );
+    if ( error != KErrNone )
+        {
+        if ( error == KErrCorrupt )
+            {
+            iKeeper.ShowErrorNoteL( error );
+            User::Exit( KErrNone );
+            }
+        else
+            {
+            // have to call straight away the Exit
+            // showing any error notes would corrupt the display
+            User::Exit( error );
+            }
+        }
+
+    // If this view is being activated from main view,
+    // current position is 0. The declaration of KCertManUIViewMainId is
+    // located in certmanuiviewid.h which is not public header --> constant
+    // is being used.
+    if( aPrevViewId.iViewUid == KCertManUIViewMainId )
+        {
+        iCurrentPosition = 0;
+        }
+
+    if ( iContainerPersonal )
+        {
+        ((CAknViewAppUi*)iAvkonAppUi)->RemoveFromViewStack( *this, iContainerPersonal );
+        delete iContainerPersonal;
+        iContainerPersonal = NULL;
+        }
+    iContainerPersonal = new ( ELeave ) CCertManUIContainerPersonal( *this, iKeeper );
+    iContainerPersonal->SetMopParent(this);
+    iContainerPersonal->ConstructL( ClientRect(), iCurrentPosition, iTopItem );
+
+    iKeeper.ActivateTitleL( KViewTitleCertManUIPersonal );
+
+    iContainerPersonal->DrawListBoxL( iCurrentPosition, iTopItem );
+    ((CAknViewAppUi*)iAvkonAppUi)->AddToStackL( *this, iContainerPersonal );
+
+    UpdateMenuBar();
+
+    CleanupStack::PopAndDestroy();    // closes wait dialog
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIViewPersonal::DoActivateL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewPersonal::DoDeactivate()
+// Saves focus position when closing view
+// ---------------------------------------------------------
+//
+void CCertManUIViewPersonal::DoDeactivate()
+    {
+    CERTMANUILOGGER_ENTERFN( "CCertManUIViewPersonal::DoDeactivate" );
+
+    iCurrentPosition = iContainerPersonal->iListBox->CurrentItemIndex();
+    iTopItem = iContainerPersonal->iListBox->TopItemIndex();
+    if ( iContainerPersonal )
+        {
+        ((CAknViewAppUi*)iAvkonAppUi)->RemoveFromViewStack(*this, iContainerPersonal);
+        delete iContainerPersonal;
+        iContainerPersonal = NULL;
+        }
+
+    CERTMANUILOGGER_LEAVEFN( "CCertManUIViewPersonal::DoDeactivate" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewPersonal::Container()
+// Returns iContainerPersonal to be used in CertManUIContainerPersonal
+// ---------------------------------------------------------
+//
+CCoeControl* CCertManUIViewPersonal::Container()
+    {
+    return iContainerPersonal;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewPersonal::UpdateMenuBar()
+// Updates the menu bar
+// ---------------------------------------------------------
+//
+void CCertManUIViewPersonal::UpdateMenuBar()
+    {
+    CEikButtonGroupContainer*  cba = Cba();
+
+    if ( cba == NULL )
+        {
+        return;
+        }
+
+    if ( iKeeper.iUserLabelEntries.Count() == 0 )
+        {
+        // No certificate. Don't show MSK
+        UpdateCba( R_CERTMANUI_OPTIONS_OPEN_BACK );
+        cba->MakeCommandVisible( ECertManUICmdAppViewDtls, EFalse );
+        }
+    else
+        {
+        if ( iContainerPersonal->iListBox->SelectionIndexes()->Count() > 0 )
+            {
+            MenuBar()->SetContextMenuTitleResourceId( R_CERTMANUI_MENUBAR_OPTIONS_MARKED );
+            UpdateCba( R_CERTMANUI_OPTIONS_CONTEXT_BACK );
+            }
+        else
+            {
+            MenuBar()->SetMenuTitleResourceId( R_CERTMANUI_MENUBAR_VIEW_PERSONAL );
+            UpdateCba( R_CERTMANUI_OPTIONS_OPEN_BACK );
+            }
+         cba->MakeCommandVisible( ECertManUICmdAppViewDtls, ETrue );
+         }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewPersonal::UpdateCba( TInt aCbaResourceId )
+// Updates cba
+// ---------------------------------------------------------
+//
+void CCertManUIViewPersonal::UpdateCba( TInt aCbaResourceId )
+    {
+    CEikButtonGroupContainer*  cba = Cba();
+
+    if ( cba )
+        {
+        cba->SetCommandSetL( aCbaResourceId );
+        cba->DrawNow();
+        }
+    }
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuiviewTrust.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,452 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIViewTrust
+*                Updates Options list depending on the status of the
+*                trusted clients (unavailable, located in WIM).
+*                Handles Softkey and Options list commands.
+*
+*/
+
+
+// INCLUDE FILES
+#include <certificateapps.h>
+#include <certmanui.rsg>
+#include "CertmanuiKeeper.h"
+#include "CertmanuiviewTrust.h"
+#include "CertmanuicontainerTrust.h"
+#include "CertmanuicontainerAuthority.h"
+#include "CertmanuiSyncWrapper.h"
+#include "Certmanuitrustids.h"
+#include "Certmanui.hrh"
+#include "CertmanuiCommon.h"
+#include "CertManUILogger.h"
+#include "securityuisvariant.hrh"
+#include "CertmanuiCertificateHelper.h"
+
+#include    <hlplch.h>            // For HlpLauncher
+#include    <featmgr.h>           // For FeatureManager
+
+
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::CCertManUIViewTrust(CCertManUIKeeper& aKeeper)
+// Constructor
+// ---------------------------------------------------------
+//
+CCertManUIViewTrust::CCertManUIViewTrust( CCertManUIKeeper& aKeeper )
+    : iKeeper( aKeeper )
+    {
+    CERTMANUILOGGER_WRITE_TIMESTAMP(
+        "CCertManUIViewTrust::CCertManUIViewTrust" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::~CCertManUIViewTrust()
+// Destructor
+// ---------------------------------------------------------
+//
+CCertManUIViewTrust::~CCertManUIViewTrust()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrust::~CCertManUIViewTrust" );
+
+    if ( iContainerTrust )
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainerTrust );
+        delete iContainerTrust;
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrust::~CCertManUIViewTrust" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust* CCertManUIViewTrust::NewL(const TRect& /*aRect*/,
+//      CCertManUIKeeper& aKeeper)
+// ---------------------------------------------------------
+//
+CCertManUIViewTrust* CCertManUIViewTrust::NewL(
+    const TRect& /*aRect*/, CCertManUIKeeper& aKeeper )
+    {
+    CCertManUIViewTrust* self = new (ELeave) CCertManUIViewTrust( aKeeper );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust* CCertManUIViewTrust::NewLC(const TRect& /*aRect*/,
+//      CCertManUIKeeper& aKeeper)
+// ---------------------------------------------------------
+//
+CCertManUIViewTrust* CCertManUIViewTrust::NewLC(const TRect& /*aRect*/,
+    CCertManUIKeeper& aKeeper)
+    {
+    CCertManUIViewTrust* self = new (ELeave) CCertManUIViewTrust(aKeeper);
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::ConstructL()
+// EPOC two-phased constructor
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrust::ConstructL()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrust::ConstructL" );
+
+    BaseConstructL( R_CERTMANUI_VIEW_TRUST );
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrust::ConstructL" );
+  }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::DynInitMenuPaneL(TInt aResourceId,CEikMenuPane* aMenuPane)
+// Updates Options list with correct items depending on
+// whether the listbox is empty or if the trust can be changed
+// Change trust is not shown if certificate location is not supported
+// unsupported certificate locations are ECrCertLocationWIMCard,
+//                    ECrCertLocationWIMURL,
+//                    ECrCertLocationPhoneMemory,
+//                    ECrCertLocationPhoneMemoryURL
+// Change trust is not shown if certificate format is not supported
+// unsupported certificate formats are ECrX968Certificate
+//                    ECrCertificateURL
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrust::DynInitMenuPaneL(
+    TInt aResourceId, CEikMenuPane* aMenuPane )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrust::DynInitMenuPaneL" );
+
+    if ( aResourceId == R_CERTMANUI_VIEW_TRUST_MENU )
+        {
+        if( !FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+             {
+             aMenuPane->DeleteMenuItem( EAknCmdHelp );
+             }
+
+        TInt currentItemTrust = iContainerTrust->iListBox->CurrentItemIndex();
+        if ( currentItemTrust == -1 )
+            {
+            aMenuPane->SetItemDimmed( ECertManUICmdAppChangeTrust, ETrue );
+            }
+
+        CCertManUIViewAuthority* authorityView = STATIC_CAST(
+            CCertManUIViewAuthority*, AppUi()->View( KCertManUIViewAuthorityId ) );
+        TInt currentItem = authorityView->
+            iContainerAuthority->iListBox->CurrentItemIndex();
+        CCTCertInfo& entry = *( iKeeper.iCALabelEntries[ currentItem ]->iCAEntry );
+
+        if ( !iKeeper.iCertificateHelper->IsOneMarkedCertificateDeletable(
+                authorityView->iContainerAuthority->iListBox, KCertTypeAuthority ) )
+                {
+                LOG_WRITE( "Read only Certificate" );
+                aMenuPane->SetItemDimmed( ECertManUICmdAppChangeTrust, ETrue );
+                }
+
+        if ( currentItem >= 0 )
+            {
+            if( KCertManUIViewTrustApplicationControllerId ==
+                iContainerTrust->iClientUids[ currentItemTrust ] &&
+                iKeeper.IsLocalFeatureSupported( KSecurityUIsNoNativeAppTrustSettingChange ) )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdAppChangeTrust, ETrue );
+                }
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrust::DynInitMenuPaneL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::Id() const
+// Returns Trust view id
+// ---------------------------------------------------------
+//
+TUid CCertManUIViewTrust::Id() const
+    {
+    return KCertManUIViewTrustId;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::HandleCommandL(TInt aCommand)
+// Handles Softkey and Options list commands
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrust::HandleCommandL( TInt aCommand )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrust::HandleCommandL" );
+
+    if ( iKeeper.iWrapper->IsActive() )
+        {
+        return;
+        }
+
+    switch ( aCommand )
+        {
+        case EAknSoftkeyBack:
+            {
+            AppUi()->ActivateLocalViewL( KCertManUIViewAuthorityId );
+            break;
+            }
+        // put the view specific menu commands here
+        case EAknCmdExit:
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->HandleCommandL( EAknCmdExit );
+            break;
+            }
+        case ECertManUICmdAppChangeTrust:
+            {
+            PopupTrustChangeSettingPageL();
+            break;
+            }
+
+        case EAknCmdHelp:
+            {
+            if( FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+                {
+                HlpLauncher::LaunchHelpApplicationL( iEikonEnv->WsSession(),
+                    AppUi()->AppHelpContextL() );
+                }
+            break;
+            }
+
+        default:
+            {
+            AppUi()->HandleCommandL( aCommand );
+            break;
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrust::HandleCommandL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::HandleClientRectChange()
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrust::HandleClientRectChange()
+    {
+    if ( iContainerTrust )
+        {
+        iContainerTrust->SetRect( ClientRect() );
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::DoActivateL(
+//      const TVwsViewId& /*aPrevViewId*/,
+//      TUid aCustomMessageId, const TDesC8& /*aCustomMessage*/)
+// Updates the view when opening it
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrust::DoActivateL( const TVwsViewId& /*aPrevViewId*/,
+    TUid aCustomMessageId, const TDesC8& /*aCustomMessage*/ )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrust::DoActivateL" );
+
+    if ( iContainerTrust )
+        {
+        ((CAknViewAppUi*)iAvkonAppUi)->RemoveFromViewStack(
+            *this, iContainerTrust );
+        delete iContainerTrust;
+        iContainerTrust = NULL;
+        }
+
+    TInt trustViewItem = STATIC_CAST( TInt, aCustomMessageId.iUid );
+    iContainerTrust = new(ELeave) CCertManUIContainerTrust( *this, iKeeper );
+    // to fix problem of focus if trust view has more than one item
+    TInt currentPosition = 0;
+    TInt topItem = 0;
+    iContainerTrust->SetMopParent( this );
+    iContainerTrust->ConstructL( ClientRect());
+
+    UpdateMenuBar();
+
+    UpdateNaviPaneL();
+
+    iContainerTrust->DrawListBoxL( currentPosition, topItem, trustViewItem );
+    ((CAknViewAppUi*)iAvkonAppUi)->AddToStackL( *this, iContainerTrust );
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrust::DoActivateL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::DoDeactivate()
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrust::DoDeactivate()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrust::DoDeactivate" );
+
+    if ( iContainerTrust )
+        {
+        ((CAknViewAppUi*)iAvkonAppUi)->RemoveFromViewStack( *this, iContainerTrust );
+        delete iContainerTrust;
+        iContainerTrust = NULL;
+        }
+
+    RemoveNaviPane();
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrust::DoDeactivate" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::Container()
+// Returns iContainerTrust
+// ---------------------------------------------------------
+//
+CCoeControl* CCertManUIViewTrust::Container()
+    {
+    return iContainerTrust;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::ChangeTrustL()
+// Calls Change trust method UpdateTrustSettingsViewL in certmanuicontainertrust
+// for not supported certificate formats ECrX968Certificate and ECrCertificateURL
+// and for not supported certificate locations  ECrCertLocationWIMCard, ECrCertLocationWIMURL,
+// ECrCertLocationPhoneMemory, ECrCertLocationPhoneMemoryURL UpdateTrustSettingsViewL is not called
+// also UpdateTrustSettingsViewL is not called if there are no clients in Trust view.
+// This function is called when user presses joystick key in trusters list.
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrust::ChangeTrustL()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrust::ChangeTrustL" );
+    CCertManUIViewAuthority* authorityView = STATIC_CAST(
+            CCertManUIViewAuthority*, AppUi()->View(KCertManUIViewAuthorityId) );
+    // Policy decision: Trusters of read-only certs cannot be changed
+    if ( iKeeper.iCertificateHelper->IsOneMarkedCertificateDeletable(
+                authorityView->iContainerAuthority->iListBox, KCertTypeAuthority ) )
+
+        {
+        TInt currentItem = authorityView->
+            iContainerAuthority->iListBox->CurrentItemIndex();
+
+        CCTCertInfo& entry = *( iKeeper.iCALabelEntries[ currentItem ]->iCAEntry );
+
+        TInt currentTruster = iContainerTrust->iListBox->CurrentItemIndex();
+
+        if ( currentItem >= 0 )
+            {
+            TUid uid = iContainerTrust->iClientUids[ currentTruster ];
+
+            iContainerTrust->ChangeTrustValueL( entry, uid );
+            iContainerTrust->UpdateTrustListboxItemL( entry, currentTruster );
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrust::ChangeTrustL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::PopupTrustChangeSettingPageL()
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrust::PopupTrustChangeSettingPageL()
+    {
+    CCertManUIViewAuthority* authorityView =
+    STATIC_CAST( CCertManUIViewAuthority*,
+            AppUi()->View( KCertManUIViewAuthorityId ) );
+    TInt helpIndex3 = authorityView->
+            iContainerAuthority->iListBox->CurrentItemIndex();
+    iContainerTrust->PopupTrustChangeSettingPageL( helpIndex3 );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::UpdateMenuBar()
+// Updates the menu bar
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrust::UpdateMenuBar()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrust::UpdateMenuBar" );
+
+    CCertManUIViewAuthority* authorityView = STATIC_CAST(
+            CCertManUIViewAuthority*, AppUi()->View(KCertManUIViewAuthorityId) );
+
+    CEikButtonGroupContainer*  cba = Cba();
+
+    if (( cba == NULL ) || ( authorityView == NULL ))
+        {
+        return;
+        }
+
+    if ( !iKeeper.iCertificateHelper->IsOneMarkedCertificateDeletable(
+                authorityView->iContainerAuthority->iListBox, ETrue ))
+        {
+        // Read-only certificate
+        cba->MakeCommandVisible( ECertManUICmdAppChangeTrust, EFalse );
+        }
+    else
+       {
+       cba->MakeCommandVisible( ECertManUICmdAppChangeTrust, ETrue );
+       }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrust::UpdateMenuBar" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::UpdateNaviPaneL()
+// Updates navi pane
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrust::UpdateNaviPaneL()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrust::UpdateNaviPaneL" );
+
+    CEikStatusPane* sp = STATIC_CAST(
+        CAknAppUi*, iEikonEnv->EikAppUi())->StatusPane();
+
+    iNaviPane = STATIC_CAST(CAknNavigationControlContainer*,
+        sp->ControlL(TUid::Uid(EEikStatusPaneUidNavi)));
+
+    TResourceReader reader;
+    iCoeEnv->CreateResourceReaderLC( reader, R_CM_NAVI_PANE_TRUST_SETTINGS );
+    iTrustSettingsNaviPane = iNaviPane->CreateMessageLabelL( reader );
+    CleanupStack::PopAndDestroy();  // reader
+
+    iNaviPane->PushL( *iTrustSettingsNaviPane );
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrust::UpdateNaviPaneL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrust::RemoveNaviPane()
+// Removes navi pane
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrust::RemoveNaviPane()
+  {
+  CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrust::RemoveNaviPane" );
+
+  if ( iNaviPane )
+    {
+    iNaviPane->Pop( iTrustSettingsNaviPane );
+    }
+
+  delete iTrustSettingsNaviPane;
+  iTrustSettingsNaviPane = NULL;
+
+  CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrust::RemoveNaviPane" );
+  }
+
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/CertmanuiviewTrustedSite.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,519 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUIViewTrustedSite
+*                Updates Options list depending of the number of
+*                marked and unmarked certificates in the listbox.
+*                Handles softkey and Option list commands.
+*                Handles certificate deletion including confirmation note.
+*                Shows certificate details view with appropriate
+*                warning notes if certificate is corrupted/expired/not valid.
+*
+*/
+
+
+// INCLUDE FILES
+#include <aknmessagequerydialog.h>
+#include <aknnotewrappers.h>            // for warning & information notes
+#include <X509CertNameParser.h>
+#include <ErrorUI.h>
+#include <x509cert.h>
+#include <pkixcertchain.h>              //for validation
+#include <certmanui.rsg>
+#include "CertmanuiCertificateHelper.h"
+#include "CertmanuiKeeper.h"
+#include "CertmanuiviewTrustedSite.h"
+#include "CertmanuicontainerTrustedSite.h"
+#include "Certmanui.hrh"
+#include "CertmanuiSyncWrapper.h"
+#include "CertmanuiCommon.h"
+#include "CertManUILogger.h"
+
+#include    <hlplch.h>                  // For HlpLauncher
+#include    <featmgr.h>                 // For FeatureManager
+
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CCertManUIViewTrustedSite::CCertManUIViewTrustedSite(CCertManUIKeeper& aKeeper)
+// : iKeeper(aKeeper), iCrMgr(iKeeper.CertManager())
+// Constructor
+// ---------------------------------------------------------
+//
+CCertManUIViewTrustedSite::CCertManUIViewTrustedSite( CCertManUIKeeper& aKeeper )
+    : iKeeper( aKeeper )
+    {
+    CERTMANUILOGGER_WRITE_TIMESTAMP(
+        "CCertManUIViewTrustedSite::CCertManUIViewTrustedSite" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrustedSite::~CCertManUIViewTrustedSite()
+// Destructor
+// ---------------------------------------------------------
+//
+CCertManUIViewTrustedSite::~CCertManUIViewTrustedSite()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrustedSite::~CCertManUIViewTrustedSite" );
+
+    if ( iContainerTrustedSite )
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainerTrustedSite );
+        delete iContainerTrustedSite;
+        }
+
+     CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrustedSite::~CCertManUIViewTrustedSite" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrustedSite* CCertManUIViewTrustedSite::NewL(
+//      const TRect& /*aRect*/, CCertManUIKeeper& aKeeper)
+// ---------------------------------------------------------
+//
+CCertManUIViewTrustedSite* CCertManUIViewTrustedSite::NewL(
+    const TRect& /*aRect*/, CCertManUIKeeper& aKeeper )
+    {
+    CCertManUIViewTrustedSite* self =
+        new ( ELeave ) CCertManUIViewTrustedSite( aKeeper );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrustedSite* CCertManUIViewTrustedSite::NewLC(
+//  const TRect& /*aRect*/, CCertManUIKeeper& aKeeper)
+// ---------------------------------------------------------
+//
+CCertManUIViewTrustedSite* CCertManUIViewTrustedSite::NewLC(
+    const TRect& /*aRect*/, CCertManUIKeeper& aKeeper )
+    {
+    CCertManUIViewTrustedSite* self =
+        new ( ELeave ) CCertManUIViewTrustedSite( aKeeper );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrustedSite::ConstructL()
+// EPOC two-phased constructor
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrustedSite::ConstructL()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrustedSite::ConstructL" );
+
+    BaseConstructL( R_CERTMANUI_VIEW_MAIN_TRUSTED_SITE );
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrustedSite::ConstructL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrustedSite::DynInitMenuPaneL(
+//      TInt aResourceId,CEikMenuPane* aMenuPane)
+// Updates Options list with correct items depending on
+// whether the listbox is empty or if it has any marked items
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrustedSite::DynInitMenuPaneL(
+    TInt aResourceId, CEikMenuPane* aMenuPane )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrustedSite::DynInitMenuPaneL" );
+
+    if (( iKeeper.iWrapper->IsActive()) ||
+        ( iContainerTrustedSite->iListBox->CurrentItemIndex() >= iKeeper.iPeerLabelEntries.Count() ))
+        {
+        return;
+        }
+
+    const CListBoxView::CSelectionIndexArray* selections =
+            iContainerTrustedSite->iListBox->SelectionIndexes();
+    const TInt markedCount = selections->Count();
+    const TInt currentItemIndex = iContainerTrustedSite->iListBox->CurrentItemIndex();
+
+    switch ( aResourceId )
+        {
+        case R_CERTMANUI_VIEW_MENU_TRUSTED_SITES:
+            {
+             if( !FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+                {
+                aMenuPane->DeleteMenuItem( EAknCmdHelp );
+                }
+
+            // the certificate list is empty, all except Exit are dimmed
+            if ( currentItemIndex == -1 )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdAppViewDtls, ETrue );
+                aMenuPane->SetItemDimmed( ECertManUICmdAppDelete, ETrue );
+                aMenuPane->SetItemDimmed( ECertManUICmdMarkUnmark, ETrue );
+                }
+            else
+                {
+                if ( markedCount > 0 )
+                    {
+                    aMenuPane->SetItemDimmed( ECertManUICmdAppViewDtls, ETrue );
+                    }
+
+                if ( !iKeeper.iCertificateHelper->IsOneMarkedCertificateDeletable(
+                        iContainerTrustedSite->iListBox, KCertTypeTrustedSite ) )
+                    {
+                    aMenuPane->SetItemDimmed( ECertManUICmdAppDelete, ETrue );
+                    }
+                }
+            break;
+            }
+
+        case R_CERTMANUI_MENUPANE_OPTIONS_MARKED:
+            {
+            if ( !iKeeper.iCertificateHelper->IsOneMarkedCertificateDeletable(
+                    iContainerTrustedSite->iListBox, KCertTypeTrustedSite ) )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdAppDelete, ETrue );
+                }
+
+            // not available for trusted site certificates
+            aMenuPane->SetItemDimmed( ECertManUICmdMoveToDevice, ETrue );
+            aMenuPane->SetItemDimmed( ECertManUICmdMoveToPersonal, ETrue );
+            }
+            // FALLTHROUGH
+
+        case R_CERTMANUI_MENU_PANE_MARK_UNMARK:
+            {
+            TInt index = 0;
+            TKeyArrayFix key( 0, ECmpTInt );
+            if ( selections->Find( currentItemIndex, key, index ) )
+                {   // focus is on unmarked item
+                aMenuPane->SetItemDimmed( ECertManUICmdUnmark, ETrue );
+                }
+            else
+                {   // focus is on marked item
+                aMenuPane->SetItemDimmed( ECertManUICmdMark, ETrue );
+                }
+
+            // if all items are marked, dim "mark all" option
+            if ( markedCount == iContainerTrustedSite->iListBox->Model()->NumberOfItems() )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdMarkAll, ETrue );
+                }
+
+            // if no items are marked, dim "unmark all" option
+            if ( markedCount == 0 )
+                {
+                aMenuPane->SetItemDimmed( ECertManUICmdUnmarkAll, ETrue );
+                }
+            break;
+            }
+
+        default:
+            break;
+        }
+
+     CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrustedSite::DynInitMenuPaneL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrustedSite::Id() const
+// Returns Authority view id
+// ---------------------------------------------------------
+//
+TUid CCertManUIViewTrustedSite::Id() const
+    {
+    return KCertManUIViewTrustedSiteId;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrustedSite::HandleCommandL(TInt aCommand)
+// Handles Softkey and Options list commands
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrustedSite::HandleCommandL( TInt aCommand )
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrustedSite::HandleCommandL" );
+
+    if (( iKeeper.iWrapper->IsActive() ) ||
+        ( iContainerTrustedSite->iListBox->CurrentItemIndex() >= iKeeper.iPeerLabelEntries.Count() ))
+        {
+        return;
+        }
+
+    switch ( aCommand )
+        {
+        case EAknSoftkeyBack:
+            {
+            // Activate main view
+            AppUi()->ActivateLocalViewL( KCertManUIViewMainId );
+            break;
+            }
+        // put the view specific menu commands here
+        case EAknCmdExit:
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->HandleCommandL( EAknCmdExit );
+            break;
+            }
+        case ECertManUICmdAppViewDtls:
+            {
+            iKeeper.iCertificateHelper->MessageQueryViewDetailsL(
+                iContainerTrustedSite->iListBox->CurrentItemIndex(), KCertTypeTrustedSite, iEikonEnv );
+            break;
+            }
+        case ECertManUICmdAppDelete:
+            {
+            if ( iKeeper.iCertificateHelper->ConfirmationQueryDeleteCertL( KCertTypeTrustedSite,
+                                                    iContainerTrustedSite->iListBox ) )
+                {
+                // goes here if at least one certificate is deleted
+                iCurrentPosition = iContainerTrustedSite->iListBox->CurrentItemIndex();
+                iTopItem = iContainerTrustedSite->iListBox->TopItemIndex();
+
+                iContainerTrustedSite->DrawListBoxL(iCurrentPosition, iTopItem );
+                TRAPD( error, iKeeper.RefreshPeerCertEntriesL() );
+                if ( error != KErrNone )
+                    {
+                    if ( error == KErrCorrupt )
+                        {
+                        iKeeper.ShowErrorNoteL( error );
+                        User::Exit( KErrNone );
+                        }
+                    else
+                        {
+                        // have to call straight away the Exit
+                        // showing any error notes would corrupt the display
+                        User::Exit( error );
+                        }
+                    }
+                UpdateMenuBar();
+                }
+            break;
+            }
+        case ECertManUICmdMark:
+        case ECertManUICmdUnmark:
+        case ECertManUICmdMarkAll:
+        case ECertManUICmdUnmarkAll:
+            {
+            // Gets pointer of current listbox.
+            CEikListBox* listbox = iContainerTrustedSite->iListBox;
+            if ( listbox )
+                {
+                AknSelectionService::HandleMarkableListProcessCommandL(
+                    aCommand, listbox );
+                iKeeper.iCertificateHelper->HandleMarkableListCommandL(
+                                      aCommand, iContainerTrustedSite->iListBox );
+
+                UpdateMenuBar();
+                }
+
+            break;
+            }
+        case EAknCmdHelp:
+            {
+            if( FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+                {
+                HlpLauncher::LaunchHelpApplicationL(
+                   iEikonEnv->WsSession(), AppUi()->AppHelpContextL() );
+                }
+
+            break;
+            }
+
+        default:
+            {
+            AppUi()->HandleCommandL( aCommand );
+            break;
+            }
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrustedSite::HandleCommandL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrustedSite::HandleClientRectChange()
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrustedSite::HandleClientRectChange()
+    {
+    if ( iContainerTrustedSite )
+        {
+        iContainerTrustedSite->SetRect( ClientRect() );
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrustedSite::DoActivateL(const TVwsViewId& /*aPrevViewId*/,
+//      TUid /*aCustomMessageId*/, const TDesC8& /*aCustomMessage*/)
+// Updates the view when opening it
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrustedSite::DoActivateL(
+    const TVwsViewId& aPrevViewId,
+    TUid /*aCustomMessageId*/, const TDesC8& /*aCustomMessage*/)
+    {
+     CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrustedSite::DoActivateL" );
+
+     iKeeper.StartWaitDialogL( ECertmanUiWaitDialog );
+     CleanupCloseWaitDialogPushL( iKeeper );
+
+     TRAPD ( error, iKeeper.RefreshPeerCertEntriesL() );
+     if ( error != KErrNone )
+         {
+         if ( error == KErrCorrupt )
+             {
+             iKeeper.ShowErrorNoteL( error );
+             User::Exit( KErrNone );
+             }
+         else
+             {
+             // have to call straight away the Exit
+             // showing any error notes would corrupt the display
+             User::Exit( error );
+             }
+         }
+
+    // If this view is being activated from main view,
+    // current position is 0. The declaration of KCertManUIViewMainId is
+    // located in certmanuiviewid.h which is not public header --> constant
+    // is being used.
+    if( aPrevViewId.iViewUid == KCertManUIViewMainId )
+        {
+        iCurrentPosition = 0;
+        }
+
+    if ( iContainerTrustedSite )
+        {
+        ((CAknViewAppUi*)iAvkonAppUi)->RemoveFromViewStack(
+            *this, iContainerTrustedSite );
+
+        delete iContainerTrustedSite;
+        iContainerTrustedSite = NULL;
+        }
+    iContainerTrustedSite = new (ELeave) CCertManUIContainerTrustedSite(
+        *this, iKeeper );
+
+    iContainerTrustedSite->SetMopParent( this );
+    iContainerTrustedSite->ConstructL(
+        ClientRect(), iCurrentPosition, iTopItem );
+
+    if ( !iKeeper.iCertsDatOK )
+        {
+        iCurrentPosition = 0;
+        iTopItem = 0;
+        }
+
+    iKeeper.ActivateTitleL( KViewTitleCertManUITrustedSite );
+
+    iContainerTrustedSite->DrawListBoxL( iCurrentPosition, iTopItem );
+    ((CAknViewAppUi*)iAvkonAppUi)->AddToStackL( *this, iContainerTrustedSite );
+
+    UpdateMenuBar();
+
+    CleanupStack::PopAndDestroy();    // closes wait dialog
+
+    iKeeper.iStartup = EFalse;
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrustedSite::DoActivateL" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrustedSite::DoDeactivate()
+// Saves focus position when closing view
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrustedSite::DoDeactivate()
+    {
+    CERTMANUILOGGER_ENTERFN( " CCertManUIViewTrustedSite::DoDeactivate" );
+
+    if ( iKeeper.iCertsDatOK )
+        {
+        iCurrentPosition = iContainerTrustedSite->iListBox->CurrentItemIndex();
+        iTopItem = iContainerTrustedSite->iListBox->TopItemIndex();
+        // do not destroy iContainerTrustedSite here because
+        // TrustSettings view needs it !
+        }
+    else
+        {
+        iCurrentPosition = 0;
+        iTopItem = 0;
+        }
+
+    CERTMANUILOGGER_LEAVEFN( " CCertManUIViewTrustedSite::DoDeactivate" );
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrustedSite::Container()
+// Returns iContainerTrustedSite to be used in CertManUiContainerTrustedSite
+// ---------------------------------------------------------
+//
+CCoeControl* CCertManUIViewTrustedSite::Container()
+    {
+    return iContainerTrustedSite;
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrustedSite::UpdateMenuBar()
+// Updates the menu bar
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrustedSite::UpdateMenuBar()
+    {
+    CEikButtonGroupContainer*  cba = Cba();
+
+    if ( cba == NULL )
+        {
+        return;
+        }
+
+    if ( iKeeper.iPeerLabelEntries.Count() == 0 )
+        {
+        // No certificate. Don't show MSK
+        UpdateCba( R_CERTMANUI_OPTIONS_OPEN_BACK );
+        cba->MakeCommandVisible( ECertManUICmdAppViewDtls, EFalse );
+        }
+    else
+        {
+        if ( iContainerTrustedSite->iListBox->SelectionIndexes()->Count() > 0 )
+            {
+            MenuBar()->SetContextMenuTitleResourceId( R_CERTMANUI_MENUBAR_OPTIONS_MARKED );
+            UpdateCba( R_CERTMANUI_OPTIONS_CONTEXT_BACK );
+            }
+        else
+            {
+            MenuBar()->SetMenuTitleResourceId( R_CERTMANUI_MENUBAR_VIEW_TRUSTED_SITES );
+            UpdateCba( R_CERTMANUI_OPTIONS_OPEN_BACK );
+            }
+        cba->MakeCommandVisible( ECertManUICmdAppViewDtls, ETrue );
+        }
+    }
+
+// ---------------------------------------------------------
+// CCertManUIViewTrustedSite::UpdateCba( TInt aCbaResourceId )
+// Updates cba
+// ---------------------------------------------------------
+//
+void CCertManUIViewTrustedSite::UpdateCba( TInt aCbaResourceId )
+    {
+    CEikButtonGroupContainer*  cba = Cba();
+
+    if ( cba )
+        {
+        cba->SetCommandSetL( aCbaResourceId );
+        cba->DrawNow();
+        }
+    }
+
+
+// End of File
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/SRC/certmanui.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,109 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of class CCertManUI. Methods for reading
+*                the resources
+*
+*/
+
+
+// INCLUDE FILES
+#include <eikenv.h>
+#include <bautils.h>
+#include <data_caging_path_literals.hrh>
+#include "Certmanui.h"
+
+// CONSTANTS
+
+_LIT( KResourceFile, "z:CertManUi.rsc" );
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ----------------------------------------------------------
+// CCertManUi::InitializeLibL()
+// Initializes CCertManUi resource file
+// ----------------------------------------------------------
+//
+void CCertManUi::InitializeLibL()
+  {
+  if ( Dll::Tls() != NULL )
+    {
+    return;
+    }
+  CCertManUi* self = new ( ELeave ) CCertManUi();
+  CleanupStack::PushL( self );
+  self->ConstructL();
+  Dll::SetTls( self );
+  CleanupStack::Pop(); // self
+  }
+
+// ----------------------------------------------------------
+// CCertManUi::UnInitializeLib()
+// Uninitializes CCertManUi resource file
+// ----------------------------------------------------------
+//
+void CCertManUi::UnInitializeLib()
+  {
+  CCertManUi* instance = STATIC_CAST( CCertManUi*, Dll::Tls() );
+  delete instance;
+  Dll::SetTls( NULL );
+  }
+
+// ----------------------------------------------------------
+// CCertManUi::CCertManUi()
+// C++ default constructor
+// ----------------------------------------------------------
+//
+CCertManUi::CCertManUi() : iResourceLoader( *iCoeEnv )
+  {
+  }
+
+// ----------------------------------------------------------
+// CCertManUi::~CCertManUi()
+// Destructor
+// ----------------------------------------------------------
+//
+CCertManUi::~CCertManUi()
+  {
+  iResourceLoader.Close();
+  }
+
+// ----------------------------------------------------------
+// CCertManUi::ConstructL()
+// EPOC default constructor
+// ----------------------------------------------------------
+//
+void CCertManUi::ConstructL()
+  {
+  AddResourceFileL();
+  }
+
+// ----------------------------------------------------------
+// CCertManUi::AddResourceFileL()
+// Used in ConstructL to get resource file
+// ----------------------------------------------------------
+//
+void CCertManUi::AddResourceFileL()
+  {
+  TFileName fileName;
+
+  TParse parse;
+  parse.Set( KResourceFile, &KDC_RESOURCE_FILES_DIR, NULL );
+
+  fileName = parse.FullName();
+  iResourceLoader.OpenL( fileName );
+  }
+
+// End of File
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/data/10008D3D.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2003-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   ECOM plugin resource file for CertManUI
+*
+*/
+
+
+// INCLUDES
+#include <ecom/registryinfo.rh>
+
+
+RESOURCE REGISTRY_INFO theInfo
+  {
+  dll_uid     = 0x10008D3D;
+  interfaces  =
+    {
+    INTERFACE_INFO
+      {
+      interface_uid   = 0x10207236;
+      implementations =
+        {
+        IMPLEMENTATION_INFO
+          {
+          implementation_uid  = 0x10008D3D;
+          version_no          = 1;
+          display_name        = "CertmanUI Plugin";
+          default_data        = "0x1020743A";
+          opaque_data         = "1";//Order number
+          }
+        };
+      }
+    };
+  }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/data/certmanui.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1622 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This resource file contains all the resources for CertManUI.
+*
+*/
+
+
+//  RESOURCE IDENTIFIER
+NAME CMUI
+
+//  INCLUDES
+#include <eikon.rh>
+#include <avkon.rsg>
+#include <avkon.rh>
+#include <avkon.hrh>
+#include <avkon.mbg>
+#include <bldvariant.hrh>
+#include <avkon.loc>
+#include <certmanui.loc>
+#include "Certmanui.hrh"
+
+RESOURCE RSS_SIGNATURE { }
+
+RESOURCE TBUF { buf=""; }
+
+
+// RESOURCE DEFINITIONS
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_main_authority
+//     CertManUI Authority View Menubar & Soft keys
+//
+//----------------------------------------------------
+//
+RESOURCE AVKON_VIEW r_certmanui_view_main_authority
+     {
+     hotkeys=r_certmanui_hotkeys;
+     menubar=r_certmanui_menubar_view_authority;
+     cba=r_certmanui_options_open_back;
+     }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_main_personal
+//     CertManUI Personal View Menubar & Soft keys
+//
+//----------------------------------------------------
+//
+RESOURCE AVKON_VIEW r_certmanui_view_main_personal
+     {
+     hotkeys=r_certmanui_hotkeys;
+     menubar=r_certmanui_menubar_view_personal;
+     cba=r_certmanui_options_open_back;
+     }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_trust
+//     CertManUI Trust View Menubar & Soft keys
+//
+//----------------------------------------------------
+//
+RESOURCE AVKON_VIEW r_certmanui_view_trust
+     {
+     hotkeys=r_certmanui_hotkeys;
+     menubar=r_certmanui_menubar_view_trust;
+     cba=r_certmanui_options_change_back;
+     }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_main
+//     CertManUI Personal View Menubar & Soft keys
+//
+//----------------------------------------------------
+//
+RESOURCE AVKON_VIEW r_certmanui_view_main
+     {
+     hotkeys=r_certmanui_hotkeys;
+     menubar=r_certmanui_menubar_view_main;
+     cba=r_certmanui_options_open_back;
+     }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_main_trusted_site
+//     CertManUI Trusted site certificate View
+//     Menubar & Soft keys
+//
+//----------------------------------------------------
+//
+RESOURCE AVKON_VIEW r_certmanui_view_main_trusted_site
+     {
+     hotkeys=r_certmanui_hotkeys;
+     menubar=r_certmanui_menubar_view_trusted_sites;
+     cba=r_certmanui_options_open_back;
+     }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_main_device
+//     CertManUI Device certificate View Menubar & Soft keys
+//
+//----------------------------------------------------
+//
+RESOURCE AVKON_VIEW r_certmanui_view_main_device
+     {
+     hotkeys=r_certmanui_hotkeys;
+     menubar=r_certmanui_menubar_view_device;
+     cba=r_certmanui_options_open_back;
+     }
+
+//----------------------------------------------------
+//
+//     r_certmanui_hotkeys
+//     CertManUI hotkeys
+//
+//----------------------------------------------------
+//
+RESOURCE HOTKEYS r_certmanui_hotkeys
+    {
+    control=
+        {
+        HOTKEY { command=EAknCmdExit; key='e'; }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_menubar_view_authority
+//     Menubar for Authority certificate view
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_BAR r_certmanui_menubar_view_authority
+    {
+     titles=
+        {
+        MENU_TITLE { menu_pane = r_certmanui_view_menu_authority; }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_menubar_view_personal
+//     Menubar for Personal certificate view
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_BAR r_certmanui_menubar_view_personal
+    {
+     titles=
+        {
+        MENU_TITLE { menu_pane = r_certmanui_view_menu_personal; }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_menubar_view_trust
+//     Menubar for Trust view
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_BAR r_certmanui_menubar_view_trust
+    {
+    titles=
+        {
+        MENU_TITLE { menu_pane = r_certmanui_view_trust_menu; }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_menubar_view_main
+//     Menubar for main view
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_BAR r_certmanui_menubar_view_main
+    {
+     titles=
+        {
+        MENU_TITLE { menu_pane = r_certmanui_view_menu_main; }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_menubar_view_device
+//     Menubar for Device certificate view
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_BAR r_certmanui_menubar_view_device
+    {
+     titles=
+        {
+        MENU_TITLE { menu_pane = r_certmanui_view_menu_device; }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_menubar_view_trusted_sites
+//     Menubar for Trusted site certificate view
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_BAR r_certmanui_menubar_view_trusted_sites
+    {
+     titles=
+        {
+        MENU_TITLE { menu_pane = r_certmanui_view_menu_trusted_sites; }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_menubar_options_marked
+//     OK-Options menubar for views
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_BAR r_certmanui_menubar_options_marked
+    {
+    titles =
+        {
+        MENU_TITLE { menu_pane = r_certmanui_menupane_options_marked; }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_menu_authority
+//     Menu pane for Authority certificate view
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_PANE r_certmanui_view_menu_authority
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            command = ECertManUICmdAppViewDtls;
+            txt = qtn_cm_option_view_details;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = ECertManUICmdAppDelete;
+            txt = qtn_fldr_delete;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = ECertManUICmdAppTrustSet;
+            txt = qtn_cm_option_trust_settings;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            cascade = r_certmanui_menu_pane_mark_unmark;
+            command = ECertManUICmdMarkUnmark;
+            txt = qtn_options_list;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdHelp;
+            txt = qtn_options_help;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdExit;
+            txt = qtn_options_exit;
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_menu_main
+//     Menu pane for main view
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_PANE r_certmanui_view_menu_main
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            command = ECertManUICmdAppOpen;
+            txt = qtn_fldr_open;
+            flags = EEikMenuItemAction;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdHelp;
+            txt = qtn_options_help;
+            },
+        MENU_ITEM
+            {
+            command=EAknCmdExit;
+            txt = qtn_options_exit;
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//    r_certmanui_menu_pane__unmark
+//    Mark/unmark sub-menu pane for certmanui views
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_PANE r_certmanui_menu_pane_mark_unmark
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            command = ECertManUICmdMark;
+            txt = qtn_options_list_mark_one;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = ECertManUICmdUnmark;
+            txt = qtn_options_list_unmark_one;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = ECertManUICmdMarkAll;
+            txt = qtn_options_list_mark_all;
+            },
+        MENU_ITEM
+            {
+            command = ECertManUICmdUnmarkAll;
+            txt = qtn_options_list_unmark_all;
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_menu_personal
+//     Menu pane for Personal certificate view
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_PANE r_certmanui_view_menu_personal
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            command = ECertManUICmdAppViewDtls;
+            txt = qtn_cm_option_view_details;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = ECertManUICmdAppDelete;
+            txt = qtn_fldr_delete;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = ECertManUICmdMoveToDevice;
+            txt = qtn_cm_option_move_to_device_certificates;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            cascade = r_certmanui_menu_pane_mark_unmark;
+            command = ECertManUICmdMarkUnmark;
+            txt = qtn_options_list;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdHelp;
+            txt = qtn_options_help;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdExit;
+            txt = qtn_options_exit;
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_menu_device
+//     Menu pane for Device certificate view
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_PANE r_certmanui_view_menu_device
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            command = ECertManUICmdAppViewDtls;
+            txt = qtn_cm_option_view_details;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = ECertManUICmdAppDelete;
+            txt = qtn_fldr_delete;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = ECertManUICmdMoveToPersonal;
+            txt = qtn_cm_option_move_to_personal_certificates;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            cascade = r_certmanui_menu_pane_mark_unmark;
+            command = ECertManUICmdMarkUnmark;
+            txt = qtn_options_list;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdHelp;
+            txt = qtn_options_help;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdExit;
+            txt = qtn_options_exit;
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_menu_trusted_sites
+//     Menu pane for Trusted site certificate view
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_PANE r_certmanui_view_menu_trusted_sites
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            command = ECertManUICmdAppViewDtls;
+            txt = qtn_cm_option_view_details;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = ECertManUICmdAppDelete;
+            txt = qtn_fldr_delete;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            cascade = r_certmanui_menu_pane_mark_unmark;
+            command = ECertManUICmdMarkUnmark;
+            txt = qtn_options_list;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdHelp;
+            txt = qtn_options_help;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdExit;
+            txt = qtn_options_exit;
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_menupane_options_marked
+//     For marked certificate views
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_PANE r_certmanui_menupane_options_marked
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            command = ECertManUICmdAppDelete;
+            txt = qtn_fldr_delete;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command=ECertManUICmdMoveToDevice;
+            txt = qtn_cm_option_move_to_device_certificates;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command=ECertManUICmdMoveToPersonal;
+            txt = qtn_cm_option_move_to_personal_certificates;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = ECertManUICmdMark;
+            txt = qtn_options_list_mark_one;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = ECertManUICmdUnmark;
+            txt = qtn_options_list_unmark_one;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = ECertManUICmdMarkAll;
+            txt = qtn_options_list_mark_all;
+            },
+        MENU_ITEM
+            {
+            command = ECertManUICmdUnmarkAll;
+            txt = qtn_options_list_unmark_all;
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_trust_menu
+//     Menu pane for Trust view
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_PANE r_certmanui_view_trust_menu
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            command = ECertManUICmdAppChangeTrust;
+            txt = qtn_cm_option_change_trust;
+            flags = EEikMenuItemAction;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdHelp;
+            txt = qtn_options_help;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdExit;
+            txt = qtn_options_exit;
+            }
+        };
+    }
+
+//----------------------------------------------------
+//  r_gs_certmanui_caption
+//
+// CertManUI view caption for plugin
+//----------------------------------------------------
+//
+RESOURCE TBUF r_gs_certmanui_caption
+    {
+    buf = qtn_set_certmanui_security;
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_title
+//     CertManUI title
+//
+//----------------------------------------------------
+//
+RESOURCE TITLE_PANE r_certmanui_view_title
+    {
+    txt = qtn_cm_title;
+    }
+
+//////////////////////////////////////////////////////////////////////
+//////////////////////////// TEXT RESOURCES //////////////////////////
+//////////////////////////////////////////////////////////////////////
+
+//----------------------------------------------------
+//
+//     r_text_resource_main_view_authority
+//     item for Authority certificates
+//     used in main list view
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_main_view_authority
+    {
+    buf = " \t"qtn_cm_list_text_authority;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_main_view_trusted
+//     item for Trusted site certificates
+//     used in main list view
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_main_view_trusted
+    {
+    buf = " \t"qtn_cm_list_text_trusted;
+    }
+
+
+//----------------------------------------------------
+//
+//     r_text_resource_main_view_personal
+//     item for Personal certificates
+//     used in main list view
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_main_view_personal
+    {
+    buf = " \t"qtn_cm_list_text_personal;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_main_view_device
+//     item for Device certificates
+//     used in main list view
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_main_view_device
+    {
+    buf = " \t"qtn_cm_list_text_device;
+    }
+
+//----------------------------------------------------
+//
+//     r_confirmation_query_delete_cert
+//     Delete certificate confirmation query text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_confirmation_query_delete_cert
+    {
+    buf = qtn_query_common_conf_delete;
+    }
+
+//----------------------------------------------------
+//
+//     r_confirmation_query_delete_cert_no_label
+//     Delete certificate confirmation query text
+//     for certificate that has no label.
+//     The confirmation in only "Delete certificate?"
+//     and it does not dontain any "No label" or "No subject" string
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_confirmation_query_delete_cert_no_label
+    {
+    buf = qtn_query_conf_delete_no_label;
+    }
+
+//----------------------------------------------------
+//
+//     r_confirmation_query_delete_cert_plural
+//     Delete certificate confirmation query text
+//     for deleting multiple certificates
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_confirmation_query_delete_cert_plural
+    {
+    buf = qtn_fldr_del_items_query_cm;
+    }
+
+//----------------------------------------------------
+//
+//     r_info_note_text_certificate_read_only
+//     Certificate read-only info note text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_info_note_text_certificate_read_only
+    {
+    buf = qtn_fldr_cant_delete_item;
+    }
+
+//----------------------------------------------------
+//
+//     r_info_note_text_certificate_read_only_no_label
+//     Certificate read-only info note text
+//     for certificates that have no name
+//     The note in only "Can't delete certificate"
+//     and it does not dontain any "No label" or "No subject" string
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_info_note_text_certificate_read_only_no_label
+    {
+    buf = qtn_cant_delete_item_no_label;
+    }
+
+//----------------------------------------------------
+//
+//     r_info_note_text_certificate_read_only_multiple
+//     Certificate read-only info note text
+//     for multiple read-only certificates
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_info_note_text_certificate_read_only_multiple
+    {
+    buf = qtn_fldr_cant_delete_items;
+    }
+
+//----------------------------------------------------
+//
+//     r_warning_note_text_certificate_expired
+//     Certificate expired information note text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_warning_note_text_certificate_expired
+    {
+    buf = qtn_cm_expired;
+    }
+
+//----------------------------------------------------
+//
+//     r_warning_note_text_certificate_not_valid_yet
+//     Certificate not yet valid information note text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_warning_note_text_certificate_not_valid_yet
+    {
+    buf = qtn_cm_not_valid_yet;
+    }
+
+//----------------------------------------------------
+//
+//     r_warning_note_text_certificate_corrupted
+//     Certificate corrupted information note text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_warning_note_text_certificate_corrupted
+    {
+    buf = qtn_cm_corrupted;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_view_authority_empty_list
+//     Empty Authority certificate list text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_view_authority_empty_list
+    {
+    buf = qtn_authority_empty_list;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_view_trusted_empty_list
+//     Empty Trusdted site certificate list text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_view_trusted_empty_list
+    {
+    buf = qtn_trusted_empty_list;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_view_personal_empty_list
+//     Empty Personal certificate list text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_view_personal_empty_list
+    {
+    buf = qtn_personal_empty_list;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_view_device_empty_list
+//     Empty Device certificate list text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_view_device_empty_list
+    {
+    buf = qtn_device_empty_list;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_view_trust_settings_empty_list
+//     Empty Trust settings list text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_view_trust_settings_empty_list
+    {
+    buf = qtn_cm_empty_trust_settings;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_view_no_subject_list
+//     Certificate has no subject
+//     used in main certificate list view
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_view_no_subject_list
+    {
+    buf = " \t"qtn_cm_no_subject_list;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_view_no_subject_details
+//     Certificate has no subject
+//     used in certificate details view
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_view_no_subject_details
+    {
+    buf = qtn_cm_no_subject_details;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_view_digital_signing
+//     Key usage is digital signing
+//     used in client certificate details view
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_details_view_digital_signing
+    {
+    buf = qtn_cm_digital_signing;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_view_digital_signing
+//     Key usage is digital signing
+//     used in client certificate details view
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_details_view_client_authentication
+    {
+    buf = qtn_cm_client_authentication;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_details_view_unknown
+//     Certificate algorithm is unknown
+//     used in certificate details view
+//
+//----------------------------------------------------
+//
+
+RESOURCE TBUF r_text_resource_details_view_unknown
+    {
+    buf = qtn_cm_algorithm_unknown;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_details_view_location_phone_memory
+//     Certificate location is phone memory
+//     used in certificate details view
+//
+//----------------------------------------------------
+//
+
+RESOURCE TBUF r_text_resource_details_view_location_phone_memory
+    {
+    buf = qtn_cm_phone_memory;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_details_view_location_smart_card
+//     Certificate location is smart card
+//     used in certificate details view
+//
+//----------------------------------------------------
+//
+
+RESOURCE TBUF r_text_resource_details_view_location_smart_card
+    {
+    buf = qtn_cm_smart_card;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_details_view_cert_format_x509
+//     Certificate format is x509
+//     used in certificate details view
+//
+//----------------------------------------------------
+//
+
+RESOURCE TBUF r_text_resource_details_view_cert_format_x509
+    {
+    buf = qtn_cm_cert_format_x509;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_details_view_no_private_key
+//     No private key available
+//     used in certificate details view
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_details_view_no_private_key
+    {
+    buf = qtn_cm_no_private_key;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_details_view_not_defined
+//     used in certificate details view
+//
+//----------------------------------------------------
+//
+
+RESOURCE TBUF r_text_resource_details_view_not_defined
+    {
+    buf = qtn_cm_not_defined;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_view_no_label_details
+//     Certificate has no label
+//     used in certificate details view
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_view_no_label_details
+    {
+    buf = qtn_cm_no_label_details;
+    }
+
+//----------------------------------------------------
+//
+//     r_text_resource_view_no_subject_title
+//     Certificate has no subject
+//     used in trust settings view title
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_view_no_subject_title
+    {
+    buf = qtn_cm_no_subject_title;
+    }
+
+// ----- All the resource strings needed for the Certificate Details View -------
+
+RESOURCE TBUF r_text_resource_details_view_site
+    {
+    buf = qtn_cm_site;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_sites
+    {
+    buf = qtn_cm_sites;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_header
+    {
+    buf = qtn_cm_details_heading;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_label
+    {
+    buf = qtn_cm_label;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_issuer
+    {
+    buf = qtn_cm_issuer;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_subject
+    {
+    buf = qtn_cm_subject;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_key_usage
+    {
+    buf = qtn_cm_key_usage;
+    }
+
+RESOURCE TBUF r_qtn_sn_key_length_label
+    {
+    buf = qtn_sn_key_length_label;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_validity_period
+    {
+    buf = qtn_cm_validity_period;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_valid_from
+    {
+    buf = qtn_cm_valid_from;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_valid_until
+    {
+    buf = qtn_cm_valid_until;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_certificate_location
+    {
+    buf = qtn_cm_certificate_location;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_cert_format
+    {
+    buf = qtn_cm_cert_format;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_private_key_location
+    {
+    buf = qtn_cm_key_location;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_algorithm
+    {
+    buf = qtn_cm_algorithm;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_serial_number
+    {
+    buf = qtn_cm_serial_number;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_fingerprint
+    {
+    buf = qtn_cm_fingerprint;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_fingerprint_md5
+    {
+    buf = qtn_cm_fingerprint_md;
+    }
+
+RESOURCE TBUF r_text_resource_details_view_public_key
+    {
+    buf = qtn_cm_public_key;
+    }
+
+// Certificate details algorithm names
+RESOURCE TBUF r_text_resource_details_view_algorithm_RSA
+    {
+    buf = qtn_cm_algorithm_rsa;
+    }
+RESOURCE TBUF r_text_resource_details_view_algorithm_DSA
+    {
+    buf = qtn_cm_algorithm_dsa;
+    }
+RESOURCE TBUF r_text_resource_details_view_algorithm_DH
+    {
+    buf = qtn_cm_algorithm_dh;
+    }
+RESOURCE TBUF r_text_resource_details_view_algorithm_MD2
+    {
+    buf = qtn_cm_algorithm_md2;
+    }
+RESOURCE TBUF r_text_resource_details_view_algorithm_MD5
+    {
+    buf = qtn_cm_algorithm_md5;
+    }
+RESOURCE TBUF r_text_resource_details_view_algorithm_SHA1
+    {
+    buf = qtn_cm_algorithm_sha1;
+    }
+
+//----------------------------------------------------
+//
+//     r_error_note_text_cacerts_db_corrupted
+//     Cacerts.dat certificate database corrupted error note text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_error_note_text_cacerts_db_corrupted
+    {
+    buf = qtn_memlo_database_corrupted;
+    }
+
+//----------------------------------------------------
+//
+//     r_error_note_text_internal_error
+//     Internal error text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_error_note_text_internal_error
+    {
+    buf = qtn_cm_internal_error;
+    }
+
+//----------------------------------------------------
+//
+//     r_warning_note_text_certificate_not_trusted
+//     Certificate not trusted information note text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_warning_note_text_certificate_not_trusted
+    {
+    buf = qtn_cm_not_trusted;
+    }
+
+
+//----------------------------------------------------
+//
+//     r_qtn_cm_conf_move_to_device
+//     Confirmation query text shown before moving
+//     certificate to Device certificates
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_cm_conf_move_to_device
+    {
+    buf = qtn_cm_conf_move_to_device;
+    }
+
+//----------------------------------------------------
+//
+//     r_qtn_cm_conf_move_to_personal
+//     Confirmation query text shown before moving
+//     certificate to Personal certificates
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_cm_conf_move_to_personal
+    {
+    buf = qtn_cm_conf_move_to_personal;
+    }
+
+
+//////////////////////// DIALOGS //////////////////////////////////////////
+
+// ---------------------------------------------------------
+//
+//     r_certmanui_confirmation_query_yes_no
+//     Delete certificate confirmation query
+//
+// ---------------------------------------------------------
+//
+RESOURCE DIALOG r_certmanui_confirmation_query_yes_no
+    {
+    flags = EGeneralQueryFlags;
+    buttons = R_AVKON_SOFTKEYS_YES_NO;
+    items =
+        {
+        DLG_LINE
+            {
+            type = EAknCtQuery;
+            id = EGeneralQuery;
+            control = AVKON_CONFIRMATION_QUERY
+                {
+                layout = EConfirmationLayout;
+                label = "";
+                };
+            }
+        };
+    }
+
+// ---------------------------------------------------------
+//
+//     r_certmanui_wait_note
+//     Display wait note
+//
+// ---------------------------------------------------------
+//
+RESOURCE DIALOG r_certmanui_wait_note
+    {
+    flags = EAknWaitNoteFlags;
+    buttons = R_AVKON_SOFTKEYS_EMPTY;
+    items =
+        {
+        DLG_LINE
+            {
+            type = EAknCtNote;
+            id = ECertManUIWaitNote;
+            control= AVKON_NOTE
+                {
+                layout = EWaitLayout;
+                singular_label = qtn_gen_note_processing;
+                animation = R_QGN_GRAF_WAIT_BAR_ANIM;
+                };
+            }
+        };
+    }
+
+// ---------------------------------------------------------
+//
+//     r_certmanui_delete_wait_dialog
+//     Display delete wait note
+//
+// ---------------------------------------------------------
+//
+RESOURCE DIALOG r_certmanui_delete_wait_note
+    {
+    flags = EAknWaitNoteFlags;
+    buttons = R_AVKON_SOFTKEYS_EMPTY;
+    items =
+        {
+        DLG_LINE
+            {
+            type = EAknCtNote;
+            id = ECertManUIDeleteNote;
+            control= AVKON_NOTE
+                {
+                layout = EWaitLayout;
+                singular_label = qtn_fldr_deleting_wait_note;
+                imagefile = AVKON_BITMAP_FILE;
+                imageid = EMbmAvkonQgn_note_erased;
+                imagemask = EMbmAvkonQgn_note_erased_mask;
+                animation = R_QGN_GRAF_WAIT_BAR_ANIM;
+                };
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_message_query_details_view
+//     Certificate Management Details view query
+//
+//----------------------------------------------------
+//
+RESOURCE DIALOG r_message_query_details_view
+    {
+    flags = EGeneralQueryFlags | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow;
+    buttons = R_AVKON_SOFTKEYS_OK_EMPTY;
+    items =
+        {
+        DLG_LINE
+            {
+            type = EAknCtPopupHeadingPane;
+            id = EAknMessageQueryHeaderId;
+            control = AVKON_HEADING
+                {
+                };
+            },
+        DLG_LINE
+            {
+            type = EAknCtMessageQuery;
+            id = EAknMessageQueryContentId;
+            control = AVKON_MESSAGE_QUERY
+                {
+                };
+            }
+        };
+    }
+
+//-----------------------------------------------------------------------------
+//
+//  r_certmanui_view_trust_settings_listbox
+//  Items in CertManUI trust settings view
+//
+//-----------------------------------------------------------------------------
+//
+RESOURCE ARRAY r_certmanui_view_trust_settings_listbox
+     {
+    items =
+        {
+        LBUF
+            {//WAP connection
+            txt = " \t"qtn_cm_lipri_wap_connection"\t\t";
+            },
+        LBUF
+            {//mail and image connection
+            txt = " \t"qtn_cm_lipri_mail_image_conn"\t\t";
+            },
+        LBUF
+            {//Native installer
+            txt = " \t"qtn_cm_lipri_native_installing"\t\t";
+            },
+        LBUF
+            {//Java installer
+            txt = " \t"qtn_cm_lipri_java_installing"\t\t";
+            },
+        LBUF
+            {//OCSP validation
+            txt = " \t"qtn_cm_lipri_ocsp"\t\t";
+            },
+        LBUF
+            {//VPN
+            txt = " \t"qtn_cm_lipri_vpn"\t\t";
+            }
+        };
+    }
+
+//-----------------------------------------------------------------------------
+//
+//  r_certmanui_trust_settings_values
+//  Values in CertManUI trust settings view
+//
+//-----------------------------------------------------------------------------
+//
+RESOURCE ARRAY r_certmanui_trust_settings_values
+    {
+    items =
+        {
+        LBUF
+            {
+            txt = qtn_cm_trust_value_yes;
+            },
+        LBUF
+            {
+            txt = qtn_cm_trust_value_no;
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//      r_certmanui_view_trust_yes_no_setting_page_lbx
+//     CertManUI Trust View Yes No Setting Page Listbox
+//
+//----------------------------------------------------
+//
+RESOURCE ARRAY r_certmanui_view_trust_yes_no_setting_page_lbx
+     {
+    items =
+        {
+        LBUF
+            {
+            txt = qtn_cm_trust_value_yes;
+            },
+        LBUF
+            {
+            txt = qtn_cm_trust_value_no;
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_setting_listbox
+//     Common listbox editor resource for setting pages.
+//
+//----------------------------------------------------
+//
+RESOURCE LISTBOX r_setting_listbox
+    {
+    flags = EEikListBoxMultipleSelection;
+    }
+
+//----------------------------------------------------
+//
+//     r_cm_navi_pane_trust_settings
+//     Certificate Management Trust Settings view navi pane text
+//
+//----------------------------------------------------
+//
+RESOURCE NAVI_LABEL r_cm_navi_pane_trust_settings
+    {
+    txt = qtn_cm_title_trust_settings;
+    }
+
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_trust_yes_no_setting_page
+//     CertManUI Trust View Yes No Setting Page
+//
+//----------------------------------------------------
+//
+RESOURCE AVKON_SETTING_PAGE r_certmanui_view_trust_yes_no_setting_page
+    {
+    number = EAknSettingPageNoOrdinalDisplayed;
+    softkey_resource = R_AVKON_SOFTKEYS_OK_CANCEL;
+    type = EAknSetListBox;
+    editor_resource_id = r_setting_listbox;
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_certificate_listbox_mark_icons
+//     Mark, unmark icons for certificate list
+//
+//----------------------------------------------------
+//
+RESOURCE AKN_ICON_ARRAY r_certmanui_certificate_listbox_mark_icons
+     {
+     bmpfile = AVKON_BITMAP_FILE;
+     icons =
+          {
+          AKN_ICON {
+                    iconId = EMbmAvkonQgn_indi_marked_add;
+                    maskId = EMbmAvkonQgn_indi_marked_add_mask;
+                    }
+          };
+     }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_main_title
+//     CertManUI main title
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_certmanui_view_main_title
+    {
+    buf = qtn_cm_title;
+    }
+
+//----------------------------------------------------
+//
+//    r_certmanui_options_open_back
+//    Text association with MSK ( OPEN )
+//
+//----------------------------------------------------
+//
+RESOURCE CBA r_certmanui_options_open_back
+    {
+    buttons =
+        {
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyOptions;
+            txt = text_softkey_option;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyBack;
+            txt = text_softkey_back;
+            },
+        CBA_BUTTON
+            {
+            id=ECertManUICmdAppViewDtls;
+            txt = qtn_msk_open;
+            }
+        };
+    }
+
+
+//----------------------------------------------------
+//
+//    r_certmanui_options_context_back
+//    Text association with MSK ( context )
+//
+//----------------------------------------------------
+//
+RESOURCE CBA r_certmanui_options_context_back
+    {
+    buttons =
+        {
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyOptions;
+            txt = text_softkey_option;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyBack;
+            txt = text_softkey_back;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyContextOptions;
+            txt = text_softkey_option;
+            }
+        };
+    }
+
+
+//----------------------------------------------------
+//
+//    r_certmanui_options_open_back
+//    Text association with MSK ( OPTIONS )
+//
+//----------------------------------------------------
+//
+RESOURCE CBA r_certmanui_options_back
+    {
+    buttons =
+        {
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyOptions;
+            txt = text_softkey_option;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyBack;
+            txt = text_softkey_back;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyOptions;
+            txt = text_softkey_option;
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//    r_certmanui_options_change_back
+//    Text association with MSK ( CHANGE )
+//
+//----------------------------------------------------
+//
+RESOURCE CBA r_certmanui_options_change_back
+    {
+    buttons =
+        {
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyOptions;
+            txt = text_softkey_option;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyBack;
+            txt = text_softkey_back;
+            },
+        CBA_BUTTON
+            {
+            id=ECertManUICmdAppChangeTrust;
+            txt = qtn_msk_change;
+            }
+        };
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_title_authority
+//     CertManUI Authority certificates view title
+//
+//----------------------------------------------------
+//
+RESOURCE TITLE_PANE r_certmanui_view_title_authority
+    {
+    txt = qtn_cm_title_authority;
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_title_trusted_site
+//     CertManUI Trusted Site certificates view title
+//
+//----------------------------------------------------
+//
+RESOURCE TITLE_PANE r_certmanui_view_title_trusted_site
+    {
+    txt = qtn_cm_title_trusted;
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_title_personal
+//     CertManUI Personal certificates view title
+//
+//----------------------------------------------------
+//
+RESOURCE TITLE_PANE r_certmanui_view_title_personal
+    {
+    txt = qtn_cm_title_personal;
+    }
+
+//----------------------------------------------------
+//
+//     r_certmanui_view_title_device
+//     CertManUI Device certificates view title
+//
+//----------------------------------------------------
+//
+RESOURCE TITLE_PANE r_certmanui_view_title_device
+    {
+    txt = qtn_cm_title_device;
+    }
+
+// End of File
Binary file pkiutilities/CertmanUi/help/data/xhtml.zip has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/help/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - Initial contribution
+*
+* Contributors:
+*
+* Description:  Export help related files.
+*
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_EXPORTS
+:zip ../data/xhtml.zip   /epoc32/data/z/resource/ overwrite
+:zip ../data/xhtml.zip   /epoc32/winscw/c/resource/ overwrite
+
+../inc/cm.hlp.hrh   MW_LAYER_PLATFORM_EXPORT_PATH(csxhelp/cm.hlp.hrh)
+../rom/certmanuihelps_variant.iby       CUSTOMER_APP_LAYER_IBY_EXPORT_PATH(certmanuihelps_variant.iby)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/help/inc/cm.hlp.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*/
+	
+//
+// cm.hlp.hrh generated by CSXHelp Utilities.
+//           
+
+#ifndef __CM_HLP_HRH__
+#define __CM_HLP_HRH__
+
+_LIT(KCM_HLP_AUTHORITY, "CM_HLP_AUTHORITY"); // 
+_LIT(KCM_HLP_DEVICE, "CM_HLP_DEVICE"); // 
+_LIT(KCM_HLP_MAIN, "CM_HLP_MAIN"); // 
+_LIT(KCM_HLP_PERSONAL, "CM_HLP_PERSONAL"); // 
+_LIT(KCM_HLP_TRUSTED_SITE, "CM_HLP_TRUSTED_SITE"); // 
+_LIT(KCM_HLP_TRUST_SETTINGS, "CM_HLP_TRUST_SETTINGS"); // 
+
+#endif 
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/help/rom/certmanuihelps_variant.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Image description file for CertmanUi helps
+*
+*/
+
+#ifndef __CERTMANUIHELPS_VARIANT_IBY__
+#define __CERTMANUIHELPS_VARIANT_IBY__
+
+#if defined(FF_S60_HELPS_IN_USE)
+    data=LOCALISE(DATAZ_\resource\xhtml\%02d\0x10008D3D\contents.zip, RESOURCE_FILES_DIR\xhtml\%02d\0x10008D3D\contents.zip)
+    data=LOCALISE(DATAZ_\resource\xhtml\%02d\0x10008D3D\index.xml, RESOURCE_FILES_DIR\xhtml\%02d\0x10008D3D\index.xml)
+    data=LOCALISE(DATAZ_\resource\xhtml\%02d\0x10008D3D\keywords.xml, RESOURCE_FILES_DIR\xhtml\%02d\0x10008D3D\keywords.xml)
+    data=LOCALISE(DATAZ_\resource\xhtml\%02d\0x10008D3D\meta.xml, RESOURCE_FILES_DIR\xhtml\%02d\0x10008D3D\meta.xml)
+#endif
+
+#endif  // __CERTMANUIHELPS_VARIANT_IBY__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/CertmanUi/loc/certmanui.loc	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,426 @@
+/*
+* Copyright (c) 2002-2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Localisation of CertManUI
+*
+*/
+
+
+// LOCALISATION STRINGS
+
+//d: Command in general settings security folder, opens Certificate management view
+//l: list_setting_pane_t1
+//
+#define qtn_set_certmanui_security      "Certificate management"
+
+//d:Name of the dll for title pane
+//l:title_pane_t2/opt9
+#define qtn_cm_title                    "Certificate management"
+
+//d:Command for the options menus.
+//l:list_single_pane_t1_cp2
+#define qtn_cm_option_view_details      "View details"
+
+//d:Command for the options menus.
+//l:list_single_pane_t1_cp2
+#define qtn_cm_option_trust_settings    "Trust settings"
+
+//d:Command for the options menus.
+//l:list_single_pane_t1_cp2
+#define qtn_cm_option_change_trust      "Change trust"
+
+//d:Certificate view list item
+//d: used in Certificate Main view
+//l:list_single_pane_t1
+#define qtn_cm_no_subject_list          "(No subject)"
+
+//d:Certificate details view item
+//d: used in certificate details,
+//l:popup_info_list_pane_t1
+#define qtn_cm_no_subject_details       "(No subject)"
+
+//d:Certificate trust settings title
+//d: used in Trust Settings Title pane
+//l:title_pane_t2/opt9
+#define qtn_cm_no_subject_title         "(No subject)"
+
+//d:Certificate details changeable list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_not_defined              "(Not defined)"
+
+//d:Certificate details view item
+//d: used in certificate details,
+//l:popup_info_list_pane_t1
+#define qtn_cm_no_label_details         "(No label)"
+
+//d:Name of the Authority Certificates view tab.
+//l:tabs_2_long_active_pane_t1
+#define qtn_cm_tab_authority            "Authority"
+
+//d:Name of the Personal Certificates view tab.
+//l:tabs_2_long_active_pane_t1
+#define qtn_cm_tab_personal             "Personal"
+
+//d:Confirmation query text in Certificates View
+//l:popup_note_window
+#define qtn_query_conf_delete_no_label  "Delete certificate?"
+
+//d:Confirmation query text in Certificates View: about to delete more items
+//l:popup_note_window
+#define qtn_fldr_del_items_query_cm     "Delete %N items?"
+
+//d:Information note text in Certificates View: could not delete one item
+//l:popup_note_window
+#define qtn_cant_delete_item_no_label     "Can't delete certificate"
+
+// Certificate details algorithm names
+///////////////////////////////////////////////////////////
+//d:Certificate details algorithm name
+//l:popup_info_list_pane_t1
+#define qtn_cm_algorithm_rsa            "RSA"
+
+//d:Certificate details algorithm name
+//l:popup_info_list_pane_t1
+#define qtn_cm_algorithm_dsa            "DSA"
+
+//d:Certificate details algorithm name
+//l:popup_info_list_pane_t1
+#define qtn_cm_algorithm_dh             "DH"
+
+//d:Certificate details algorithm name
+//l:popup_info_list_pane_t1
+#define qtn_cm_algorithm_md2            "MD2"
+
+//d:Certificate details algorithm name
+//l:popup_info_list_pane_t1
+#define qtn_cm_algorithm_md5            "MD5"
+
+//d:Certificate details algorithm name
+//l:popup_info_list_pane_t1
+#define qtn_cm_algorithm_sha1           "SHA1"
+
+//d:Certificate details algorithm unknown
+//l:popup_info_list_pane_t1
+#define qtn_cm_algorithm_unknown        "Unknown"
+
+//d:Certificate details list's heading
+//l:heading_pane_t1
+#define qtn_cm_details_heading          "Certificate details"
+
+//d:Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_label                    "Label:"
+
+//d:Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_subject                  "Subject:"
+
+//d:Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_issuer                   "Issuer:"
+
+//d:Rel 2.8 Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_key_usage                "Key usage:"
+
+//d:Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_validity_period          "Validity period:"
+
+//d:Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_valid_from               "Valid from:"
+
+//d:Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_valid_until              "Valid until:"
+
+//d:Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_certificate_location     "Location:"
+
+//d:Certificate details changeable list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_phone_memory             "Phone memory"
+
+//d:Certificate details changeable list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_smart_card               "Smart card"
+
+//d:Rel 2.8 Certificate details changeable list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_no_private_key           "No private key"
+
+//d:Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_cert_format              "Certificate format:"
+
+//d:Rel 2.8 Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_key_location             "Private key location:"
+
+//d:Certificate details changeable list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_cert_format_x509         "X509"
+
+//d:Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_algorithm                "Algorithm:"
+
+//d:Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_serial_number            "Serial number:"
+
+//d:Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_fingerprint              "Fingerprint (SHA1):"
+
+//d:Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_fingerprint_md           "Fingerprint (MD5):"
+
+//d:Certificate details list item
+//l:popup_info_list_pane_t1
+//r:3.2
+//
+#define qtn_cm_public_key               "Public key (%0U %1N bits):"
+
+//d:Certificate details list item
+//l:popup_info_list_pane_t1
+//w:
+//r:3.0
+#define qtn_sn_key_length_label         "Key length:"
+
+//d:Rel 2.8 Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_digital_signing          "Digital signing"
+
+//d:Rel 2.8 Certificate details list item
+//l:popup_info_list_pane_t1
+#define qtn_cm_client_authentication    "Client authentication"
+
+//d:Certificate trust settings WAP connection
+//l:list_single_graphic_pane_t1_cp2
+#define qtn_cm_lipri_wap_connection     "WAP connection"
+
+//d:Certificate trust settings application controller
+//l:list_single_graphic_pane_t1_cp2
+#define qtn_cm_lipri_app_control        "Application controller"
+
+//d:Certificate trust settings mail and image connection
+//l:list_single_graphic_pane_t1_cp2
+#define qtn_cm_lipri_mail_image_conn    "Mail and Image conn."
+
+//d:Certificate trust settings for java installing.
+//d:With this user can decide if certificate is trusted for
+//d:installing java applications.
+//l:list_single_graphic_pane_t1_cp2
+#define qtn_cm_lipri_java_installing    "Java installing"
+
+//d:Certificate trust settings native installing.
+//d:With this user can decide if certificate is trusted for
+//d:native application installing (i.e. SOS applications).
+//l:list_single_graphic_pane_t1_cp2
+#define qtn_cm_lipri_native_installing    "Native installing"
+
+//d:Certificate trust settings for OCSP validation.
+//d:With this user can decide if certificate is trusted to
+//d:validate ocsp response (i.e. SOS applications).
+//l:list_single_graphic_pane_t1_cp2
+#define qtn_cm_lipri_ocsp "OCSP validation"
+
+//d:Certificate trust settings value yes
+//l:list_set_graphic_pane_t1
+#define qtn_cm_trust_value_yes            "Yes"
+
+//d:Certificate trust settings value no
+//l:list_set_graphic_pane_t1
+#define qtn_cm_trust_value_no             "No"
+
+//d:Certificate trust settings X.509 authority certificate in WIM note
+//l:main_list_empty_pane
+#define qtn_cm_empty_trust_settings       "(No trusting\napplications)"
+
+//d:Certificate trust settings text in navi pane
+//d:Trust setting list view
+//l:navi_text_pane_t1
+#define qtn_cm_title_trust_settings       "Trust settings"
+
+
+//d:Certificate warning notes
+//l:popup_note_window
+#define qtn_cm_expired                    "The certificate has expired"
+
+//d:Certificate warning notes
+//l:popup_note_window
+#define qtn_cm_not_valid_yet              "The certificate is not valid yet"
+
+//d:Certificate warning notes
+//l:popup_note_window
+#define qtn_cm_corrupted                  "The certificate is corrupted"
+
+//d:Certificate warning notes
+//l:popup_note_window
+#define qtn_cm_not_trusted                "Certificate not trusted"
+
+//d:Internal error warning note
+//l:popup_note_window
+//w:
+//r:3.2
+//
+#define qtn_cm_internal_error             "Internal error"
+
+//d:Certificate trust settings for VPN.
+//d:With this user can decide if certificate is trusted for VPN.
+//l:list_single_graphic_pane_t1_cp2
+//w:
+//r:3.0
+#define qtn_cm_lipri_vpn                  "VPN"
+
+//d:Site name
+//d:%U stands for site name
+//l:popup_info_list_pane_t1
+//w:
+//r:3.2
+//
+#define qtn_cm_site                   "Site:"
+
+//d:Site names.
+//d:%U stands for site names
+//l:popup_info_list_pane_t1
+//w:
+//r:3.2
+//
+#define qtn_cm_sites                  "Sites:"
+
+
+//d::Text of Authority list item in Security view's main pane
+//l:list_single_pane_t1
+//w:
+//r:3.2
+//
+#define qtn_cm_list_text_authority    "Authority"
+
+
+//d::Text of Trusted sites list item in Security view's main pane
+//l:list_single_pane_t1
+//w:
+//r:3.2
+//
+#define qtn_cm_list_text_trusted    "Trusted sites"
+
+//d::Text of Device list item in Security view's main pane
+//l:list_single_pane_t1
+//w:
+//r:3.2
+//
+#define qtn_cm_list_text_device     "Device"
+
+//d::Text of Personal certificates list item in Security view's main pane
+//l:list_single_pane_t1
+//w:
+//r:3.2
+//
+#define qtn_cm_list_text_personal   "Personal"
+
+//d::Title of Authority certificates view
+//l:title_pane_t2/opt9
+//w:
+//r:3.2
+//
+#define qtn_cm_title_authority      "Authority certificates"
+
+//d::Title of Trusted site certificates view
+//l:title_pane_t2/opt9
+//w:
+//r:3.2
+//
+#define qtn_cm_title_trusted        "Trusted site certificates"
+
+//d::Title of Personal certificates view
+//l:title_pane_t2/opt9
+//w:
+//r:3.2
+//
+#define qtn_cm_title_personal       "Personal certificates"
+
+//d:Title of Device certificates view
+//l:title_pane_t2/opt9
+//w:
+//r:3.2
+//
+#define qtn_cm_title_device         "Device certificates"
+
+//d:Item in Options menu (Personal certificates view)
+//d:for moving the selected certificate(s) to
+//d:the Device Certificates.
+//l:list_single_pane_t1_cp2
+//w:
+//r:3.2
+//
+#define qtn_cm_option_move_to_device_certificates   "Move to Device Certificates"
+
+//d:Item in Options menu (Device certificates view)
+//d:for moving the selected certificate(s) to the
+//d:Personal Certificates.
+//l:list_single_pane_t1_cp2
+//w:
+//r:3.2
+//
+#define qtn_cm_option_move_to_personal_certificates   "Move to Personal Certificates"
+
+//d:Confirmation query text shown before moving
+//d:certificate to Device certificates
+//l:popup_note_window
+//w:
+//r:3.2
+//
+#define qtn_cm_conf_move_to_device    "Device certificates can be used without user confirmation. Use of device lock recommended. Proceed ?"
+
+//d:Confirmation query text shown before moving
+//d:certificate to Personal certificates
+//l:popup_note_window
+//w:
+//r:3.2
+//
+#define qtn_cm_conf_move_to_personal    "Use of Personal certificates may require user confirmation. Proceed?"
+
+//d:Empty list text for Authority certificates view
+//l:main_list_empty_pane
+//w:
+//r:3.2
+//
+#define qtn_authority_empty_list    "(no authority certificates)"
+
+//d:Empty list text for Trusted site certificates view
+//l:main_list_empty_pane
+//w:
+//r:3.2
+//
+#define qtn_trusted_empty_list      "(no trusted site certificates)"
+
+//d:Empty list text for Personal certificates view
+//l:main_list_empty_pane
+//w:
+//r:3.2
+//
+#define qtn_personal_empty_list     "(no personal certificates)"
+
+//d:Empty list text for Device certificates view
+//l:main_list_empty_pane
+//w:
+//r:3.2
+//
+#define qtn_device_empty_list       "(no device certificates)"
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/BWINS/DevTokenClientu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,11 @@
+EXPORTS
+	??1CTrustSitesStore@@UAE@XZ @ 1 NONAME ; CTrustSitesStore::~CTrustSitesStore(void)
+	?AddForgivenSiteL@CTrustSitesStore@@QAEHABVTDesC16@@ABH@Z @ 2 NONAME ; int CTrustSitesStore::AddForgivenSiteL(class TDesC16 const &, int const &)
+	?AddL@CTrustSitesStore@@QAEHABVTDesC8@@ABVTDesC16@@@Z @ 3 NONAME ; int CTrustSitesStore::AddL(class TDesC8 const &, class TDesC16 const &)
+	?GetTrustedSitesL@CTrustSitesStore@@QAEHABVTDesC8@@AAV?$RPointerArray@VHBufC16@@@@@Z @ 4 NONAME ; int CTrustSitesStore::GetTrustedSitesL(class TDesC8 const &, class RPointerArray<class HBufC16> &)
+	?IsTrustedSiteL@CTrustSitesStore@@QAEHABVTDesC8@@ABVTDesC16@@@Z @ 5 NONAME ; int CTrustSitesStore::IsTrustedSiteL(class TDesC8 const &, class TDesC16 const &)
+	?NewL@CDevTokenType@@SAPAVCCTTokenType@@VTUid@@@Z @ 6 NONAME ; class CCTTokenType * CDevTokenType::NewL(class TUid)
+	?NewL@CTrustSitesStore@@SAPAV1@XZ @ 7 NONAME ; class CTrustSitesStore * CTrustSitesStore::NewL(void)
+	?IsOutOfDateAllowedL@CTrustSitesStore@@QAEHABVTDesC8@@ABVTDesC16@@@Z @ 8 NONAME ; int CTrustSitesStore::IsOutOfDateAllowedL(class TDesC8 const &, class TDesC16 const &)
+	?RemoveForgivenSiteL@CTrustSitesStore@@QAEHABVTDesC16@@@Z @ 9 NONAME ; int CTrustSitesStore::RemoveForgivenSiteL(class TDesC16 const &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/BWINS/DevTokenSharedu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,64 @@
+EXPORTS
+	??0CDevTokenDHParams@@AAE@VRInteger@@0@Z @ 1 NONAME ; CDevTokenDHParams::CDevTokenDHParams(class RInteger, class RInteger)
+	??1CDevTokenDHParams@@UAE@XZ @ 2 NONAME ; CDevTokenDHParams::~CDevTokenDHParams(void)
+	?CreateLC@@YAXAAVRReadStream@@AAVRInteger@@@Z @ 3 NONAME ; void CreateLC(class RReadStream &, class RInteger &)
+	?DecryptAndCreateLC@@YAXAAVRReadStream@@AAVRInteger@@PAVMKeyEncryptor@@@Z @ 4 NONAME ; void DecryptAndCreateLC(class RReadStream &, class RInteger &, class MKeyEncryptor *)
+	?EncryptAndStoreL@@YAXABVTInteger@@AAVRWriteStream@@PAVMKeyEncryptor@@@Z @ 5 NONAME ; void EncryptAndStoreL(class TInteger const &, class RWriteStream &, class MKeyEncryptor *)
+	?ExternalizeL@@YAXABVTInteger@@AAVRWriteStream@@@Z @ 6 NONAME ; void ExternalizeL(class TInteger const &, class RWriteStream &)
+	?NewL@CDevTokenCertInfo@@SAPAV1@AAVRReadStream@@@Z @ 7 NONAME ; class CDevTokenCertInfo * CDevTokenCertInfo::NewL(class RReadStream &)
+	?NewL@CDevTokenCertInfo@@SAPAV1@ABV1@@Z @ 8 NONAME ; class CDevTokenCertInfo * CDevTokenCertInfo::NewL(class CDevTokenCertInfo const &)
+	?NewL@CDevTokenCertInfo@@SAPAV1@ABVTDesC16@@W4TCertificateFormat@@W4TCertificateOwnerType@@HPBV?$TBuf8@$0BE@@@3H@Z @ 9 NONAME ; class CDevTokenCertInfo * CDevTokenCertInfo::NewL(class TDesC16 const &, enum TCertificateFormat, enum TCertificateOwnerType, int, class TBuf8<20> const *, class TBuf8<20> const *, int)
+	?NewL@CDevTokenCertInfo@@SAPAV1@ABVTDesC16@@W4TCertificateFormat@@W4TCertificateOwnerType@@HPBV?$TBuf8@$0BE@@@3HH@Z @ 10 NONAME ; class CDevTokenCertInfo * CDevTokenCertInfo::NewL(class TDesC16 const &, enum TCertificateFormat, enum TCertificateOwnerType, int, class TBuf8<20> const *, class TBuf8<20> const *, int, int)
+	?NewL@CDevTokenDHParams@@SAPAV1@ABVTInteger@@0@Z @ 11 NONAME ; class CDevTokenDHParams * CDevTokenDHParams::NewL(class TInteger const &, class TInteger const &)
+	?NewL@CDevTokenKeyInfo@@SAPAV1@AAVRReadStream@@@Z @ 12 NONAME ; class CDevTokenKeyInfo * CDevTokenKeyInfo::NewL(class RReadStream &)
+	?NewLC@CDevTokenCertInfo@@SAPAV1@AAVRReadStream@@@Z @ 13 NONAME ; class CDevTokenCertInfo * CDevTokenCertInfo::NewLC(class RReadStream &)
+	?NewLC@CDevTokenCertInfo@@SAPAV1@ABV1@@Z @ 14 NONAME ; class CDevTokenCertInfo * CDevTokenCertInfo::NewLC(class CDevTokenCertInfo const &)
+	?NewLC@CDevTokenCertInfo@@SAPAV1@ABVTDesC16@@W4TCertificateFormat@@W4TCertificateOwnerType@@HPBV?$TBuf8@$0BE@@@3H@Z @ 15 NONAME ; class CDevTokenCertInfo * CDevTokenCertInfo::NewLC(class TDesC16 const &, enum TCertificateFormat, enum TCertificateOwnerType, int, class TBuf8<20> const *, class TBuf8<20> const *, int)
+	?NewLC@CDevTokenCertInfo@@SAPAV1@ABVTDesC16@@W4TCertificateFormat@@W4TCertificateOwnerType@@HPBV?$TBuf8@$0BE@@@3HH@Z @ 16 NONAME ; class CDevTokenCertInfo * CDevTokenCertInfo::NewLC(class TDesC16 const &, enum TCertificateFormat, enum TCertificateOwnerType, int, class TBuf8<20> const *, class TBuf8<20> const *, int, int)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAPAVCCertAttributeFilter@@@Z @ 17 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class CCertAttributeFilter * &)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAPAVCDHPublicKey@@@Z @ 18 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class CDHPublicKey * &)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAPAVCDSASignature@@@Z @ 19 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class CDSASignature * &)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAPAVCDevTokenCertInfo@@@Z @ 20 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class CDevTokenCertInfo * &)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAPAVCDevTokenDHParams@@@Z @ 21 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class CDevTokenDHParams * &)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAPAVCDevTokenKeyInfo@@@Z @ 22 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class CDevTokenKeyInfo * &)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAPAVCRSASignature@@@Z @ 23 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class CRSASignature * &)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAV?$RArray@VTCertificateAppInfo@@@@@Z @ 24 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class RArray<class TCertificateAppInfo> &)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAV?$RArray@VTUid@@@@@Z @ 25 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class RArray<class TUid> &)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAV?$RPointerArray@VHBufC16@@@@@Z @ 26 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class RPointerArray<class HBufC16> &)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAVMCTToken@@AAPAVCCTCertInfo@@@Z @ 27 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class MCTToken &, class CCTCertInfo * &)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAVMCTToken@@AAPAVCCTKeyInfo@@@Z @ 28 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class MCTToken &, class CCTKeyInfo * &)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAVMCTToken@@AAV?$RMPointerArray@VCCTCertInfo@@@@@Z @ 29 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class MCTToken &, class RMPointerArray<class CCTCertInfo> &)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAVMCTToken@@AAVMDevTokenKeyInfoArray@@@Z @ 30 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class MCTToken &, class MDevTokenKeyInfoArray &)
+	?ReadL@DevTokenDataMarshaller@@SAXABVTDesC8@@AAVRInteger@@@Z @ 31 NONAME ; void DevTokenDataMarshaller::ReadL(class TDesC8 const &, class RInteger &)
+	?SetManagementPolicy@CDevTokenKeyInfo@@QAEXABVTSecurityPolicy@@@Z @ 32 NONAME ; void CDevTokenKeyInfo::SetManagementPolicy(class TSecurityPolicy const &)
+	?SetPKCS8AttributeSet@CDevTokenKeyInfo@@QAEXPAVHBufC8@@@Z @ 33 NONAME ; void CDevTokenKeyInfo::SetPKCS8AttributeSet(class HBufC8 *)
+	?SetUsePolicy@CDevTokenKeyInfo@@QAEXABVTSecurityPolicy@@@Z @ 34 NONAME ; void CDevTokenKeyInfo::SetUsePolicy(class TSecurityPolicy const &)
+	?Size@DevTokenDataMarshaller@@SAHABV?$RArray@VTCertificateAppInfo@@@@@Z @ 35 NONAME ; int DevTokenDataMarshaller::Size(class RArray<class TCertificateAppInfo> const &)
+	?Size@DevTokenDataMarshaller@@SAHABV?$RArray@VTUid@@@@@Z @ 36 NONAME ; int DevTokenDataMarshaller::Size(class RArray<class TUid> const &)
+	?Size@DevTokenDataMarshaller@@SAHABV?$RPointerArray@VCDevTokenCertInfo@@@@@Z @ 37 NONAME ; int DevTokenDataMarshaller::Size(class RPointerArray<class CDevTokenCertInfo> const &)
+	?Size@DevTokenDataMarshaller@@SAHABV?$RPointerArray@VCDevTokenKeyInfo@@@@@Z @ 38 NONAME ; int DevTokenDataMarshaller::Size(class RPointerArray<class CDevTokenKeyInfo> const &)
+	?Size@DevTokenDataMarshaller@@SAHABV?$RPointerArray@VHBufC16@@@@@Z @ 39 NONAME ; int DevTokenDataMarshaller::Size(class RPointerArray<class HBufC16> const &)
+	?Size@DevTokenDataMarshaller@@SAHABVCCertAttributeFilter@@@Z @ 40 NONAME ; int DevTokenDataMarshaller::Size(class CCertAttributeFilter const &)
+	?Size@DevTokenDataMarshaller@@SAHABVCDHPublicKey@@@Z @ 41 NONAME ; int DevTokenDataMarshaller::Size(class CDHPublicKey const &)
+	?Size@DevTokenDataMarshaller@@SAHABVCDSASignature@@@Z @ 42 NONAME ; int DevTokenDataMarshaller::Size(class CDSASignature const &)
+	?Size@DevTokenDataMarshaller@@SAHABVCDevTokenDHParams@@@Z @ 43 NONAME ; int DevTokenDataMarshaller::Size(class CDevTokenDHParams const &)
+	?Size@DevTokenDataMarshaller@@SAHABVCKeyInfoBase@@@Z @ 44 NONAME ; int DevTokenDataMarshaller::Size(class CKeyInfoBase const &)
+	?Size@DevTokenDataMarshaller@@SAHABVCRSASignature@@@Z @ 45 NONAME ; int DevTokenDataMarshaller::Size(class CRSASignature const &)
+	?Size@DevTokenDataMarshaller@@SAHABVMCertInfo@@@Z @ 46 NONAME ; int DevTokenDataMarshaller::Size(class MCertInfo const &)
+	?Size@DevTokenDataMarshaller@@SAHABVTInteger@@@Z @ 47 NONAME ; int DevTokenDataMarshaller::Size(class TInteger const &)
+	?TakeG@CDevTokenDHParams@@QAE?AVRInteger@@XZ @ 48 NONAME ; class RInteger CDevTokenDHParams::TakeG(void)
+	?TakeN@CDevTokenDHParams@@QAE?AVRInteger@@XZ @ 49 NONAME ; class RInteger CDevTokenDHParams::TakeN(void)
+	?Write@DevTokenDataMarshaller@@SAXABV?$RArray@VTCertificateAppInfo@@@@AAVTDes8@@@Z @ 50 NONAME ; void DevTokenDataMarshaller::Write(class RArray<class TCertificateAppInfo> const &, class TDes8 &)
+	?Write@DevTokenDataMarshaller@@SAXABV?$RArray@VTUid@@@@AAVTDes8@@@Z @ 51 NONAME ; void DevTokenDataMarshaller::Write(class RArray<class TUid> const &, class TDes8 &)
+	?Write@DevTokenDataMarshaller@@SAXABV?$RPointerArray@VCDevTokenCertInfo@@@@AAVTDes8@@@Z @ 52 NONAME ; void DevTokenDataMarshaller::Write(class RPointerArray<class CDevTokenCertInfo> const &, class TDes8 &)
+	?Write@DevTokenDataMarshaller@@SAXABV?$RPointerArray@VCDevTokenKeyInfo@@@@AAVTDes8@@@Z @ 53 NONAME ; void DevTokenDataMarshaller::Write(class RPointerArray<class CDevTokenKeyInfo> const &, class TDes8 &)
+	?Write@DevTokenDataMarshaller@@SAXABV?$RPointerArray@VHBufC16@@@@AAVTDes8@@@Z @ 54 NONAME ; void DevTokenDataMarshaller::Write(class RPointerArray<class HBufC16> const &, class TDes8 &)
+	?Write@DevTokenDataMarshaller@@SAXABVCKeyInfoBase@@AAVTDes8@@@Z @ 55 NONAME ; void DevTokenDataMarshaller::Write(class CKeyInfoBase const &, class TDes8 &)
+	?Write@DevTokenDataMarshaller@@SAXABVMCertInfo@@AAVTDes8@@@Z @ 56 NONAME ; void DevTokenDataMarshaller::Write(class MCertInfo const &, class TDes8 &)
+	?WriteL@DevTokenDataMarshaller@@SAXABVCCertAttributeFilter@@AAVTDes8@@@Z @ 57 NONAME ; void DevTokenDataMarshaller::WriteL(class CCertAttributeFilter const &, class TDes8 &)
+	?WriteL@DevTokenDataMarshaller@@SAXABVCDHPublicKey@@AAVTDes8@@@Z @ 58 NONAME ; void DevTokenDataMarshaller::WriteL(class CDHPublicKey const &, class TDes8 &)
+	?WriteL@DevTokenDataMarshaller@@SAXABVCDSASignature@@AAVTDes8@@@Z @ 59 NONAME ; void DevTokenDataMarshaller::WriteL(class CDSASignature const &, class TDes8 &)
+	?WriteL@DevTokenDataMarshaller@@SAXABVCDevTokenDHParams@@AAVTDes8@@@Z @ 60 NONAME ; void DevTokenDataMarshaller::WriteL(class CDevTokenDHParams const &, class TDes8 &)
+	?WriteL@DevTokenDataMarshaller@@SAXABVCRSASignature@@AAVTDes8@@@Z @ 61 NONAME ; void DevTokenDataMarshaller::WriteL(class CRSASignature const &, class TDes8 &)
+	?WriteL@DevTokenDataMarshaller@@SAXABVTInteger@@AAVTDes8@@@Z @ 62 NONAME ; void DevTokenDataMarshaller::WriteL(class TInteger const &, class TDes8 &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Data/101FB667.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,48 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   ECom Registration File for DeviceCert Store Plugin
+*
+*/
+
+
+
+#include <cryptotokenregistryinfo.rh>
+
+RESOURCE REGISTRY_INFO theInfo
+  {
+  dll_uid = 0x101FB667;
+  interfaces = 
+    {
+    INTERFACE_INFO
+      {
+      interface_uid = CT_INTERFACE_UID;
+      implementations = 
+        {
+        BINARY_IMPLEMENTATION_INFO
+          {
+          implementation_uid = 0x101FB668;
+          version_no = 1;
+          display_name = "device certstore";
+          default_data = { 0xFA, 0x20, 0x20, 0x10,
+                   0xFB, 0x20, 0x20, 0x10 };
+          opaque_data = { CT_SOFTWARE, CT_TRUE,
+                  CT_REMOVABLE, CT_FALSE,
+                  CT_ACCESS_CONTROLLED, CT_FALSE,
+                  CT_MAX_TOKEN_COUNT, CT_NUM8(1),
+                  CT_MIN_TOKEN_COUNT, CT_NUM8(1) };
+          }
+        };
+      }
+    };
+  }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Data/101FB669.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   ECom Registration File for DeviceCertKeyStore Store Plugin
+*
+*/
+
+
+
+#include <cryptotokenregistryinfo.rh>
+
+RESOURCE REGISTRY_INFO theInfo
+  {
+  dll_uid = 0x101FB669;
+  interfaces = 
+    {
+    INTERFACE_INFO
+      {
+      interface_uid = CT_INTERFACE_UID;
+      implementations = 
+        {
+        BINARY_IMPLEMENTATION_INFO
+          {
+          implementation_uid = 0x101FB66A;
+          version_no = 1;
+          display_name = "device cert keystore";
+          default_data = { 0x34, 0x73, 0x1F, 0x10,  
+                   0x35, 0x73, 0x1F, 0x10 };  
+          opaque_data = { CT_SOFTWARE, CT_TRUE,
+                  CT_REMOVABLE, CT_FALSE,
+                  CT_ACCESS_CONTROLLED, CT_FALSE,
+                  CT_MAX_TOKEN_COUNT, CT_NUM8(1),
+                  CT_MIN_TOKEN_COUNT, CT_NUM8(1) };
+          }
+        };
+      }
+    };
+  }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Data/101FB66E.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   ECom Registration File for TrustServer Store Plugin
+*
+*/
+
+
+
+#include <cryptotokenregistryinfo.rh>
+
+RESOURCE REGISTRY_INFO theInfo
+  {
+  dll_uid = 0x101FB66E;
+  interfaces = 
+    {
+    INTERFACE_INFO
+      {
+      interface_uid = CT_INTERFACE_UID;
+      implementations = 
+        {
+        BINARY_IMPLEMENTATION_INFO
+          {
+          implementation_uid = 0x101FB66F;
+          version_no = 1;
+          display_name = "trust server certstore";
+          default_data = { 0xFA, 0x20, 0x20, 0x10,
+                   0xFB, 0x20, 0x20, 0x10 };
+          opaque_data = { CT_SOFTWARE, CT_TRUE,
+                  CT_REMOVABLE, CT_FALSE,
+                  CT_ACCESS_CONTROLLED, CT_FALSE,
+                  CT_MAX_TOKEN_COUNT, CT_NUM8(1),
+                  CT_MIN_TOKEN_COUNT, CT_NUM8(1) };
+          }
+        };
+      }
+    };
+  }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/EABI/DevTokenClientu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+EXPORTS
+	_ZN13CDevTokenType4NewLE4TUid @ 1 NONAME
+	_ZN16CTrustSitesStore14IsTrustedSiteLERK6TDesC8RK7TDesC16 @ 2 NONAME
+	_ZN16CTrustSitesStore16GetTrustedSitesLERK6TDesC8R13RPointerArrayI7HBufC16E @ 3 NONAME
+	_ZN16CTrustSitesStore4AddLERK6TDesC8RK7TDesC16 @ 4 NONAME
+	_ZN16CTrustSitesStore4NewLEv @ 5 NONAME
+	_ZN16CTrustSitesStoreD0Ev @ 6 NONAME
+	_ZN16CTrustSitesStoreD1Ev @ 7 NONAME
+	_ZN16CTrustSitesStoreD2Ev @ 8 NONAME
+	_ZTI13CDevTokenType @ 9 NONAME ; #<TI>#
+	_ZTI16CDevCertKeyStore @ 10 NONAME ; #<TI>#
+	_ZTI16CTrustSitesStore @ 11 NONAME ; #<TI>#
+	_ZTI17CDevCertOpenedKey @ 12 NONAME ; #<TI>#
+	_ZTI19CDevCertDHAgreement @ 13 NONAME ; #<TI>#
+	_ZTI20CDevCertRSADecryptor @ 14 NONAME ; #<TI>#
+	_ZTI20CDevTokenTypeSession @ 15 NONAME ; #<TI>#
+	_ZTI22CDevandTruSrvCertStore @ 16 NONAME ; #<TI>#
+	_ZTI27CDevCertDSARepudiableSigner @ 17 NONAME ; #<TI>#
+	_ZTI27CDevCertRSARepudiableSigner @ 18 NONAME ; #<TI>#
+	_ZTI9CDTClient @ 19 NONAME ; #<TI>#
+	_ZTI9CDevToken @ 20 NONAME ; #<TI>#
+	_ZTV13CDevTokenType @ 21 NONAME ; #<VT>#
+	_ZTV16CDevCertKeyStore @ 22 NONAME ; #<VT>#
+	_ZTV16CTrustSitesStore @ 23 NONAME ; #<VT>#
+	_ZTV17CDevCertOpenedKey @ 24 NONAME ; #<VT>#
+	_ZTV19CDevCertDHAgreement @ 25 NONAME ; #<VT>#
+	_ZTV20CDevCertRSADecryptor @ 26 NONAME ; #<VT>#
+	_ZTV20CDevTokenTypeSession @ 27 NONAME ; #<VT>#
+	_ZTV22CDevandTruSrvCertStore @ 28 NONAME ; #<VT>#
+	_ZTV27CDevCertDSARepudiableSigner @ 29 NONAME ; #<VT>#
+	_ZTV27CDevCertRSARepudiableSigner @ 30 NONAME ; #<VT>#
+	_ZTV9CDTClient @ 31 NONAME ; #<VT>#
+	_ZTV9CDevToken @ 32 NONAME ; #<VT>#
+	_ZN16CTrustSitesStore16AddForgivenSiteLERK7TDesC16RKi @ 33 NONAME
+	_ZN16CTrustSitesStore19IsOutOfDateAllowedLERK6TDesC8RK7TDesC16 @ 34 NONAME
+	_ZN16CTrustSitesStore19RemoveForgivenSiteLERK7TDesC16 @ 35 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/EABI/DevTokenSharedu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,71 @@
+EXPORTS
+	_Z12ExternalizeLRK8TIntegerR12RWriteStream @ 1 NONAME
+	_Z16EncryptAndStoreLRK8TIntegerR12RWriteStreamP13MKeyEncryptor @ 2 NONAME
+	_Z18DecryptAndCreateLCR11RReadStreamR8RIntegerP13MKeyEncryptor @ 3 NONAME
+	_Z8CreateLCR11RReadStreamR8RInteger @ 4 NONAME
+	_ZN16CDevTokenKeyInfo12SetUsePolicyERK15TSecurityPolicy @ 5 NONAME
+	_ZN16CDevTokenKeyInfo19SetManagementPolicyERK15TSecurityPolicy @ 6 NONAME
+	_ZN16CDevTokenKeyInfo20SetPKCS8AttributeSetEP6HBufC8 @ 7 NONAME
+	_ZN16CDevTokenKeyInfo4NewLER11RReadStream @ 8 NONAME
+	_ZN17CDevTokenCertInfo4NewLER11RReadStream @ 9 NONAME
+	_ZN17CDevTokenCertInfo4NewLERK7TDesC1618TCertificateFormat21TCertificateOwnerTypeiPK5TBuf8ILi20EES8_i @ 10 NONAME
+	_ZN17CDevTokenCertInfo4NewLERK7TDesC1618TCertificateFormat21TCertificateOwnerTypeiPK5TBuf8ILi20EES8_ii @ 11 NONAME
+	_ZN17CDevTokenCertInfo4NewLERKS_ @ 12 NONAME
+	_ZN17CDevTokenCertInfo5NewLCER11RReadStream @ 13 NONAME
+	_ZN17CDevTokenCertInfo5NewLCERK7TDesC1618TCertificateFormat21TCertificateOwnerTypeiPK5TBuf8ILi20EES8_i @ 14 NONAME
+	_ZN17CDevTokenCertInfo5NewLCERK7TDesC1618TCertificateFormat21TCertificateOwnerTypeiPK5TBuf8ILi20EES8_ii @ 15 NONAME
+	_ZN17CDevTokenCertInfo5NewLCERKS_ @ 16 NONAME
+	_ZN17CDevTokenDHParams4NewLERK8TIntegerS2_ @ 17 NONAME
+	_ZN17CDevTokenDHParams5TakeGEv @ 18 NONAME
+	_ZN17CDevTokenDHParams5TakeNEv @ 19 NONAME
+	_ZN17CDevTokenDHParamsC1E8RIntegerS0_ @ 20 NONAME
+	_ZN17CDevTokenDHParamsC2E8RIntegerS0_ @ 21 NONAME
+	_ZN17CDevTokenDHParamsD0Ev @ 22 NONAME
+	_ZN17CDevTokenDHParamsD1Ev @ 23 NONAME
+	_ZN17CDevTokenDHParamsD2Ev @ 24 NONAME
+	_ZN22DevTokenDataMarshaller4SizeERK12CDHPublicKey @ 25 NONAME
+	_ZN22DevTokenDataMarshaller4SizeERK12CKeyInfoBase @ 26 NONAME
+	_ZN22DevTokenDataMarshaller4SizeERK13CDSASignature @ 27 NONAME
+	_ZN22DevTokenDataMarshaller4SizeERK13CRSASignature @ 28 NONAME
+	_ZN22DevTokenDataMarshaller4SizeERK13RPointerArrayI16CDevTokenKeyInfoE @ 29 NONAME
+	_ZN22DevTokenDataMarshaller4SizeERK13RPointerArrayI17CDevTokenCertInfoE @ 30 NONAME
+	_ZN22DevTokenDataMarshaller4SizeERK13RPointerArrayI7HBufC16E @ 31 NONAME
+	_ZN22DevTokenDataMarshaller4SizeERK17CDevTokenDHParams @ 32 NONAME
+	_ZN22DevTokenDataMarshaller4SizeERK20CCertAttributeFilter @ 33 NONAME
+	_ZN22DevTokenDataMarshaller4SizeERK6RArrayI19TCertificateAppInfoE @ 34 NONAME
+	_ZN22DevTokenDataMarshaller4SizeERK6RArrayI4TUidE @ 35 NONAME
+	_ZN22DevTokenDataMarshaller4SizeERK8TInteger @ 36 NONAME
+	_ZN22DevTokenDataMarshaller4SizeERK9MCertInfo @ 37 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8R13RPointerArrayI7HBufC16E @ 38 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8R6RArrayI19TCertificateAppInfoE @ 39 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8R6RArrayI4TUidE @ 40 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8R8MCTTokenR14RMPointerArrayI11CCTCertInfoE @ 41 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8R8MCTTokenR21MDevTokenKeyInfoArray @ 42 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8R8MCTTokenRP10CCTKeyInfo @ 43 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8R8MCTTokenRP11CCTCertInfo @ 44 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8R8RInteger @ 45 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8RP12CDHPublicKey @ 46 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8RP13CDSASignature @ 47 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8RP13CRSASignature @ 48 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8RP16CDevTokenKeyInfo @ 49 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8RP17CDevTokenCertInfo @ 50 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8RP17CDevTokenDHParams @ 51 NONAME
+	_ZN22DevTokenDataMarshaller5ReadLERK6TDesC8RP20CCertAttributeFilter @ 52 NONAME
+	_ZN22DevTokenDataMarshaller5WriteERK12CKeyInfoBaseR5TDes8 @ 53 NONAME
+	_ZN22DevTokenDataMarshaller5WriteERK13RPointerArrayI16CDevTokenKeyInfoER5TDes8 @ 54 NONAME
+	_ZN22DevTokenDataMarshaller5WriteERK13RPointerArrayI17CDevTokenCertInfoER5TDes8 @ 55 NONAME
+	_ZN22DevTokenDataMarshaller5WriteERK13RPointerArrayI7HBufC16ER5TDes8 @ 56 NONAME
+	_ZN22DevTokenDataMarshaller5WriteERK6RArrayI19TCertificateAppInfoER5TDes8 @ 57 NONAME
+	_ZN22DevTokenDataMarshaller5WriteERK6RArrayI4TUidER5TDes8 @ 58 NONAME
+	_ZN22DevTokenDataMarshaller5WriteERK9MCertInfoR5TDes8 @ 59 NONAME
+	_ZN22DevTokenDataMarshaller6WriteLERK12CDHPublicKeyR5TDes8 @ 60 NONAME
+	_ZN22DevTokenDataMarshaller6WriteLERK13CDSASignatureR5TDes8 @ 61 NONAME
+	_ZN22DevTokenDataMarshaller6WriteLERK13CRSASignatureR5TDes8 @ 62 NONAME
+	_ZN22DevTokenDataMarshaller6WriteLERK17CDevTokenDHParamsR5TDes8 @ 63 NONAME
+	_ZN22DevTokenDataMarshaller6WriteLERK20CCertAttributeFilterR5TDes8 @ 64 NONAME
+	_ZN22DevTokenDataMarshaller6WriteLERK8TIntegerR5TDes8 @ 65 NONAME
+	_ZTI17CDevTokenDHParams @ 66 NONAME ; #<TI>#
+	_ZTI8TNullBuf @ 67 NONAME ; #<TI>#
+	_ZTV17CDevTokenDHParams @ 68 NONAME ; #<VT>#
+	_ZTV8TNullBuf @ 69 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Group/DevTokenClient.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,67 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Project definition file for DevTokenClient
+*
+*/
+
+
+#include <platform_paths.hrh>
+TARGET DevTokenClient.dll
+TARGETTYPE DLL
+UID 0x1000008d 0x101FB66B
+
+CAPABILITY All -TCB
+VENDORID VID_DEFAULT
+
+USERINCLUDE ../Inc 
+
+MW_LAYER_SYSTEMINCLUDE
+
+// generic device tokens client code
+SOURCEPATH ../Src/Generic/Client
+SOURCE DevToken.cpp
+SOURCE DevTokenType.cpp 
+SOURCE DevTokenTypeSession.cpp
+SOURCE DevTokenClientSession.cpp 
+SOURCE DevTokenUtils.cpp
+SOURCE DevTokenInterfaceFactory.cpp
+SOURCE DTClient.cpp
+
+// generic common client/server code  
+SOURCEPATH ../Src/Generic/Common
+SOURCE DevTokenCliServ.cpp
+
+// keystore specific client code
+SOURCEPATH ../Src/KeyStore/Client
+SOURCE DevCertKeyStore.cpp
+SOURCE DevCertOpenedKeys.cpp
+
+// certstore specific client code 
+SOURCEPATH ../Src/Certstore/client
+SOURCE DevandTruSrvCertStore.cpp
+
+// trusted sites store client code 
+SOURCEPATH ../Src/TruSitesStore/Client
+SOURCE TrustedSitesStore.cpp
+
+LIBRARY euser.lib 
+LIBRARY ctframework.lib 
+LIBRARY cryptography.lib
+LIBRARY hash.lib 
+LIBRARY DevTokenShared.lib
+LIBRARY x509.lib            // CX509Certificate
+LIBRARY crypto.lib
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Group/DevTokenDevCertStorePlugin.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,44 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Project definition file for DevTokenDevCertStorePlugin
+*
+*/
+
+
+#include <platform_paths.hrh>
+TARGET      DevCertStore.dll
+TARGETTYPE  PLUGIN
+UID         0x10009D8D 0x101FB667
+
+CAPABILITY  ALL -TCB
+VENDORID    VID_DEFAULT
+
+
+START RESOURCE ../Data/101FB667.rss
+TARGET DevCertStore.rsc
+END
+
+SOURCEPATH  ../Src/Certstore/DevECOMPlugin
+SOURCE      DevTokenDevCertStorePlugin.cpp
+
+USERINCLUDE ../Inc
+
+SYSTEMINCLUDE /epoc32/include/ecom      // cryptotokenregistryinfo.rh needs this
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY euser.lib
+LIBRARY DevTokenClient.lib
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Group/DevTokenKeyStorePlugin.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Project definition file for DevTokenDevKeyStorePlugin
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET DevKeyStore.dll
+TARGETTYPE plugin
+
+UID 0x10009D8D 0x101FB669
+
+CAPABILITY All -TCB
+VENDORID VID_DEFAULT
+
+START resource ../Data/101FB669.rss
+TARGET DevKeyStore.rsc
+END
+ 
+SOURCEPATH ../Src/KeyStore/EComPlugin
+SOURCE DevTokenKeyStorePlugin.cpp
+
+USERINCLUDE ../Inc 
+
+SYSTEMINCLUDE   /epoc32/include/ecom    // cryptotokenregistryinfo.rh needs this
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY euser.lib 
+LIBRARY DevTokenClient.lib
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Group/DevTokenServer.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,81 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Project definition file for DevTokenServer
+*
+*/
+
+
+#include <platform_paths.hrh>
+TARGET DevTokenServer.exe
+TARGETTYPE exe
+UID 0x1000008D 0x101FB66C
+
+CAPABILITY TrustedUI ProtServ
+VENDORID VID_DEFAULT
+
+MW_LAYER_SYSTEMINCLUDE
+
+USERINCLUDE ../Inc
+
+//  generic server code
+SOURCEPATH ../Src/Generic/Server
+SOURCE DevTokenServer.cpp
+SOURCE DevTokenUtil.cpp
+SOURCE DevTokenServerDebug.cpp
+SOURCE DevTokenDialog.cpp
+
+//  keystore specific server code
+SOURCEPATH ../Src/KeyStore/Server
+SOURCE DevCertKeyStoreConduit.cpp
+SOURCE DevCertKeyStoreSession.cpp
+SOURCE DevCertKeyStoreServer.cpp
+SOURCE DevCertKeyDataManager.cpp
+SOURCE DevCertCreateKey.cpp
+SOURCE DevCertOpenedKeysSrv.cpp
+SOURCE DevCertKeyStreamUtils.cpp
+SOURCE DevCertKeyEncryptor.cpp
+SOURCE DevTokenPWManager.cpp
+
+//  certstore specific server code
+SOURCEPATH ../Src/Certstore/server
+SOURCE DevandTruSrvCertStoreConduit.cpp
+SOURCE DevandTruSrvCertStoreSession.cpp
+SOURCE DevandTruSrvCertStoreServer.cpp
+SOURCE DevandTruSrvCertStoreEntry.cpp
+SOURCE DevandTruSrvCertStoreEntryList.cpp
+
+// trusted sites server code
+SOURCEPATH ../Src/TruSitesStore/Server
+SOURCE TrustedSitesConduit.cpp
+SOURCE TrustedSitesSession.cpp
+SOURCE TrustedSitesServer.cpp
+
+LIBRARY euser.lib 
+LIBRARY efsrv.lib 
+LIBRARY estor.lib 
+LIBRARY bafl.lib 
+LIBRARY ctframework.lib 
+LIBRARY cryptography.lib
+LIBRARY asnpkcs.lib 
+LIBRARY x509.lib 
+LIBRARY asn1.lib
+LIBRARY DevTokenShared.lib
+LIBRARY charconv.lib
+LIBRARY Edbms.lib             // Database server
+LIBRARY ecom.lib
+LIBRARY crypto.lib 
+LIBRARY X500.lib
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Group/DevTokenShared.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Project definition file for DevTokenShared
+*
+*/
+
+
+#include <platform_paths.hrh>
+TARGET DevTokenShared.dll
+TARGETTYPE dll
+UID 0x1000008d 0x101FB66D
+
+CAPABILITY All -TCB
+VENDORID VID_DEFAULT
+
+USERINCLUDE ../Inc 
+MW_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH ../Src/Shared
+SOURCE DevTokenDataMarshaller.cpp
+SOURCE DevTokenKeyInfo.cpp
+SOURCE DevTokenCertInfo.cpp
+SOURCE DevTokenDHParams.cpp
+SOURCE DevTokenNullStream.cpp
+
+LIBRARY euser.lib 
+LIBRARY estor.lib
+LIBRARY ctframework.lib 
+LIBRARY cryptography.lib
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Group/DevTokenTruSrvCertStorePlugin.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,44 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Project definition file for DevTokenTruSrvCertStorePlugin
+*
+*/
+
+
+#include <platform_paths.hrh>
+TARGET      DevSrvCertStore.dll
+TARGETTYPE  PLUGIN
+UID         0x10009D8D 0x101FB66E
+
+CAPABILITY  ALL -TCB
+VENDORID    VID_DEFAULT
+
+START RESOURCE ../Data/101FB66E.rss
+TARGET DevSrvCertStore.rsc
+END
+
+SOURCEPATH  ../Src/Certstore/TruSrvECOMPlugin
+SOURCE      DevTokenTruSrvCertStorePlugin.cpp
+
+USERINCLUDE ../Inc
+
+SYSTEMINCLUDE /epoc32/include/ecom      // cryptotokenregistryinfo.rh needs this
+MW_LAYER_SYSTEMINCLUDE
+
+
+LIBRARY euser.lib
+LIBRARY DevTokenClient.lib
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Build information file 
+*
+*/
+
+
+
+#ifdef RD_CLIENT_CERTIFICATES
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+DevTokenShared.mmp
+DevTokenClient.mmp
+DevTokenKeyStorePlugin.mmp
+DevTokenDevCertStorePlugin.mmp
+DevTokenTruSrvCertStorePlugin.mmp
+DevTokenServer.mmp
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DTClient.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,117 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DTClient
+*
+*/
+
+
+
+#ifndef __DTCLIENT_H__
+#define __DTCLIENT_H__
+
+#include <e32base.h>
+#include "DevTokenCliServ.h"
+
+class MCTToken;
+class RDevTokenClientSession;
+
+/**
+ * Base class for implementations of ctframework interfaces.  Derived classes
+ * inherit from this and also implement the appropriate interface.
+ * It provides asynchronous functionality for sending requests to the filetokens
+ * server and processing the responses.
+ * Some methods are const so they can be called by the cert apps client, whose
+ * interface contains several const methods.  These methods need to create
+ * internal buffers, and this leads to iRequestDataBuf and iRequestPtr being
+ * mutable.
+ *
+ *  @lib DevTokenClient.dll
+ *  @since S60 v3.2
+ */
+class CDTClient : public CActive
+    {
+    public:
+        virtual ~CDTClient();
+
+    protected:
+        
+        CDTClient(TInt aUID, MCTToken& aToken, RDevTokenClientSession& aClient);
+        
+        TInt AllocRequestBuffer(TInt aReqdSize) const;
+        
+        void FreeRequestBuffer() const;
+        
+        void SendSyncRequestAndHandleOverflowL(TDevTokenMessages aMessage,
+                                               TInt aInitialBufSize,
+                                               const TIpcArgs& aArgs) const;
+
+    protected:
+        // From CActive
+        virtual void DoCancel();  
+        
+        virtual TInt RunError(TInt aError);
+
+    protected:
+        /**
+        * Maintains state for async requests to device tokens server, and completes
+        * caller when required.
+        */
+        class TAsyncRequest
+            {
+            public:
+               
+                void operator()(TDevTokenMessages aRequest, TRequestStatus* aStatus);
+               
+                void Complete(TInt aCompletionResult);      
+               
+                void Cancel();
+               
+                inline TDevTokenMessages OutstandingRequest() { return iRequest; }
+            
+            public:
+              
+                ~TAsyncRequest();
+            
+            private:
+              
+                TDevTokenMessages iRequest;
+              
+                TRequestStatus* iClientStatus;
+            };
+        
+        //The outstanding server request
+        TAsyncRequest iCurrentRequest;    
+
+    private:
+        //Buffer for messages passed to the server
+        mutable HBufC8* iRequestDataBuf;    
+    
+    protected:
+        // The token we belong to
+        MCTToken& iToken;        
+       
+        // UID of the cryptoken interface we implement
+        TInt iInterfaceUID;        
+       
+        // Client session object for sending messages to the server
+        RDevTokenClientSession& iClientSession; 
+       
+        // Buffer pointer for derived classes to use
+        mutable TPtr8 iRequestPtr;
+    };
+
+#endif  //  __DTCLIENT_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevCertCreateKey.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,123 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevCertCreateKey
+*
+*/
+
+
+
+#ifndef __DEVCERTCREATEKEY_H__
+#define __DEVCERTCREATEKEY_H__
+
+#include <bigint.h>
+#include <e32std.h>
+#include <mctkeystore.h>
+#include <asymmetrickeys.h>
+#include "DevTokenDataTypes.h"
+
+class CSimpleDHKey;
+class CDevCertKeyCreatorData;
+
+_LIT(KCreateKeyName, "AsymmetricKeysCreator");
+
+/**
+ *  class CDevCertKeyCreator
+ *
+ * Server side
+ * Class to make key creation "asynchronous" by spinning off a thread
+ * to make the synchronous call to the appropriate key creation function
+ * The thread entry point is a static member of this class, which holds the 
+ * thread and thread parameter data too.  When the key has been created, the
+ * thread terminates using Rendezvous to notify the main thread.  The created key
+ * is returned through the CAsymmetricCipher member of CKeyCreatorData
+ *
+ *  @lib 
+ *  @since S60 v3.2
+ */
+class CDevCertKeyCreator : public CActive
+    {
+    public:
+        
+        CDevCertKeyCreator();
+        
+        ~CDevCertKeyCreator();
+        
+    public: //  Spin a thread to create an appropriate key, if successful, left on CleanupStack
+        
+        void DoCreateKeyAsyncL(CDevTokenKeyInfo::EKeyAlgorithm aAlgorithm, TInt aSize, TRequestStatus& aStatus);
+        
+    public:
+        
+        //  JCS this needs improvement when new crypto api is reviewed
+        CRSAKeyPair* GetCreatedRSAKey();
+        
+        CDSAKeyPair* GetCreatedDSAKey();
+        
+        void GetCreatedDHKey(RInteger& aDHKey);
+        
+    protected:
+        
+        void DoCancel();
+        
+        void RunL();
+        
+        TInt RunError(TInt anError);
+        
+    private:
+        
+        static TInt CreatorThreadEntryPoint(TAny*);
+        
+    private:
+        
+        enum TAction {EIdle, EReadyToCreateKey, ECreatedKey};
+        
+        TAction iAction;
+    private:
+        
+        TRequestStatus* iClientStatus;
+        
+        RThread iCreatorThread;
+        
+    private:
+        
+        class CDevCertKeyCreatorData : public CBase
+            {
+            public:
+        
+                CDevCertKeyCreatorData(CDevTokenKeyInfo::EKeyAlgorithm aAlgorithm, TInt aSize);
+        
+                ~CDevCertKeyCreatorData();
+                
+            public: //  Don't bother hiding the data from myself
+        
+                TInt iSize;
+        
+                //  Algorithm identified by iKeyAlgorithm
+                CDevTokenKeyInfo::EKeyAlgorithm iKeyAlgorithm;
+
+            union CreatedKey
+                {
+                CRSAKeyPair* iRSAKey;
+                CDSAKeyPair* iDSAKey;
+                CSimpleDHKey* iDHKey;
+                } iKey;
+            };
+
+    CDevCertKeyCreatorData* iCreateData;
+    };
+
+#endif  //  __DEVCERTCREATEKEY_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevCertKeyDataManager.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,228 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevCertKeyDataManager
+*
+*/
+
+
+
+#ifndef __DEVCERTKEYDATAMANAGER_H__
+#define __DEVCERTKEYDATAMANAGER_H__
+
+#include <s32file.h>
+#include <ct/tcttokenobjecthandle.h>
+#include <ct.h>
+
+class CDevTokenKeyInfo;
+
+/**
+ *  class CDevCertKeyData
+ *
+ * Server side in-memory representation of a key for file key store management
+ * purposes. Objects of this type are stored in an in-memory array for quick
+ * keystore lookup
+ *
+ *  @lib
+ *  @since S60 v3.2
+ */
+class CDevCertKeyData : public CBase
+    {
+    public:
+        
+        // Create a new key data object
+        static CDevCertKeyData* NewLC(TInt aObjectId, const TDesC& aLabel, TStreamId aInfoData,
+        
+        TStreamId aPublicData, TStreamId aPrivateData);
+        
+        // Read a key data object from a stream
+        static CDevCertKeyData* NewL(RStoreReadStream& aReadStream);
+        
+    public:
+        
+        ~CDevCertKeyData(); 
+        
+    public:
+        
+        // Write out the key data to a stream
+        void ExternalizeL(RWriteStream&) const;
+        
+    public:
+        
+        inline const TDesC& Label() const;
+        
+        inline TInt32 Handle() const;
+        
+        inline TStreamId InfoDataStreamId() const;
+        
+        inline TStreamId PublicDataStreamId() const;
+        
+        inline TStreamId PrivateDataStreamId() const;
+        
+    private:
+        
+        CDevCertKeyData(TInt aObjectId, TStreamId aInfoData,
+        
+        TStreamId aPublicData, TStreamId aPrivateData);
+        
+        CDevCertKeyData();
+        
+        void ConstructL(const TDesC& aLabel);
+        
+        void InternalizeL(RReadStream&);
+        
+    private:
+        
+        TInt iObjectId;       // Data to identify the key
+        
+        TStreamId iInfoData;    // ID of stream holding publicly available data for key 
+        
+        TStreamId iPublicKeyData; // ID of stream holding public key data
+        
+        TStreamId iPrivateKeyData;  // ID of stream holding private key data
+        
+        HBufC* iLabel;        // Key label data
+    };
+
+inline const TDesC& CDevCertKeyData::Label() const
+    {
+    return *iLabel;
+    }
+
+inline TInt32 CDevCertKeyData::Handle() const
+    {
+    return iObjectId;
+    }
+
+inline TStreamId CDevCertKeyData::InfoDataStreamId() const
+    {
+    return iInfoData;
+    }
+
+inline TStreamId CDevCertKeyData::PublicDataStreamId() const
+    {
+    return iPublicKeyData;
+    }
+
+inline TStreamId CDevCertKeyData::PrivateDataStreamId() const
+    {
+    return iPrivateKeyData;
+    }
+
+
+/**
+ *  class CDevCertKeyDataManager
+ *
+ * Access the server file store of all keys and key data. The only class to
+ * access the store, which maintains store integrity When a new key is created,
+ * it is represented by a CDevCertKeyData object and added to the array.  
+ *
+ *  @lib
+ *  @since S60 v3.2
+ */
+class CDevCertKeyDataManager : public CBase
+    {
+    public:
+        
+        static CDevCertKeyDataManager* NewL();
+        
+        ~CDevCertKeyDataManager();
+        
+    public: 
+        
+        void AddL(const CDevCertKeyData*);
+        
+        void RemoveL(TInt aObjectId);
+        
+        TBool IsKeyAlreadyInStore(const TDesC& aKeyLabel) const;
+        
+    public:
+        
+        // Create a new key data object for a key create/import and leave it one the cleanup stack
+        const CDevCertKeyData* CreateKeyDataLC( const TDesC& aLabel );
+        
+        // Reads the info data for a given key, returning a new CKeyInfo that's on the cleanup stack
+        CDevTokenKeyInfo* ReadKeyInfoLC(const CDevCertKeyData& aKeyData) const;
+        
+        // Writes key info data for a key
+        void WriteKeyInfoL(const CDevCertKeyData& aKeyData, const CDevTokenKeyInfo& aKeyInfo);
+        
+        // Writes key info data and reverts changes to the store if if leaves
+        void SafeWriteKeyInfoL(const CDevCertKeyData& aKeyData, const CDevTokenKeyInfo& aKeyInfo);
+        
+        // Methods for opening data streams for a key
+        void OpenPublicDataStreamLC(const CDevCertKeyData& aKeyData, RStoreWriteStream& aStream);
+        
+        void OpenPublicDataStreamLC(const CDevCertKeyData& aKeyData, RStoreReadStream& aStream) const;
+        
+        void OpenPrivateDataStreamLC(const CDevCertKeyData& aKeyData, RStoreWriteStream& aStream);
+        
+        void OpenPrivateDataStreamLC(const CDevCertKeyData& aKeyData, RStoreReadStream& aStream);
+
+    public:
+        
+        TInt Count() const;
+        
+        const CDevCertKeyData* operator[](TInt aIndex) const;
+        
+        const CDevCertKeyData* Lookup(TInt aObjectId) const;
+
+    private:
+        
+        CDevCertKeyDataManager();
+        
+        void ConstructL();
+        
+    private:                      //  Manages access to store
+        
+        void OpenStoreL();
+        
+        void OpenStoreInFileL(const TDesC& aFile);
+        
+        void CreateStoreInFileL(const TDesC& aFile);
+        
+    private:
+        
+        void OpenInfoDataStreamLC(const CDevCertKeyData& aKeyData, RStoreWriteStream&);
+        
+        static void RevertStore(TAny* aStore);      //  Cleanupitem
+        
+        void WriteKeysToStoreL();
+        
+        TStreamId CreateWriteStreamL();
+        
+        void CompactStore();
+        
+    private:
+        
+        RFile iFile;
+        
+        RFs iFs;
+        
+        CPermanentFileStore* iFileStore;
+        
+        TStreamId iRootStreamId;      // Root of the store
+        
+        TStreamId iInfoStreamId;      // Stream that contains list of key data
+
+    private:
+        
+        TInt iKeyIdentifier;
+        
+        RPointerArray<const CDevCertKeyData> iKeys; // In memory representation of keys in the store
+    };
+
+#endif
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevCertKeyEncryptor.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,67 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevCertKeyEncryptor
+*
+*/
+
+
+
+#ifndef __DEVCERTKEYENCRYPTOR_H__
+#define __DEVCERTKEYENCRYPTOR_H__
+
+#include <e32base.h>
+#include <keyencryptor.h>
+
+/**
+ *  class CDevCertKeyEncryptor
+ *
+ *  Encrypt key before putting into keystore 
+ *  by using key encryptor plugin
+ *
+ *  @lib
+ *  @since S60 v3.2
+ */
+class CDevCertKeyEncryptor : public CBase
+    {
+    public:
+
+      static CDevCertKeyEncryptor* NewL();
+      
+      static CDevCertKeyEncryptor* NewLC();
+      
+      virtual ~CDevCertKeyEncryptor();
+      
+      MKeyEncryptor* CreateImplementationL();
+      
+      TBool IsPluginExistL();
+  
+    private:
+    
+      CDevCertKeyEncryptor();
+      
+      void ConstructL();
+    
+    private:
+      
+      TUid iImplementationUID;
+      
+      TUid iDtorIDKey;
+      
+      MKeyEncryptor* iKeyEncryptor;
+    };
+
+#endif  //  __DEVCERTKEYENCRYPTOR_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevCertKeyStore.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,292 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevCertKeyStore
+*
+*/
+
+
+
+#ifndef __DEVKEYSTORE_H__
+#define __DEVKEYSTORE_H__
+
+#include <mctkeystoremanager.h>
+#include <ct/rmpointerarray.h>
+#include "DTClient.h"
+
+
+// Maximum allowed size of digest to RSA sign (implied by max 2048 bit key length).
+const TInt KMaxRSADigestSize = 2048 / 8;
+
+// Maximum allowed size of digest to DSA sign (implied by 160 bit output of SHA1).
+const TInt KMaxDSADigestSize = 160 / 8;
+
+class CDevCertOpenedKey;
+class MDevTokenKeyInfoArray;
+class CDevTokenDHParams;
+
+
+/**
+ * Implements the MCTKeyStoreManager interface.  Inherits from CDTClient.
+ *
+ * The class implements the keystore manager token interface for the software
+ * keystore.  It will be created and owned by the unified keystore.  Its main
+ * function is to marshall user requests to the filetokens server and unmarshall
+ * the results back again.
+ 
+ *  @lib DevTokenClient.dll
+ *  @since S60 v3.2
+ */
+class CDevCertKeyStore : public CDTClient, public MCTKeyStoreManager
+    {
+    public:// One creator function for each token interface
+        
+        static MCTTokenInterface* NewKeyStoreUserInterfaceL(MCTToken& aToken, RDevTokenClientSession& aClient);
+        
+        static MCTTokenInterface* NewKeyStoreManagerInterfaceL(MCTToken& aToken, RDevTokenClientSession& aClient);
+        
+    public:
+        
+        virtual ~CDevCertKeyStore();
+        
+        void AddRef();
+        
+    public:
+        
+        //  MKeyStore
+        virtual void List(RMPointerArray<CCTKeyInfo>& aKeys, const TCTKeyAttributeFilter& aFilter, TRequestStatus& aStatus);
+        
+        virtual void CancelList();
+        
+        virtual void GetKeyInfo(TCTTokenObjectHandle aHandle, CCTKeyInfo*& aInfo, TRequestStatus& aStatus);
+        
+        virtual void CancelGetKeyInfo();
+        
+        /**
+         * Open an RSA key for signing
+         *
+         * @param aHandle Handle to the key 
+         * @param aSigner pointer to a RSA Signer
+         * @param aStatus
+         * @return 
+         */
+        virtual void Open(const TCTTokenObjectHandle& aHandle, 
+                          MRSASigner*& aSigner,
+                          TRequestStatus& aStatus);
+        
+        /**
+         * Open an DSA key for signing
+         *
+         * @param aHandle Handle to the key 
+         * @param aSigner pointer to a DSA Signer
+         * @param aStatus
+         * @return 
+         */
+        virtual void Open(const TCTTokenObjectHandle& aHandle, 
+                          MDSASigner*& aSigner, 
+                          TRequestStatus& aStatus);
+
+        /**
+         * Open a RSA key for private decryption
+         *
+         * @param aHandle Handle to the key 
+         * @param aSigner pointer to a RSA Decryptor
+         * @param aStatus
+         * @return 
+         */
+        virtual void Open(const TCTTokenObjectHandle& aHandle, 
+                          MCTDecryptor*& aDecryptor,
+                          TRequestStatus& aStatus);
+        
+        /**
+         * Open a DH key for key agreement
+         *
+         * @param aHandle Handle to the key 
+         * @param aSigner pointer to a DH 
+         * @param aStatus
+         * @return 
+         */
+        virtual void Open(const TCTTokenObjectHandle& aHandle, 
+                          MCTDH*& aDH, TRequestStatus& aStatus);
+        
+        /**
+         * Cancels an ongoing open request
+         *
+         * @param 
+         * @return 
+         */
+        virtual void CancelOpen();
+        
+        /**
+         * Returns the public key in DER-encoded ASN-1
+         *
+         * @param aHandle handle to the public key
+         * @param aPublicKey buffer for the public key
+         * @param aStatus
+         * @return 
+         */
+        virtual void ExportPublic(const TCTTokenObjectHandle& aHandle,
+                                  HBufC8*& aPublicKey,
+                                  TRequestStatus& aStatus);
+        
+        virtual void CancelExportPublic();
+
+    public:
+        //  MCTKeyStoreManager
+        virtual void CreateKey(CCTKeyInfo*& aReturnedKey, TRequestStatus& aStatus);
+        
+        virtual void CancelCreateKey();
+        
+        virtual void ImportKey(const TDesC8& aKey, CCTKeyInfo*& aReturnedKey, TRequestStatus& aStatus);
+        
+        virtual void CancelImportKey();
+        
+        virtual void ImportEncryptedKey(const TDesC8& aKey, CCTKeyInfo*& aReturnedKey, TRequestStatus& aStatus);
+        
+        virtual void CancelImportEncryptedKey();
+        
+        virtual void ExportKey(TCTTokenObjectHandle aHandle, HBufC8*& aKey, TRequestStatus& aStatus); 
+        
+        virtual void CancelExportKey();
+        
+        virtual void ExportEncryptedKey(TCTTokenObjectHandle aHandle, const CPBEncryptParms& aParams, HBufC8*& aKey, TRequestStatus& aStatus);
+        
+        virtual void CancelExportEncryptedKey();
+        
+        virtual void DeleteKey(TCTTokenObjectHandle aHandle, TRequestStatus& aStatus);
+        
+        virtual void CancelDeleteKey(); 
+        
+        virtual void SetUsePolicy(TCTTokenObjectHandle aHandle, const TSecurityPolicy& aPolicy, TRequestStatus& aStatus);
+        
+        virtual void CancelSetUsePolicy();
+        
+        virtual void SetManagementPolicy(TCTTokenObjectHandle aHandle, const TSecurityPolicy& aPolicy, TRequestStatus& aStatus);
+        
+        virtual void CancelSetManagementPolicy();
+        
+        virtual void SetPassphraseTimeout(TInt aTimeout, TRequestStatus& aStatus) ;
+        
+        virtual void CancelSetPassphraseTimeout();  
+        
+        virtual void Relock(TRequestStatus& aStatus);
+        
+        virtual void CancelRelock();  
+        
+        void ReleaseObject(const TCTTokenObjectHandle& aObject);
+        
+    public: 
+        
+        //  From MCTTokenInterface
+        virtual MCTToken& Token();
+        
+    public:
+        
+        void RepudiableDSASign(const TCTTokenObjectHandle& aObject, const TDesC8& aDigest, CDSASignature*& aSignature, TRequestStatus& aStatus);
+        
+        void RepudiableRSASign(const TCTTokenObjectHandle& aObject, const TDesC8& aDigest, CRSASignature*& aSignature, TRequestStatus& aStatus);
+        
+        void Decrypt(const TCTTokenObjectHandle& aObject, const TDesC8& aCiphertext, TDes8& aPlaintext, TRequestStatus& aStatus);
+        
+        void DHPublicKey(const TCTTokenObjectHandle& aHandle, const TInteger& aN, const TInteger& aG, CDHPublicKey*& aX, TRequestStatus& aStatus);
+        
+        void DHAgree(const TCTTokenObjectHandle& aHandle, const CDHPublicKey& iY, HBufC8*& aAgreedKey, TRequestStatus& aStatus);
+
+    protected:
+        
+        //  From MCTTokenInterface
+        virtual void DoRelease();
+        
+    protected:
+        
+        //  From CActive
+        virtual void RunL();
+        
+        virtual TInt RunError(TInt aError);
+        
+        virtual void DoCancel();
+        
+    protected:
+        
+        CDevCertKeyStore(TInt aUID, MCTToken& aToken, RDevTokenClientSession& aClient);
+        
+        virtual void ConstructL();
+        
+    private:
+        
+        void DoListL(const TCTKeyAttributeFilter& aFilter, MDevTokenKeyInfoArray& aOut);
+        
+        void DoGetKeyInfoL(TCTTokenObjectHandle aHandle, CCTKeyInfo*& aInfo);
+        
+        TInt DoOpenKey(TDevTokenMessages aMessage, const TCTTokenObjectHandle& aHandle, CDevCertOpenedKey* aOpenedKey);
+        
+        void DoImportKey(TDevTokenMessages aMessage, const TDesC8& aKey, CCTKeyInfo*& aReturnedKey, TRequestStatus& aStatus);
+        
+        void DoExportPublicL(const TCTTokenObjectHandle& aHandle, HBufC8*& aPublicKey);
+        
+        TInt MarshalKeyInfo(CCTKeyInfo& aKey);
+        
+        void Process(const TCTTokenObjectHandle& aHandle,const TDesC8& aText,TDevTokenMessages aMessage,TRequestStatus& aStatus,TInt aBufSize);
+        
+        void DoDHPublicKeyL(const TCTTokenObjectHandle& aHandle, const TInteger& aN, const TInteger& aG, CDHPublicKey*& aX, TRequestStatus& aStatus);
+
+    private:
+        
+        TInt AllocKeyBuffer(TInt aReqdSize);
+        
+        void FreeKeyBuffer();
+        
+        void UpdateKey();
+        
+        TUint GetKeySizeL(TInt aObjectId);
+        
+        void Cleanup();
+    
+    private:
+        
+        TInt iRefCount;
+        
+        //  Data holders for server to write into
+        TPckgBuf<TInt> iIntOut;
+
+        TInt iObjectId;     // Id of object passed to server
+
+    private:
+        
+        // Pointers to client pointers, which we set to return created objects.
+        // Only one of these is ever in use at any one time, determined by the
+        // state.
+        union 
+            {
+            TAny* iAny;           // generic pointer, used to zero the contents of the union
+            CCTKeyInfo** iKeyInfo;      // key info object, used for create and import
+            HBufC8** iBuffer;       // generic buffer, used for export key and DH agree
+            TDes8* iDecryptedText;      // decypled plaintext, used for RSA decrypt
+            CDSASignature** iDSASignature;  // DSA signature
+            CRSASignature** iRSASignature;  // RSA signature
+            CDHPublicKey** iDHPublicKey;  // DH public key
+            } iClientPtr;
+            
+    private:
+        
+        HBufC8* iKey;           // Key data buffer for import/export
+        
+        HBufC8* iText;            // Buffer used to hold text for decrypt and sign
+        
+        CDevTokenDHParams* iDHParams;       // DH params for DH public key
+        
+    };
+
+#endif  //  __DEVKEYSTORE_H__
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevCertKeyStoreConduit.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,229 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevCertKeyStoreConduit
+*
+*/
+
+
+
+#ifndef __CDEVCERTKEYSTORECONDUIT_H__
+#define __CDEVCERTKEYSTORECONDUIT_H__
+
+#include <bigint.h>
+#include "DevTokenServer.h"
+
+class CDSASignature;
+class CRSASignature;
+class CDevCertKeyStoreServer;
+class CDevCertKeyStoreSession;
+class CDevCertRSARepudiableSigner;
+class CDevCertDSARepudiableSigner;
+class CDevCertRSADecryptor;
+class CDevTokenDHParams;
+class CDevCertOpenedKeySrv;
+class CDevTokenKeyInfo;
+class CDHPublicKey;
+
+/**
+ * The key store server object (CDevtokenKeyStoreServer) owns one instance of this
+ * object, which it calls for every client request.  This object unmarshalls the
+ * client data and fulfills the request by calling back to the server object.
+ * Any return information is then marshalled back to the client.
+ *
+ *  @lib
+ *  @since S60 v3.2
+ */
+class CDevCertKeyStoreConduit : public CActive
+    {
+    public:
+        
+        static CDevCertKeyStoreConduit* NewL(CDevCertKeyStoreServer& aServer);
+        
+        virtual ~CDevCertKeyStoreConduit();
+    
+    public:
+        
+        void ServiceRequestL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession);
+    
+    protected: 
+        
+        //  From CActive
+        virtual void DoCancel();
+        
+        virtual void RunL();
+        
+        virtual TInt RunError(TInt aError);
+    
+    private:
+        
+        CDevCertKeyStoreConduit(CDevCertKeyStoreServer& aServer); 
+        
+        void ConstructL();
+    
+    private:
+        
+        CDevCertKeyStoreConduit(const CDevCertKeyStoreConduit&);        //  No copying
+        
+        CDevCertKeyStoreConduit& operator=(const CDevCertKeyStoreConduit&); //  No copying
+    
+    private:
+        
+        // For MKeyStore
+        void ListL(const RMessage2& aMessage);
+        
+        void CancelList(const RMessage2& aMessage);
+        
+        void GetKeyInfoL(const RMessage2& aMessage);
+        
+        void CancelGetKeyInfo(const RMessage2& aMessage);
+    
+    private:
+        
+        // For MCTKeyStoreManager
+        void CreateKeyL(const RMessage2& aMessage);
+        
+        void CancelCreateKey(const RMessage2& aMessage);
+        
+        void ImportKeyL(const RMessage2& aMessage);
+        
+        void CancelImportKey(const RMessage2& aMessage);
+        
+        void ExportKeyL(const RMessage2& aMessage); 
+        
+        void CancelExportKey(const RMessage2& aMessage);
+        
+        void ExportPublicL(const RMessage2& aMessage); 
+        
+        void CancelExportPublic(const RMessage2& aMessage);
+        
+        void DeleteKeyL(const RMessage2& aMessage);
+        
+        void SetUsePolicyL(const RMessage2& aMessage);
+        
+        void SetManagementPolicyL(const RMessage2& aMessage); 
+        
+        void OpenKeyL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession, TUid aType);
+        
+        void CloseObjectL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession);
+    
+    private:
+        
+        void GetKeyLengthL(const RMessage2& aMessage); 
+        
+        TUid GetClientUidL(const RMessage2& aMessage) const;
+        
+        void OpenKeyGetInfoL(const RMessage2& aMessage);
+        
+        void RepudiableDSASignL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession);
+        
+        void CancelDSASign(const RMessage2& aMessage);
+        
+        void RepudiableRSASignL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession);
+        
+        void CancelRSASign(const RMessage2& aMessage);
+        
+        void DecryptL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession);
+        
+        void CancelDecrypt(const RMessage2& aMessage);
+        
+        void DHPublicKeyL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession);
+        
+        void DoDHPublicKeyL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession);
+        
+        void FinishDHPublicKeyL();
+        
+        void DHAgreeL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession);
+        
+        void DoDHAgreeL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession);
+        
+        void FinishDHAgreeL();
+        
+        void CancelDH(const RMessage2& aMessage);
+        
+        CDevCertOpenedKeySrv* ProcessL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession,
+        
+        const TUid& aCKeyInfoID, const TDevTokenMessages& aState, TPtr8& aPtr);
+        
+        void FinishOpenL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession, CDevCertOpenedKeySrv& aOpenedKey);
+        
+        void Cleanup();
+    
+    private:
+    
+        /** 
+         * Encapsulate data about the current request.
+         */
+        class TAsyncRequest
+            {
+            public:
+                
+                void Set(TDevTokenMessages aRequest, const RMessage2& aMessage);
+                
+                void Complete(TInt aResult);
+                
+                void Cancel();
+            
+            public:
+                
+                inline TDevTokenMessages OutstandingRequest() { return iRequest; }
+                
+                inline const RMessage2& Message() { return iMessage ;}
+        
+            public:
+                
+                TAsyncRequest(TRequestStatus& aStatus);
+            
+                ~TAsyncRequest();
+            
+            private:
+                
+                TDevTokenMessages iRequest;
+                
+                RMessage2 iMessage;
+                
+                TRequestStatus& iOwnerStatus;
+            };
+             
+    private:
+    
+        CDevCertKeyStoreServer& iServer;    // The server object used to execute client requests
+
+        TAsyncRequest iCurrentRequest;      // The client request we are currently servicing
+
+        HBufC8* iImportKey;           // Buffer for key imported key data 
+
+        CDevTokenKeyInfo* iKeyInfo;       // Key info, used by create, import and export
+
+        HBufC8* iText;              // Stores input data for sign and decrypt operations
+
+        HBufC8* iExportBuf;           // Holds the exported key data
+        
+        CDevCertOpenedKeySrv* iOpenedKey;     // The key object for crypto operations
+        
+        CDSASignature* iDSASignature;     // Signature to return for DSA sign operation
+        
+        CRSASignature* iRSASignature;     // Signature to return for RSA sign operation
+        
+        CDevTokenDHParams* iDHParams;     // DH parameters for DU public key operation
+        
+        RInteger iDHPublicKeyOut;       // DH public key to return to client
+        
+        CDHPublicKey* iDHPublicKey;       // DH public key and params object for agree operation 
+        
+        HBufC8* iDHAgreedKeyOut;        // Agreed key to return to client
+        
+        HBufC8* iPlaintext;           // Buffer to hold decrypted data
+    };
+
+#endif  //  __CDEVCERTKEYSTORECONDUIT_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevCertKeyStoreServer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,201 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevCertKeyStoreServer
+*
+*/
+
+
+
+#ifndef __DEVCERTKEYSTORESERVER_H__
+#define __DEVCERTKEYSTORESERVER_H__
+
+#include <mctkeystoremanager.h>
+#include <s32file.h>
+#include <secdlg.h>
+
+class CDecPKCS8Data;
+class CDevCertRSARepudiableSigner;
+class CDevCertDSARepudiableSigner;
+class CDevCertRSADecryptor;
+class CDevCertDHAgreement;
+class CDevCertKeyCreator;
+class CDevCertKeyData;
+class CDevCertKeyDataManager;
+class CDevCertOpenedKeySrv;
+class CDevTokenKeyInfo;
+class CDevCertKeyStoreSession;
+class CDevCertKeyStoreConduit;
+
+/** 
+ * Server side implementation of keystore interfaces as an active object.
+ * 
+ *  @lib 
+ *  @since S60 v3.2
+ */
+class CDevCertKeyStoreServer : public CActive
+    {
+    public:
+        
+        static CDevCertKeyStoreServer* NewL();
+        
+        virtual ~CDevCertKeyStoreServer();
+        
+        CDevCertKeyStoreSession* CreateSessionL();
+        
+        void RemoveSession(CDevCertKeyStoreSession& aSession);
+        
+        void ServiceRequestL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession);
+    
+    public:
+        
+        // For MKeyStore
+        void ListL(const TCTKeyAttributeFilter& aFilter, RPointerArray<CDevTokenKeyInfo>& aKeys);
+        
+        void GetKeyInfoL(TInt aObjectId, CDevTokenKeyInfo*& aInfo);
+        
+        CDevCertOpenedKeySrv* OpenKeyL(TInt aHandle, TUid aOpenedKeyType);
+        
+        void ExportPublicL(TInt aObjectId, TDes8& aOut);
+        
+        TInt GetKeyLengthL(TInt aObjectId);
+    
+    public:
+        
+        // For MCTKeyStoreManager
+        void CreateKey(CDevTokenKeyInfo& aReturnedKey, TRequestStatus& aStatus);
+        
+        void CancelCreateKey();
+        
+        void ImportKey(const TDesC8& aKey, CDevTokenKeyInfo& aReturnedKey, TBool aIsEncrypted,TRequestStatus& aStatus);
+        
+        void CancelImportKey();
+        
+        void ExportKey(TInt aObjectId, const TPtr8& aKey, TRequestStatus& aStatus); 
+        
+        void CancelExportKey();
+        
+        void DeleteKeyL(TInt aObjectId);
+        
+        void SetUsePolicyL(TInt aObjectId, const TSecurityPolicy& aPolicy);
+        
+        void SetManagementPolicyL(TInt aObjectId, const TSecurityPolicy& aPolicy);
+
+    private:
+        
+        CDevCertKeyStoreServer();
+        
+        void ConstructL();
+    
+    private:
+        
+        //  From CActive
+        void RunL();
+        
+        TInt RunError(TInt aError);
+        
+        void DoCancel();
+    
+    private:
+        
+        enum ECurrentAction
+            {
+            EIdle,
+            EImportOpenPrivateStream,
+            ECreateKeyCreate,
+            ECreateKeyFinal,
+            EImportKey, 
+            EExportKey,
+            EKeyCreated
+            };
+
+        /**
+        * The operations that can create a new key, used by CheckKeyAttributes.
+        */
+        enum TNewKeyOperation
+            {
+            ENewKeyCreate,
+            ENewKeyImportPlaintext
+            };
+
+    private:
+    
+        CDevCertKeyStoreServer(const CDevCertKeyStoreServer&);      //  No copying
+    
+        CDevCertKeyStoreServer& operator=(const CDevCertKeyStoreServer&); //  No copying
+    
+    private:
+
+        TInt CheckKeyAttributes(CDevTokenKeyInfo& aKey, TNewKeyOperation aOp);
+        
+        TInt CheckKeyAlgorithmAndSize(CDevTokenKeyInfo& aKey);
+        
+        void DoCreateKeyL();
+        
+        void DoStoreKeyL();
+        
+        void DoImportKeyL();
+        
+        void DoExportKeyL(TInt aObjectId, const TPtr8& aKey, TRequestStatus& aStatus);
+        
+        void CompleteKeyExportL();
+        
+        void OpenPrivateStream();
+
+    private:
+    
+        void PKCS8ToKeyL(CDecPKCS8Data* aPKCS8Data);
+        
+        TBool KeyMatchesFilterL(const CDevTokenKeyInfo& aInfo,
+        
+        const TCTKeyAttributeFilter& aFilter);
+    
+    private:
+        
+        CDevCertKeyDataManager* iKeyDataManager;
+        
+        CDevCertKeyStoreConduit* iConduit;
+        
+        RPointerArray<CDevCertKeyStoreSession> iSessions;
+        
+        const RMessage2* iMessage;    //The request currently being processed, not owned by us
+        
+        CDevCertKeyStoreSession* iSession;      // The session of the request being processed, not owned through here
+        
+        TRequestStatus* iCallerRequest;
+        
+        ECurrentAction iAction;
+    
+    private:
+        
+        CDevTokenKeyInfo* iKeyInfo;
+        
+        CDevCertKeyCreator* iKeyCreator;
+
+        TPtr8 iExportBuf;
+
+        TInt iObjectId;
+    
+        TPtrC8 iPKCS8Data;
+        
+        TBool iImportingEncryptedKey;
+        
+        TPINValue iPassword;
+        
+        const CDevCertKeyData* iKeyData;
+    };
+
+#endif  //  __CDevCertKeyStoreServer_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevCertKeyStoreSession.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,86 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevCertKeyStoreSession
+*
+*/
+
+
+
+#ifndef __DEVTOKENKEYSTORESESSION_H__
+#define __DEVTOKENKEYSTORESESSION_H__
+
+#include "DevTokenServer.h"
+
+class CDevCertKeyStoreConduit;
+class CDevCertOpenedKeySrv;
+
+/**
+ * Encapsulates an opened key object and its handle.
+ */
+struct TObjectIndex
+    {
+    TInt iHandle;
+    CDevCertOpenedKeySrv* iObject;
+    };
+
+/**
+ * A keystore session.
+ * Handles client requests by passing them to the keystore conduit.  Keeps track
+ * of uids/passphrases for the session.
+ *
+ *  @lib 
+ *  @since S60 v3.2
+ */
+class CDevCertKeyStoreSession : public CDevTokenServerSession
+    {
+    public:
+        
+        /**
+        * Create a new session object.
+        *
+        * @param aConduit The keystore conduit used to service user requests.
+        * @return 
+        */
+        static CDevCertKeyStoreSession* NewL(CDevCertKeyStoreServer& aServer );
+        
+        virtual ~CDevCertKeyStoreSession();
+
+        TInt AddOpenedKeyL(CDevCertOpenedKeySrv& aObject);
+        
+        void RemoveOpenedKeyL(TInt aHandle);
+        
+        CDevCertOpenedKeySrv* OpenedKey(TInt aHandle);
+
+        /**
+        * Determine if this session has a key open.
+        *
+        * @param aHandle The key data handle - not the session's open key handle!
+        * @return ETrue if has open key
+        */
+        TBool HasOpenKey(TInt aHandle);
+
+        CDevCertKeyStoreSession(CDevCertKeyStoreServer& aServer );
+    
+    private:
+       
+        virtual void DoServiceL(const RMessage2& aMessage);
+    
+    private:
+        
+        CDevCertKeyStoreServer& iServer;
+        TInt iLastHandle;
+        RArray<TObjectIndex> iOpenedKeys;
+    };
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevCertKeyStreamUtils.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevCertKeySteamUtils
+*
+*/
+
+
+
+#ifndef __DEVCERTKEYSTREAMUTILS_H__
+#define __DEVCERTKEYSTREAMUTILS_H__
+
+#include <s32strm.h>
+#include "DevTokenMarshaller.h"
+
+class CRSAPublicKey;
+class CRSAPrivateKey;
+class CDSAPublicKey;
+class CDSAPrivateKey;
+class RInteger;
+
+EXTERNALIZE_FUNCTION(CRSAPublicKey)
+
+EXTERNALIZE_FUNCTION(CRSAPrivateKey)
+
+EXTERNALIZE_FUNCTION(CDSAPublicKey)
+
+EXTERNALIZE_FUNCTION(CDSAPrivateKey)
+
+void ExternalizeL(const CRSAPublicKey& aData, RWriteStream& aStream);
+
+void ExternalizeL(const CRSAPrivateKey& aData, RWriteStream& aStream);
+
+void ExternalizeL(const CDSAPublicKey& aData, RWriteStream& aStream);
+
+void ExternalizeL(const CDSAPrivateKey& aData, RWriteStream& aStream);
+
+void CreateL(RReadStream& aStream, CRSAPublicKey*& aOut);
+
+void CreateL(RReadStream& aStream, CRSAPrivateKey*& aOut);
+
+void CreateL(RReadStream& aStream, CDSAPublicKey*& aOut);
+
+void CreateL(RReadStream& aStream, CDSAPrivateKey*& aOut);
+
+#endif //__DEVCERTKEYSTREAMUTILS_H__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevCertOpenedKeys.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,299 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevCertOpenedKeys
+*
+*/
+
+
+
+#ifndef __DEVCERTOPENEDKEYS_H__
+#define __DEVCERTOPENEDKEYS_H__
+
+class CDevCertKeyStore;
+class CMessageDigest;
+
+
+/**
+ * DevToken Client side
+ * Abstract base class for performing crypto operations on keys.
+ * 
+ *  @lib DevTokenClient.dll
+ *  @since S60 v3.2
+ */
+class CDevCertOpenedKey : protected CBase
+    {
+    public:
+        void SetObjectID(TInt aObjectId) {iHandle.iObjectId = aObjectId;}
+        void SetLabel(HBufC* aLabel) {iLabel = aLabel;}
+        // Virtual Release method visible though CDevCertOpenedKey pointers - the
+        // implementation just calls the Release method from the mixin class in each
+        // case.
+        virtual void Release() = 0;
+
+    protected:
+        virtual ~CDevCertOpenedKey();
+
+    protected:
+        TCTTokenObjectHandle iHandle;
+        CDevCertKeyStore* iClient;
+        HBufC* iLabel;
+    };
+
+
+/**
+ * DevToken Client side
+ * class for performing crypto operations on RSA keys.
+ * 
+ *  @lib DevTokenClient.dll
+ *  @since S60 v3.2
+ */
+class CDevCertRSARepudiableSigner : public CDevCertOpenedKey, public MRSASigner
+    {
+    public:
+        static CDevCertRSARepudiableSigner* New(CDevCertKeyStore* aClient);
+    
+        // MCTTokenObject 
+    public:
+        /**
+         * The object's human-readable label 
+         *
+         * @param 
+         * @return The object's human-readable label
+         */
+        virtual const TDesC& Label() const;
+        
+        /**
+         * A reference to the associated token 
+         *
+         * @param 
+         * @return A reference to the associated token
+         */
+        virtual MCTToken& Token() const;
+        
+        /**
+         * A UID representing the type of the token object. The
+         * meanings of possible UIDs should be documented in the
+         * documentation for the interface that returns them.  
+         *
+         * @param 
+         * @return A UID representing the type of the token object
+         */
+        virtual TUid Type() const;
+        
+        /**
+         * A handle for the object. The primary purpose of the
+         * handle is to allow token objects to be 'passed' between
+         * processes. See TCTTokenObjectHandle for more details.
+         *
+         * @param 
+         * @return A handle for the object
+         */
+        virtual TCTTokenObjectHandle Handle() const;
+        
+        // MSigner 
+    public:
+        /**
+         * Sign some data. 
+         * The data is hashed before the signature is created using the SHA-1
+         * algorithm.
+         *
+         * @param aPlaintext The string to be signed.
+         * @param aSignature The returned signature. This remains owned
+                             by the signer, and is valid until the signer 
+                             is released or until the next Sign.
+           @param aStatus Async status notification
+         * @return 
+         */
+        virtual void SignMessage(const TDesC8& aPlaintext, CRSASignature*& aSignature, 
+        TRequestStatus& aStatus);
+
+        /** 
+         * Perform a raw signing operation.
+         *
+         * @param aDigest The data to be signed - this should be some form of hash of
+         *                the actual message to be signed.  If the data is too long,
+                          this method will return KErrOverflow through aStatus.  
+         * @param aSignature The returned signature. This remains owned by the signer,
+                             and is valid until the signer is released or until the next 
+                             Sign.
+         * @param aStatus Async status notification
+         * @return
+         */
+        virtual void Sign(const TDesC8& aData, CRSASignature*& aSignature, 
+        TRequestStatus& aStatus);
+
+        /** 
+         * Cancel an ongoing sign.
+         *
+         * @param 
+         * @return
+         */
+        virtual void CancelSign();
+
+        virtual void Release();
+
+    private:
+        CDevCertRSARepudiableSigner(CDevCertKeyStore* aClient);
+        virtual ~CDevCertRSARepudiableSigner();
+
+    private:
+        CMessageDigest* iDigest;
+        HBufC8* iSignature; 
+    };
+
+
+/**
+ * DevToken Client side
+ * class for performing crypto operations on DSA keys.
+ * 
+ *  @lib DevTokenClient.dll
+ *  @since S60 v3.2
+ */
+class CDevCertDSARepudiableSigner : public CDevCertOpenedKey, public MDSASigner
+    {
+    public:
+        
+        static CDevCertDSARepudiableSigner* New(CDevCertKeyStore* aClient);
+        
+        virtual const TDesC& Label() const;
+        
+        virtual MCTToken& Token() const;
+        
+        virtual TUid Type() const;
+        
+        virtual TCTTokenObjectHandle Handle() const;
+        
+        virtual void SignMessage(const TDesC8& aPlaintext, CDSASignature*& aSignature, 
+                                 TRequestStatus& aStatus);
+        
+        virtual void Sign(const TDesC8& aData, CDSASignature*& aSignature, 
+                         TRequestStatus& aStatus);
+        
+        virtual void CancelSign();
+        
+        virtual void Release();
+
+    private:
+        
+        CDevCertDSARepudiableSigner(CDevCertKeyStore* aClient);
+        
+        virtual ~CDevCertDSARepudiableSigner();
+
+    private:
+        
+        CMessageDigest* iDigest;
+    };
+
+
+/**
+ * DevToken Client side
+ * class for performing decrypt operations on RSA keys.
+ * 
+ *  @lib DevTokenClient.dll
+ *  @since S60 v3.2
+ */
+class CDevCertRSADecryptor : public CDevCertOpenedKey, public MCTDecryptor
+    {
+    public:
+        
+        static CDevCertRSADecryptor* New(CDevCertKeyStore* aClient);
+        
+        virtual const TDesC& Label() const;
+        
+        virtual MCTToken& Token() const;
+        
+        virtual TUid Type() const;
+        
+        virtual TCTTokenObjectHandle Handle() const;
+        
+        /** 
+         * Perform a decrypt operation.
+         *
+         * @param aCiphertext The data to be decrypted 
+         * @param aPlaintext The returned decrypted text
+         * @param aStatus Async status notification
+         * @return
+         */
+        virtual void Decrypt(const TDesC8& aCiphertext, TDes8& aPlaintext,
+                             TRequestStatus& aStatus);
+        
+        virtual void CancelDecrypt();
+        
+        virtual void Release();
+
+    private:
+    
+        CDevCertRSADecryptor(CDevCertKeyStore* aClient);
+        
+        virtual ~CDevCertRSADecryptor();
+    };
+
+
+/**
+ * DevToken Client side
+ * class for performing crypto operations on DH keys.
+ * 
+ *  @lib DevTokenClient.dll
+ *  @since S60 v3.2
+ */
+class CDevCertDHAgreement : public CDevCertOpenedKey, public MCTDH
+    {
+    public:
+        
+        static CDevCertDHAgreement* New(CDevCertKeyStore* aClient);
+        
+        virtual const TDesC& Label() const;
+        
+        virtual MCTToken& Token() const;
+        
+        virtual TUid Type() const;
+        
+        virtual TCTTokenObjectHandle Handle() const;
+        
+        /** 
+         * Get DH public key.
+         *
+         * @param aN Integer N 
+         * @param aG Integer G
+         * @param aX DH public key
+         * @param aStatus Async status notification
+         * @return
+         */
+        
+        virtual void PublicKey(const TInteger& aN, const TInteger& aG, 
+                               CDHPublicKey*& aX,
+                               TRequestStatus& aStatus);
+        /** 
+         * Agrees a session key given the public key of the other party.
+         *
+         * @param aY DH PublicKey 
+         * @param aAgreedKey Agreed key
+         * @param aStatus Async status notification
+         * @return
+         */
+         virtual void Agree(const CDHPublicKey& iY,
+                            HBufC8*& aAgreedKey,
+                            TRequestStatus& aStatus);
+                            
+         virtual void CancelAgreement();
+    
+         virtual void Release();
+
+    private:
+    
+         CDevCertDHAgreement(CDevCertKeyStore* aClient);
+    
+         virtual ~CDevCertDHAgreement();
+    };
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevCertOpenedKeysSrv.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,363 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevCertOpenedKeysSrv
+*
+*/
+
+
+
+#ifndef __DEVCERTOPENEDKEYSSRV_H__
+#define __DEVCERTOPENEDKEYSSRV_H__
+
+#include "DevCertKeyDataManager.h"
+#include "DevTokenDataTypes.h"
+
+class CRSAPrivateKey;
+class CRSASignature;
+class CDSAPrivateKey;
+class CDSASignature;
+class CDevTokenDHParams;
+class CDHPublicKey;
+class CDevCertKeyStoreServer;
+
+/**
+ * DevToken Server side
+ * Abstract base class for performing crypto operations on keys.
+ * 
+ *  @lib
+ *  @since S60 v3.2
+ */
+class CDevCertOpenedKeySrv : public CActive
+    {
+    public:
+    
+        /**
+         * Factory function for creating CDevCertOpenedKeySrv-derived classes.
+         * 
+         * @param aKeyData representing the key
+         * @param aType Type of opened key
+         * @param aMessage IPC message
+         * @param aKeyDataMan Key data manager
+         * @return new object of CDevCertOpenedKeySrv
+         */
+        static CDevCertOpenedKeySrv* NewL(const CDevCertKeyData& aKeyData, TUid aType, const RMessage2& aMessage,
+                                          CDevCertKeyDataManager& aKeyDataMan );
+        
+        virtual ~CDevCertOpenedKeySrv();
+
+         /**
+         * Returns the object's human-readable label.
+         * 
+         * @param 
+         * @return the object's human-readable label
+         */
+        const TDesC& Label() const;
+        
+        /**
+         * Returns the key's handle so we can identifiy it.
+         * 
+         * @param 
+         * @return the hadnle of key
+         */
+        TInt Handle() const;
+
+        /**
+         * The type of opened key.
+         * 
+         * @param 
+         * @return the uid of opened key
+         */
+        virtual TUid Type() const = 0;
+
+    protected:
+        
+        CDevCertOpenedKeySrv(const CDevCertKeyData& aKeyData, CDevCertKeyDataManager& aKeyDataMan );
+        
+        void DoOperation(TRequestStatus& aStatus);
+        
+        // Methods supplied by derived classes
+        
+    protected:
+    
+        /**
+         * The key algorithm this operation applies to
+         * 
+         * @param
+         * @return
+         */
+        virtual CDevTokenKeyInfo::EKeyAlgorithm Algorithm() const = 0;
+
+        /**
+         * The key usage required to perform this operation
+         * 
+         * @param
+         * @return
+         */
+        virtual TKeyUsagePKCS15 RequiredUsage() const = 0;
+        
+        /**
+         * Load the private key data
+         * 
+         * @param aStream used to read data
+         * @return
+         */
+        virtual void ReadPrivateKeyL(RReadStream& aStream) = 0;
+        
+        /**
+         * Perform the operation, called from RunL
+         * 
+         * @param 
+         * @return
+         */
+        virtual void PerformOperationL() = 0;
+        
+        /**
+         * Clean up, called after normal end error completion
+         * 
+         * @param 
+         * @return
+         */
+        virtual void Cleanup() = 0;
+
+    private:
+        enum TState
+            {
+            EIdle,
+            EOperation
+            };
+            
+        // from CActive
+        
+        virtual void RunL();
+        
+        virtual TInt RunError(TInt aError);
+        
+        virtual void DoCancel();
+
+    private:
+        
+        void ConstructL(const RMessage2& aMessage);
+        
+        void CheckKeyL(const CDevTokenKeyInfo& aKeyInfo, const RMessage2& aMessage);
+        
+        void Complete(TInt aError);
+
+    private:
+        
+        const CDevCertKeyData&  iKeyData;
+        
+        CDevCertKeyDataManager& iKeyDataMan;
+        
+        HBufC*         iLabel;
+        
+        TState         iState;
+        
+        TRequestStatus*    iClientStatus;
+
+    protected:
+        
+        TBool        iKeyRead;
+    };
+
+
+/**
+ * DevToken Server side
+ * class for performing crypto operations on RSA keys.
+ *
+ *  @lib
+ *  @since S60 v3.2
+ */
+class CDevCertRSARepudiableSignerSrv : public CDevCertOpenedKeySrv
+    {
+    public:
+        
+        CDevCertRSARepudiableSignerSrv(const CDevCertKeyData& aKeyData, CDevCertKeyDataManager& aKeyDataMan );
+        
+        ~CDevCertRSARepudiableSignerSrv();
+        
+        void Sign(const TDesC8& aPlaintext, CRSASignature*& aSignature, TRequestStatus& aStatus);
+
+    private:
+        
+        virtual TUid Type() const;
+        
+        virtual CDevTokenKeyInfo::EKeyAlgorithm Algorithm() const;
+        
+        virtual TKeyUsagePKCS15 RequiredUsage() const;
+        
+        virtual void ReadPrivateKeyL(RReadStream& aStream);
+        
+        virtual void PerformOperationL();
+        
+        virtual void Cleanup();
+
+    private:
+        
+        CRSAPrivateKey* iPrivateKey;
+        
+        TPtrC8      iPlaintext;
+        
+        CRSASignature** iSignaturePtr;  
+    };
+
+
+/**
+ * DevToken Server side
+ * class for performing crypto operations on DSA keys.
+ *
+ *  @lib
+ *  @since S60 v3.2
+ */
+class CDevCertDSARepudiableSignerSrv : public CDevCertOpenedKeySrv
+    {
+    public:
+        
+        CDevCertDSARepudiableSignerSrv(const CDevCertKeyData& aKeyData, CDevCertKeyDataManager& aKeyDataMan );
+        
+        ~CDevCertDSARepudiableSignerSrv();
+        
+        void Sign(const TDesC8& aPlaintext, CDSASignature*& aSignature, TRequestStatus& aStatus);
+
+    private: 
+        
+        virtual TUid Type() const;
+        
+        virtual CDevTokenKeyInfo::EKeyAlgorithm Algorithm() const;
+        
+        virtual TKeyUsagePKCS15 RequiredUsage() const;
+        
+        virtual void ReadPrivateKeyL(RReadStream& aStream);
+        
+        virtual void PerformOperationL();
+        
+        virtual void Cleanup();
+
+    private:
+        
+        CDSAPrivateKey* iPrivateKey;
+        
+        TPtrC8      iPlaintext;
+        
+        CDSASignature** iSignaturePtr;  
+    };
+
+
+/**
+ * DevToken Server side
+ * class for performing decrypt operations on RSA keys.
+ *
+ *  @lib
+ *  @since S60 v3.2
+ */
+class CDevCertRSADecryptorSrv : public CDevCertOpenedKeySrv
+    {
+    public:
+        
+        CDevCertRSADecryptorSrv(const CDevCertKeyData& aKeyData, CDevCertKeyDataManager& aKeyDataMan );
+        
+        ~CDevCertRSADecryptorSrv();
+        
+        void Decrypt(const TDesC8& aCiphertext, HBufC8*&, TRequestStatus& aStatus);
+
+    private:
+        
+        virtual TUid Type() const;
+        
+        virtual CDevTokenKeyInfo::EKeyAlgorithm Algorithm() const;
+        
+        virtual TKeyUsagePKCS15 RequiredUsage() const;
+        
+        virtual void ReadPrivateKeyL(RReadStream& aStream);
+        
+        virtual void PerformOperationL();
+        
+        virtual void Cleanup();
+
+    private:
+        
+        CRSAPrivateKey* iPrivateKey;
+        
+        TPtrC8      iCiphertext;
+        
+        HBufC8**    iPlaintextPtr;
+    };
+
+
+/**
+ * DevToken Server side
+ * class for performing crypto operations on DH keys.
+ *
+ *  @lib
+ *  @since S60 v3.2
+ */
+class CDevCertDHAgreementSrv : public CDevCertOpenedKeySrv
+    {
+    public:
+    
+        CDevCertDHAgreementSrv(const CDevCertKeyData& aKeyData, CDevCertKeyDataManager& aKeyDataMan );
+        
+        ~CDevCertDHAgreementSrv();
+        
+        void PublicKey(CDevTokenDHParams& aParameters, RInteger& aPublicKey, TRequestStatus& aStatus);
+        
+        void Agree(CDHPublicKey& aY, HBufC8*& aAgreedKey, TRequestStatus& aStatus);
+
+    private:
+        
+        virtual TUid Type() const;
+        
+        virtual CDevTokenKeyInfo::EKeyAlgorithm Algorithm() const;
+        
+        virtual TKeyUsagePKCS15 RequiredUsage() const;
+        
+        virtual void ReadPrivateKeyL(RReadStream& aStream);
+        
+        virtual void PerformOperationL();
+        
+        virtual void Cleanup();
+
+    private:
+        
+        void DoPublicKeyL();
+        
+        void DoAgreeL();
+
+    enum TDHState
+        {
+        EIdle,
+        EPublicKey,
+        EAgree
+        };
+
+    private:
+        
+        RInteger    iKey;
+        
+        TDHState    iDHState;
+        
+        // For public key operation
+        CDevTokenDHParams*    iPKParams;
+        
+        RInteger*     iPKPublicKeyPtr;
+        
+        // For agree key operation
+        CDHPublicKey* iAKPublicKey;
+        
+        HBufC8**    iAKAgreedKeyPtr;
+    };
+
+#endif  //__DEVCERTOPENEDKEYSSRV_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevToken.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,81 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevToken
+*
+*/
+
+
+
+#ifndef __DEVTOKEN_H__
+#define __DEVTOKEN_H__
+
+#include <ct.h>
+#include "DevTokenClientSession.h"
+#include "DevTokenTypesEnum.h"
+
+
+/**
+ * Devicetokens client side representation of MCTToken, 
+ * provides client-side reference counting
+ * which calls server with ECloseToken request when appropriate.
+ * 
+ * Created by CDevTokenTypeSession as part of OpenToken call
+ * Uses RDevTokenClientSession to communicate with DevTokens server
+ *
+ *  @lib DevTokenClient.dll
+ *  @since S60 v3.2
+ */
+class CDevToken : public CBase, public MCTToken
+    {
+    public:
+    
+        static MCTToken* NewL(EDevTokenEnum aTokenTypeVal, MCTTokenType* aTokenType, RDevTokenClientSession& aClient);
+    
+    public: //  From MCTToken
+    
+        virtual MCTTokenType& TokenType();
+    
+        virtual const TDesC& Label();
+    
+        virtual TCTTokenHandle Handle();
+    
+    protected:  //  From MCTToken
+    
+        virtual TInt& ReferenceCount();
+    
+        virtual void DoGetInterface(TUid aRequiredInterface, MCTTokenInterface*& aReturnedInterface, TRequestStatus& aStatus);
+    
+        virtual TBool DoCancelGetInterface();
+    
+        virtual const TDesC& Information(TTokenInformation aRequiredInformation);
+    
+    private:
+    
+        CDevToken(EDevTokenEnum aTokenTypeVal, MCTTokenType* aTokenType, RDevTokenClientSession& aClient);
+    
+    private:
+    
+        EDevTokenEnum iTokenEnum;
+    
+        MCTTokenType* iTokenType;
+    
+        TInt iRefCount;
+    
+        RDevTokenClientSession& iClientSession;
+    };
+
+#endif  //__DEVTOKEN_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenCliServ.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,135 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Project definition file for DevTokenClient
+*
+*/
+
+
+
+#ifndef __DEVTOKENCLISERV_H__
+#define __DEVTOKENCLISERV_H__
+
+#include <e32base.h>
+#include "DevTokenTypesEnum.h"
+
+const TUid KUidDevTokenServer = {0x101FB66C};
+
+
+// Classes provide static lookup for tokens supported by the device tokens server
+// According to either description (string) or UID
+
+/** 
+ * Stores the _LIT description of each token with its associated ETokenEnum. 
+ *
+ * @lib DevTokenClient.dll
+ * @since S60 v3.2
+ */
+class RSupportedTokensArray : public TFixedArray<const TDesC*, ETotalTokensSupported>
+    {
+    public:
+    RSupportedTokensArray();
+    };
+
+
+/** 
+ * Stores the UID of each token type against the associated ETokenEnum. 
+ *
+ * @lib DevTokenClient.dll
+ * @since S60 v3.2
+ */
+class RTokenTypeUIDLookup : public TFixedArray<TInt, ETotalTokensSupported>
+    {
+    public:
+    RTokenTypeUIDLookup();
+    };
+
+// Client server protocol major version
+//   1 => 8.0 - 8.1
+//   2 => 9.0 onwards
+const TInt KDevTokenProtolVersion = 2;  
+
+// Request message enumeration between client and server.
+enum TDevTokenMessages
+    {
+    EIdle           = 0,
+    ESupportsToken        = 1,
+    // For MCertStore
+    EListCerts          = 10,
+    EGetCert          = 11,
+    EApplications       = 12,
+    EIsApplicable       = 13,
+    ETrusted          = 14,
+    ERetrieve         = 15,
+
+    // For MCTWritableCertStore
+    EAddCert          = 16,
+    ERemoveCert         = 17,
+    ESetApplicability       = 18,
+    ESetTrust           = 19,
+    // For MKeyStore
+    EListKeys           = 50,
+    EGetKeyInfo           = 51,
+    // For MCTKeyStoreManager
+    ECreateKey            = 52,
+    ECancelCreateKey        = 53,
+    EImportKey            = 54,
+    ECancelImportKey        = 55,
+    EImportEncryptedKey       = 56,
+    ECancelImportEncryptedKey   = 57,
+    EExportKey            = 58,
+    ECancelExportKey        = 59,
+    EExportEncryptedKey       = 60,
+    ECancelExportEncryptedKey   = 61,
+    EDeleteKey            = 62,
+
+    EOpenKeyRepudiableRSASign   = 64,
+    EOpenKeyRepudiableDSASign   = 65,
+    EOpenKeyDecrypt             = 66,
+    EOpenKeyAgree               = 67,
+    ECloseObject          = 68,
+    ERepudiableDSASign        = 69,
+    ECancelDSASign          = 70,
+    ERepudiableRSASign        = 71,
+    ECancelRSASign          = 72,
+    EExportPublic         = 73,
+    EDecryptText          = 74,
+    ECancelDecrypt          = 75,
+    EDHPublicKey          = 76,
+    EDHAgree            = 77,
+    ECancelDH           = 78,
+
+
+    EGetKeyLength       = 90,
+    ESetUsePolicy       = 91,
+    ESetManagementPolicy    = 92,
+
+    // For server OOM testing
+    EStartOOMTest       = 100,
+    EIncHeapFailPoint     = 101,
+    EResetHeapFail        = 102,
+    EAllocCount         = 103,
+
+    //For Trusted Site Store
+    EAddTrustSite = 125,
+    EIsTrustedSite = 126,
+    EGetTrustedSites = 127,
+    EAddForgivenSite = 128,
+    ERemoveForgivenSite = 129,
+    EIsOutOfDateAllowed = 130,
+    };
+
+#endif  //  __DEVTOKENCLISERV_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenClientSession.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenClientSession
+*
+*/
+
+
+
+#ifndef __DEVTOKENCLIENTSESSION_H__
+#define __DEVTOKENCLIENTSESSION_H__
+
+#include <e32base.h>
+#include "DevTokenCliServ.h"
+
+/**
+ * Makes SendReceive requests on the filetokens server
+ *
+ *  @lib DevTokenClient.dll
+ *  @since S60 v3.2
+*/
+class RDevTokenClientSession : public RSessionBase
+    {
+    public:
+    
+        RDevTokenClientSession();
+    
+        static RDevTokenClientSession* ClientSessionL();
+    
+        TInt Connect(EDevTokenEnum aTokenEnum);
+    
+        TInt SendRequest(TDevTokenMessages aRequest, const TIpcArgs& aArgs) const;
+    
+        void SendAsyncRequest(TDevTokenMessages aRequest, const TIpcArgs& aArgs, TRequestStatus* aStatus) const;
+    };
+
+#endif  //  __DEVTOKENCLIENTSESSION_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenDataTypes.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,260 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenDataTypes
+*
+*/
+
+
+
+#ifndef __DEVTOKENDATATYPES_H__
+#define __DEVTOKENDATATYPES_H__
+
+#include <mctkeystore.h>
+#include <cctcertinfo.h>
+#include <bigint.h>
+
+/**
+ * Server-side key info.
+ * 
+ * This is the server-side counterpart to the CCTKeyInfo class, containing all
+ * the key attributes.
+ 
+ * @lib DevTokenShared.dll
+ * @since S60 v3.2
+ */
+class CDevTokenKeyInfo : public CKeyInfoBase
+    {
+    public:
+        // Creates a new CKeyInfo from a stream.
+        IMPORT_C static CDevTokenKeyInfo* NewL(RReadStream& aStream);
+        
+        // Make destructor public again.
+        inline ~CDevTokenKeyInfo();
+        
+        // Push object onto the cleanup stack (pointer won't convert to CBase* due
+        // to protected inheritance.
+        inline void CleanupPushL();
+
+    public:
+        
+        // Get the handle of the key.
+        inline TInt Handle() const;
+        
+        // Set the key access type.
+        inline void SetAccessType(TInt aAccessType);
+        
+        // Set the security policy for key use operations.
+        IMPORT_C void SetUsePolicy(const TSecurityPolicy& aPolicy);
+        
+        // Set the security policy for key management operations.
+        IMPORT_C void SetManagementPolicy(const TSecurityPolicy& aPolicy);
+        
+        // Sets the set of DER encoded PKCS8 attributes.
+        IMPORT_C void SetPKCS8AttributeSet(HBufC8* aPKCS8AttributeSet);
+
+    private:
+    
+        inline CDevTokenKeyInfo();    
+    };
+
+
+/**
+ * An internal abstraction for Diffie-Hellman parmeters.
+ *
+ * @lib DevTokenShared.dll
+ * @since S60 v3.2
+ */
+class CDevTokenDHParams : public CBase
+    {
+    public:
+    
+        IMPORT_C static CDevTokenDHParams* NewL(const TInteger& aN, const TInteger& aG);
+    
+        IMPORT_C ~CDevTokenDHParams();
+    
+        inline const TInteger& N() const;
+    
+        inline const TInteger& G() const;
+    
+        //Return N and release ownership
+    
+        IMPORT_C RInteger TakeN();
+    
+        //Return G and release ownership
+    
+        IMPORT_C RInteger TakeG();
+        
+    private:
+    
+        IMPORT_C CDevTokenDHParams(RInteger aN, RInteger aG);
+    
+        RInteger iN;
+    
+        RInteger iG;
+    };
+
+
+/** A common interface for arrays of key infos.  
+ *
+ * @lib DevTokenShared.dll
+ * @since S60 v3.2
+ */
+class MDevTokenKeyInfoArray
+    {
+    public:
+    
+        virtual TInt Count() = 0;
+    
+        virtual CCTKeyInfo* operator[](TInt aIndex) = 0;
+    
+        virtual TInt Append(CCTKeyInfo* aInfo) = 0;
+    
+        virtual void Close() = 0;
+    };
+
+
+/**
+ * Information sent back to client when a key has been created or imported.
+ * 
+ * @lib DevTokenShared.dll
+ * @since S60 v3.2
+ */
+struct TDevTokenKeyUpdate
+    {
+    
+    TInt iReference;
+    
+    TKeyIdentifier iId;
+    
+    TUint iSize;
+    
+    CKeyInfoBase::EKeyAlgorithm iAlgorithm;
+    };
+
+
+/**
+ * Server-side cert info.
+ * 
+ * This is the server-side counterpart to the CCTCertInfo class, containing all
+ * the certificate attributes.
+ * We don't support the issuer hash, as it is not
+ * stored.
+ *
+ * @lib DevTokenShared.dll
+ * @since S60 v3.2
+ */
+
+class CDevTokenCertInfo : public CBase, public MCertInfo
+    {
+    public:
+        
+        // Copy a CCertInfo.
+        IMPORT_C static CDevTokenCertInfo* NewL(const CDevTokenCertInfo& aOther);
+        
+        // Copy a CCertInfo. 
+        IMPORT_C static CDevTokenCertInfo* NewLC(const CDevTokenCertInfo& aOther);
+        
+        // Makes a new CCTCertInfo from its constituent parts.
+        IMPORT_C static CDevTokenCertInfo* NewL(const TDesC& aLabel,
+                                                TCertificateFormat aFormat,
+                                                TCertificateOwnerType aCertificateOwnerType,
+                                                TInt aSize,
+                                                const TKeyIdentifier* aSubjectKeyId,
+                                                const TKeyIdentifier* aIssuerKeyId,
+                                                TInt aCertificateId);
+        
+        IMPORT_C static CDevTokenCertInfo* NewL(const TDesC& aLabel,
+                                                TCertificateFormat aFormat,
+                                                TCertificateOwnerType aCertificateOwnerType,
+                                                TInt aSize,
+                                                const TKeyIdentifier* aSubjectKeyId,
+                                                const TKeyIdentifier* aIssuerKeyId,
+                                                TInt aCertificateId,
+                                                const TBool aDeletable);
+        
+        // Makes a new CCTCertInfo from its constituent parts. 
+        IMPORT_C static CDevTokenCertInfo* NewLC(const TDesC& aLabel,
+                                                 TCertificateFormat aFormat,
+                                                 TCertificateOwnerType aCertificateOwnerType,
+                                                 TInt aSize,
+                                                 const TKeyIdentifier* aSubjectKeyId,
+                                                 const TKeyIdentifier* aIssuerKeyId,
+                                                 TInt aCertificateId);
+        
+        IMPORT_C static CDevTokenCertInfo* NewLC(const TDesC& aLabel,
+                                                 TCertificateFormat aFormat,
+                                                 TCertificateOwnerType aCertificateOwnerType,
+                                                 TInt aSize,
+                                                 const TKeyIdentifier* aSubjectKeyId,
+                                                 const TKeyIdentifier* aIssuerKeyId,
+                                                 TInt aCertificateId,
+                                                 const TBool aDeletable);
+        
+        // Reads a CDevTokenCertInfo from a stream. 
+        IMPORT_C static CDevTokenCertInfo* NewL(RReadStream& aStream);
+        
+        // Reads a CCertInfo from a stream. 
+        IMPORT_C static CDevTokenCertInfo* NewLC(RReadStream& aStream);
+        
+        // Accessors
+        inline const TDesC& Label() const;
+        
+        inline TInt Reference() const;
+        
+        inline const TKeyIdentifier& SubjectKeyId() const;
+        
+        inline const TKeyIdentifier& IssuerKeyId() const;
+        
+        inline TCertificateFormat CertificateFormat() const;
+        
+        inline TCertificateOwnerType CertificateOwnerType() const;
+        
+        inline TInt Size() const;
+        
+        inline TInt CertificateId() const;
+        
+        inline TBool IsDeletable() const;
+
+    private:
+        
+        // Default constructor. 
+        CDevTokenCertInfo();    
+        
+        // Copy constructor. 
+        CDevTokenCertInfo(const CDevTokenCertInfo& aOther);
+        
+        CDevTokenCertInfo(const TDesC& aLabel,
+                          TCertificateFormat aFormat,
+                          TCertificateOwnerType aCertificateOwnerType, 
+                          TInt aSize,
+                          const TKeyIdentifier* aSubjectKeyId,
+                          const TKeyIdentifier* aIssuerKeyId,
+                          TInt aCertificateId,
+                          const TBool aDeletable = ETrue);  
+    };
+
+
+struct TDevTokenAddCertDataStruct
+    {
+    TCertLabel iLabel;
+    TCertificateFormat iFormat;
+    TCertificateOwnerType iCertificateOwnerType;
+    TKeyIdentifier iSubjectKeyId;
+    TKeyIdentifier iIssuerKeyId;
+    TBool iDeletable;
+    };
+
+#include "DevTokenDataTypes.inl"
+
+#endif //__DEVTOKENDATATYPES_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenDataTypes.inl	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,102 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The inl file of DevTokenDataTypes
+*
+*/
+
+
+// Data types used by the device tokens server
+
+inline CDevTokenKeyInfo::CDevTokenKeyInfo() :
+    CKeyInfoBase()
+    {
+    }
+
+inline CDevTokenKeyInfo::~CDevTokenKeyInfo()
+    {
+    }
+
+inline void CDevTokenKeyInfo::CleanupPushL()
+    {
+    CleanupStack::PushL(this);
+    }
+
+inline TInt CDevTokenKeyInfo::Handle() const
+    {
+    return iHandle;
+    }
+
+inline void CDevTokenKeyInfo::SetAccessType(TInt aAccessType)
+    {
+    iAccessType = aAccessType;
+    }
+
+inline const TInteger& CDevTokenDHParams::N() const
+    {
+    return iN;
+    }
+
+inline const TInteger& CDevTokenDHParams::G() const
+    {
+    return iG;
+    }
+
+inline const TDesC& CDevTokenCertInfo::Label() const
+    {
+    return iLabel;
+    }
+
+inline TInt CDevTokenCertInfo::Reference() const
+    {
+    return iCertificateId;
+    }
+
+inline const TKeyIdentifier& CDevTokenCertInfo::SubjectKeyId() const
+    {
+    return iSubjectKeyId;
+    }
+
+inline const TKeyIdentifier& CDevTokenCertInfo::IssuerKeyId() const
+    {
+    return iIssuerKeyId;
+    }
+
+inline TCertificateFormat CDevTokenCertInfo::CertificateFormat() const
+    {
+    return iFormat;
+    }
+
+inline TCertificateOwnerType CDevTokenCertInfo::CertificateOwnerType() const
+    {
+    return iCertificateOwnerType;
+    }
+
+inline TInt CDevTokenCertInfo::Size() const
+    {
+    return iSize;
+    }
+
+inline TInt CDevTokenCertInfo::CertificateId() const
+    {
+    return iCertificateId;
+    }
+
+inline TBool CDevTokenCertInfo::IsDeletable() const
+    {
+    return iDeletable;
+    }
+
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenDialog.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenDialog
+*
+*/
+
+
+
+#ifndef __DEVTOKENDIALOG_H__
+#define __DEVTOKENDIALOG_H__
+
+
+class MSecurityDialog;
+
+/**
+ *  Lauch the dialog for asking password from user
+ *
+ *  @lib 
+ *  @since S60 v3.2
+ */
+class DevTokenDialog
+	  {
+    public:
+	      inline static MSecurityDialog* Dialog();
+	      static void InitialiseL();
+	      static void Cleanup();
+	      
+    private:
+	      static MSecurityDialog* iDialog;
+	  };
+
+inline MSecurityDialog* DevTokenDialog::Dialog()
+	  {
+	  return iDialog;
+	  }
+
+#endif //__DEVTOKENDIALOG_H__
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenImplementationUID.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenImplementationUID
+*
+*/
+
+
+
+#ifndef DEVTOKENIMPLEMENTATIONUID_HRH
+#define DEVTOKENIMPLEMENTATIONUID_HRH
+
+//Implementation UID of Device Token CertStore
+#define DEVCERTSTORE_IMPLEMENTATION_UID 0x101FB668  
+
+//Implementation UID of Trust server CertStore
+#define TRUSRVCERTSTORE_IMPLEMENTATION_UID  0x101FB66F
+
+//Implementation UID of Device Token KeyStore
+#define DEVCERTKEYSTORE_IMPLEMENTATION_UID  0x101FB66A
+
+#endif // DEVTOKENIMPLEMENTATIONUID_HRH
+
+// EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenInterfaceFactory.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenInterfaceFactory
+*
+*/
+
+
+
+#ifndef __DEVTOKENINTERFACEFACTORIES_H__
+#define __DEVTOKENINTERFACEFACTORIES_H__
+
+#include "DevTokenClientSession.h"
+
+class MCTTokenInterface;
+class MCTToken;
+
+/**
+ * Factory class to create the appropriate token interface object according
+ * to the UID required
+ * 
+ *  @lib DevTokenClient.dll
+ *  @since S60 v3.2
+*/
+class DevTokenInterfaceFactory
+    {
+    public:
+    
+        static MCTTokenInterface* ClientInterfaceL(TInt32 aUid, MCTToken& aToken, RDevTokenClientSession& aClient);
+    };
+
+#endif // __DEVTOKENINTERFACEFACTORIES_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenKeyInfoArray.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenKeyInfoArray
+*
+*/
+
+
+
+#ifndef __DEVTOKENKEYINFOARRAY_H__
+#define __DEVTOKENKEYINFOARRAY_H__
+
+#include "DevTokenDataTypes.h" //MDevTokenKeyInfoArray
+
+/**
+ * A class that wraps an array of key info pointers.
+ * Implements the MDevTokenKeyInfoArray interface required for marshalling key info
+ * arrays.  
+ *
+ *  @lib DevTokenClient.dll
+ *  @since S60 v3.2
+ */
+class TDevTokenKeyInfoArray : public MDevTokenKeyInfoArray
+    {
+    public:
+    
+        TDevTokenKeyInfoArray(RMPointerArray<CCTKeyInfo>& aArray) : iArray(aArray) { }
+        
+        virtual TInt Count() { return iArray.Count(); }
+        
+        virtual CCTKeyInfo* operator[](TInt aIndex) { return static_cast<CCTKeyInfo*>(iArray[aIndex]); }
+        
+        virtual TInt Append(CCTKeyInfo* aInfo) { return iArray.Append(aInfo); }
+        
+        virtual void Close() { iArray.Close(); }
+    
+    private:
+        
+        RMPointerArray<CCTKeyInfo>& iArray;
+    };
+    
+#endif //__DEVTOKENKEYINFOARRAY_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenMarshaller.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,209 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenMarshaller
+*
+*/
+
+
+
+#ifndef __DEVTOKENMARSHALLER_H__
+#define __DEVTOKENMARSHALLER_H__
+
+#include <e32std.h>
+#include <s32strm.h>
+#include <ct/rmpointerarray.h>
+
+/**
+ * Marshalling and unmarshalling utils for the filetokens server This is used by
+ * both client and server dlls.
+ */
+
+class MCTToken;
+class CKeyInfoBase;
+class CCTKeyInfo;
+class CDevTokenKeyInfo;
+class MDevTokenKeyInfoArray;
+class CDSASignature;
+class CRSASignature;
+struct TDHParams;
+class CDevTokenDHParams;
+class CDHPublicKey;
+class TInteger;
+class RInteger;
+class MCertInfo;
+class CCTCertInfo;
+class CDevTokenCertInfo;
+class TCertificateAppInfo;
+class CCertAttributeFilter;
+class MKeyEncryptor;
+
+// A macro that marks a type as externalized by a global function
+#define EXTERNALIZE_FUNCTION(TYPE) \
+inline Externalize::Function Externalization(const TYPE*) \
+    { \
+    return Externalize::Function(); \
+    }
+
+// Serialization for bigints, used in server
+
+// Maximum size of integer to decode - keys are limited to 2048 bits, so nothing
+// we pass around should be bigger than this.
+
+// Add 48 bytes on top of 256 bytes ( 2048 bits ) for
+// Size of info data which is added to encrypt output. 
+// padding 16 bytes + salt 32 bytes = 48. 
+const TInt KMaxIntegerSize = 304;
+const TInt KMaxSiteName = 100;
+
+// Maximum size in bytes of serialised representations, given the limit on key
+// size.
+const TInt KMaxDSASignatureSize = 48; // Two 160 bit integers
+const TInt KMaxRSASignatureSize = 516;  // One 4096 bit integer
+const TInt KMaxRSAPlaintextSize = 516;  // One 4096 bit integer
+const TInt KMaxDHAgreedKeySize = 516; // One 4096 bit integer
+
+// enum for handling panics
+enum KTokenMarshallerPanics
+    { 
+    ESerialisationPanic
+    };
+
+
+EXTERNALIZE_FUNCTION(TInteger)
+
+IMPORT_C void ExternalizeL(const TInteger& aIn, RWriteStream& aOut);
+
+IMPORT_C void CreateLC(RReadStream& aIn, RInteger& aOut);
+
+/** 
+ * Decrypted the content and create the object.
+ * 
+ *  @lib DevTokenShared.dll
+ *  @since S60 v3.2
+ */
+IMPORT_C void DecryptAndCreateLC(RReadStream& aIn, RInteger& aOut, MKeyEncryptor* aEncryptor);
+
+/** 
+ * encrypted the content and store.
+ * 
+ *  @lib DevTokenShared.dll
+ *  @since S60 v3.2
+ */
+ 
+IMPORT_C void EncryptAndStoreL(const TInteger& aIn, RWriteStream& aOut, MKeyEncryptor* aEncryptor );
+
+
+/** 
+ * Marshals data over the IPC boundary between filetokens client and server.
+ * 
+ *  @lib DevTokenShared.dll
+ *  @since S60 v3.2
+ */
+class DevTokenDataMarshaller
+    {
+    // Common
+    public:
+        IMPORT_C static void ReadL(const TDesC8& aIn, RArray<TUid>& aOut);
+        
+        IMPORT_C static TInt Size(const CKeyInfoBase& aIn);
+        
+        IMPORT_C static void Write(const CKeyInfoBase& aIn, TDes8& aOut);
+        
+        IMPORT_C static TInt Size(const RArray<TUid>& aIn);
+        
+        IMPORT_C static void Write(const RArray<TUid>& aIn, TDes8& aOut);
+        
+        IMPORT_C static TInt Size(const MCertInfo& aIn);
+        
+        IMPORT_C static void Write(const MCertInfo& aIn, TDes8& aOut);
+
+    // Used by client 
+    public: 
+        
+        IMPORT_C static void ReadL(const TDesC8& aIn, MCTToken& aToken, MDevTokenKeyInfoArray& aOut);
+        
+        IMPORT_C static void ReadL(const TDesC8& aIn, MCTToken& aToken, CCTKeyInfo*& aOut);
+        
+        IMPORT_C static void ReadL(const TDesC8& aIn, CDSASignature*& aOut);
+        
+        IMPORT_C static void ReadL(const TDesC8& aIn, CRSASignature*& aOut);
+        
+        IMPORT_C static TInt Size(const CDevTokenDHParams& aIn);
+        
+        IMPORT_C static void WriteL(const CDevTokenDHParams& aIn, TDes8& aOut);
+        
+        IMPORT_C static TInt Size(const CDHPublicKey& aIn);
+        
+        IMPORT_C static void WriteL(const CDHPublicKey& aIn, TDes8& aOut);
+        
+        IMPORT_C static void ReadL(const TDesC8& aIn, RInteger& aInteger);
+        
+        IMPORT_C static void ReadL(const TDesC8& aIn, MCTToken& aToken, RMPointerArray<CCTCertInfo>& aOut);
+        
+        IMPORT_C static void ReadL(const TDesC8& aIn, MCTToken& aToken, CCTCertInfo*& aOut);
+        
+        IMPORT_C static void ReadL(const TDesC8& aIn, RArray<TCertificateAppInfo>& aOut);
+        
+        IMPORT_C static TInt Size(const CCertAttributeFilter& aIn);
+        
+        IMPORT_C static void WriteL(const CCertAttributeFilter& aIn, TDes8& aOut);
+        
+        IMPORT_C static void ReadL(const TDesC8& aIn, RPointerArray<HBufC>& aOut);
+        
+        IMPORT_C static TInt Size(const RPointerArray<HBufC>& aIn);
+        
+        IMPORT_C static void Write(const RPointerArray<HBufC>& aIn, TDes8& aOut );
+
+    // Used by server
+    public:
+        
+        IMPORT_C static void ReadL(const TDesC8& aIn, CDevTokenKeyInfo*& aOut);
+        
+        IMPORT_C static TInt Size(const RPointerArray<CDevTokenKeyInfo>& aIn);
+        
+        IMPORT_C static void Write(const RPointerArray<CDevTokenKeyInfo>& aIn, TDes8& aOut);
+        
+        IMPORT_C static TInt Size(const CDSASignature& aIn);
+        
+        IMPORT_C static void WriteL(const CDSASignature& aIn, TDes8& aOut);
+        
+        IMPORT_C static TInt Size(const CRSASignature& aIn);
+        
+        IMPORT_C static void WriteL(const CRSASignature& aIn, TDes8& aOut);
+        
+        IMPORT_C static void ReadL(const TDesC8& aIn, CDevTokenDHParams*& aOut);
+        
+        IMPORT_C static void ReadL(const TDesC8& aIn, CDHPublicKey*& aOut);
+        
+        IMPORT_C static TInt Size(const TInteger& aIn);
+        
+        IMPORT_C static void WriteL(const TInteger& aIn, TDes8& aOut);
+        
+        IMPORT_C static void ReadL(const TDesC8& aIn, CDevTokenCertInfo*& aOut);
+        
+        IMPORT_C static TInt Size(const RPointerArray<CDevTokenCertInfo>& aIn);
+        
+        IMPORT_C static void Write(const RPointerArray<CDevTokenCertInfo>& aIn, TDes8& aOut);
+        
+        IMPORT_C static TInt Size(const RArray<TCertificateAppInfo>& aIn);   
+        
+        IMPORT_C static void Write(const RArray<TCertificateAppInfo>& aIn, TDes8& aOut);
+        
+        IMPORT_C static void ReadL(const TDesC8& aIn, CCertAttributeFilter*& aOut);
+    };
+
+#endif //__DEVTOKENMARSHALLER_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenNullStream.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,72 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenNullStream
+*
+*/
+
+
+
+#ifndef __DEVTOKENNULLSTREAM_H__
+#define __DEVTOKENNULLSTREAM_H__
+
+#include <s32strm.h>
+#include <s32buf.h>
+
+/**
+ * Implementation of the MStreamBuf interface that throws away all data written
+ * to it.  It does not support reading
+ *
+ *  @lib DevTokenShared.dll
+ *  @since S60 v3.2.
+ */
+class TNullBuf : public MStreamBuf
+    {
+    public:
+    
+        TNullBuf();
+    
+        TUint BytesWritten();
+        
+    private:
+    
+        virtual void DoWriteL(const TAny* aPtr,TInt aLength);
+        
+    private:
+    
+        TUint iBytesWritten;
+    }; 
+
+
+/**
+ * A write stream that throws away all its input, but keeps track of how many
+ * bytes have been written to it.  It is used for determining the amount of
+ * memory needed to store externalised objects.
+ * 
+ *  @lib DevTokenShared.dll
+ *  @since S60 v3.2.
+ */
+class RNullWriteStream : public RWriteStream
+    {
+    public:
+        RNullWriteStream();
+        TUint BytesWritten();
+    
+    private:
+        TNullBuf iSink;
+    };
+
+#endif //__DEVTOKENNULLSTREAM_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenPWManager.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenPWManager
+*
+*/
+
+
+
+#ifndef __DEVTOKENPWMANAGER_H__
+#define __DEVTOKENPWMANAGER_H__
+
+#include <pbe.h>
+#include <e32std.h>
+#include <s32crypt.h>
+#include <e32base.h>
+#include <secdlg.h>
+
+
+/**
+ *  Password management class. Ask password from 
+ *  user when encrypted key is imported to devcert
+ *  key store.
+ *
+ *  @lib 
+ *  @since S60 v3.2
+ */
+class TDevTokenPWManager
+    {
+    public:
+	      static void ImportPassword(TPINValue& aValue, TRequestStatus& aStatus);
+	      static void Cancel();
+    private:
+	      static void GetPassword( TPINValue& aValue, TRequestStatus& aStatus, TBool aRetry = EFalse);
+	  };
+
+#endif	//__DEVTOKENPWMANAGER_H__
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenServer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,154 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenServer
+*
+*/
+
+
+
+#ifndef __DEVTOKENSERVER_H__
+#define __DEVTOKENSERVER_H__
+
+
+#include <e32base.h>
+#include "DevTokenCliServ.h"
+#include "DevTokenTypesEnum.h"
+
+class CDevCertKeyStoreServer;
+class CDevandTruSrvCertStoreServer;
+class CTrustedSitesServer;
+
+/**
+ * Implements shutdown of the server.  When the last client disconnects, this
+ * class is activated, and when the timer expires, causes the server to
+ * close.
+ *
+ *  @lib
+ *  @since S60 v3.2
+ */
+class CShutdown : public CTimer
+    {  
+    public:
+    
+        inline CShutdown();
+        
+        inline void ConstructL();
+        
+        inline void Start();
+        
+    private:
+        
+        void RunL();
+    };
+
+
+/** 
+ * Device Tokens server class, manages sessions. 
+ * 
+ *  @lib
+ *  @since S60 v3.2
+ */
+class CDevTokenServer : public CServer2
+    {
+    public:
+        
+        static CServer2* NewLC();
+        
+        ~CDevTokenServer();
+        
+        void AddSession();
+        
+        void DropSession();
+        
+        /**
+         * return the server object of keystore
+         *
+         * @param 
+         * @return server object of keystore
+         */
+        CDevCertKeyStoreServer& KeyStoreServerL() const;
+        
+        /**
+         * return the server object of certstore
+         *
+         * @param 
+         * @return server object of certstore
+         */
+        CDevandTruSrvCertStoreServer& CertStoreServerL() const;
+        
+        /**
+         * return the server object of Trusted Sites
+         *
+         * @param 
+         * @return server object of Truste sites
+         */
+        CTrustedSitesServer& CDevTokenServer::TrustedSitesL() const;
+        
+    // For CServer2
+    private:
+
+        virtual CSession2* NewSessionL(const TVersion& aVersion, const RMessage2& aMessage) const;
+    
+    private:
+    
+        CDevTokenServer();
+       
+        void ConstructL();
+    
+    private:
+       
+        TInt iSessionCount;
+       
+        CShutdown iShutdown;
+       
+        mutable CDevCertKeyStoreServer* iKeyStoreServer;
+       
+        mutable CDevandTruSrvCertStoreServer* iCertStoreServer;
+       
+        mutable CTrustedSitesServer* iTrustedSitesServer;
+    };
+
+/**
+ * Base class for session objects.
+ *
+ *  @lib
+ *  @since S60 v3.2
+ */
+class CDevTokenServerSession : public CSession2
+    {
+    public:
+       
+        CDevTokenServerSession();
+       
+        virtual ~CDevTokenServerSession();
+       
+        inline CDevTokenServer& Server();
+    
+    protected:
+       
+        virtual void DoServiceL(const RMessage2& aMessage) = 0;
+    
+    private:
+       
+        virtual void CreateL();
+       
+        virtual void ServiceError(const RMessage2& aMessage, TInt aError);
+       
+        virtual void ServiceL(const RMessage2& aMessage);
+    };
+
+#endif  //  __DEVTOKENSERVER_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenServerDebug.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,73 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenServerDebug
+*
+*/
+
+
+
+#ifndef __DEVTOKENSERVERDEBUG_H__
+#define __DEVTOKENSERVERDEBUG_H__
+
+#ifdef _DEBUG
+
+#include <e32std.h>
+
+
+/**
+ * OOM testing functionality.
+ *
+ *  @lib 
+ *  @since S60 v3.2
+ */
+class DevTokenServerDebug
+    {
+    public:
+        // Server-side OOM testing
+        static void StartOOMTest();
+        
+        static void IncHeapFailPoint();
+        
+        static void ResetHeapFail();
+        
+        static void PauseOOMTest();
+        
+        static void ResumeOOMTest();
+        
+        // Heap checking
+        static void HeapCheckStart();
+        
+        static void HeapCheckEnd();
+        
+    private:
+        
+        static void HeapErrorL(TBool aError);
+        
+    private:
+        
+        static TInt iCounter;
+        
+        static TInt iStartCount;
+        
+        static TInt iPauseCount;
+        
+        static TInt iInitialAllocCount;
+    };
+
+#endif // _DEBUG
+
+#endif //__DEVTOKENSERVERDEBUG_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenServerName.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenServerName
+*
+*/
+
+
+
+#ifndef __DEVTOKENSERVERNAME_H__
+#define __DEVTOKENSERVERNAME_H__
+
+#include <e32base.h>
+
+_LIT(KDevTokenServerName, "!DevTokenServer");
+
+#endif //__DEVTOKENSERVERNAME_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenType.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,87 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenType
+*
+*/
+
+
+
+#ifndef __CDEVTOKENTYPE_H__
+#define __CDEVTOKENTYPE_H__
+
+#include <ct/ccttokentype.h>
+
+class CDevTokenTypeSession; 
+
+/**
+ * DevToken Type
+ * Derived from CCTTokenType to represent devicetoken type
+ * 
+ *  @lib DevTokenClient.dll
+ *  @since S60 v3.2
+ */
+class CDevTokenType :  public CCTTokenType
+    {
+    public:
+    
+        /** 
+        * Creates a client side representation of the CCTTokenType represented by the UID parameter
+        * Called by ECom or directly accessible.  Initiates a session with the filetokens server, and
+        * corresponding token type access server-side
+        *
+        *  @param aUid The UID of the appropriate token type (devcertstore, devkeystore)
+        *  @return
+        */
+        IMPORT_C static CCTTokenType* NewL(TUid aUid);
+    
+    public:
+    
+        virtual ~CDevTokenType();
+    
+    public: 
+         
+        //  From MCTTokenType
+        virtual void List(RCPointerArray<HBufC>& aTokens, TRequestStatus& aStatus);
+        
+        virtual void CancelList();
+        
+        virtual void OpenToken(const TDesC& aTokenInfo, MCTToken*& aToken, TRequestStatus& aStatus);
+        
+        virtual void OpenToken(TCTTokenHandle aHandle, MCTToken*& aToken, TRequestStatus& aStatus);
+        
+        virtual void CancelOpenToken();
+    
+    private:
+    
+        void OpenToken(MCTTokenType* aTokenType);
+    
+    private:
+    
+        CDevTokenType();
+    
+        void ConstructL(TUid aUid);
+    
+    public:
+    
+        TUid iUid;    
+    
+    private:
+    
+        CDevTokenTypeSession* iTokenTypeSession;
+    };
+
+#endif  //  __CDTTOKENTYPE_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenTypeSession.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,72 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenTypeSession
+*
+*/
+
+
+
+#ifndef __DEVTOKENTYPESESSION_H__
+#define __DEVTOKENTYPESESSION_H__
+
+#include <ct/ccttokentype.h>
+#include "DevTokenClientSession.h"
+
+/**
+ * Token type session.
+ * It is owned and created by the CDevTokenType so is not released until
+ * all references to the tokentype object are relinquished.  It creates
+ * RDevTokenClientSession, with which it communicates with the filetokens
+ * server.
+ *
+ * @lib DevTokenClient.dll
+ * @since S60 v3.2
+ */
+class CDevTokenTypeSession : public CBase
+    {
+    public:
+    
+        virtual ~CDevTokenTypeSession();
+    
+    public:
+    
+        static CDevTokenTypeSession* NewL(TUid aUid);
+    
+    public:
+    
+        void ListTokensL(RCPointerArray<HBufC>& aTokens);
+    
+        void OpenTokenL(const TDesC& aTokenInfo, MCTTokenType* aTokenType, MCTToken*& aToken);
+    
+        void OpenTokenL(TCTTokenHandle aHandle, MCTTokenType* aTokenType, MCTToken*& aToken);
+    
+    private:
+    
+        CDevTokenTypeSession(TUid aUid);
+    
+        void ConstructL();
+    
+    private:
+    
+        RDevTokenClientSession iClientSession;
+    
+        TUid iUid;
+    
+        EDevTokenEnum iTokenId;
+    };
+
+#endif  //  __DEVTOKENTYPESESSION_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenTypesEnum.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,98 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenTypeEnum
+*
+*/
+
+
+
+#ifndef __DEVTOKENTYPESENUM_H__
+#define __DEVTOKENTYPESENUM_H__
+
+#include <e32std.h>
+
+enum EDevTokenEnum  //  Interchangeable between tokens & tokentypes (ie 1:1 mapping)
+    {
+    EDevCertKeyStore      = 0,
+    EDevCertStore     = 1,
+    ETruSrvCertStore        = 2,
+    ETotalTokensSupported,
+    ETruSitesStore
+    };
+
+enum EDevTokenTypeClientPanic
+    {
+    EInvalidTokenType   = 1,
+    EInvalidToken     = 2,
+    EInvalidInterface   = 3,
+    //EClientSession      = 4,
+    ETokenTypeSession   = 4,
+    EBadTokenHandle     = 5,
+    EBadArgument      = 6,
+    ENotInitialised     = 7,
+    EBadTokenIFHandle   = 8,
+    EInvalidRequest     = 9,
+    ERequestOutstanding   = 10,
+    ENoRequestOutstanding = 11,
+    ENoDataMarshalled   = 12,
+    EMarshalDescriptorErr = 13,
+    EClientInvalidState   = 14
+    };
+
+enum ETokenTypeServerPanic
+    {
+    EPanicBadDescriptor     = 0,
+    EPanicIllegalFunction   = 1,
+    EPanicInvalidRequest    = 2,
+    EPanicAlreadyInitialised  = 3,
+    EPanicNotInitialised    = 4,
+    EPanicBadSession      = 5,
+    EPanicNoToken       = 6,
+    EPanicInvalidTokenRequest = 7,
+    EPanicNotIndexed      = 8,
+    EOutstandingIFPtr     = 9,
+    EOutstandingTokenPtr    = 10,
+    EOutstandingTokenTypePtr  = 11,
+    EOutstanding        = 12,
+    EPanicBadHandle       = 13,   
+    EPanicRequestOutstanding  = 14,
+    EPanicBadArgument     = 15,
+    EPanicArrayCleanup      = 16,
+    EPanicTokenMismatch     = 17,
+    EPanicNoCert        = 18,
+    EPanicNoAllocation      = 19,
+    EPanicNoKeyStore      = 20,
+    EPanicECreateKeyNotReady  = 21,
+    EPanicNoClientData      = 22,
+    EPanicInvalidKeyCreateReq = 23,
+    EPanicStoreInitialised    = 24,
+    EPanicRootStreamNotReady  = 25,
+    EPanicSaltStreamNotReady  = 26,
+    EPanicManagerStreamNotReady = 27,
+    ENoCreatedKeyData     = 28,
+    EPanicInvalidState      = 30,
+
+    // For cert store
+    EPanicCertStoreReplaceArguments      = 101,
+    EPanicCertStoreRestoreState        = 103,
+    EPanicCertStoreOpenState         = 104,
+    EPanicCertStoreEntryConstructArguments   = 102,
+    EPanicCertStoreEntryInternalizeState   = 105,
+    EPanicCertStoreEntryListAppendArguments  = 106,
+    EPanicCertStoreEntryListReplaceArguments = 107
+    };
+
+#endif
+
+//EOF
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenUtil.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenUtil
+*
+*/
+
+
+
+#ifndef __DEVTOKENUTIL_H__
+#define __DEVTOKENUTIL_H__
+
+#include "DevTokenTypesEnum.h"
+#include "DevTokenCliServ.h"
+
+// Panic the client
+void PanicClient(const RMessage2& aMessage, ETokenTypeServerPanic aPanic);
+// Panic the server
+void PanicServer(ETokenTypeServerPanic aPanicCode);
+// Assert macro
+#define assert(TEST, PANIC) __ASSERT_ALWAYS(TEST, PanicServer(PANIC))
+
+class RFs;
+
+// Length of filename buffer for store path
+const TUint KMaxFilenameLength = 60;
+
+/**
+ * Files utilities used by all servers.
+ 
+ * @lib 
+ * @since S60 v3.2
+ */
+struct FileUtils
+    {
+    // Determine whether a file exists
+    static TBool ExistsL(RFs& aFs, const TDesC& aFile);
+    
+    // Ensure all directories in a file's path exist, creating them if not
+    static void EnsurePathL(RFs& aFs, const TDesC& aFile);
+    
+    // Copy a file from one location to another
+    static void CopyL(RFs& aFs, const TDesC& aSouce, const TDesC& aDest);
+    
+    // Construct a filename in the server's private area
+    static void MakePrivateFilenameL(RFs& aFs, const TDesC& aLeafName, TDes& aNameOut);
+    
+    // Construct a filename in the server's private area in ROM
+    static void MakePrivateROMFilenameL(RFs& aFs, const TDesC& aLeafName, TDes& aNameOut);
+    };
+
+#endif  // __DEVTOKENUTIL_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevTokenUtils.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevTokenUtils
+*
+*/
+
+
+
+#ifndef __DEVTOKENUTILS_H__
+#define __DEVTOKENUTILS_H__
+
+#include <e32std.h>
+#include "DevTokenTypesEnum.h"
+
+_LIT(KDevTokenTypeClientPanic, "DEVTOKENTYPECLIENT");
+
+void DevTokenPanic(EDevTokenTypeClientPanic aPanicCode);
+
+
+#endif //__DEVTOKENUTILS_H__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevandTruSrvCertStore.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,152 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevandTruSrvCertStore
+*
+*/
+
+
+
+#ifndef __DEVANDTRUSRVCERTSTORE_H__
+#define __DEVANDTRUSRVCERTSTORE_H__
+
+#include <mctwritablecertstore.h>
+#include "DevTokenMarshaller.h"
+#include "DevTokenDataTypes.h"
+#include "DTClient.h"
+
+
+/**
+ * The device tokens Certstore client interface.
+ * 
+ * Implements the MCTWritableCertStore interface, with inheritance from
+ * CFSClient.  Instances of this class are created by CClientInterfaceFactory.
+ * Marshals client data for server requests and unpacks returned parameter data
+ * across IPC boundary.
+ * Note that although this class is derived from CActive (via CDTClient) is does
+ * not act an active object, or use CActive functionality.
+ *
+ *  @lib DevTokenClient.dll
+ *  @since S60 v3.2
+ */
+class CDevandTruSrvCertStore : public CDTClient, public MCTWritableCertStore
+    {
+    public:
+        
+        static MCTTokenInterface* NewWritableInterfaceL(MCTToken& aToken, RDevTokenClientSession& aClient);
+        
+        static MCTTokenInterface* NewReadableInterfaceL(MCTToken& aToken, RDevTokenClientSession& aClient);
+        
+    public:
+        
+        virtual ~CDevandTruSrvCertStore();
+        
+    public: 
+        
+        // From MCTTokenInterface
+        virtual MCTToken& Token();
+        
+        virtual void DoRelease();
+        
+    public:
+        
+        // From MCTCertStore
+        virtual void List(RMPointerArray<CCTCertInfo>& aCerts, 
+                          const CCertAttributeFilter& aFilter, 
+                          TRequestStatus& aStatus);
+        
+        virtual void CancelList();  
+        
+        virtual void GetCert(CCTCertInfo*& aCertInfo, const TCTTokenObjectHandle& aHandle,
+                             TRequestStatus& aStatus);
+        
+        virtual void CancelGetCert(); 
+        
+        virtual void Applications(const CCTCertInfo& aCertInfo, RArray<TUid>& aApplications,
+                                  TRequestStatus& aStatus); 
+                                  
+        virtual void CancelApplications();  
+        
+        virtual void IsApplicable(const CCTCertInfo& aCertInfo, TUid aApplication, 
+                                  TBool& aIsApplicable, TRequestStatus& aStatus);
+        
+        virtual void CancelIsApplicable();  
+        
+        virtual void Trusted(const CCTCertInfo& aCertInfo, TBool& aTrusted, 
+                             TRequestStatus& aStatus);
+        
+        virtual void CancelTrusted(); 
+        
+        virtual void Retrieve(const CCTCertInfo& aCertInfo, TDes8& aEncodedCert,
+                              TRequestStatus& aStatus);
+        
+        virtual void CancelRetrieve();
+        
+        // From MCTWritableCertStore
+        virtual void Add(const TDesC& aLabel, TCertificateFormat aFormat,
+                         TCertificateOwnerType aCertificateOwnerType, 
+                         const TKeyIdentifier* aSubjectKeyId, const TKeyIdentifier* aIssuerKeyId,
+                         const TDesC8& aCert, TRequestStatus& aStatus);
+        
+        virtual void Add(const TDesC& aLabel, TCertificateFormat aFormat,
+                         TCertificateOwnerType aCertificateOwnerType, 
+                         const TKeyIdentifier* aSubjectKeyId, const TKeyIdentifier* aIssuerKeyId,
+                         const TDesC8& aCert, const TBool aDeletable,
+                         TRequestStatus& aStatus);
+        
+        virtual void CancelAdd(); 
+        
+        virtual void Remove(const CCTCertInfo& aCertInfo, TRequestStatus& aStatus);
+        
+        virtual void CancelRemove();  
+        
+        virtual void SetApplicability(const CCTCertInfo& aCertInfo, 
+        
+        const RArray<TUid>& aApplications, TRequestStatus &aStatus);
+        
+        virtual void CancelSetApplicability();
+        
+        virtual void SetTrust(const CCTCertInfo& aCertInfo, TBool aTrusted, 
+                              TRequestStatus& aStatus);
+        
+        virtual void CancelSetTrust();  
+
+    protected:
+        
+        // From CActive
+        virtual void RunL();
+
+    private:
+        
+        CDevandTruSrvCertStore(TInt aUID, MCTToken& aToken, RDevTokenClientSession& aClient);
+        
+        void ConstructL();
+        
+        void DoListL(RMPointerArray<CCTCertInfo>& aCerts, const CCertAttributeFilter& aFilter);
+        
+        void DoGetCertL(CCTCertInfo*& aCertInfo, const TCTTokenObjectHandle& aHandle);
+        
+        void DoApplicationsL(const CCTCertInfo& aCertInfo, RArray<TUid>& aApplications);
+        
+        TInt DoRetrieve(const CCTCertInfo& aCertInfo, TDes8& aEncodedCert);
+        
+        void CopyFilter( CCertAttributeFilter* aDesFilter, const CCertAttributeFilter& aSrcFilter);
+        
+    private:
+        
+        CCertAttributeFilter* iFilter;    
+    };
+
+#endif  //__DEVANDTRUSRVCERTSTORE_H__
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevandTruSrvCertStoreConduit.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,93 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevandTruSrvCertStoreConduit
+*
+*/
+
+
+
+#ifndef __DEVANDTRUSRVCERTSTORECONDUIT_H__
+#define __DEVANDTRUSRVCERTSTORECONDUIT_H__
+
+#include "DevTokenCliServ.h"
+#include "DevTokenMarshaller.h"
+#include "DevTokenDataTypes.h"
+#include <ccertattributefilter.h>
+
+class CDevandTruSrvCertStoreServer;
+
+/**
+ *  class CDevandTruSrvCertStoreConduit
+ *
+ * Unmarshalls incoming client request data and uses it to execute certstore
+ * operations.  Marshalls the return data into a suitable format to pass back to
+ * to the client
+ *
+ *  @lib 
+ *  @since S60 v3.2
+ */
+class CDevandTruSrvCertStoreConduit : public CBase
+    {
+    public:
+        
+        static CDevandTruSrvCertStoreConduit* NewL(CDevandTruSrvCertStoreServer& aServer);
+        
+        virtual ~CDevandTruSrvCertStoreConduit();
+        
+        void ServiceCertStoreRequestL(const RMessage2& aMessage);
+
+    private:
+        
+        // For MCTCertStore
+        void ListCertsL(const RMessage2& aMessage);
+        
+        void GetCertL(const RMessage2& aMessage);
+        
+        void ApplicationsL(const RMessage2& aMessage);
+        
+        TInt IsApplicableL(const RMessage2& aMessage);
+        
+        TInt TrustedL(const RMessage2& aMessage);
+        
+        void RetrieveL(const RMessage2& aMessage);
+
+        // For MCTWritableCertStore
+        void AddCertL(const RMessage2& aMessage);
+        
+        void RemoveCertL(const RMessage2& aMessage);
+        
+        void SetApplicabilityL(const RMessage2& aMessage);
+        
+        void SetTrustL(const RMessage2& aMessage);
+
+    private:
+        
+        CDevandTruSrvCertStoreConduit(CDevandTruSrvCertStoreServer& aServer);
+        
+        HBufC8* AllocResponseBufferLC(TInt aSize, const RMessage2& aMessage);
+        
+        CDevandTruSrvCertStoreConduit(const CDevandTruSrvCertStoreConduit&);      //  No copying
+        
+        CDevandTruSrvCertStoreConduit& operator=(const CDevandTruSrvCertStoreConduit&); //  No copying
+
+    private:
+        
+        // The cert store server used to fulfill client requests
+        CDevandTruSrvCertStoreServer& iServer;
+    };
+
+#endif  //  __DEVANDTRUSRVCERTSTORECONDUIT_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevandTruSrvCertStoreEntry.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,91 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevandTruSrvCertStoreEntry
+*
+*/
+
+
+
+#ifndef __DEVANDTRUSRVCERTSTOREENRY_H__
+#define __DEVANDTRUSRVCERTSTOREENRY_H__
+
+#include <e32base.h>
+#include <s32std.h>
+
+class CDevTokenCertInfo;
+
+/**
+ *  class CDevandTruSrvCertStoreEntry
+ *
+ * This class represents a cert in the store.  It contains the cert info, the id
+ * of the stream containing the certificate itself and its applications and
+ * trust settings.
+ *
+ *  @lib 
+ *  @since S60 v3.2
+ */
+class CDevandTruSrvCertStoreEntry : public CBase
+    {
+    public:
+        
+        // Create a new CDevTokenCertStoreEntry
+        static CDevandTruSrvCertStoreEntry* NewL(const CDevTokenCertInfo& aEntry,
+                                                 RArray<TUid> aCertificateApps,
+                                                 TBool aTrusted,
+                                                 TStreamId aDataStreamId);
+        
+        // Read a CDevTokenCertStoreEntry from a stream.
+        static CDevandTruSrvCertStoreEntry* NewLC(RReadStream& aStream);
+        
+        virtual ~CDevandTruSrvCertStoreEntry();
+        
+        // Write a CDevTokenCertStoreEntry to a stream.
+        void ExternalizeL(RWriteStream& aDataStream) const;
+        
+        // Accessors
+        const CDevTokenCertInfo& CertInfo() const;
+        
+        TStreamId DataStreamId() const;
+        
+        const RArray<TUid>& CertificateApps() const;
+        
+        TBool IsApplicable(const TUid& aApplication) const;
+        
+        TBool Trusted() const;
+
+    private:
+        
+        CDevandTruSrvCertStoreEntry();
+        
+        void ConstructL(const CDevTokenCertInfo& aEntry, RArray<TUid> aCertificateApps,
+        
+        TBool aTrusted, TStreamId aDataStreamId);
+        
+        void InternalizeL(RReadStream& aStream);
+
+    private:
+        
+        CDevTokenCertInfo* iCertInfo;
+        
+        RArray<TUid> iCertificateApps;
+        
+        TBool iTrusted;
+        
+        TStreamId iDataStreamId;
+    };
+
+#endif __DEVANDTRUSRVCERTSTOREENRY_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevandTruSrvCertStoreEntryList.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,100 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevandTruSrvCertStoreEntryList
+*
+*/
+
+
+
+#ifndef __DEVANDTRUSRVCERTSTOREENTRYLIST_H__
+#define __DEVANDTRUSRVCERTSTOREENTRYLIST_H__
+
+#include <s32file.h>
+
+class CDevandTruSrvCertStoreEntry;
+
+/**
+ * An in-memory list of the certs in the store
+ *
+ * @lib
+ * @since S60 v3.2.
+ */
+class CDevandTruSrvCertStoreEntryList : public CBase
+    {
+    public:
+    
+        // Create a new, empty cert list
+        static CDevandTruSrvCertStoreEntryList* NewLC();
+
+        // Read the cert list from a stream
+        static CDevandTruSrvCertStoreEntryList* NewL(RReadStream& aStream);
+
+        virtual ~CDevandTruSrvCertStoreEntryList();
+
+        // Write the cert list to a stream
+        void ExternalizeL(RWriteStream& aStream) const;
+
+        // Get the number of certificates in the list
+        TInt Count() const;
+
+        /**
+         * Get the index of a mapping given the cert handle
+         *
+         * @param aHandle 
+         * @return The index of the cert or KErrNotFound if it is not present
+         */
+        TInt IndexForHandle(TInt aHandle) const;
+
+        // Determine whether a certificate exists with the specified label
+        TBool LabelExists(const TDesC& aLabel) const;
+
+        /**
+         * Get a mapping given the cert handle
+         * leave KErrNotFound If the specified cert is not present
+         * 
+         * @param aHandle 
+         * @return 
+         */
+        const CDevandTruSrvCertStoreEntry& GetByHandleL(TInt aHandle) const;
+
+        // Get a mapping given its index.
+        const CDevandTruSrvCertStoreEntry& GetByIndex(TInt aIndex) const;
+
+        // Get the next free handle to use when adding a cert
+        TInt NextFreeHandle() const;
+
+        // Add a mapping and return its index, takes ownership
+        TInt AppendL(CDevandTruSrvCertStoreEntry* aEntry);
+
+        // Removes and returns an entry from the list, relinquishes ownership
+        CDevandTruSrvCertStoreEntry* Remove(TInt aIndex);
+
+        // Replace an entry and return the old one, takes/relinquishes ownership
+        CDevandTruSrvCertStoreEntry* Replace(TInt aIndex, CDevandTruSrvCertStoreEntry* aEntry); 
+
+    private:
+        
+        CDevandTruSrvCertStoreEntryList();
+        
+        void InternalizeL(RReadStream& aStream);
+
+    private:
+        
+        RPointerArray<CDevandTruSrvCertStoreEntry> iEntries;
+    };
+
+#endif //__DEVANDTRUSRVCERTSTOREENTRYLIST_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevandTruSrvCertStoreServer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,151 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevandTruSrvCertStoreServer
+*
+*/
+
+
+
+#ifndef __DEVANDTRUSRVCERTSTORESERVER_H__
+#define __DEVANDTRUSRVCERTSTORESERVER_H__
+
+#include <s32file.h>
+#include <e32std.h>
+#include <securitydefs.h>
+
+class CDevTokenCertInfo;
+class CDevandTruSrvCertStoreSession;
+class CDevandTruSrvCertStoreConduit;
+class CDevandTruSrvCertStoreEntry;
+class CDevandTruSrvCertStoreEntryList;
+class CCertAttributeFilter;
+class CTrustedSitesServer;
+
+struct TDevTokenAddCertDataStruct;
+
+/**
+ *  class CDevandTruSrvCertStoreServer
+ *
+ * This class implements a certificate store which is stored on a file on the
+ * device.  NewL calls the constructor and ConstructL. The constructor does
+ * nothing except initializing to 0. ConstructL calls OpenStoreL, then RestoreL
+ * and then sets the values of iStoreInfo.  OpenStoreL opens the store and
+ * copies it from the ROM if necessary.  RestoreL()
+ *
+ *  @lib 
+ *  @since S60 3.2
+ */
+class CDevandTruSrvCertStoreServer : public CBase
+    {
+    public:
+        
+        static CDevandTruSrvCertStoreServer* NewL( CTrustedSitesServer* aTrustedSitesServer);
+        
+        virtual ~CDevandTruSrvCertStoreServer();
+        
+        CDevandTruSrvCertStoreSession* CreateSessionL();
+
+    public:
+        
+        // List certs, returned pointers are owned by this class
+        void ListL(const CCertAttributeFilter& aFilter, RPointerArray<CDevTokenCertInfo>& aCertsOut, const RMessage2& aMessage, TBool aFromTruSiteSrv ) const;
+        
+        // Get cert info, returned pointer owned by this class, leaves if not found
+        const CDevTokenCertInfo& GetCertL(TInt aHandle) const;
+        
+        const RArray<TUid>& ApplicationsL(TInt aHandle) const;  
+        
+        TBool IsApplicableL(TInt aHandle, TUid aApplication) const;
+        
+        TBool TrustedL(TInt aHandle) const;
+        
+        HBufC8* RetrieveLC(TInt aHandle, const RMessage2& aMessage, TBool aFromTruSiteSrv ) const;
+        
+        void AddL(const TDevTokenAddCertDataStruct& aInfo,
+                  const TDesC8& aCert,
+                  const RMessage2& aMessage, TBool aFromTruSiteSrv );
+        
+        void RemoveL(TInt aHandle, const RMessage2& aMessage, TBool aFromTruSiteSrv );
+        
+        void SetApplicabilityL(TInt aHandle,
+                               const RArray<TUid>& aApplications,
+                               const RMessage2& aMessage);
+        
+        void SetTrustL(TInt aHandle,
+                       TBool aTrusted,
+                       const RMessage2& aMessage);
+
+    private:
+        
+        CDevandTruSrvCertStoreServer( CTrustedSitesServer* aTrustedSitesServer );
+        
+        void ConstructL();
+        
+        // Security policy
+        const TSecurityPolicy& AddRemovePolicy(TCertificateOwnerType aOwnerType) const;
+        
+        const TSecurityPolicy& RetrievePolicy(TCertificateOwnerType aOwnerType) const;
+        
+        const TSecurityPolicy& ListPolicy(TCertificateOwnerType aOwnerType) const;
+        
+        const TSecurityPolicy& WriteTrustSettingsPolicy() const;
+        
+        TBool CertEntryMatchesFilter(const CCertAttributeFilter& aFilter,
+        
+        const CDevandTruSrvCertStoreEntry& aEntry) const;
+        
+        void DoAddL(const CDevTokenCertInfo& aCertInfo, const TDesC8& aCertData);
+        
+        TStreamId WriteCertDataStreamL(const TDesC8& aData);
+        
+        // Write the cert entry list to the store
+        void UpdateStoreL();
+        
+        void CompactStoreL();
+        
+        // Open the store and load the index from a file
+        void RestoreL(const TDesC& aFilename);
+        
+        // Open the store file, copying from ROM or creating it first if necessary
+        void OpenStoreL();
+        
+        // Create an empty store file, and leave it closed
+        void CreateStoreFileL(const TDesC& aFile);
+        
+        void DoCreateStoreFileL(const TDesC& aFile);
+
+    private:
+        
+        // Conduit for marshalling/unmarshalling client communications
+        
+        CDevandTruSrvCertStoreConduit* iConduit;
+        
+        RFs iFs;
+        
+        CPermanentFileStore* iStore;
+        
+        // The list of certificates contained in the store.
+        
+        CDevandTruSrvCertStoreEntryList* iEntryList;
+        
+        // The store stream containing the list of certs
+        TStreamId iStreamId;
+        
+        CTrustedSitesServer* iTrustedSitesServer; //Not owned;
+    };
+
+#endif  //__DEVANDTRUSRVCERTSTORESERVER_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevandTruSrvCertStoreSession.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of DevandTruSrvCertStoreSession
+*
+*/
+
+
+
+#ifndef __DEVANDTRUSRVCERSTORESESSION_H__
+#define __DEVANDTRUSRVCERSTORESESSION_H__
+
+#include "DevTokenServer.h"
+
+class RMessage2;
+class CDevandTruSrvCertStoreConduit;
+
+/**
+ * A cert store session
+ *
+ * Handles client requests by passing them to the cert store conduit.
+ *
+ *  @lib 
+ *  @since S60 v3.2
+ */
+class CDevandTruSrvCertStoreSession : public CDevTokenServerSession
+    {
+    public:
+        
+        /**
+         * Create a new session object.
+         *
+         * @param aConduit The cert store conduit used to service user requests
+         * @return 
+         */
+        static CDevandTruSrvCertStoreSession* NewL(CDevandTruSrvCertStoreConduit& aConduit);
+
+    private:
+        
+        CDevandTruSrvCertStoreSession(CDevandTruSrvCertStoreConduit& aConduit);
+        
+        virtual void DoServiceL(const RMessage2& aMessage);
+        
+    private:
+        
+        CDevandTruSrvCertStoreConduit& iConduit;
+    };
+
+#endif //__DEVANDTRUSRVCERSTORESESSION_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/DevtokenLog.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Print debug log 
+*
+*/
+
+
+
+#ifndef	DEVTOKENLOG_H
+#define	DEVTOKENLOG_H
+
+#include <e32base.h>
+
+
+#ifdef _DEBUG
+#include <e32svr.h>
+#define TRACE_PRINT( aText ) { RDebug::Print( _L(aText) ); }
+#define TRACE_PRINT_NUM( aText, aNum ) \
+		{ RDebug::Print( _L(aText), aNum ); }
+#define TRACE_PRINT_RAW( aBuf ) { RDebug::RawPrint( aBuf ); }
+
+#else
+
+#define TRACE_PRINT( aText )
+#define TRACE_PRINT_NUM( aText, aNum ) 
+#define TRACE_PRINT_RAW( aBuf )
+#endif
+
+#endif	//DEVTOKENLOG_H
+//EOF
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/SimpleDHKey.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of SimpleDHKey
+*
+*/
+
+
+#ifndef __SIMPLEDHKEY_H__
+#define __SIMPLEDHKEY_H__
+
+#include <e32base.h>
+
+/**
+ * Wrapper class because we differ from crypto on what a DH key is
+ *
+ *  @lib
+ *  @since S60 v3.2
+ */
+class CSimpleDHKey : public CBase
+    {
+    public:
+        
+        static CSimpleDHKey* NewL(TInt aSize);
+        
+        ~CSimpleDHKey();
+    
+    public:
+        
+        inline RInteger& DHKey() {return (iKey);};
+    
+    private:
+        
+        CSimpleDHKey() {};
+        
+        void ConstructL(TInt aSize);
+    
+    private:
+        
+        RInteger iKey;
+    };
+
+#endif //__SIMPLEDHKEY_H__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/TrustedSitesConduit.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,78 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of TrustedSiteConduit
+*
+*/
+
+
+
+#ifndef __TRUSTEDSITESCONDUIT_H__
+#define __TRUSTEDSITESCONDUIT_H__
+
+#include "DevTokenCliServ.h"
+#include "DevTokenMarshaller.h"
+#include "DevTokenDataTypes.h"
+
+class CTrustedSitesServer;
+
+/**
+* Trust sites store implementation in server side
+* 
+ *  @lib 
+ *  @since S60 v3.2
+*/
+class CTrustedSitesConduit : public CBase
+    {
+    public:
+    
+        static CTrustedSitesConduit* NewL(CTrustedSitesServer& aServer);
+    
+        virtual ~CTrustedSitesConduit();
+    
+        void ServiceTrustedSitesRequestL(const RMessage2& aMessage);
+
+    private:
+    
+        void AddL( const RMessage2& aMessage );
+    
+        TInt IsTrustedSiteL( const RMessage2& aMessage );   
+    
+        void GetTrustedSitesL( const RMessage2& aMessage ); 
+
+        void AddForgivenSiteL(const RMessage2& aMessage );
+        
+        void RemoveForgivenSiteL( const RMessage2& aMessage );
+        
+        TInt IsOutOfDateAllowedL(const RMessage2& aMessage); 
+    private:
+     
+        CTrustedSitesConduit(CTrustedSitesServer& aServer);
+     
+        HBufC8* AllocResponseBufferLC(TInt aSize, const RMessage2& aMessage);
+     
+        //  No copying
+        CTrustedSitesConduit(const CTrustedSitesConduit&);      
+     
+        //  No copying
+        CTrustedSitesConduit& operator=(const CTrustedSitesConduit&); 
+
+    private:
+      
+        CTrustedSitesServer& iServer;
+    };
+
+#endif  //__TRUSTEDSITESCONDUIT_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/TrustedSitesServer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,182 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of TrustedSitesServer
+*
+*/
+
+
+
+#ifndef __TRUSTEDSITESSERVER_H__
+#define __TRUSTEDSITESSERVER_H__
+
+#include <s32file.h>
+#include <e32std.h>
+#include <securitydefs.h>
+#include <d32dbms.h>
+
+class CTrustedSitesSession;
+class CTrustedSitesConduit;
+class CDevTokenServer;
+/**
+* Trust sites store implementation in server side
+* 
+ *  @lib 
+ *  @since S60 3.2
+*/
+class CTrustedSitesServer : public CBase
+    {
+    public:
+        
+        static CTrustedSitesServer* NewL( CDevTokenServer* aServer );
+        
+        virtual ~CTrustedSitesServer();
+        
+        CTrustedSitesSession* CreateSessionL();
+
+    public:
+
+        /**
+         * add new trust record to trust site store
+         *
+         * @param aCert a certificate
+         * @param aSiteName trusted site name
+         * @param aMessage IPC message
+         * @return 
+         */
+        void AddL(const TDesC8& aCert, const TDesC& aSiteName, const RMessage2& aMessage );
+        
+        /**
+         * add new trust record to trust site store, this is called internally in DeviceToken server
+         *
+         * @param aCert a certificate
+         * @param aSiteName trusted site name
+         * @return 
+         */
+        void AddL(const TDesC8& aCertHash, const TDesC& aSiteName );
+
+        /**
+         * check whether the given cert is trusted for the given site
+         *
+         * @param aCert a certificate
+         * @param aSiteName trusted site name
+         * @param aCertBuf
+         * @param aMessage IPC message
+         * @return ETrue /EFalse
+         */
+        TBool IsTrustedSiteL( const TDesC8& aCert, const TDesC& aSiteName, const TDesC8& aCertBuf, const RMessage2& aMessage );
+        
+        
+        /**
+         * check whether the out of date certificate is allowed for the forgiven sites
+         *
+         * @param aCert a certificate
+         * @param aSiteName trusted site name
+         * @param aCertBuf
+         * @param aMessage IPC message
+         * @return ETrue /EFalse
+         */
+        TBool IsOutOfDateAllowedL( const TDesC8& aCertHash, const TDesC& aSiteName, const RMessage2& aMessage );
+
+        /**
+         * list all of the sites for which the cert is trusted
+         *
+         * @param aCert a certificate
+         * @param aListOfSites trusted sites' name
+         * @param aMessage IPC message
+         * @return ETrue /EFalse
+         */
+        void GetTrustedSitesL( const TDesC8& aCert, RPointerArray<HBufC>& aListOfSites, const RMessage2& aMessage);
+
+        /**
+         * Remove trust record from trust site store
+         *
+         * @param aCert a certificate
+         * @return 
+         */
+        void RemoveL( const TDesC8& aCert );
+        
+        /**
+         * Add forgiven site. The site will be forgiven for untrusted certificate
+         *
+         * @param aSite
+         * @param aOutOfDateAllowed
+         * @param aMessage IPC message
+         */
+        void AddForgivenSiteL(const TDesC& aSite,const TBool& aOutOfDateAllowed, const RMessage2& aMessage );
+        
+        /**
+         * Remove all forgiven sites set by this client
+         *
+         * @param aMessage IPC message
+         */
+        void RemoveAllForgivenSitesL( const RMessage2& aMessage );
+        
+        
+        /**
+         * Remove the given site 
+         * 
+         * @param aMessage IPC message
+         */
+        void RemoveThisForgivenSiteL( const TDesC& aSite, const RMessage2& aMessage );
+
+    private:
+        
+        CTrustedSitesServer( CDevTokenServer* aServer );
+        
+        void ConstructL();
+        
+        void CreateDBL();
+        
+        TBool IsSiteAlreadyExistL(const TInt& aCertID, const TDesC& aSiteName);
+        
+        TBool IsOutOfDateAllowedForTheSiteL(const TInt& aCertID, const TDesC& aSiteName);
+        
+        void DoAddSiteNameL(const TInt& aCertID, const TDesC& aSiteName );
+        
+        void DoAddCertL( const TDesC8& aCertHash );
+        
+        void GetCertIDL( const TDesC8& aCertHash, TInt& aCertID );
+        
+        void DoRemoveL(const TInt& aCertID );
+        
+        void DoGetTrustedSitesL( const TInt& aCertID, RPointerArray<HBufC>& aListOfSites);   
+        
+        const TSecurityPolicy& AddRemovePolicy() const;
+        
+        const TSecurityPolicy& ReadPolicy() const;
+        
+        void DoOverWriteOutOfDateL( const TDesC& aSite, const TBool& aOutOfDateAllowed );
+        
+        void DoOverWriteCertL( const TDesC& aSiteName, const TDesC8& aCertHash );
+
+        void DoAddForgivenSiteL(const TDesC& aSite, const TBool& aOutOfDateAllowed, const TUint32& aUID );
+        
+        TBool IsForgivenSiteAlreadyL(const TDesC& aSite );
+
+    private:
+        
+        // Conduit for marshalling/unmarshalling client communications
+        CTrustedSitesConduit* iConduit;
+        
+        RFs iFs;
+        
+        RDbNamedDatabase iDatabase;
+        
+        CDevTokenServer* iServer; //not owned
+    };
+
+#endif //_TRUSTEDSITESSERVER_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/TrustedSitesSession.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of TrustedSitesSession
+*
+*/
+
+
+
+#ifndef __TRUSTEDSITESSESSION_H__
+#define __TRUSTEDSITESSESSION_H__
+
+#include "DevTokenServer.h"
+
+class RMessage2;
+class CTrustedSitesConduit;
+
+/**
+ * trusted sites session
+ *
+ * The class implementes in the server side to
+ * handle the trust site session
+ * 
+ *  @lib 
+ *  @since S60 v3.2
+ */
+class CTrustedSitesSession : public CDevTokenServerSession
+    {
+    public:
+    
+        static CTrustedSitesSession* NewL(CTrustedSitesConduit& aConduit);
+
+    private:
+    
+        CTrustedSitesSession(CTrustedSitesConduit& aConduit);
+    
+        virtual void DoServiceL(const RMessage2& aMessage);
+
+    private:
+    
+        CTrustedSitesConduit& iConduit;
+    };
+
+#endif //__TRUSTEDSITESSESSION_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Inc/TrustedSitesStore.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,127 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   The header file of TrustedSitesStore
+*
+*/
+
+
+
+#ifndef __TRUSTEDSITESSTORE_H__
+#define __TRUSTEDSITESSTORE_H__
+
+#include <e32base.h>
+
+class RDevTokenClientSession;
+
+/**
+ * Handle trusted sites store
+ *
+ * The class implementes the interface to handle the trust sites store.
+ * Trusted sites are stored associated with certificates, which means for this
+ * site the attached certificate is trusted.
+ * 
+ *  @lib DevTokenClient.dll
+ *  @since S60 v3.2
+ */
+class CTrustSitesStore : public CBase
+    {
+    public:  
+        IMPORT_C static CTrustSitesStore* NewL();
+        IMPORT_C virtual ~CTrustSitesStore();
+
+    public: // New functions
+
+        /**
+         * add new trust record to trust site store
+         *
+         * @param aCert a certificate
+         * @param aSiteName trusted site name
+         * @return 
+         */
+        IMPORT_C TInt AddL( const TDesC8& aCert, const TDesC& aTrustedSite );
+        
+        
+        /**
+         * add forgiven site 
+         *
+         * @param aSite the untrusted certificate from this site is allowed
+         * @param aIsOutOfDateAllowed outofdate certificate is allowed 
+         * @return 
+         */
+        IMPORT_C TInt AddForgivenSiteL( const TDesC& aSite, const TBool& aIsOutOfDateAllowed );        
+        
+        /**
+         * Remove forgiven sites set by this client 
+         *
+         * @param aSite, empty then remove all of the forgiven sites set by the client
+         *               otherwise, remove the given site from forgiven site list
+         * @return 
+         */
+        IMPORT_C TInt RemoveForgivenSiteL( const TDesC& aSite = KNullDesC );
+        
+        
+        /**
+         * check whether the given cert is trusted for the given site
+         *
+         * @param aCert a certificate
+         * @param aSiteName trusted site name
+         * @return ETrue /EFalse
+         */
+        IMPORT_C TBool IsTrustedSiteL( const TDesC8& aCert, const TDesC& aTrustedSite );
+        
+        /**
+         * check whether out of date certificate is allowed for this site
+         *
+         * @param aCertificate 
+         * @param aTrustedSite 
+         * @return ETrue/EFalse
+         */
+        IMPORT_C TBool IsOutOfDateAllowedL( const TDesC8& aCertificate, const TDesC& aTrustedSite );
+        
+        /**
+         * list all of the sites for which the cert is trusted
+         *
+         * @param aCert a certificate
+         * @param aListOfSites trusted sites' name
+         * @param aMessage IPC message
+         * @return ETrue /EFalse
+         */
+        IMPORT_C TInt GetTrustedSitesL( const TDesC8& aCert, RPointerArray<HBufC>& aListOfSites );
+
+    private:
+        
+        CTrustSitesStore();
+        
+        void ConstructL();
+        
+        void FreeRequestBuffer();
+        
+        TInt AllocRequestBuffer(TInt aReqdSize);
+        
+        void SendSyncRequestAndHandleOverflowL(TInt aInitialBufSize,
+                                               const TIpcArgs& aArgs);
+
+    private:
+        
+        RDevTokenClientSession* iClientSession;
+        
+        HBufC8* iRequestDataBuf;    
+        
+        TPtr8 iRequestPtr;
+    };
+
+#endif //__TRUSTEDSITESSTORE_H__
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Certstore/DevECOMPlugin/DevTokenDevCertStorePlugin.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,69 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenDevCertStorePlugin
+*
+*/
+
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include <mctcertstore.h>
+#include <ct.h>
+#include "DevTokenImplementationUID.hrh"
+#include "DevTokenType.h"
+
+static CCTTokenType* NewFunctionL();
+
+// ======== LOCAL FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CCTTokenType* NewFunctionL()
+// ---------------------------------------------------------------------------
+//
+CCTTokenType* NewFunctionL()
+    {
+    CCTTokenType* DevCertStore = NULL;
+    //Implementation UID of Device Token KeyStore
+    TUid uid;
+    uid.iUid = DEVCERTSTORE_IMPLEMENTATION_UID;
+    DevCertStore = CDevTokenType::NewL( uid );
+    return ( DevCertStore );
+    }
+
+
+// -----------------------------------------------------------------------------
+// TImplementationProxy ImplementationTable[] 
+// -----------------------------------------------------------------------------
+//
+const TImplementationProxy ImplementationTable[] =
+    {
+    IMPLEMENTATION_PROXY_ENTRY( DEVCERTSTORE_IMPLEMENTATION_UID, NewFunctionL )
+    };
+
+
+// -----------------------------------------------------------------------------
+// TImplementationProxy* ImplementationGroupProxy()
+// This function is needed by ECom and is the only one exported function
+// -----------------------------------------------------------------------------
+//
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt& aTableCount )
+    {
+    aTableCount = sizeof( ImplementationTable) / sizeof( TImplementationProxy );
+    return ( ImplementationTable );
+    }
+
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Certstore/TruSrvECOMPlugin/DevTokenTruSrvCertStorePlugin.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,68 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevandTruSrvCertStorePlugin
+*
+*/
+
+
+
+#include <e32std.h>
+#include <implementationproxy.h>
+#include <mctcertstore.h>
+#include <ct.h>
+#include "DevTokenImplementationUID.hrh"
+#include "DevTokenType.h"
+
+static CCTTokenType* NewFunctionL();
+
+// ======== LOCAL FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CCTTokenType* NewFunctionL()
+// ---------------------------------------------------------------------------
+//
+CCTTokenType* NewFunctionL()
+    {
+    CCTTokenType* TruSrvCertStore = NULL;
+    //Implementation UID of Trust Server Certstore
+    TUid uid;
+    uid.iUid = TRUSRVCERTSTORE_IMPLEMENTATION_UID;
+    TruSrvCertStore = CDevTokenType::NewL( uid );
+    return ( TruSrvCertStore );
+    }
+
+
+// -----------------------------------------------------------------------------
+// TImplementationProxy ImplementationTable[] 
+// -----------------------------------------------------------------------------
+//
+const TImplementationProxy ImplementationTable[] =
+    {
+    IMPLEMENTATION_PROXY_ENTRY( TRUSRVCERTSTORE_IMPLEMENTATION_UID, NewFunctionL )
+    };
+
+
+// -----------------------------------------------------------------------------
+// TImplementationProxy* ImplementationGroupProxy()
+// This function is needed by ECom and is the only one exported function
+// -----------------------------------------------------------------------------
+//
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt& aTableCount )
+    {
+    aTableCount = sizeof( ImplementationTable) / sizeof( TImplementationProxy );
+    return ( ImplementationTable );
+    }
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Certstore/client/DevandTruSrvCertStore.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,696 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevandTruSrvCertStore
+*
+*/
+
+
+
+#include "DevandTruSrvCertStore.h"
+#include "DevTokenType.h"
+#include "DevToken.h"
+#include "DevTokenUtils.h"
+#include "DevTokenImplementationUID.hrh"
+
+// This is sized for roughly five cert infos, to ensure that the overflow
+// mechanism gets tested.
+const TInt KDefaultBufferSize = 256;
+
+// ======== MEMBER FUNCTIONS ========
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::NewWritableInterfaceL()
+// -----------------------------------------------------------------------------
+//
+MCTTokenInterface* CDevandTruSrvCertStore::NewWritableInterfaceL(MCTToken& aToken, 
+                         RDevTokenClientSession& aClient)
+    {
+    // Destroyed by MCTTokenInterface::DoRelease() (no refcounting)
+    CDevandTruSrvCertStore* me = new (ELeave) CDevandTruSrvCertStore(KInterfaceWritableCertStore, 
+                                                                     aToken, 
+                                                                     aClient);
+    CleanupStack::PushL(me);
+    me->ConstructL();
+    CleanupStack::Pop(me);
+    return (me);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::NewReadableInterfaceL()
+// -----------------------------------------------------------------------------
+//
+MCTTokenInterface* CDevandTruSrvCertStore::NewReadableInterfaceL(MCTToken& aToken, 
+                         RDevTokenClientSession& aClient)
+    {
+    // Destroyed by MCTTokenInterface::DoRelease() (no refcounting)
+    CDevandTruSrvCertStore* me = new (ELeave) CDevandTruSrvCertStore(KInterfaceCertStore,
+                                                                     aToken, 
+                                                                     aClient);
+    CleanupStack::PushL(me);
+    me->ConstructL();
+    CleanupStack::Pop(me);
+    return (me);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::CDevandTruSrvCertStore()
+// -----------------------------------------------------------------------------
+//
+CDevandTruSrvCertStore::CDevandTruSrvCertStore(TInt aUID,
+                                               MCTToken& aToken, 
+                                               RDevTokenClientSession& aClient) :
+    CDTClient(aUID, aToken, aClient)  
+    {
+    iFilter = NULL;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::~CDevandTruSrvCertStore()
+// -----------------------------------------------------------------------------
+//
+CDevandTruSrvCertStore::~CDevandTruSrvCertStore()
+    {
+    if( iFilter )
+        {
+    	delete iFilter;
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::ConstructL()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::ConstructL()
+    {
+    CActiveScheduler::Add(this);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::DoRelease()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::DoRelease()
+    {
+    MCTTokenInterface::DoRelease();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::Token()
+// -----------------------------------------------------------------------------
+//
+MCTToken& CDevandTruSrvCertStore::Token()
+    {
+    return iToken;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::RunL()
+// -----------------------------------------------------------------------------
+//  
+void CDevandTruSrvCertStore::RunL()
+    {
+    // Never active, so should never get called
+    DevTokenPanic(ENoRequestOutstanding);
+    }
+
+
+//MCTCertStore 
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::List()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::List(RMPointerArray<CCTCertInfo>& aCerts, 
+                                  const CCertAttributeFilter& aFilter,
+                                  TRequestStatus& aStatus)
+    {
+    CDevToken* token = static_cast<CDevToken*>( &iToken ); 
+    
+    CDevTokenType* tokenType = static_cast<CDevTokenType*>( &(token->TokenType()) );
+    
+    if ( tokenType->iUid.iUid == DEVCERTSTORE_IMPLEMENTATION_UID )
+        {
+        if (aFilter.iOwnerType != EUserCertificate)
+            {
+            if( aFilter.iOwnerTypeIsSet )
+                {
+                TRequestStatus* status = &aStatus;
+                User::RequestComplete( status, KErrNone );
+                return;	
+                }
+            //If the owner type is not set, we create a filter and 
+            // set the type to EUserCertificate    
+            else
+                {
+                //alway use new filter.
+                if( iFilter )
+                    {
+                	delete iFilter;
+                	iFilter = NULL;
+                    }
+                TRAPD( err, iFilter = CCertAttributeFilter::NewL() );	
+                if ( err != KErrNone )    
+                    {
+                    TRequestStatus* status = &aStatus;
+                    User::RequestComplete( status, err ); 
+                    return;	
+                	  }
+                
+                CopyFilter( iFilter, aFilter );
+                //Set owner type to user certificate
+                iFilter->SetOwnerType( EUserCertificate );
+                
+                TRAPD(r, DoListL(aCerts, *iFilter));
+                FreeRequestBuffer();
+                TRequestStatus* status = &aStatus;
+                User::RequestComplete(status, r); 
+                return;
+                }
+            }
+        }
+    else if ( tokenType->iUid.iUid == TRUSRVCERTSTORE_IMPLEMENTATION_UID )
+        {
+        if (aFilter.iOwnerType != EPeerCertificate)
+            {
+            if( aFilter.iOwnerTypeIsSet )
+                {
+                TRequestStatus* status = &aStatus;
+                User::RequestComplete( status, KErrNone );
+                return;	
+                }
+            //If the owner type is not set, we create a filter and 
+            // set the type to EPeerCertificate      
+            else
+                {
+                if( iFilter )
+                    {
+                	delete iFilter;
+                	iFilter = NULL;
+                    }
+                    
+                TRAPD( er, iFilter = CCertAttributeFilter::NewL() );	
+                if ( er != KErrNone )    
+                    {
+                    TRequestStatus* status = &aStatus;
+                    User::RequestComplete( status, er ); 
+                    return;	
+                	  }    
+
+                CopyFilter( iFilter, aFilter );
+                
+                iFilter->SetOwnerType( EPeerCertificate );
+                TRAPD(r, DoListL(aCerts, *iFilter));
+                FreeRequestBuffer();
+                TRequestStatus* status = &aStatus;
+                User::RequestComplete(status, r); 
+                return;	
+                }
+            }
+        }
+    else
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete( status, KErrNone );  
+        return; 
+        }    
+
+    TRAPD(r, DoListL(aCerts, aFilter));
+    FreeRequestBuffer();
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, r); 
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::CopyFilterL()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::CopyFilter( CCertAttributeFilter* aDesFilter, const CCertAttributeFilter& aSrcFilter )
+    {
+    if ( aSrcFilter.iLabelIsSet )
+        {
+    	aDesFilter->SetLabel( aSrcFilter.iLabel );
+        }
+
+	if ( aSrcFilter.iUidIsSet )
+	    {
+		aDesFilter->SetUid( aSrcFilter.iUid );
+	    }
+
+	if ( aSrcFilter.iFormatIsSet )
+	    {
+		aDesFilter->SetFormat( aSrcFilter.iFormat );
+	    }
+
+	if ( aSrcFilter.iOwnerTypeIsSet )
+	    {
+		aDesFilter->SetOwnerType( aSrcFilter.iOwnerType );
+	    }
+	
+
+	if ( aSrcFilter.iSubjectKeyIdIsSet )
+	   {
+	   aDesFilter->SetSubjectKeyId( aSrcFilter.iSubjectKeyId );	
+	   }
+
+	if ( aSrcFilter.iIssuerKeyIdIsSet )
+	    {
+		aDesFilter->SetIssuerKeyId( aSrcFilter.iIssuerKeyId );
+	    }
+	    
+    aDesFilter->SetKeyUsage( aSrcFilter.iKeyUsage );    
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::DoListL()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::DoListL(RMPointerArray<CCTCertInfo>& aCerts, 
+                 const CCertAttributeFilter& aFilter)
+    {
+    HBufC8* filterBuf = HBufC8::NewLC(DevTokenDataMarshaller::Size(aFilter));
+    TPtr8 ptr(filterBuf->Des());
+    DevTokenDataMarshaller::WriteL(aFilter, ptr);
+    TIpcArgs args(0, filterBuf, 0, &iRequestPtr);
+    SendSyncRequestAndHandleOverflowL(EListCerts, KDefaultBufferSize, args);
+    CleanupStack::PopAndDestroy(filterBuf);
+    DevTokenDataMarshaller::ReadL(iRequestPtr, iToken, aCerts);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::CancelList()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::CancelList()
+    {
+    // synchronous, nothing to do
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::GetCert()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::GetCert(CCTCertInfo*& aCertInfo, 
+                                     const TCTTokenObjectHandle& aHandle,
+                                     TRequestStatus& aStatus)
+    {
+    TRAPD(r, DoGetCertL(aCertInfo, aHandle));
+    FreeRequestBuffer();
+    TRequestStatus* stat = &aStatus;
+    User::RequestComplete(stat, r); 
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::DoGetCertL()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::DoGetCertL(CCTCertInfo*& aCertInfo, 
+                                        const TCTTokenObjectHandle& aHandle)
+    {
+    User::LeaveIfError(AllocRequestBuffer(sizeof(CCTCertInfo))); // assumes serialized size <= sizeof class
+    TIpcArgs args(aHandle.iObjectId, 0, 0, &iRequestPtr);
+    User::LeaveIfError(iClientSession.SendRequest(EGetCert, args));
+    DevTokenDataMarshaller::ReadL(iRequestPtr, iToken, aCertInfo);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::CancelGetCert()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::CancelGetCert()
+    {
+    // synchronous, nothing to do
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::Applications()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::Applications(const CCTCertInfo& aCertInfo, 
+                                          RArray<TUid>& aApplications,
+                                          TRequestStatus& aStatus)
+    {
+    TRAPD(r, DoApplicationsL(aCertInfo, aApplications));
+    FreeRequestBuffer();
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, r); 
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::DoApplicationsL()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::DoApplicationsL(const CCTCertInfo& aCertInfo, 
+                                             RArray<TUid>& aApplications)
+    {
+    TIpcArgs args(aCertInfo.Handle().iObjectId, 0, 0, &iRequestPtr);
+    SendSyncRequestAndHandleOverflowL(EApplications, KDefaultBufferSize, args);
+    DevTokenDataMarshaller::ReadL(iRequestPtr, aApplications);        
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::CancelApplications()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::CancelApplications()
+    {
+    // synchronous, nothing to do
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::IsApplicable()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::IsApplicable(const CCTCertInfo& aCertInfo, TUid aApplication, 
+                    TBool& aIsApplicable, TRequestStatus& aStatus)
+    {
+    TIpcArgs args(aCertInfo.Handle().iObjectId, 0, aApplication.iUid);
+    TInt r = iClientSession.SendRequest(EIsApplicable, args); 
+    if (r >= 0)
+        {
+        aIsApplicable = !!r;  // Convert TInt to TBool
+        r = KErrNone;
+        }
+
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, r); 
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::CancelIsApplicable()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::CancelIsApplicable()
+    {
+    // synchronous, nothing to do
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::Trusted()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::Trusted(const CCTCertInfo& aCertInfo, TBool& aTrusted, 
+                 TRequestStatus& aStatus)
+    {
+    TIpcArgs args(aCertInfo.Handle().iObjectId);
+    TInt r = iClientSession.SendRequest(ETrusted, args);  
+    if (r >= 0)
+        {
+        aTrusted = !!r;  // Convert TInt to TBool
+        r = KErrNone;
+        }
+
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, r); 
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::CancelTrusted()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::CancelTrusted()
+    {
+    // synchronous, nothing to do
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::Retrieve()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::Retrieve(const CCTCertInfo& aCertInfo, TDes8& aEncodedCert,
+                  TRequestStatus& aStatus)
+    {
+    TInt err = DoRetrieve(aCertInfo, aEncodedCert);
+    FreeRequestBuffer();
+    TRequestStatus* stat = &aStatus;
+    User::RequestComplete(stat, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::DoRetrieve()
+// -----------------------------------------------------------------------------
+//
+TInt CDevandTruSrvCertStore::DoRetrieve(const CCTCertInfo& aCertInfo, TDes8& aEncodedCert)
+    {
+    if (aCertInfo.Size() <= 0)
+        {
+        return KErrArgument;
+        }
+
+    if (aEncodedCert.MaxSize() < aCertInfo.Size())
+        {
+        return KErrOverflow;
+        }
+
+    TInt r = AllocRequestBuffer(aEncodedCert.MaxSize());  
+    if (KErrNone!=r)
+        {
+        return r;
+        }
+
+    TIpcArgs args(aCertInfo.Handle().iObjectId, 0, 0, &iRequestPtr);
+    r = iClientSession.SendRequest(ERetrieve, args);
+    if (r == KErrNone)
+        {
+        aEncodedCert.Copy(iRequestPtr);
+        }
+
+    return r;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::CancelRetrieve()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::CancelRetrieve()
+    {
+    // synchronous, nothing to do
+    }
+
+
+//  MCTWritableCertStore interface
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::Add()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::Add(const TDesC& aLabel, TCertificateFormat aFormat,
+               TCertificateOwnerType aCertificateOwnerType, 
+               const TKeyIdentifier* aSubjectKeyId, const TKeyIdentifier* aIssuerKeyId,
+               const TDesC8& aCert, TRequestStatus& aStatus)
+    {
+    Add(aLabel, aFormat, aCertificateOwnerType, aSubjectKeyId, aIssuerKeyId, aCert, 
+    ETrue, aStatus);
+    } 
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::Add()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::Add(const TDesC& aLabel, TCertificateFormat aFormat,
+               TCertificateOwnerType aCertificateOwnerType, 
+               const TKeyIdentifier* aSubjectKeyId, const TKeyIdentifier* aIssuerKeyId,
+               const TDesC8& aCert, const TBool aDeletable,
+               TRequestStatus& aStatus)
+    {
+    CDevToken* token = static_cast<CDevToken*>( &iToken ); 
+
+    CDevTokenType* tokenType = static_cast<CDevTokenType*>( &(token->TokenType()) );
+
+    if ( tokenType->iUid.iUid == DEVCERTSTORE_IMPLEMENTATION_UID )
+        {
+        if (aCertificateOwnerType != EUserCertificate)
+            {
+            TRequestStatus* status = &aStatus;
+            User::RequestComplete( status, KErrArgument );  
+            return; 
+            }
+        }
+    else if ( tokenType->iUid.iUid == TRUSRVCERTSTORE_IMPLEMENTATION_UID )
+        {
+        if (aCertificateOwnerType != EPeerCertificate)
+            {
+            TRequestStatus* status = &aStatus;
+            User::RequestComplete( status, KErrArgument );  
+            return; 
+            }
+        }
+    else
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete( status, KErrArgument );  
+        return; 
+        } 
+
+
+    TRequestStatus* stat = &aStatus;
+    if (aLabel.Length() > KMaxCertLabelLength)
+        {
+        //  Too long to be a label
+        User::RequestComplete(stat, KErrOverflow);
+        return;
+        }
+
+    TPckgBuf<TDevTokenAddCertDataStruct> data;
+    data().iLabel.Zero();
+    data().iSubjectKeyId.Zero();
+    data().iIssuerKeyId.Zero();   
+    data().iLabel.Copy(aLabel);   
+    data().iFormat = aFormat;
+    data().iCertificateOwnerType = aCertificateOwnerType;
+    if (aSubjectKeyId)
+        {
+        data().iSubjectKeyId.Copy(*aSubjectKeyId);
+        }
+    if (aIssuerKeyId)
+        {
+        data().iIssuerKeyId.Copy(*aIssuerKeyId);
+        }
+    data().iDeletable = aDeletable;
+
+    TInt r = AllocRequestBuffer(aCert.Size());
+
+    if (r!=KErrNone)
+        {
+        User::RequestComplete(stat, r);
+        return;
+        }
+
+    iRequestPtr.FillZ();
+    iRequestPtr.Copy(aCert);
+
+    TIpcArgs args(0, &data, 0, &iRequestPtr);
+    r = iClientSession.SendRequest(EAddCert, args);
+
+    FreeRequestBuffer();
+    User::RequestComplete(stat, r);
+    } 
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::CancelAdd()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::CancelAdd()
+    {
+    // synchronous, nothing to do
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::Remove()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::Remove(const CCTCertInfo& aCertInfo, TRequestStatus& aStatus)
+    {
+    TIpcArgs args(aCertInfo.Handle().iObjectId);
+    TInt r = iClientSession.SendRequest(ERemoveCert, args); 
+    TRequestStatus* stat = &aStatus;
+    User::RequestComplete(stat, r);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::CancelRemove()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::CancelRemove()
+    {
+    // synchronous, nothing to do
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::SetApplicability()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::SetApplicability(const CCTCertInfo& aCertInfo, 
+                      const RArray<TUid>& aApplications,
+                      TRequestStatus &aStatus)
+    {
+    TInt r = AllocRequestBuffer(DevTokenDataMarshaller::Size(aApplications));
+    if (r != KErrNone)
+        {
+        TRequestStatus* stat = &aStatus;
+        User::RequestComplete(stat, r);
+        return;
+        }
+    DevTokenDataMarshaller::Write(aApplications, iRequestPtr);
+
+    TIpcArgs args(aCertInfo.Handle().iObjectId, 0, &iRequestPtr);
+    TInt err = iClientSession.SendRequest(ESetApplicability, args);
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::CancelSetApplicability()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::CancelSetApplicability()
+    {
+    // synchronous, nothing to do
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::SetTrust()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::SetTrust(const CCTCertInfo& aCertInfo,
+                  TBool aTrusted, 
+                  TRequestStatus& aStatus)
+    {
+    TIpcArgs args(aCertInfo.Handle().iObjectId, 0, aTrusted);
+    TInt err = iClientSession.SendRequest(ESetTrust, args);
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevandTruSrvCertStore::CancelSetTrust()
+// -----------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStore::CancelSetTrust()
+    {
+    // synchronous, nothing to do
+    }
+    
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Certstore/server/DevandTruSrvCertStoreConduit.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,337 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevandTruSrvCertStoreConduit
+*
+*/
+
+
+
+#include "DevandTruSrvCertStoreConduit.h"
+#include "DevandTruSrvCertStoreServer.h"
+#include "DevTokenMarshaller.h"
+#include "DevTokenUtil.h"
+#include "DevTokenDataTypes.h"
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::NewL()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreConduit* CDevandTruSrvCertStoreConduit::NewL(CDevandTruSrvCertStoreServer& aServer)
+    {
+    return new (ELeave) CDevandTruSrvCertStoreConduit(aServer);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::CDevandTruSrvCertStoreConduit()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreConduit::CDevandTruSrvCertStoreConduit(CDevandTruSrvCertStoreServer& aServer) :
+  iServer(aServer)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::~CDevandTruSrvCertStoreConduit()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreConduit::~CDevandTruSrvCertStoreConduit()
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::AllocResponseBufferLC()
+// Allocate a buffer for the externalised response - this is then copied into
+// the client's buffer.
+//
+// This also checks that the client's buffer is big enough (this is assumed to
+// be in message slot 3).  If the client buffer isn't big enough, the required
+// length is passed back in the first word of the buffer and the method leaves
+// with KErrOverflow.
+// ---------------------------------------------------------------------------
+// 
+HBufC8* CDevandTruSrvCertStoreConduit::AllocResponseBufferLC(TInt aSize, const RMessage2& aMessage)
+    {
+    TInt writeBufLen = aMessage.GetDesLengthL(3);
+
+    if (aSize > writeBufLen)
+        {
+        TPckg<TInt> theRequiredLength(aSize);
+        aMessage.WriteL(3, theRequiredLength);
+        User::Leave(KErrOverflow);
+        }
+
+    HBufC8* result = HBufC8::NewMaxLC(aSize);
+    TPtr8 ptr = result->Des();
+    ptr.FillZ();
+
+    return result;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::ServiceCertStoreRequestL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreConduit::ServiceCertStoreRequestL(const RMessage2& aMessage)
+    {
+    TDevTokenMessages request = (TDevTokenMessages) aMessage.Function();
+    TInt result = KErrNone;
+
+    switch (request)
+        {
+        case EListCerts:
+            ListCertsL(aMessage);   
+            break;
+
+        case EGetCert:
+            GetCertL(aMessage);     
+            break;
+
+        case EApplications:
+            ApplicationsL(aMessage);  
+            break;
+
+        case EIsApplicable:
+            result = IsApplicableL(aMessage); 
+            break;
+
+        case ETrusted:
+            result = TrustedL(aMessage);      
+            break;
+
+        case ERetrieve:
+            RetrieveL(aMessage);    
+            break;
+
+        case EAddCert:
+            AddCertL(aMessage);     
+            break;
+
+        case ERemoveCert:
+            RemoveCertL(aMessage);    
+            break;
+
+        case ESetApplicability:
+            SetApplicabilityL(aMessage);
+            break;
+
+        case ESetTrust:
+            SetTrustL(aMessage);
+            break;
+
+        default:
+            // Client made an illegal request
+            PanicClient(aMessage, EPanicInvalidRequest);
+            return;
+        }
+
+    aMessage.Complete(result);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::ListCertsL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreConduit::ListCertsL(const RMessage2& aMessage)
+    {
+    // p[1] has filter as set by the client
+
+    TInt bufLength = aMessage.GetDesLengthL(1);
+    HBufC8* certFilterBuf = HBufC8::NewMaxLC(bufLength);
+    TPtr8 ptr(certFilterBuf->Des());  
+    aMessage.ReadL(1, ptr);
+    CCertAttributeFilter* certFilter = NULL;
+    DevTokenDataMarshaller::ReadL(*certFilterBuf, certFilter);
+    CleanupStack::PopAndDestroy(certFilterBuf);
+    CleanupStack::PushL(certFilter);
+
+    RPointerArray<CDevTokenCertInfo> certs;
+    CleanupClosePushL(certs);
+    iServer.ListL(*certFilter, certs, aMessage, EFalse );
+
+    HBufC8* clientBuffer = AllocResponseBufferLC(DevTokenDataMarshaller::Size(certs), aMessage);  
+    TPtr8 theData(clientBuffer->Des());
+    DevTokenDataMarshaller::Write(certs, theData);
+    aMessage.WriteL(3, theData);
+    CleanupStack::PopAndDestroy(3, certFilter);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::GetCertL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreConduit::GetCertL(const RMessage2& aMessage)
+    {
+    // p[0] is the cert handle
+
+    const CDevTokenCertInfo& certInfo = iServer.GetCertL(aMessage.Int0());
+
+    HBufC8* clientBuffer = AllocResponseBufferLC(DevTokenDataMarshaller::Size(certInfo), aMessage); 
+    TPtr8 ptr(clientBuffer->Des());
+    DevTokenDataMarshaller::Write(certInfo, ptr);
+    aMessage.WriteL(3, ptr);
+    CleanupStack::PopAndDestroy(clientBuffer);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::ApplicationsL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreConduit::ApplicationsL(const RMessage2& aMessage)
+    {
+    // p[0] is the cert handle
+
+    const RArray<TUid>& apps = iServer.ApplicationsL(aMessage.Int0());
+
+    HBufC8* clientBuffer = AllocResponseBufferLC(DevTokenDataMarshaller::Size(apps), aMessage); 
+    TPtr8 outPtr(clientBuffer->Des());
+    DevTokenDataMarshaller::Write(apps, outPtr);
+    aMessage.WriteL(3, outPtr);
+    CleanupStack::PopAndDestroy(clientBuffer);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::IsApplicableL()
+// ---------------------------------------------------------------------------
+//
+TInt CDevandTruSrvCertStoreConduit::IsApplicableL(const RMessage2& aMessage)
+    {
+    // p[0] is the cert handle
+    // p[2] is the UID
+    // p[3] to return the applicability bool
+
+        TUid uid = { aMessage.Int2() };
+    TBool result = iServer.IsApplicableL(aMessage.Int0(), uid);
+    return result ? 1 : 0;  // Convert TBool to TInt
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::TrustedL()
+// ---------------------------------------------------------------------------
+//
+TInt CDevandTruSrvCertStoreConduit::TrustedL(const RMessage2& aMessage)
+    {
+    //  p[1] has CCertInfo in question, p[2] to return the trusted bool
+
+    TBool result = iServer.TrustedL(aMessage.Int0()); 
+    return result ? 1 : 0;  // Convert TBool to TInt
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::RetrieveL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreConduit::RetrieveL(const RMessage2& aMessage)
+    {
+    // p[0] is the cert handle
+    // p[3] the buffer to return the retrieved certificate
+
+    HBufC8* certData = iServer.RetrieveLC(aMessage.Int0(), aMessage, EFalse );
+
+    TInt maxSize = aMessage.GetDesLengthL(3);
+    if (maxSize < certData->Size())
+        {
+        //  Client has passed in a descriptor which is too short
+        User::Leave(KErrOverflow);
+        }
+
+    aMessage.WriteL(3, *certData);
+    CleanupStack::PopAndDestroy(certData);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::AddCertL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreConduit::AddCertL(const RMessage2& aMessage)
+    {
+    //  p[1] has TDevTokenAddCertDataStruct, p[3] has certificate data
+    TPckgBuf<TDevTokenAddCertDataStruct> data;
+    aMessage.ReadL(1, data);
+
+    TInt maxSize = aMessage.GetDesLengthL(3);
+    HBufC8* certData = HBufC8::NewMaxLC(maxSize);
+    TPtr8 ptr(certData->Des());
+    ptr.FillZ();
+    aMessage.ReadL(3, ptr);
+
+    iServer.AddL(data(), *certData, aMessage, EFalse );
+
+    CleanupStack::PopAndDestroy(certData);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::RemoveCertL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreConduit::RemoveCertL(const RMessage2& aMessage)
+    {
+    // p[0] is the cert handle
+
+    iServer.RemoveL(aMessage.Int0(), aMessage, EFalse );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::SetApplicabilityL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreConduit::SetApplicabilityL(const RMessage2& aMessage)
+    {
+    // p[0] is the cert handle
+    // p[2] the array of UIDs
+
+    TInt bufLen = aMessage.GetDesLengthL(2);
+    HBufC8* buf = HBufC8::NewLC(bufLen);
+    TPtr8 bufPtr(buf->Des());
+    aMessage.ReadL(2, bufPtr);
+
+    RArray<TUid> apps;
+    CleanupClosePushL(apps);
+    DevTokenDataMarshaller::ReadL(*buf, apps);
+
+    iServer.SetApplicabilityL(aMessage.Int0(), apps, aMessage);
+    CleanupStack::PopAndDestroy(2, buf);  
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreConduit::SetTrustL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreConduit::SetTrustL(const RMessage2& aMessage)
+    {
+    // p[0] is the cert handle
+    // p[2] the trust setting
+
+    TBool trusted = !!aMessage.Int2();    
+    iServer.SetTrustL(aMessage.Int0(), trusted, aMessage);
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Certstore/server/DevandTruSrvCertStoreEntry.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,199 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevandTruSrvCertStoreEntry
+*
+*/
+
+
+
+#include "DevandTruSrvCertStoreEntry.h"
+#include "DevTokenDataTypes.h"
+#include "DevTokenUtil.h"
+
+
+// ======== MEMBER FUNCTIONS ========
+
+//CDevandTruSrvCertStoreEntry
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntry::NewL()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreEntry* CDevandTruSrvCertStoreEntry::NewL(const CDevTokenCertInfo& aCertInfo,
+                     RArray<TUid> aCertificateApps,
+                     TBool aTrusted,
+                     TStreamId aDataStreamId)
+    {
+    CDevandTruSrvCertStoreEntry* self = new(ELeave) CDevandTruSrvCertStoreEntry();
+    CleanupStack::PushL(self);
+    self->ConstructL(aCertInfo, aCertificateApps, aTrusted, aDataStreamId);
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntry::NewLC()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreEntry* CDevandTruSrvCertStoreEntry::NewLC(RReadStream& aStream)
+    {
+    CDevandTruSrvCertStoreEntry* self = new(ELeave) CDevandTruSrvCertStoreEntry();
+    CleanupStack::PushL(self);
+    self->InternalizeL(aStream);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntry::CDevandTruSrvCertStoreEntry()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreEntry::CDevandTruSrvCertStoreEntry()
+    { 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntry::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreEntry::ConstructL(const CDevTokenCertInfo& aCertInfo,
+                 RArray<TUid> aCertificateApps,
+                 TBool aTrusted,
+                 TStreamId aDataStreamId)
+    {
+    assert(aDataStreamId != KNullStreamId, EPanicCertStoreEntryConstructArguments);
+
+    iCertInfo = CDevTokenCertInfo::NewL(aCertInfo);
+
+    for (TInt i = 0 ; i < aCertificateApps.Count() ; ++i)
+        {
+        User::LeaveIfError(iCertificateApps.Append(aCertificateApps[i]));
+        }
+
+    iTrusted = aTrusted;  
+    iDataStreamId = aDataStreamId;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntry::~CDevandTruSrvCertStoreEntry()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreEntry::~CDevandTruSrvCertStoreEntry()
+    {
+    delete iCertInfo;
+    iCertificateApps.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntry::ExternalizeL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreEntry::ExternalizeL(RWriteStream& aStream) const
+    {
+    aStream << *iCertInfo;
+    TInt count = iCertificateApps.Count();
+    aStream.WriteInt32L(count);
+    for (TInt i = 0 ; i < count ; ++i)
+        {
+        aStream << iCertificateApps[i];
+        }
+    aStream.WriteUint8L(iTrusted);
+    aStream << iDataStreamId;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntry::InternalizeL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreEntry::InternalizeL(RReadStream& aStream)
+    {
+    assert(!iCertInfo, EPanicCertStoreEntryInternalizeState);
+    iCertInfo = CDevTokenCertInfo::NewL(aStream);
+
+    TInt count = aStream.ReadInt32L();
+    for (TInt i = 0 ; i < count ; ++i)
+        {
+        TUid id;
+        aStream >> id;
+        User::LeaveIfError(iCertificateApps.Append(id));
+        }
+
+    iTrusted = !!aStream.ReadUint8L();
+    aStream >> iDataStreamId;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntry::CertInfo()
+// ---------------------------------------------------------------------------
+//
+const CDevTokenCertInfo& CDevandTruSrvCertStoreEntry::CertInfo() const
+    {
+    return *iCertInfo;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntry::CertificateApps()
+// ---------------------------------------------------------------------------
+//
+const RArray<TUid>& CDevandTruSrvCertStoreEntry::CertificateApps() const
+    {
+    return iCertificateApps;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntry::IsApplicable()
+// ---------------------------------------------------------------------------
+//
+TBool CDevandTruSrvCertStoreEntry::IsApplicable(const TUid& aApplication) const
+    {
+    for (TInt i = 0 ; i < iCertificateApps.Count() ; ++i)
+        {
+        if (iCertificateApps[i] == aApplication)
+            {
+            return ETrue;
+            }
+        }
+    return EFalse;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntry::Trusted()
+// ---------------------------------------------------------------------------
+//
+TBool CDevandTruSrvCertStoreEntry::Trusted() const
+    {
+    return iTrusted;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntry::DataStreamId()
+// ---------------------------------------------------------------------------
+//
+TStreamId CDevandTruSrvCertStoreEntry::DataStreamId() const
+    {
+    return iDataStreamId;
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Certstore/server/DevandTruSrvCertStoreEntryList.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,246 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevandTruSrvCertStoreEntryList
+*
+*/
+
+
+
+#include "DevandTruSrvCertStoreEntryList.h"
+#include "DevandTruSrvCertStoreEntry.h"
+#include "DevTokenDataTypes.h"
+#include "DevTokenUtil.h"
+
+
+// ======== MEMBER FUNCTIONS ========
+
+//CDevandTruSrvCertStoreEntryList
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::NewLC()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreEntryList* CDevandTruSrvCertStoreEntryList::NewLC()
+    {
+    CDevandTruSrvCertStoreEntryList* self = new(ELeave) CDevandTruSrvCertStoreEntryList();
+    CleanupStack::PushL(self);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::NewL()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreEntryList* CDevandTruSrvCertStoreEntryList::NewL(RReadStream& aStream)
+    {
+    CDevandTruSrvCertStoreEntryList* self = new(ELeave) CDevandTruSrvCertStoreEntryList();
+    CleanupStack::PushL(self);
+    self->InternalizeL(aStream);
+    CleanupStack::Pop();
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::CDevandTruSrvCertStoreEntryList()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreEntryList::CDevandTruSrvCertStoreEntryList()
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::~CDevandTruSrvCertStoreEntryList()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreEntryList::~CDevandTruSrvCertStoreEntryList()
+    {
+    iEntries.ResetAndDestroy();
+    iEntries.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::ExternalizeL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreEntryList::ExternalizeL(RWriteStream& aStream) const
+    {
+    TInt count = iEntries.Count();
+    aStream.WriteInt32L(count);
+    for (TInt i = 0 ; i < count ; ++i)
+        {
+        aStream << *iEntries[i];
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::InternalizeL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreEntryList::InternalizeL(RReadStream& aStream)
+    {
+    TInt count = aStream.ReadInt32L();
+
+    for (TInt i = 0 ; i < count ; ++i)
+        {
+        CDevandTruSrvCertStoreEntry* entry = CDevandTruSrvCertStoreEntry::NewLC(aStream);
+
+        // Check certificate id is unique
+        TInt handle = entry->CertInfo().CertificateId();
+        if (IndexForHandle(handle) != KErrNotFound)
+            {
+            User::Leave(KErrCorrupt);
+            }
+
+        AppendL(entry);
+        CleanupStack::Pop(entry);   
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::Count()
+// ---------------------------------------------------------------------------
+//
+TInt CDevandTruSrvCertStoreEntryList::Count() const
+    {
+    return iEntries.Count();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::AppendL()
+// ---------------------------------------------------------------------------
+//
+TInt CDevandTruSrvCertStoreEntryList::AppendL(CDevandTruSrvCertStoreEntry* aCertInfo)
+    {
+    assert(aCertInfo, EPanicCertStoreEntryListAppendArguments);
+    User::LeaveIfError(iEntries.Append(aCertInfo));
+    return iEntries.Count() - 1;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::Remove()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreEntry* CDevandTruSrvCertStoreEntryList::Remove(TInt aIndex)
+    {
+    CDevandTruSrvCertStoreEntry* entry = iEntries[aIndex];
+    iEntries.Remove(aIndex);
+    return entry;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::Replace()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreEntry* CDevandTruSrvCertStoreEntryList::Replace(TInt aIndex, CDevandTruSrvCertStoreEntry* aNewEntry)
+    {
+    assert(aNewEntry, EPanicCertStoreEntryListReplaceArguments);
+    CDevandTruSrvCertStoreEntry* entry = iEntries[aIndex];
+    iEntries[aIndex] = aNewEntry;
+    return entry;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::IndexForHandle()
+// ---------------------------------------------------------------------------
+//
+TInt CDevandTruSrvCertStoreEntryList::IndexForHandle(TInt aHandle) const
+    {
+    for (TInt i = 0 ; i < iEntries.Count() ; ++i)
+        {
+        CDevandTruSrvCertStoreEntry* entry = iEntries[i];
+        if (entry->CertInfo().Reference() == aHandle)
+            {
+            return i;
+            }
+        }
+
+    return KErrNotFound;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::LabelExists()
+// ---------------------------------------------------------------------------
+//
+TBool CDevandTruSrvCertStoreEntryList::LabelExists(const TDesC& aLabel) const
+    {
+    for (TInt i = 0 ; i < iEntries.Count() ; ++i)
+        {
+        CDevandTruSrvCertStoreEntry* entry = iEntries[i];
+        if (entry->CertInfo().Label() == aLabel)
+            {
+            return ETrue;
+            }
+        }
+
+    return EFalse;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::GetByIndex()
+// ---------------------------------------------------------------------------
+//
+const CDevandTruSrvCertStoreEntry& CDevandTruSrvCertStoreEntryList::GetByIndex(
+    TInt aIndex) const
+    {
+    return *iEntries[aIndex];
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::GetByHandleL()
+// ---------------------------------------------------------------------------
+//
+const CDevandTruSrvCertStoreEntry& CDevandTruSrvCertStoreEntryList::GetByHandleL(
+    TInt aHandle) const
+    {
+    TInt index = IndexForHandle(aHandle);
+    User::LeaveIfError(index);
+    return GetByIndex(index);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreEntryList::NextFreeHandle()
+// ---------------------------------------------------------------------------
+//
+TInt CDevandTruSrvCertStoreEntryList::NextFreeHandle() const 
+    {
+    TInt count = iEntries.Count();
+    TInt maxHandle = -1;
+    for (TInt i = 0; i < count; i++)
+        {
+        CDevandTruSrvCertStoreEntry* entry = iEntries[i];
+        if (entry->CertInfo().Reference() > maxHandle)
+            {
+            maxHandle = entry->CertInfo().Reference();
+            }
+        }
+
+    return maxHandle + 1;
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Certstore/server/DevandTruSrvCertStoreServer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,684 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevandTruSrvCertStoreServer
+*
+*/
+
+
+#include <ccertattributefilter.h>
+#include <signed.h>
+#include <x509cert.h>
+#include <x509certext.h>
+#include <x509keys.h>
+#include <wtlscert.h>
+#include <x500dn.h>
+#include "DevandTruSrvCertStoreServer.h"
+#include "DevandTruSrvCertStoreConduit.h"
+#include "DevandTruSrvCertStoreSession.h"
+#include "DevandTruSrvCertStoreEntry.h"
+#include "DevandTruSrvCertStoreEntryList.h"
+#include "DevTokenCliServ.h"
+#include "DevTokenUtil.h"
+#include "DevTokenDataTypes.h"
+#include "TrustedSitesServer.h"
+
+_LIT(KCertStoreFilename,"devandtrusrvcerts.dat");
+
+const TInt KSHA1Length = 20;
+
+// API policing 
+_LIT_SECURITY_POLICY_PASS(KPolicyAlwaysPass);
+_LIT_SECURITY_POLICY_FAIL(KPolicyAlwaysFail);
+_LIT_SECURITY_POLICY_C1(KPolicyRequireReadUserData, ECapabilityReadUserData);
+_LIT_SECURITY_POLICY_C1(KPolicyRequireWriteDeviceData, ECapabilityWriteDeviceData);
+
+// ======== MEMBER FUNCTIONS ========
+
+//CDevandTruSrvCertStoreServer
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::NewL()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreServer* CDevandTruSrvCertStoreServer::NewL(CTrustedSitesServer* aTrustedSitesServer )
+    {
+    CDevandTruSrvCertStoreServer* self = new (ELeave) CDevandTruSrvCertStoreServer( aTrustedSitesServer );
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::CDevandTruSrvCertStoreServer()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreServer::CDevandTruSrvCertStoreServer( CTrustedSitesServer* aTrustedSitesServer )
+: iTrustedSitesServer( aTrustedSitesServer )
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreServer::ConstructL()
+    {
+    iConduit = CDevandTruSrvCertStoreConduit::NewL(*this);
+    User::LeaveIfError(iFs.Connect());
+    OpenStoreL();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::~CDevandTruSrvCertStoreServer()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreServer::~CDevandTruSrvCertStoreServer()
+    {
+    delete iStore;
+    delete iEntryList;
+    delete iConduit;
+    iFs.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::CreateSessionL()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreSession* CDevandTruSrvCertStoreServer::CreateSessionL()
+    {
+    return CDevandTruSrvCertStoreSession::NewL(*iConduit);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::ListPolicy()
+// ---------------------------------------------------------------------------
+//
+const TSecurityPolicy& CDevandTruSrvCertStoreServer::ListPolicy(TCertificateOwnerType aOwnerType) const
+    {
+    switch (aOwnerType)
+        {
+        case EUserCertificate:
+            return KPolicyAlwaysPass;
+        case EPeerCertificate:
+            return KPolicyRequireReadUserData;
+
+        default:
+            return KPolicyAlwaysFail;
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::AddRemovePolicy()
+// ---------------------------------------------------------------------------
+//
+const TSecurityPolicy& CDevandTruSrvCertStoreServer::AddRemovePolicy(TCertificateOwnerType aOwnerType) const
+    {
+    switch (aOwnerType)
+        {
+        case EUserCertificate:
+        case EPeerCertificate:
+            return KPolicyRequireWriteDeviceData;
+
+        default:
+            return KPolicyAlwaysFail;
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::RetrievePolicy()
+// ---------------------------------------------------------------------------
+//
+const TSecurityPolicy& CDevandTruSrvCertStoreServer::RetrievePolicy(TCertificateOwnerType aOwnerType) const
+    {
+    switch (aOwnerType)
+        {
+        case EUserCertificate:
+        case EPeerCertificate:
+            return KPolicyRequireReadUserData;
+
+        default:
+            return KPolicyAlwaysFail;
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::WriteTrustSettingsPolicy()
+// ---------------------------------------------------------------------------
+//
+const TSecurityPolicy& CDevandTruSrvCertStoreServer::WriteTrustSettingsPolicy() const
+    {
+    return KPolicyRequireWriteDeviceData;
+    }
+
+
+// Read-only interface 
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::ListL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreServer::ListL(const CCertAttributeFilter& aFilter,
+                 RPointerArray<CDevTokenCertInfo>& aCertsOut,
+                 const RMessage2& aMessage, TBool aFromTruSiteSrv ) const
+    {
+
+    // check that if KeyUsage is set, only User certificates are requested
+    if (aFilter.iKeyUsage != EX509UsageAll &&
+    (!aFilter.iOwnerTypeIsSet || aFilter.iOwnerType != EUserCertificate))
+        {
+        User::Leave(KErrArgument);
+        }
+
+    // API policing
+    if (!aFromTruSiteSrv)
+        {
+        if (!ListPolicy( aFilter.iOwnerType ).CheckPolicy(aMessage))
+            {
+            User::Leave(KErrPermissionDenied);
+            } 	
+        } 
+
+    TInt count = iEntryList->Count();
+    for (TInt index = 0; index < count; index++)
+        {
+        const CDevandTruSrvCertStoreEntry& entry = iEntryList->GetByIndex(index);
+
+        if (CertEntryMatchesFilter(aFilter, entry))
+            {
+            User::LeaveIfError(aCertsOut.Append(&entry.CertInfo()));
+            }
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::CertEntryMatchesFilter()
+// ---------------------------------------------------------------------------
+//
+TBool CDevandTruSrvCertStoreServer::CertEntryMatchesFilter(const CCertAttributeFilter& aFilter,
+                         const CDevandTruSrvCertStoreEntry& aEntry) const
+    {
+    if (aFilter.iUidIsSet && !aEntry.IsApplicable(aFilter.iUid))
+        {
+        return EFalse;
+        }
+
+    const CDevTokenCertInfo& certInfo = aEntry.CertInfo();
+
+    if (aFilter.iFormatIsSet && aFilter.iFormat != certInfo.CertificateFormat())
+        {
+        return EFalse;
+        }
+
+    if (aFilter.iOwnerTypeIsSet && aFilter.iOwnerType != certInfo.CertificateOwnerType())
+        {
+        return EFalse;
+        }
+
+    if (aFilter.iSubjectKeyIdIsSet && aFilter.iSubjectKeyId != certInfo.SubjectKeyId())
+        {
+        return EFalse;
+        }
+
+    if (aFilter.iLabelIsSet && aFilter.iLabel != certInfo.Label())
+        {
+        return EFalse;
+        }
+
+    return ETrue;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::GetCertL()
+// ---------------------------------------------------------------------------
+//
+const CDevTokenCertInfo& CDevandTruSrvCertStoreServer::GetCertL(TInt aHandle) const 
+    {
+    // Leaves if not found
+    return iEntryList->GetByHandleL(aHandle).CertInfo();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::ApplicationsL()
+// ---------------------------------------------------------------------------
+//
+const RArray<TUid>& CDevandTruSrvCertStoreServer::ApplicationsL(TInt aHandle) const
+    {
+    return iEntryList->GetByHandleL(aHandle).CertificateApps();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::IsApplicableL()
+// ---------------------------------------------------------------------------
+//
+TBool CDevandTruSrvCertStoreServer::IsApplicableL(TInt aHandle, TUid aApplication) const
+    {
+    return iEntryList->GetByHandleL(aHandle).IsApplicable(aApplication);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::TrustedL()
+// ---------------------------------------------------------------------------
+//
+TBool CDevandTruSrvCertStoreServer::TrustedL(TInt aHandle) const
+    { 
+    return iEntryList->GetByHandleL(aHandle).Trusted();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::RetrieveLC()
+// ---------------------------------------------------------------------------
+//
+HBufC8* CDevandTruSrvCertStoreServer::RetrieveLC(TInt aHandle, const RMessage2& aMessage, TBool aFromTruSiteSrv) const
+    {
+    const CDevandTruSrvCertStoreEntry& entry = iEntryList->GetByHandleL(aHandle);
+
+    // API policing
+    if ( !aFromTruSiteSrv )
+        {
+        if (!RetrievePolicy(entry.CertInfo().CertificateOwnerType()).CheckPolicy(aMessage))
+            {
+            User::Leave( KErrPermissionDenied );
+            }	
+        }
+
+    TInt size = entry.CertInfo().Size();
+    HBufC8* buf = HBufC8::NewMaxLC(size);
+    TPtr8 ptr = buf->Des();
+    ptr.FillZ();
+
+    RStoreReadStream stream;
+    stream.OpenLC(*iStore, entry.DataStreamId());
+    stream.ReadL(ptr, size);
+    CleanupStack::PopAndDestroy(&stream);
+
+    return buf;
+    }
+
+
+// Writable interface
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::AddL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreServer::AddL(const TDevTokenAddCertDataStruct& aInfo,
+                const TDesC8& aCert,
+                const RMessage2& aMessage, TBool aFromTruSiteSrv )
+    {
+    // Check if a certificate with this name already exists
+    if (iEntryList->LabelExists(aInfo.iLabel))
+        {
+        User::Leave(KErrBadName);
+        }
+
+    // Check subject key id and cert data are supplied, issuer key id is optional
+    if (aInfo.iSubjectKeyId == KNullDesC8 || aCert == KNullDesC8)
+        {
+        User::Leave(KErrArgument);
+        }
+
+    // Create cert entry (this sanity checks the rest of the arguments)
+    CDevTokenCertInfo* certInfo = CDevTokenCertInfo::NewLC(
+        aInfo.iLabel,
+        aInfo.iFormat, 
+        aInfo.iCertificateOwnerType,
+        aCert.Length(),
+        &aInfo.iSubjectKeyId,
+        &aInfo.iIssuerKeyId,
+        iEntryList->NextFreeHandle(),
+        aInfo.iDeletable);
+
+    // API policing
+    if ( !aFromTruSiteSrv )
+        {
+        if (!AddRemovePolicy(aInfo.iCertificateOwnerType).CheckPolicy(aMessage))
+            {
+            User::Leave(KErrPermissionDenied);
+            }	
+        }
+
+    CompactStoreL();
+
+    TRAPD(err, DoAddL(*certInfo, aCert));
+    CleanupStack::PopAndDestroy(certInfo);
+
+    if (err != KErrNone)
+        {
+        iStore->Revert();
+        User::Leave(err);
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::DoAddL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreServer::DoAddL(const CDevTokenCertInfo& aCertInfo, const TDesC8& aCertData)
+    {
+    TStreamId dataStreamId = WriteCertDataStreamL(aCertData);
+
+    RArray<TUid> initialApps;
+    CleanupClosePushL(initialApps);
+
+    CDevandTruSrvCertStoreEntry* entry = CDevandTruSrvCertStoreEntry::NewL(
+        aCertInfo,
+        initialApps,
+        EFalse,
+        dataStreamId);
+    CleanupStack::PopAndDestroy(&initialApps);
+    CleanupStack::PushL(entry);
+
+    TInt index = iEntryList->AppendL(entry);
+    CleanupStack::Pop(entry); // iEntryList has taken ownership
+
+    TRAPD(err, UpdateStoreL());
+    if ( (err == KErrNone) && (aCertInfo.CertificateOwnerType() == EPeerCertificate ))
+        {
+        CX509Certificate* cert = CX509Certificate::NewLC( aCertData );
+        TBuf8<KSHA1Length> certHash;
+        certHash.Copy(cert->Fingerprint()); 
+         
+          
+        const CX500DistinguishedName& dName = cert->SubjectName();
+        // Retrieve CN
+        HBufC* cn = dName.ExtractFieldL( KX520CommonName );  
+        CleanupStack::PushL(cn);  
+        iTrustedSitesServer->AddL( certHash, *cn );
+
+        CleanupStack::PopAndDestroy( 2 );//cert, cn	
+        }
+    if (err != KErrNone)
+        {
+        iEntryList->Remove(index);
+        delete entry;
+        User::Leave(err);
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::WriteCertDataStreamL()
+// ---------------------------------------------------------------------------
+//
+TStreamId CDevandTruSrvCertStoreServer::WriteCertDataStreamL(const TDesC8& aData)
+    {
+    RStoreWriteStream stream;
+    TStreamId streamId = stream.CreateLC(*iStore);
+    stream.WriteL(aData);
+    stream.CommitL();
+    CleanupStack::PopAndDestroy(&stream);
+    return streamId;
+    } 
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::RemoveL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreServer::RemoveL(TInt aHandle, const RMessage2& aMessage,  TBool aFromTruSiteSrv)
+    {
+    TInt index = iEntryList->IndexForHandle(aHandle);
+    User::LeaveIfError(index);
+
+    // API policing
+    const CDevandTruSrvCertStoreEntry& entry = iEntryList->GetByIndex(index);
+    if (!aFromTruSiteSrv)
+        {
+        if (!AddRemovePolicy(entry.CertInfo().CertificateOwnerType()).CheckPolicy(aMessage))
+            {
+            User::Leave(KErrPermissionDenied);
+            }	
+        }
+
+    CompactStoreL();
+
+    CDevandTruSrvCertStoreEntry* oldEntry = iEntryList->Remove(index);
+    TRAPD(err, UpdateStoreL());
+    if (err == KErrNone)
+        {
+        // If trusted site certificate is removed, the corresponding records
+        // in trusted site store should also be removed to stop trusting.
+        if( oldEntry->CertInfo().CertificateOwnerType() == EPeerCertificate )
+            {
+            TInt size = oldEntry->CertInfo().Size();
+            HBufC8* buf = HBufC8::NewMaxLC(size);
+            TPtr8 ptr = buf->Des();
+            ptr.FillZ();
+
+            RStoreReadStream stream;
+            stream.OpenLC(*iStore, oldEntry->DataStreamId());
+            stream.ReadL(ptr, size);
+            CleanupStack::PopAndDestroy(&stream);
+
+
+            CX509Certificate* cert = CX509Certificate::NewLC(*buf);
+            TBuf8<KSHA1Length> certHash;
+            certHash.Copy(cert->Fingerprint()); 
+
+            iTrustedSitesServer->RemoveL( certHash );
+
+            CleanupStack::PopAndDestroy( 2 );//buf, cert
+            }
+        delete oldEntry;
+        }
+    else
+        {
+        iStore->Revert();
+        // This will always succeed because we just did a remove
+        iEntryList->AppendL(oldEntry);
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::SetApplicabilityL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreServer::SetApplicabilityL(TInt /*aHandle*/,
+                       const RArray<TUid>& /*aApps*/,
+                       const RMessage2& aMessage)
+    {
+    // Setting Applicability is meant for CA certificate only.
+    // in DevandTruSrvCertStore, we only store Personal ceritificate(Device Cert )
+    // and Peer certificate( trust server cert ).
+    
+    aMessage.Complete( KErrNotSupported ); 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::SetTrustL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreServer::SetTrustL(TInt /*aHandle*/,
+                   TBool /*aTrusted*/,
+                   const RMessage2& aMessage)
+    {
+    // Setting Trust is meant for CA certificate only.
+    // in DevandTruSrvCertStore, we only store Personal ceritificate(Device Cert )
+    // and Peer certificate( trust server cert ).
+    
+    aMessage.Complete( KErrNotSupported ); 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::UpdateStoreL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreServer::UpdateStoreL()
+    {
+    RStoreWriteStream stream;
+    stream.ReplaceLC(*iStore, iStreamId);
+    stream << *iEntryList;
+    stream.CommitL();
+    CleanupStack::PopAndDestroy(&stream);
+
+    iStore->CommitL();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::CompactStoreL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreServer::CompactStoreL()
+    {
+    iStore->ReclaimL();
+    iStore->CompactL();
+    iStore->CommitL();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::RestoreL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreServer::RestoreL(const TDesC& aFilename)
+    {
+    // Make sure the store is not read-only
+    User::LeaveIfError(iFs.SetAtt(aFilename, KEntryAttNormal, KEntryAttReadOnly));
+
+    // Open the store
+    RFile file;
+    User::LeaveIfError(file.Open(iFs, aFilename, EFileRead | EFileWrite));
+    CleanupClosePushL(file);
+    CPermanentFileStore* store = CPermanentFileStore::FromL(file);
+    CleanupStack::Pop(&file); // now owned by store
+    CleanupStack::PushL(store);
+
+    // Read id of cert list stream
+    TStreamId caCertEntryStreamId;
+    RStoreReadStream stream;
+    stream.OpenLC(*store, store->Root());
+    stream >> iStreamId;
+    CleanupStack::PopAndDestroy(&stream);
+
+    // Read the certificate list
+    RStoreReadStream caCertEntryStream;
+    caCertEntryStream.OpenLC(*store, iStreamId);
+    iEntryList = CDevandTruSrvCertStoreEntryList::NewL(caCertEntryStream);
+    CleanupStack::PopAndDestroy(&caCertEntryStream);
+
+    assert(!iStore, EPanicCertStoreRestoreState);
+    iStore = store;
+    CleanupStack::Pop(store);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::OpenStoreL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreServer::OpenStoreL()
+    {
+    TBuf<KMaxFilenameLength> filename;
+    FileUtils::MakePrivateFilenameL(iFs, KCertStoreFilename, filename);
+
+    TRAPD(err, RestoreL(filename));
+
+    if (err == KErrNoMemory || err == KErrInUse)
+        {
+        User::Leave(err);
+        }
+
+    if (err != KErrNone)
+        {
+        // Couldn't open RAM based store, copy from ROM 
+
+        FileUtils::EnsurePathL(iFs, filename);
+
+        TBuf<KMaxFilenameLength> romFilename;
+        FileUtils::MakePrivateROMFilenameL(iFs, KCertStoreFilename, romFilename);
+
+        if (FileUtils::ExistsL(iFs, romFilename))
+            {
+            FileUtils::CopyL(iFs, romFilename, filename);
+            }
+        else
+            {
+            CreateStoreFileL(filename);
+            }
+
+        // Retry open, and leave on failure
+        RestoreL(filename);
+        }
+
+    assert(iStore, EPanicCertStoreOpenState);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::CreateStoreFileL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreServer::CreateStoreFileL(const TDesC& aFile)
+    {
+    TRAPD(err, DoCreateStoreFileL(aFile));
+    if (err != KErrNone)
+        {
+        // Attempt to delete file, but don't complain if it fails
+        iFs.Delete(aFile);  
+        User::Leave(err);
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreServer::DoCreateStoreFileL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreServer::DoCreateStoreFileL(const TDesC& aFile)
+    {
+    CPermanentFileStore* fileStore = CPermanentFileStore::ReplaceLC(iFs, aFile, EFileRead | EFileWrite | EFileShareExclusive);
+    fileStore->SetTypeL(KPermanentFileStoreLayoutUid);
+
+    // Create info stream
+    CDevandTruSrvCertStoreEntryList* emptyCertList = CDevandTruSrvCertStoreEntryList::NewLC();  
+    RStoreWriteStream infoStream;
+    TStreamId streamId = infoStream.CreateLC(*fileStore);
+    infoStream << *emptyCertList;
+    infoStream.CommitL();
+    CleanupStack::PopAndDestroy(2, emptyCertList);
+
+    // Create root stream - just contains id of info stream
+    RStoreWriteStream rootStream;
+    TStreamId rootStreamId = rootStream.CreateLC(*fileStore);
+    fileStore->SetRootL(rootStreamId);
+    rootStream << streamId;
+    rootStream.CommitL();
+    CleanupStack::PopAndDestroy(&rootStream);
+
+    fileStore->CommitL();
+    CleanupStack::PopAndDestroy(fileStore);
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Certstore/server/DevandTruSrvCertStoreSession.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevandTruSrvCertStoreSession
+*
+*/
+
+
+
+#include "DevandTruSrvCertStoreSession.h"
+#include "DevandTruSrvCertStoreConduit.h"
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreSession::NewL()
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreSession* CDevandTruSrvCertStoreSession::NewL(CDevandTruSrvCertStoreConduit& aConduit)
+    {
+    return new (ELeave) CDevandTruSrvCertStoreSession(aConduit);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreSession::CDevandTruSrvCertStoreSession()
+// ---------------------------------------------------------------------------
+//	
+CDevandTruSrvCertStoreSession::CDevandTruSrvCertStoreSession(CDevandTruSrvCertStoreConduit& aConduit) :
+    iConduit(aConduit)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevandTruSrvCertStoreSession::DoServiceL()
+// ---------------------------------------------------------------------------
+//
+void CDevandTruSrvCertStoreSession::DoServiceL(const RMessage2& aMessage)
+    {
+    iConduit.ServiceCertStoreRequestL(aMessage);
+    }
+
+//EOF
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Generic/Client/DTClient.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,181 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DTClient
+*
+*/
+
+
+
+#include "DTClient.h"
+#include "DevTokenUtils.h"
+#include "DevTokenClientSession.h"
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// -----------------------------------------------------------------------------
+// CDTClient::CDTClient()
+// -----------------------------------------------------------------------------
+//
+CDTClient::CDTClient(TInt aUID,
+           MCTToken& aToken, 
+           RDevTokenClientSession& aClient)
+  : CActive(EPriorityNormal),
+    iToken(aToken),   
+    iInterfaceUID(aUID),  
+    iClientSession(aClient),
+    iRequestPtr(NULL, 0, 0)
+    {
+    } 
+
+
+// -----------------------------------------------------------------------------
+// CDTClient::~CDTClient()
+// -----------------------------------------------------------------------------
+//
+CDTClient::~CDTClient()
+    {
+    Cancel();     
+    delete iRequestDataBuf;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDTClient::TAsyncRequest::~TAsyncRequest()
+// -----------------------------------------------------------------------------
+//
+CDTClient::TAsyncRequest::~TAsyncRequest()
+    {
+    __ASSERT_DEBUG(EIdle==iRequest, DevTokenPanic(ERequestOutstanding));
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDTClient::TAsyncRequest::operator()
+// -----------------------------------------------------------------------------
+//
+void CDTClient::TAsyncRequest::operator()(TDevTokenMessages aRequest, 
+                                          TRequestStatus* aStatus)
+    {
+    __ASSERT_DEBUG(EIdle==iRequest, DevTokenPanic(ERequestOutstanding));
+    iRequest = aRequest; 
+    iClientStatus = aStatus;
+    *aStatus = KRequestPending;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDTClient::TAsyncRequest::Complete()
+// -----------------------------------------------------------------------------
+//
+void CDTClient::TAsyncRequest::Complete(TInt aCompletionResult)
+    {
+    __ASSERT_DEBUG(EIdle!=iRequest, DevTokenPanic(ENoRequestOutstanding));
+    User::RequestComplete(iClientStatus, aCompletionResult);
+    iRequest = EIdle;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDTClient::TAsyncRequest::Cancel()
+// -----------------------------------------------------------------------------
+//
+void CDTClient::TAsyncRequest::Cancel()
+    {
+    User::RequestComplete(iClientStatus, KErrCancel);
+    iRequest = EIdle;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDTClient::TAsyncRequest::FreeRequestBuffer()
+// -----------------------------------------------------------------------------
+//
+void CDTClient::FreeRequestBuffer() const
+    {
+    delete iRequestDataBuf; 
+    iRequestDataBuf = NULL;
+    iRequestPtr.Set(NULL, 0, 0);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDTClient::AllocRequestBuffer(TInt aReqdSize) const
+// -----------------------------------------------------------------------------
+//
+TInt CDTClient::AllocRequestBuffer(TInt aReqdSize) const
+    {
+    ASSERT(aReqdSize > 0);
+    TInt result = KErrNoMemory;
+
+    FreeRequestBuffer();
+    iRequestDataBuf = HBufC8::NewMax(aReqdSize);
+    if ( iRequestDataBuf )
+        {
+        iRequestPtr.Set(iRequestDataBuf->Des());
+        iRequestPtr.FillZ();
+        result = KErrNone;
+        }
+    return result;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDTClient::SendSyncRequestAndHandleOverflowL()
+// Execute a synchronous request that returns a buffer of indetermintate length.
+// If the initial buffer is too short, the server leaves with KErrOverflow and
+// passes us the required length - the reuest is then re-sent.
+// -----------------------------------------------------------------------------
+// 
+void CDTClient::SendSyncRequestAndHandleOverflowL(TDevTokenMessages aMessage,
+                          TInt aInitialBufSize,
+                          const TIpcArgs& aArgs) const
+    {
+    User::LeaveIfError(AllocRequestBuffer(aInitialBufSize));
+
+    TInt err = iClientSession.SendRequest(aMessage, aArgs);
+    if ( err == KErrOverflow )
+        {
+        TInt sizeReqd = 0;
+        TPckg<TInt> theSize(sizeReqd);
+        theSize.Copy(iRequestPtr);
+        User::LeaveIfError(AllocRequestBuffer(sizeReqd));     
+        err = iClientSession.SendRequest(aMessage, aArgs);
+        }
+    User::LeaveIfError(err);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDTClient::DoCancel()
+// -----------------------------------------------------------------------------
+// 
+void CDTClient::DoCancel()
+    {
+    iCurrentRequest.Cancel();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDTClient::RunError()
+// -----------------------------------------------------------------------------
+// 
+TInt CDTClient::RunError(TInt aError)
+    {
+    iCurrentRequest.Complete(aError);
+    return KErrNone; // Handled
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Generic/Client/DevToken.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,166 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevToken
+*
+*/
+
+
+
+#include <e32debug.h>
+#include "DevToken.h"
+#include "DevTokenUtils.h"
+#include "DevTokenInterfaceFactory.h"
+#include "DevtokenLog.h"
+
+// Information strings returned by MCTToken::Information()
+_LIT(KVersion, "1.00");
+_LIT(KSerialNo, "0");
+_LIT(KManufacturer, "Nokia");
+
+// ======== MEMBER FUNCTIONS ========
+
+// -----------------------------------------------------------------------------
+// MCTToken* CDevToken::NewL()
+// -----------------------------------------------------------------------------
+//
+MCTToken* CDevToken::NewL(EDevTokenEnum aTokenTypeVal, 
+                          MCTTokenType* aTokenType, 
+                          RDevTokenClientSession& aClient)
+    {
+    __ASSERT_DEBUG(aTokenType, DevTokenPanic(EBadArgument));
+    //Destroyed by MCTToken::Release() (refcounted)
+    CDevToken* me = new (ELeave) CDevToken(aTokenTypeVal, aTokenType, aClient);
+    return (static_cast<MCTToken*>(me));
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevToken::CDevToken()
+// -----------------------------------------------------------------------------
+//
+CDevToken::CDevToken(EDevTokenEnum aTokenTypeVal, MCTTokenType* aTokenType, RDevTokenClientSession& aClient)
+    : iTokenEnum(aTokenTypeVal),
+    iTokenType(aTokenType),
+    iRefCount(0),
+    iClientSession(aClient)
+    {
+    ASSERT(iTokenEnum < ETotalTokensSupported);
+    }
+
+
+// -----------------------------------------------------------------------------
+// MCTTokenType& CDevToken::TokenType()
+// -----------------------------------------------------------------------------
+//
+MCTTokenType& CDevToken::TokenType()
+    {
+    __ASSERT_DEBUG(iTokenType, DevTokenPanic(ENotInitialised));
+    return (*iTokenType);
+    }
+
+
+// -----------------------------------------------------------------------------
+// const TDesC& CDevToken::Label()
+// -----------------------------------------------------------------------------
+//
+const TDesC& CDevToken::Label()
+    {
+    RSupportedTokensArray supportedTokens;
+    const TDesC* token = supportedTokens[iTokenEnum];
+    return (*token);
+    }
+
+
+// -----------------------------------------------------------------------------
+// TCTTokenHandle CDevToken::Handle()
+// -----------------------------------------------------------------------------
+//
+TCTTokenHandle CDevToken::Handle()
+    {
+    __ASSERT_DEBUG(iTokenType, DevTokenPanic(ENotInitialised));
+    return (TCTTokenHandle(iTokenType->Type(), iTokenEnum));
+    }
+
+
+// -----------------------------------------------------------------------------
+// TInt& CDevToken::ReferenceCount()
+// -----------------------------------------------------------------------------
+//
+TInt& CDevToken::ReferenceCount()
+    {
+    return (iRefCount);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevToken::DoGetInterface()
+// -----------------------------------------------------------------------------
+//
+void CDevToken::DoGetInterface(TUid aRequiredInterface, 
+                               MCTTokenInterface*& aReturnedInterface,
+                               TRequestStatus& aStatus)
+    {
+    // No longer calls server to get the interface - just creates a client object of the appropriate type
+    TRACE_PRINT("--> DoGetInterface 1");
+    aReturnedInterface = NULL;
+    TRAPD(result, aReturnedInterface = DevTokenInterfaceFactory::ClientInterfaceL(aRequiredInterface.iUid, *this, iClientSession));
+    TRACE_PRINT("--> DoGetInterface 2")
+    if (result != KErrNone)
+        {
+        TRACE_PRINT("-->DoGetInterface 3")
+        Release();
+        }
+
+    //Complete the TRequestStatus here since not asynchronous
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, result);
+    }
+
+
+// -----------------------------------------------------------------------------
+// TBool CDevToken::DoCancelGetInterface()
+// -----------------------------------------------------------------------------
+//
+TBool CDevToken::DoCancelGetInterface()
+    {//Not an asynchronous call for current file store, so nothing to do
+    return (EFalse);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevToken::Information(TTokenInformation aRequiredInformation)
+// -----------------------------------------------------------------------------
+//
+const TDesC& CDevToken::Information(TTokenInformation aRequiredInformation)
+    {
+    switch ( aRequiredInformation )
+        {
+        case EVersion:
+            return KVersion;
+
+        case ESerialNo:
+            return KSerialNo;
+
+        case EManufacturer:
+            return KManufacturer;
+
+        default:
+            DevTokenPanic(EBadArgument);
+        }
+
+    return KNullDesC;
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Generic/Client/DevTokenClientSession.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,184 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenClientSession
+*
+*/
+
+
+
+#include <e32std.h>
+#include <e32uid.h>
+#include <e32debug.h>
+#include "DevTokenUtils.h"
+#include "DevTokenServerName.h"
+#include "DevTokenClientSession.h"
+#include "DevtokenLog.h"
+
+//Forward declaration
+static TInt StartServer();
+
+_LIT(KDevTokenServerImg,"DevTokenServer");
+
+// Tokentype session class for Device token certificate stores
+// Both device certificate store and trust site certificate store share
+// the same token type.
+
+// ======== LOCAL FUNCTIONS ========
+
+// -----------------------------------------------------------------------------
+// TInt StartServer()
+// Client-server startup code
+// -----------------------------------------------------------------------------
+//
+TInt StartServer()
+    {
+    // Server startup is different for WINS in EKA1 mode ONLY (lack of process
+    // emulation - we load the library in this instance
+    const TUidType serverUid(KNullUid, KNullUid, KUidDevTokenServer);
+
+    RProcess server;  
+    TInt r = server.Create(KDevTokenServerImg, KNullDesC, serverUid);
+    
+    RDebug::Print( _L(" StartServer ") );
+    
+    if ( r != KErrNone )
+        {
+        RDebug::Print( _L("StartServer1 %d"), r );
+        return r;
+        }
+
+    // Synchronise with the process to make sure it hasn't died straight away
+    TRequestStatus stat;
+    server.Rendezvous(stat);
+    if ( stat != KRequestPending )
+        {
+        // logon failed - server is not yet running, so cannot have terminated
+        server.Kill(0);       // Abort startup
+        }
+    else
+        {
+        // logon OK - start the server
+        server.Resume();
+        }
+
+    RDebug::Print( _L(" StartServer 2") );
+
+    // Wait to synchronise with server - if it dies in the meantime, it
+    // also gets completed
+    User::WaitForRequest(stat); 
+    
+    RDebug::Print( _L(" StartServer 3") );
+    // We can't use the 'exit reason' if the server panicked as this
+    // is the panic 'reason' and may be '0' which cannot be distinguished
+    // from KErrNone
+    r = (server.ExitType()==EExitPanic) ? KErrGeneral : stat.Int();
+    
+    RDebug::Print( _L(" StartServer 4 %d"), r );
+    
+    server.Close();
+    return (r);
+    }
+    
+    
+// ======== MEMBER FUNCTIONS ========
+
+// -----------------------------------------------------------------------------
+// RDevTokenClientSession::RDevTokenClientSession()
+// -----------------------------------------------------------------------------
+//
+RDevTokenClientSession::RDevTokenClientSession()
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// RDevTokenClientSession::ClientSessionL()
+// -----------------------------------------------------------------------------
+//
+RDevTokenClientSession* RDevTokenClientSession::ClientSessionL()
+    {
+    return new( ELeave ) RDevTokenClientSession();
+    }
+
+
+// -----------------------------------------------------------------------------
+// RDevTokenClientSession::SendRequest()
+// -----------------------------------------------------------------------------
+//
+TInt RDevTokenClientSession::SendRequest(TDevTokenMessages aRequest, const TIpcArgs& aArgs) const
+    {
+    return SendReceive(aRequest, aArgs);
+    }
+
+
+// -----------------------------------------------------------------------------
+// RDevTokenClientSession::SendAsyncRequest()
+// -----------------------------------------------------------------------------
+//
+void RDevTokenClientSession::SendAsyncRequest(TDevTokenMessages aRequest, const TIpcArgs& aArgs, TRequestStatus* aStatus) const
+    {
+    __ASSERT_ALWAYS(aStatus, DevTokenPanic(EBadArgument));
+    if (aStatus)
+        {
+        *aStatus = KRequestPending;
+        SendReceive(aRequest, aArgs, *aStatus);
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// TInt RDevTokenClientSession::Connect(EDevTokenEnum aToken)
+// Connect to the server, attempting to start it if necessary
+// -----------------------------------------------------------------------------
+//
+TInt RDevTokenClientSession::Connect(EDevTokenEnum aToken)
+    {
+    // The version is made up of three pieces of information:
+    // 1. iMajor - The token we want to talk to
+    // 2. iMinor - The protocol version number
+    // 3. iBuild - unused
+    TVersion version(aToken, KDevTokenProtolVersion, 0);
+
+    TInt retry=2;
+    for (;;)
+        {
+        TInt r=CreateSession(KDevTokenServerName, version, 1);
+
+        TRACE_PRINT("connect");
+        
+        if ( r!=KErrNotFound && r!=KErrServerTerminated )
+            {
+            RDebug::Print( _L("connect1 %d"), r );
+            return r; 
+            }
+
+        if (--retry==0)
+            {
+            RDebug::Print( _L(" connect2 %d"), r );
+            return r; 
+            }
+
+        r=StartServer();
+        
+        if ( r!=KErrNone && r!=KErrAlreadyExists )
+            {
+            RDebug::Print( _L(" connect3 %d"), r );
+            return r;  
+            }
+
+        }
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Generic/Client/DevTokenInterfaceFactory.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,73 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenInterfaceFactory
+*
+*/
+
+
+
+#ifdef SYMBIAN_ENABLE_SPLIT_HEADERS
+#include <mctkeystoreuids.h>
+#endif
+#include <e32debug.h>
+#include "DevTokenInterfaceFactory.h"
+#include "DevCertKeyStore.h"
+#include "DevandTruSrvCertStore.h"
+#include "DevTokenImplementationUID.hrh"
+#include "DevtokenLog.h"
+
+// ======== MEMBER FUNCTIONS ========
+
+// -----------------------------------------------------------------------------
+// DevTokenInterfaceFactory::ClientInterfaceL()
+// -----------------------------------------------------------------------------
+//
+MCTTokenInterface* DevTokenInterfaceFactory::ClientInterfaceL(
+               TInt32 aUid, 
+               MCTToken& aToken, 
+               RDevTokenClientSession& aClient)
+    {
+    MCTTokenInterface* tokenInterface = NULL; 
+    TRACE_PRINT("ClientInterfaceL --> 1");
+    switch ( aUid )
+         {
+         case KInterfaceKeyStore:
+             TRACE_PRINT("ClientInterfaceL --> 4");
+             tokenInterface = CDevCertKeyStore::NewKeyStoreUserInterfaceL(aToken, aClient);
+             TRACE_PRINT("ClientInterfaceL --> 5");
+             break;
+
+         case KInterfaceKeyStoreManager:
+             TRACE_PRINT("ClientInterfaceL --> 2");
+             tokenInterface = CDevCertKeyStore::NewKeyStoreManagerInterfaceL(aToken, aClient);
+             TRACE_PRINT("ClientInterfaceL --> 3");
+             break;
+
+         case KInterfaceCertStore:
+             tokenInterface  = CDevandTruSrvCertStore::NewReadableInterfaceL( aToken, aClient );
+             break;
+
+         case KInterfaceWritableCertStore: 
+             tokenInterface = CDevandTruSrvCertStore::NewWritableInterfaceL( aToken, aClient );
+             break;
+
+         default:
+             User::Leave(KErrArgument);
+             break;
+         }
+
+    return (tokenInterface);
+    }
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Generic/Client/DevTokenType.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,151 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenType
+*
+*/
+
+
+
+#include <ct.h>
+#include <e32test.h>
+#include "DevTokenType.h"
+#include "DevTokenTypeSession.h"
+#include "DevTokenUtils.h"
+#include "DevtokenLog.h"
+
+// ======== MEMBER FUNCTIONS ========
+
+// -----------------------------------------------------------------------------
+// CCTTokenType* CDevTokenType::NewL(TUid aUid)
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CCTTokenType* CDevTokenType::NewL(TUid aUid)
+    {
+    TRACE_PRINT("CDevTokenType::NewL()--->");
+
+    //Destroyed by call to CCTTokenType::Release (refcounted)
+    CDevTokenType* me = new (ELeave) CDevTokenType();
+    CleanupStack::PushL(me);
+    me->ConstructL(aUid);
+
+    TRACE_PRINT("CDevTokenType::NewL()<----");
+    CleanupStack::Pop(me);
+
+    //  Caller only receives a valid CDevTokenType instance if the server has connected
+    return (me);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevTokenType::CDevTokenType()
+// -----------------------------------------------------------------------------
+//
+CDevTokenType::CDevTokenType()
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevTokenType::~CDevTokenType()
+// -----------------------------------------------------------------------------
+//
+CDevTokenType::~CDevTokenType()
+    {
+    delete iTokenTypeSession;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevTokenType::ConstructL(TUid aUid)
+// -----------------------------------------------------------------------------
+//
+void CDevTokenType::ConstructL(TUid aUid)
+    {
+    iUid = aUid;
+    iTokenTypeSession = CDevTokenTypeSession::NewL(aUid);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevTokenType::List(RCPointerArray<HBufC>& aTokens, TRequestStatus& aStatus)
+// -----------------------------------------------------------------------------
+//
+void CDevTokenType::List(RCPointerArray<HBufC>& aTokens, TRequestStatus& aStatus)
+    {
+    __ASSERT_ALWAYS(iTokenTypeSession, DevTokenPanic(ETokenTypeSession));
+    TRAPD(err, iTokenTypeSession->ListTokensL(aTokens));
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevTokenType::CancelList()
+// -----------------------------------------------------------------------------
+//
+void CDevTokenType::CancelList()
+    {
+    // implementation not asynchronous
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevTokenType::OpenToken()
+// -----------------------------------------------------------------------------
+//
+void CDevTokenType::OpenToken(const TDesC& aTokenInfo, MCTToken*& aToken, TRequestStatus& aStatus)
+    {
+    __ASSERT_ALWAYS(iTokenTypeSession, DevTokenPanic(ETokenTypeSession));
+
+    TRAPD(err, iTokenTypeSession->OpenTokenL(aTokenInfo, this, aToken));
+    if ( err == KErrNone )
+        {
+        //  Token opened, increment our reference count
+        IncReferenceCount();
+        }
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevTokenType::OpenToken()
+// -----------------------------------------------------------------------------
+//
+void CDevTokenType::OpenToken(TCTTokenHandle aHandle, MCTToken*& aToken, TRequestStatus& aStatus)
+    {
+    __ASSERT_ALWAYS(iTokenTypeSession, DevTokenPanic(ETokenTypeSession));
+
+    TRAPD(err, iTokenTypeSession->OpenTokenL(aHandle, this, aToken));
+    if ( err == KErrNone )
+        {
+        //  Token opened, increment our reference count
+        IncReferenceCount();
+        }
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevTokenType::CancelOpenToken()
+// -----------------------------------------------------------------------------
+//
+void CDevTokenType::CancelOpenToken()
+    {
+    // implementation not asynchronous
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Generic/Client/DevTokenTypeSession.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,142 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenTypeSession
+*
+*/
+
+
+
+#include <ct.h>
+#include <e32test.h>
+#include "DevTokenTypeSession.h"
+#include "DevTokenUtils.h"
+#include "DevToken.h"
+#include "DevTokenTypesEnum.h"
+#include "DevTokenCliServ.h"
+#include "DevtokenLog.h"
+
+// ======== MEMBER FUNCTIONS ========
+
+// -----------------------------------------------------------------------------
+// CDevTokenTypeSession::NewL(TUid aUid)
+// -----------------------------------------------------------------------------
+//
+CDevTokenTypeSession* CDevTokenTypeSession::NewL(TUid aUid)
+    {
+    TRACE_PRINT("CDevTokenTypeSession::NewL()");
+    // Destroyed by owner object (~CDevTokenTypeSession)
+    CDevTokenTypeSession* me = new (ELeave) CDevTokenTypeSession(aUid);
+    CleanupStack::PushL(me);
+    me->ConstructL();
+    CleanupStack::Pop(me);
+    return (me);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevTokenTypeSession::CDevTokenTypeSession(TUid aUid) 
+// -----------------------------------------------------------------------------
+//
+CDevTokenTypeSession::CDevTokenTypeSession(TUid aUid) :
+    iUid(aUid)
+    {
+    } 
+
+
+// -----------------------------------------------------------------------------
+// CDevTokenTypeSession::~CDevTokenTypeSession(TUid aUid) 
+// -----------------------------------------------------------------------------
+//
+CDevTokenTypeSession::~CDevTokenTypeSession()
+    {
+    iClientSession.Close();
+    }
+
+
+// -----------------------------------------------------------------------------
+// void CDevTokenTypeSession::ConstructL()
+// -----------------------------------------------------------------------------
+//
+void CDevTokenTypeSession::ConstructL()
+    {
+    TRACE_PRINT("CDevTokenTypeSession::ConstructL()");
+    iTokenId = (EDevTokenEnum) KErrNotFound;
+
+    RTokenTypeUIDLookup tokenUids;
+    for ( TInt i = 0 ; i < ETotalTokensSupported ; ++i )
+        {
+        TRACE_PRINT("CDevTokenTypeSession::ConstructL() 1");
+        if ( tokenUids[i] == iUid.iUid )
+            {
+            TRACE_PRINT("CDevTokenTypeSession::ConstructL() 2");
+            iTokenId = (EDevTokenEnum) i;
+            break;
+            }
+        }
+    TRACE_PRINT("CDevTokenTypeSession::ConstructL() 3");
+    User::LeaveIfError((TInt) iTokenId);
+    TRACE_PRINT("CDevTokenTypeSession::ConstructL()4 ");
+    User::LeaveIfError(iClientSession.Connect(iTokenId));
+    TRACE_PRINT("CDevTokenTypeSession::ConstructL()5 ");
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevTokenTypeSession::ListTokensL(RCPointerArray<HBufC>& aTokens)
+// -----------------------------------------------------------------------------
+//
+void CDevTokenTypeSession::ListTokensL(RCPointerArray<HBufC>& aTokens)
+    {
+    RSupportedTokensArray tokenNames;
+    HBufC* name = tokenNames[iTokenId]->AllocLC();
+    User::LeaveIfError(aTokens.Append(name));
+    CleanupStack::Pop(name);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevTokenTypeSession::OpenTokenL()
+// -----------------------------------------------------------------------------
+//
+void CDevTokenTypeSession::OpenTokenL(const TDesC& aTokenInfo, 
+                                      MCTTokenType* aTokenType, 
+                                      MCTToken*& aToken)
+    {
+    RSupportedTokensArray tokenNames;
+    if ( *tokenNames[iTokenId] != aTokenInfo )
+        {
+        User::Leave(KErrArgument);
+        }
+    aToken = CDevToken::NewL(iTokenId, aTokenType, iClientSession);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevTokenTypeSession::OpenTokenL()
+// -----------------------------------------------------------------------------
+//
+void CDevTokenTypeSession::OpenTokenL(TCTTokenHandle aHandle, 
+                                      MCTTokenType* aTokenType, 
+                                      MCTToken*& aToken)
+    {   
+    if ( aHandle.iTokenTypeUid != iUid ||
+        aHandle.iTokenId != iTokenId )
+        {
+        User::Leave(KErrArgument);
+        }
+    aToken = CDevToken::NewL(iTokenId, aTokenType, iClientSession);
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Generic/Client/DevTokenUtils.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,34 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenUtils
+*
+*/
+
+
+
+#include "DevTokenUtils.h"
+
+// ======== LOCAL FUNCTIONS ========
+
+// -----------------------------------------------------------------------------
+// DevTokenPanic( EDevTokenTypeClientPanic aPanicCode )
+// -----------------------------------------------------------------------------
+//
+void DevTokenPanic( EDevTokenTypeClientPanic aPanicCode )
+    {
+    User::Panic( KDevTokenTypeClientPanic, aPanicCode );
+    }
+    
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Generic/Common/DevTokenCliServ.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenCliServ
+*
+*/
+
+
+
+#include "DevTokenCliServ.h"
+#include "DevTokenTypesEnum.h"
+#include "DevTokenImplementationUID.hrh"
+
+const TInt KDeviceTokenTypeUidValues[] = { DEVCERTKEYSTORE_IMPLEMENTATION_UID, DEVCERTSTORE_IMPLEMENTATION_UID, TRUSRVCERTSTORE_IMPLEMENTATION_UID };
+
+// ======== MEMBER FUNCTIONS ========
+
+// -----------------------------------------------------------------------------
+// RSupportedTokensArray::RSupportedTokensArray()
+// -----------------------------------------------------------------------------
+//
+RSupportedTokensArray::RSupportedTokensArray()
+    {
+    _LIT(KKeyStoreName, "device cert keystore");
+    _LIT(KDeviceCertStoreName, "device certstore");
+    _LIT(KTruSrvCertStoreName, "trust server certstore");
+    const TDesC* array[] = {&KKeyStoreName, &KDeviceCertStoreName, &KTruSrvCertStoreName }; 
+    Copy(array, ETotalTokensSupported);
+    }
+
+
+// -----------------------------------------------------------------------------
+// RTokenTypeUIDLookup::RTokenTypeUIDLookup()
+// -----------------------------------------------------------------------------
+//
+RTokenTypeUIDLookup::RTokenTypeUIDLookup() :
+    TFixedArray<TInt, ETotalTokensSupported>(KDeviceTokenTypeUidValues, ETotalTokensSupported)
+    {
+    }
+    
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Generic/Server/DevTokenDialog.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,40 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenDialog
+*
+*/
+
+
+
+#include <e32base.h>
+#include "DevTokenDialog.h"
+#include <secdlg.h>
+
+MSecurityDialog* DevTokenDialog::iDialog;
+
+void DevTokenDialog::InitialiseL()
+    {
+	  iDialog = SecurityDialogFactory::CreateL();
+	  }
+
+
+void DevTokenDialog::Cleanup()
+    {
+	  if ( iDialog )
+	      {
+	      iDialog->Release();	
+	  	  }
+	  }
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Generic/Server/DevTokenServer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,417 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenServer
+*
+*/
+
+
+
+#include <e32debug.h>
+#include "DevTokenServer.h"
+#include "DevTokenUtil.h"
+#include "DevCertKeyStoreServer.h"
+#include "DevCertKeyStoreSession.h"
+#include "DevandTruSrvCertStoreServer.h"
+#include "DevandTruSrvCertStoreSession.h"
+#include "TrustedSitesServer.h"
+#include "TrustedSitesSession.h"
+#include "DevTokenServerDebug.h"
+#include "DevTokenServerName.h"
+#include "DevtokenLog.h"
+#include "DevTokenDialog.h"
+//  approx 2s
+const TInt KServerShutdownDelay = 0x200000; 
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// CDevTokenServerSession 
+
+// ---------------------------------------------------------------------------
+// CDevTokenServerSession::CDevTokenServerSession()
+// ---------------------------------------------------------------------------
+// 
+CDevTokenServerSession::CDevTokenServerSession()
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenServerSession::Server()
+// ---------------------------------------------------------------------------
+// 
+inline CDevTokenServer& CDevTokenServerSession::Server()
+    {
+    return static_cast<CDevTokenServer&>(const_cast<CServer2&>(*CSession2::Server()));
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenServerSession::CreateL()
+// ---------------------------------------------------------------------------
+//
+void CDevTokenServerSession::CreateL()
+    {
+    Server().AddSession();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenServerSession::~CDevTokenServerSession()
+// ---------------------------------------------------------------------------
+//
+CDevTokenServerSession::~CDevTokenServerSession()
+    {
+    Server().DropSession();
+    }
+
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenServerSession::ServiceL()
+// Handle a client request.  Leaving is handled by
+// CDevTokenServerSession::ServiceError() which reports the error code to the
+// client.
+// ---------------------------------------------------------------------------
+// 
+void CDevTokenServerSession::ServiceL(const RMessage2& aMessage)
+    {
+    #ifdef _DEBUG
+    // OOM testing
+    switch (aMessage.Function())
+        {
+        case EStartOOMTest:
+            DevTokenServerDebug::StartOOMTest();
+            aMessage.Complete(KErrNone);
+            return;
+
+        case EIncHeapFailPoint:
+            DevTokenServerDebug::IncHeapFailPoint();
+            aMessage.Complete(KErrNone);
+            return;
+
+        case EResetHeapFail:
+            DevTokenServerDebug::ResetHeapFail();
+            aMessage.Complete(KErrNone);
+            return;
+
+        case EAllocCount:
+            aMessage.Complete(User::CountAllocCells());
+            return;
+        } 
+    #endif
+
+    DoServiceL(aMessage);
+    }
+
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenServerSession::ServiceError()
+// Handle an error from ServiceL() A bad descriptor error implies a badly
+// programmed client, so panic it - otherwise report the error to the client.
+// ---------------------------------------------------------------------------
+//  
+void CDevTokenServerSession::ServiceError(const RMessage2& aMessage, TInt aError)
+    {
+    if (aError==KErrBadDescriptor)
+        {
+        PanicClient(aMessage, EPanicBadDescriptor);
+        }
+
+    CSession2::ServiceError(aMessage, aError);
+    }
+
+
+// CDevTokenServer 
+
+// ---------------------------------------------------------------------------
+// CDevTokenServer::CDevTokenServer()
+// ---------------------------------------------------------------------------
+//
+inline CDevTokenServer::CDevTokenServer() :
+  CServer2(0, ESharableSessions)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenServer::NewLC()
+// ---------------------------------------------------------------------------
+//
+CServer2* CDevTokenServer::NewLC()
+    {
+    TRACE_PRINT(" CDevTokenServer::NewLC -->");
+    CDevTokenServer* self=new(ELeave) CDevTokenServer;
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    TRACE_PRINT(" CDevTokenServer::NewLC <--");
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenServer::~CDevTokenServer()
+// ---------------------------------------------------------------------------
+//
+CDevTokenServer::~CDevTokenServer()
+    {
+    DevTokenDialog::Cleanup();
+    delete iKeyStoreServer;
+    delete iCertStoreServer;
+    delete iTrustedSitesServer;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenServer::ConstructL()
+// 2nd phase construction - ensure the timer and server objects are running.
+// ---------------------------------------------------------------------------
+//
+void CDevTokenServer::ConstructL()
+    {
+    TRACE_PRINT(" CDevTokenServer::ConstructL -->");
+    TRACE_PRINT(" CDevTokenServer::ConstructL 1");
+    DevTokenDialog::InitialiseL();
+    StartL( KDevTokenServerName );
+    TRACE_PRINT(" CDevTokenServer::ConstructL 2");
+    // Ensure that the server still exits even if the 1st client fails to connect
+    iShutdown.ConstructL();
+    iShutdown.Start();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenServer::AddSession()
+// A new session is being created - cancel the shutdown timer if it was running.
+// ---------------------------------------------------------------------------
+//
+void CDevTokenServer::AddSession()
+    {
+    ++iSessionCount;
+    iShutdown.Cancel();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenServer::DropSession()
+// A session is being destroyed - start the shutdown timer if it is the last session. 
+// ---------------------------------------------------------------------------
+//
+void CDevTokenServer::DropSession()
+    {
+    if (--iSessionCount==0)
+        {
+        iShutdown.Start();
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenServer::KeyStoreServerL()
+// Lazily create key store server object.
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyStoreServer& CDevTokenServer::KeyStoreServerL() const
+    {
+    if (!iKeyStoreServer)
+        {
+        iKeyStoreServer = CDevCertKeyStoreServer::NewL();
+        }
+
+    return *iKeyStoreServer;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenServer::CertStoreServerL()
+// Lazily create cert store server object. 
+// ---------------------------------------------------------------------------
+//
+CDevandTruSrvCertStoreServer& CDevTokenServer::CertStoreServerL() const
+    {
+    if (!iCertStoreServer)
+        {
+        iCertStoreServer = CDevandTruSrvCertStoreServer::NewL( &TrustedSitesL() );
+        }
+
+    return *iCertStoreServer;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenServer::TrustedSitesL()
+// Lazily create trusted site server object. 
+// ---------------------------------------------------------------------------
+//
+CTrustedSitesServer& CDevTokenServer::TrustedSitesL() const
+    {
+    if( !iTrustedSitesServer )
+        {
+        iTrustedSitesServer = CTrustedSitesServer::NewL((CDevTokenServer*)this);
+        }
+    return *iTrustedSitesServer;    
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenServer::NewSessionL()
+// Create a new client session.
+// ---------------------------------------------------------------------------
+//
+CSession2* CDevTokenServer::NewSessionL(const TVersion& aVersion, 
+                                        const RMessage2& /*aMessage*/) const
+    {
+    // The token the client wants to talk to is encoded in the major version number
+    EDevTokenEnum token = static_cast<EDevTokenEnum>(aVersion.iMajor);  
+
+    // The minor version number represents the version of the protocol
+    if ( aVersion.iMinor != KDevTokenProtolVersion )
+        {
+        User::Leave(KErrNotSupported);
+        }
+
+    CDevTokenServerSession* result = NULL;
+
+    switch (token)
+        {
+        case EDevCertKeyStore:
+            result = KeyStoreServerL().CreateSessionL();
+            break;
+
+        case EDevCertStore:
+        case ETruSrvCertStore:
+            result = CertStoreServerL().CreateSessionL();
+            break;
+
+        case ETruSitesStore:
+            result = TrustedSitesL().CreateSessionL();
+            break;
+        default:
+            User::Leave(KErrNotSupported);
+            break;
+        }
+
+    return result;
+    }
+
+
+// CShutdown
+
+// ---------------------------------------------------------------------------
+// CShutdown::CShutdown()
+// ---------------------------------------------------------------------------
+//
+inline CShutdown::CShutdown() :
+  CTimer(-1)
+    {
+    CActiveScheduler::Add(this);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CShutdown::ConstructL()
+// ---------------------------------------------------------------------------
+//
+inline void CShutdown::ConstructL()
+    {
+    CTimer::ConstructL();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CShutdown::Start()
+// ---------------------------------------------------------------------------
+//
+inline void CShutdown::Start()
+    {
+    After(KServerShutdownDelay);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CShutdown::RunL()
+// Initiate server exit when the timer expires.
+// ---------------------------------------------------------------------------
+//
+void CShutdown::RunL()
+    {
+    CActiveScheduler::Stop();
+    }
+
+
+// ======== LOCAL FUNCTIONS ========
+
+// Server startup 
+
+// ---------------------------------------------------------------------------
+// RunServerL()
+// Perform all server initialisation, in particular creation of the scheduler
+// and server and then run the scheduler.
+// ---------------------------------------------------------------------------
+//
+static void RunServerL()
+    {
+    TRACE_PRINT("RunServerL 1");
+    // Naming the server thread after the server helps to debug panics
+    User::LeaveIfError(User::RenameThread( KDevTokenServerName ));
+    TRACE_PRINT("RunServerL 2");
+    // Create and install the active scheduler we need
+    CActiveScheduler* s=new(ELeave) CActiveScheduler;
+    CleanupStack::PushL(s);
+    CActiveScheduler::Install(s);
+    TRACE_PRINT("RunServerL 3");
+    // Create the server and leave it on the cleanup stack
+    CDevTokenServer::NewLC();
+    TRACE_PRINT("RunServerL 4");
+    // Before starting the server, notify client that initialisation is
+    // complete.
+    // (note that WINS on EKA1 uses threads since it lacks process emulation)
+    RProcess::Rendezvous(KErrNone);
+    TRACE_PRINT("RunServerL 5");
+    // Ready to run
+    CActiveScheduler::Start();
+
+    // Cleanup the server and scheduler
+    CleanupStack::PopAndDestroy(2);
+    }
+
+
+// ---------------------------------------------------------------------------
+// E32Main()
+// Server process entry point.
+// ---------------------------------------------------------------------------
+//
+TInt E32Main()
+    {
+    #ifdef _DEBUG
+    DevTokenServerDebug::HeapCheckStart();
+    #endif
+
+    CTrapCleanup* cleanup=CTrapCleanup::New();
+    TInt r=KErrNoMemory;
+    if (cleanup)
+        {
+        TRAP(r,RunServerL());
+        delete cleanup;
+        }
+
+    #ifdef _DEBUG
+    DevTokenServerDebug::HeapCheckEnd();
+    #endif
+    return r;
+    }
+    
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Generic/Server/DevTokenServerDebug.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,153 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenServerDebug
+*
+*/
+
+
+
+#ifdef _DEBUG
+
+#include <f32file.h>
+#include "DevTokenServerDebug.h"
+
+_LIT(KHeapErrorFile, "C:\\devtokenserver_heap_error");
+
+TInt DevTokenServerDebug::iCounter = 0;
+TInt DevTokenServerDebug::iStartCount = 0;
+TInt DevTokenServerDebug::iPauseCount = 0;
+TInt DevTokenServerDebug::iInitialAllocCount = 0;
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// DevTokenServerDebug::StartOOMTest()
+// ---------------------------------------------------------------------------
+// 
+void DevTokenServerDebug::StartOOMTest()
+    {
+    iStartCount = User::CountAllocCells();
+    iCounter = 0;
+    }
+
+
+// ---------------------------------------------------------------------------
+// DevTokenServerDebug::IncHeapFailPoint()
+// ---------------------------------------------------------------------------
+// 
+void DevTokenServerDebug::IncHeapFailPoint()
+    {
+    __UHEAP_FAILNEXT(iCounter); 
+    ++iCounter;
+    }
+
+
+// ---------------------------------------------------------------------------
+// DevTokenServerDebug::ResetHeapFail()
+// ---------------------------------------------------------------------------
+// 
+void DevTokenServerDebug::ResetHeapFail()
+    {
+    __UHEAP_RESET;
+    }
+
+
+// ---------------------------------------------------------------------------
+// DevTokenServerDebug::PauseOOMTest()
+// ---------------------------------------------------------------------------
+// 
+void DevTokenServerDebug::PauseOOMTest()
+    {
+    ASSERT(iPauseCount == 0); // Don't nest
+    if (iCounter)
+        {
+        __UHEAP_RESET;
+        iPauseCount = User::CountAllocCells();
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// DevTokenServerDebug::ResumeOOMTest()
+// ---------------------------------------------------------------------------
+// 
+void DevTokenServerDebug::ResumeOOMTest()
+    {
+    if (iCounter)
+        {
+        ASSERT(iPauseCount > 0);
+        __UHEAP_FAILNEXT(iCounter - (iPauseCount - iStartCount));
+        iPauseCount = 0;
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// DevTokenServerDebug::HeapCheckStart()
+// ---------------------------------------------------------------------------
+// 
+void DevTokenServerDebug::HeapCheckStart()
+    {
+    iInitialAllocCount = User::CountAllocCells();
+    }
+
+
+// ---------------------------------------------------------------------------
+// DevTokenServerDebug::HeapCheckEnd()
+// ---------------------------------------------------------------------------
+//
+void DevTokenServerDebug::HeapCheckEnd()
+    {
+    TInt finalAllocCount = User::CountAllocCells();
+    TRAP_IGNORE(HeapErrorL(finalAllocCount != iInitialAllocCount));
+    // ignore errors
+    }
+
+
+// ---------------------------------------------------------------------------
+// DevTokenServerDebug::HeapErrorL()
+// Write or delete a file to signify to the test code that there's a memory leak
+// in the server.  This is unfortunately the best way of doing it since we can't
+// trap a panic when the server's shutting down.
+// ---------------------------------------------------------------------------
+//
+void DevTokenServerDebug::HeapErrorL(TBool aError)
+    {
+    RFs fs;
+    User::LeaveIfError(fs.Connect());
+
+    if (aError)
+        {
+        RFile file;
+        TInt err = file.Create(fs, KHeapErrorFile, EFileWrite | EFileShareExclusive);
+        if (err != KErrNone || err != KErrAlreadyExists)
+            {
+            User::Leave(err);
+            }
+        file.Close();
+        }
+    else
+        {
+        TInt err = fs.Delete(KHeapErrorFile);
+        if (err != KErrNone && err != KErrNotFound)
+            {
+            User::Leave(err);
+            }
+        }
+    }
+
+#endif
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Generic/Server/DevTokenUtil.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,149 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenUtil
+*
+*/
+
+
+#include <f32file.h>
+#include <s32file.h>
+#include "DevTokenUtil.h"
+
+/// Read/write drive the stores reside on
+_LIT(KFileStoreStandardDrive, "C:");
+/// Rom drive where the initial store data is
+_LIT(KFileStoreROMDrive, "Z:");
+
+// ======== LOCAL FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// PanicClient()
+// RMessage::Panic() also completes the message. This is:
+// (a) important for efficient cleanup within the kernel
+// (b) a problem if the message is completed a second time
+// ---------------------------------------------------------------------------
+// 
+void PanicClient(const RMessage2& aMessage, ETokenTypeServerPanic aPanic)
+    {
+    _LIT(KPanicClient,"TTSERVERCLIENT");
+    aMessage.Panic(KPanicClient,aPanic);
+    }
+
+
+// ---------------------------------------------------------------------------
+// PanicServer()
+// ---------------------------------------------------------------------------
+// 
+void PanicServer(ETokenTypeServerPanic aPanicCode)
+    {
+    _LIT(KPanicServer,"TOKENTYPESERVER");
+    User::Panic(KPanicServer, aPanicCode);
+    }
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// FileUtils::ExistsL()
+// ---------------------------------------------------------------------------
+// 
+TBool FileUtils::ExistsL(RFs& aFs, const TDesC& aFile)
+    {
+    TBool result = EFalse;
+    TBool open;
+    TInt err = aFs.IsFileOpen(aFile, open);
+
+    if (err == KErrNone)
+        {
+        result = ETrue;
+        }
+    else if (err != KErrNotFound && err != KErrPathNotFound)
+        {
+        User::Leave(err);
+        }
+
+    return result;
+    }
+
+
+// ---------------------------------------------------------------------------
+// FileUtils::EnsurePathL()
+// ---------------------------------------------------------------------------
+//
+void FileUtils::EnsurePathL(RFs& aFs, const TDesC& aFile)
+    {
+    TInt err = aFs.MkDirAll(aFile);
+    if (err != KErrNone && err != KErrAlreadyExists)
+        {
+        User::Leave(err);
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// FileUtils::CopyL()
+// ---------------------------------------------------------------------------
+//
+void FileUtils::CopyL(RFs& aFs, const TDesC& aSouce, const TDesC& aDest)
+    {
+    RFileReadStream in;
+    User::LeaveIfError(in.Open(aFs, aSouce, EFileRead | EFileShareReadersOnly));
+    CleanupClosePushL(in);
+
+    RFileWriteStream out;
+    User::LeaveIfError(out.Replace(aFs, aDest, EFileWrite | EFileShareExclusive));
+    CleanupClosePushL(out);
+
+    in.ReadL(out);  
+    CleanupStack::PopAndDestroy(2, &in);
+    }
+
+
+// ---------------------------------------------------------------------------
+// FileUtils::MakePrivateFilenameL()
+// ---------------------------------------------------------------------------
+//
+void FileUtils::MakePrivateFilenameL(RFs& aFs, const TDesC& aLeafName, 
+                                     TDes& aNameOut)
+    {
+    aNameOut.Copy(KFileStoreStandardDrive);
+
+    // Get private path
+    TBuf<20> privatePath;
+    aFs.PrivatePath(privatePath);
+    aNameOut.Append(privatePath);
+
+    aNameOut.Append(aLeafName);
+    }
+
+
+// ---------------------------------------------------------------------------
+// FileUtils::MakePrivateROMFilenameL()
+// ---------------------------------------------------------------------------
+//
+void FileUtils::MakePrivateROMFilenameL(RFs& aFs, const TDesC& aLeafName, 
+                                        TDes& aNameOut)
+    {
+    aNameOut.Copy(KFileStoreROMDrive);
+
+    // Get private path
+    TBuf<20> privatePath;
+    aFs.PrivatePath(privatePath);
+    aNameOut.Append(privatePath);
+
+    aNameOut.Append(aLeafName);
+    }
+    
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/KeyStore/Client/DevCertKeyStore.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1144 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevCertKeyStore
+*
+*/
+
+
+
+#include <asymmetrickeys.h>
+#include <e32debug.h>
+#include <mctkeystoreuids.h>            // KInterfaceKeyStore
+#include "DevCertKeyStore.h"
+#include "DevToken.h"
+#include "DevCertOpenedKeys.h"
+#include "DevTokenUtils.h"
+#include "DevTokenImplementationUID.hrh"
+#include "DevTokenMarshaller.h"
+#include "DevTokenCliServ.h"
+#include "DevTokenKeyInfoArray.h" //TDevTokenKeyInfoArray
+#include "DevtokenLog.h"
+
+
+// When retrieving data from the server we sometimes make a guess at the size of
+// the data that will be returned so we can allocate a buffer for it.  If it's
+// not big enough, the server tells us the required size and we retry.  These
+// values are the initial guesses at buffer size:
+
+const TInt KInitialBufSizeList = 1024;
+const TInt KInitialBufSizeOpen = 64;
+
+// ======== MEMBER FUNCTIONS ========
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::NewKeyStoreUserInterfaceL()
+// -----------------------------------------------------------------------------
+//
+MCTTokenInterface* CDevCertKeyStore::NewKeyStoreUserInterfaceL(
+                            MCTToken& aToken, 
+                            RDevTokenClientSession& aClient)
+    {
+    //  Destroyed by MCTTokenInterface::DoRelease() 
+    CDevCertKeyStore* me = new (ELeave) CDevCertKeyStore(KInterfaceKeyStore, 
+                                             aToken, 
+                                             aClient);                   
+    CleanupStack::PushL(me);
+    me->ConstructL();
+    CleanupStack::Pop(me);
+    return (me);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::NewKeyStoreManagerInterfaceL()
+// -----------------------------------------------------------------------------
+//
+MCTTokenInterface* CDevCertKeyStore::NewKeyStoreManagerInterfaceL(MCTToken& aToken, RDevTokenClientSession& aClient)
+    {
+    //  Destroyed by MCTTokenInterface::DoRelease()
+    TRACE_PRINT("CDevCertKeyStore::NewKeyStoreManagerInterfaceL -->1")
+    
+    CDevCertKeyStore* me = new (ELeave) CDevCertKeyStore(KInterfaceKeyStoreManager, 
+                                                         aToken, 
+                                                         aClient);
+    CleanupStack::PushL(me);
+    me->ConstructL();
+    TRACE_PRINT("CDevCertKeyStore::NewKeyStoreManagerInterfaceL -->2")
+    CleanupStack::Pop(me);
+    return (me);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::CDevCertKeyStore()
+// -----------------------------------------------------------------------------
+//
+CDevCertKeyStore::CDevCertKeyStore(TInt aUID, MCTToken& aToken, RDevTokenClientSession& aClient)
+    : CDTClient(aUID, aToken, aClient),
+    // Reference count starts at one as we're always created and 
+    // returned by a GetInterface() call on the token
+    iRefCount(1)
+    {
+    TRACE_PRINT("CDevCertKeyStore::CDevCertKeyStore: keystore client interface created");
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::ConstructL()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::ConstructL()
+    {
+    TRACE_PRINT("CDevCertKeyStore::ConstructL -->1")
+    CActiveScheduler::Add(this);
+    TRACE_PRINT("CDevCertKeyStore::ConstructL -->2")
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::~CDevCertKeyStore()
+// -----------------------------------------------------------------------------
+//
+CDevCertKeyStore::~CDevCertKeyStore()
+    {
+    Cleanup();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::Token()
+// -----------------------------------------------------------------------------
+//
+MCTToken& CDevCertKeyStore::Token()
+    {
+    return iToken;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::AddRef()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::AddRef()
+    {
+    ++iRefCount;
+    iToken.AddRef();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::DoRelease()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::DoRelease()
+    {
+    --iRefCount;
+    ASSERT( iRefCount >= 0 );
+    if ( iRefCount == 0 )
+        {
+        MCTTokenInterface::DoRelease();
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::ReleaseObject()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::ReleaseObject(const TCTTokenObjectHandle& aHandle)
+    {
+    iClientSession.SendRequest(ECloseObject, TIpcArgs(aHandle.iObjectId));
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::FreeKeyBuffer()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::FreeKeyBuffer()
+    {
+    delete iKey; 
+    iKey = NULL;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::AllocKeyBuffer()
+// -----------------------------------------------------------------------------
+//
+TInt CDevCertKeyStore::AllocKeyBuffer(TInt aReqdSize)
+    {
+    ASSERT(aReqdSize > 0);
+    
+    TInt result = KErrNoMemory;
+    FreeKeyBuffer();
+    iKey = HBufC8::NewMax(aReqdSize);
+    if ( iKey )
+        {
+        TPtr8 thePtr(iKey->Des());
+        thePtr.FillZ();
+        result = KErrNone;
+        }
+    return result;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::RunL()
+// Called when the server completes an asynchronous request.  Unmarshalls the
+// data from the server and passes it back to the caller.
+// -----------------------------------------------------------------------------
+// 
+void CDevCertKeyStore::RunL()
+    {
+    User::LeaveIfError(iStatus.Int());
+    
+    switch ( iCurrentRequest.OutstandingRequest() )
+        {
+        case ECreateKey:
+        case EImportKey:
+        case EImportEncryptedKey:
+        // Unmarshal the created key data and create CCTKeyInfo 
+        // to pass back to caller
+            UpdateKey();
+            break;
+
+        case EExportKey:
+        case EDHAgree:
+            {
+            *iClientPtr.iBuffer = HBufC8::NewL(iRequestPtr.Length());
+            TPtr8 ptr((*iClientPtr.iBuffer)->Des());
+            ptr.FillZ();
+            ptr.Copy(iRequestPtr);
+            break;
+            }
+        case ERepudiableDSASign:
+            DevTokenDataMarshaller::ReadL(iRequestPtr, *iClientPtr.iDSASignature);
+            break;
+
+        case ERepudiableRSASign:
+            DevTokenDataMarshaller::ReadL(iRequestPtr, *iClientPtr.iRSASignature);
+            break;
+
+        case EDecryptText:
+           iClientPtr.iDecryptedText->Copy(iRequestPtr);   
+           break;
+
+        case EDHPublicKey:
+           {
+           ASSERT(iDHParams);
+           RInteger n = iDHParams->TakeN();
+           CleanupStack::PushL(n);
+           RInteger g = iDHParams->TakeG();
+           CleanupStack::PushL(g);
+           RInteger X;
+           DevTokenDataMarshaller::ReadL(iRequestPtr, X);
+           CleanupStack::PushL(X);
+           *iClientPtr.iDHPublicKey = CDHPublicKey::NewL(n, g, X);
+           CleanupStack::Pop(3); // X, g, n
+           break;
+           }
+
+        default:
+            __ASSERT_DEBUG(EFalse, DevTokenPanic(EInvalidRequest));
+        }
+    Cleanup();
+    iCurrentRequest.Complete(KErrNone); 
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::Cleanup()
+// Clean up internal state
+// -----------------------------------------------------------------------------
+// 
+void CDevCertKeyStore::Cleanup()
+    {
+    FreeRequestBuffer();
+    FreeKeyBuffer();
+
+    // Zero client pointers
+    iClientPtr.iAny = NULL;
+    
+    delete iDHParams;
+    iDHParams = NULL;
+    
+    delete iText;
+    iText=NULL;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::RunError()
+// -----------------------------------------------------------------------------
+// 
+TInt CDevCertKeyStore::RunError(TInt aError)
+    {
+    Cleanup();
+    return CDTClient::RunError(aError);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::DoCancel()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::DoCancel()
+    {
+    TDevTokenMessages message = EIdle;
+
+    switch (iCurrentRequest.OutstandingRequest())
+        {
+        case ECreateKey:
+            message = ECancelCreateKey;
+            break;
+
+        case ERepudiableRSASign:
+            message = ECancelRSASign;
+            break;
+            
+        case ERepudiableDSASign:
+            message = ECancelDSASign;
+            break;
+            
+        case EDecryptText:
+            message = ECancelDecrypt;
+            break;
+      
+        case EDHPublicKey:
+        case EDHAgree:
+            message = ECancelDH;
+            break;      
+
+        case EImportKey:
+            message = ECancelImportKey;
+            break;
+        
+        case EImportEncryptedKey:
+			message = ECancelImportEncryptedKey;
+			break;
+        
+        case EExportKey:
+            message = ECancelExportKey;
+            break;
+
+        default:
+            // Nothing to do
+            break;
+        }
+
+    if ( message != EIdle )
+        {
+        iClientSession.SendRequest(message, TIpcArgs());
+        }
+
+    Cleanup();  
+    CDTClient::DoCancel();  
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::List()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::List(RMPointerArray<CCTKeyInfo>& aKeys, const TCTKeyAttributeFilter& aFilter, TRequestStatus& aStatus)
+    {
+    TDevTokenKeyInfoArray array(aKeys);
+    TRAPD(err, DoListL(aFilter, array));
+    FreeRequestBuffer();
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err); 
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::DoList()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::DoListL(const TCTKeyAttributeFilter& aFilter, MDevTokenKeyInfoArray& aOut)
+    {
+    //ASSERT(aOut.Count() == 0);
+    TPckg<TCTKeyAttributeFilter> filterPckg(aFilter);
+    SendSyncRequestAndHandleOverflowL(EListKeys, KInitialBufSizeList, TIpcArgs(&filterPckg, 0, &iRequestPtr));
+    
+    CleanupClosePushL(aOut);
+    DevTokenDataMarshaller::ReadL(iRequestPtr, iToken, aOut);
+
+    CleanupStack::Pop(&aOut);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::CancelList()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::CancelList()
+    {
+    // synchronous, nothing to do
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::GetKeyInfo()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::GetKeyInfo(TCTTokenObjectHandle aHandle, CCTKeyInfo*& aInfo, 
+                   TRequestStatus& aStatus)
+    {
+    TRAPD(err, DoGetKeyInfoL(aHandle, aInfo));
+    FreeRequestBuffer();
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::DoGetKeyInfoL()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::DoGetKeyInfoL(TCTTokenObjectHandle aHandle, 
+                                     CCTKeyInfo*& aInfo)
+    {
+    SendSyncRequestAndHandleOverflowL(EGetKeyInfo, KInitialBufSizeList, TIpcArgs(aHandle.iObjectId, 0, &iRequestPtr));
+    DevTokenDataMarshaller::ReadL(iRequestPtr, iToken, aInfo);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::CancelGetKeyInfo()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::CancelGetKeyInfo()
+    {
+    // synchronous, nothing to do
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::Open()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::Open(const TCTTokenObjectHandle& aHandle, 
+               MRSASigner*& aSigner, 
+               TRequestStatus& aStatus)
+    {
+    CDevCertRSARepudiableSigner* signer = CDevCertRSARepudiableSigner::New(this);
+    
+    TInt err = DoOpenKey(EOpenKeyRepudiableRSASign, aHandle, signer);
+    if ( err == KErrNone )
+        {
+        aSigner = signer;
+        }
+    
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::Open()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::Open(const TCTTokenObjectHandle& aHandle, 
+               MCTSigner<CDSASignature*>*& aSigner, 
+               TRequestStatus& aStatus)
+    { 
+    CDevCertDSARepudiableSigner* signer = CDevCertDSARepudiableSigner::New(this);
+    TInt err = DoOpenKey(EOpenKeyRepudiableDSASign, aHandle, signer);
+    if ( err == KErrNone )
+        {
+        aSigner = signer;
+        }
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::Open()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::Open(const TCTTokenObjectHandle& aHandle, 
+               MCTDecryptor*& aDecryptor,
+               TRequestStatus& aStatus)
+    {
+    CDevCertRSADecryptor* decryptor = CDevCertRSADecryptor::New(this);
+    TInt err = DoOpenKey(EOpenKeyDecrypt, aHandle, decryptor);
+    if ( err == KErrNone )
+        {
+        aDecryptor = decryptor;
+        }
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::Open()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::Open(const TCTTokenObjectHandle& aHandle, 
+               MCTDH*& aDH, TRequestStatus& aStatus)
+    {
+    CDevCertDHAgreement* dh = CDevCertDHAgreement::New(this);
+    TInt err = DoOpenKey(EOpenKeyAgree, aHandle, dh);
+    if ( err == KErrNone )
+        {
+        aDH = dh;
+        }
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::DoOpenKey()
+// -----------------------------------------------------------------------------
+//
+TInt CDevCertKeyStore::DoOpenKey(TDevTokenMessages aMessage,
+                  const TCTTokenObjectHandle& aHandle,
+                  CDevCertOpenedKey* aOpenedKey)
+    {
+    if ( !aOpenedKey )
+        {
+        return KErrNoMemory;
+        }
+    
+    // This is similar to SendSyncRequestAndHandleOverflowL, 
+    //but we're returning data in iLabel
+    TInt handle;
+    TPckg<TInt> handlePckg(handle);
+
+    HBufC* label = HBufC::NewMax(KInitialBufSizeOpen);
+    if ( !label )
+        {
+        aOpenedKey->Release();
+        return KErrNoMemory;
+        }
+    
+    TPtr labelPtr(label->Des());
+    
+    TIpcArgs args(aHandle.iObjectId, &handlePckg, 0, &labelPtr);
+    
+    TInt err = iClientSession.SendRequest(aMessage, args);
+    if ( err == KErrOverflow )
+        {
+        TInt sizeReqd = 0;
+        TPckg<TInt> theSize(sizeReqd);
+        TPtrC8 sizePtr(reinterpret_cast<const TUint8*>(label->Ptr()), 4);
+        theSize.Copy(sizePtr);  
+        delete label;
+        label = HBufC::NewMax(sizeReqd);
+        if ( label )
+            {
+            labelPtr.Set(label->Des());   
+            err = iClientSession.SendRequest(aMessage, args);
+            }
+        else
+            {
+            err = KErrNoMemory;
+            }
+        }
+
+    if ( err != KErrNone )
+        {
+        aOpenedKey->Release();
+        delete label;
+        return err;
+        }
+    
+    aOpenedKey->SetObjectID(handle);
+    aOpenedKey->SetLabel(label);
+    return KErrNone;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::CancelOpen()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::CancelOpen()
+    {
+    // synchronous, nothing to do
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::GetKeySizeL()
+// -----------------------------------------------------------------------------
+//
+TUint CDevCertKeyStore::GetKeySizeL(TInt aObjectId)
+    {
+    // Get the key size
+    TInt result = iClientSession.SendRequest(EGetKeyLength, TIpcArgs(aObjectId, &iRequestPtr));
+    User::LeaveIfError(result);
+    return result;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::GetKeySizeL()
+// Returns the public key in DER-encoded ASN-1 
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::ExportPublic(const TCTTokenObjectHandle& aHandle,
+                   HBufC8*& aPublicKey,
+                   TRequestStatus& aStatus)
+    {
+    TRAPD(err, DoExportPublicL(aHandle, aPublicKey));
+    FreeRequestBuffer();
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::DoExportPublicL()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::DoExportPublicL(const TCTTokenObjectHandle& aHandle, 
+                                       HBufC8*& aPublicKey)
+    {
+    // The size of the exported package is always less than keysize in bytes * 4 
+    // DSA generates packages twice as big as RSA
+    TUint bufSize = GetKeySizeL(aHandle.iObjectId) / 2;
+    SendSyncRequestAndHandleOverflowL(EExportPublic, bufSize, TIpcArgs(aHandle.iObjectId, &iRequestPtr));
+    aPublicKey = HBufC8::NewL(iRequestPtr.MaxLength());
+    TPtr8 ptr = aPublicKey->Des();
+    ptr.Copy(iRequestPtr);
+    } 
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::CancelExportPublic()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::CancelExportPublic()
+    {
+    // synchronous, nothing to do
+    }
+
+
+//  MCTKeyStoreManager
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::CreateKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::CreateKey(CCTKeyInfo*& aReturnedKey, TRequestStatus& aStatus)
+    {
+    //  [in, out] CCTKeyInfo, caller fills with data required to create the key, 
+    //  If request succeeds, iId and iHandle members are filled in by server
+    TInt r = MarshalKeyInfo(*aReturnedKey);
+    if ( KErrNone!=r )
+        {
+        TRequestStatus* stat = &aStatus;
+        User::RequestComplete(stat, r);
+        return;
+        }
+    //  Store CCTKeyInfo to write into later (server will put extra data into it)
+    iClientPtr.iKeyInfo = &aReturnedKey;
+    SetActive();
+    iCurrentRequest(ECreateKey, &aStatus);
+    iClientSession.SendAsyncRequest(ECreateKey, TIpcArgs(0, &iRequestPtr), &iStatus);   
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::CancelCreateKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::CancelCreateKey()
+    {
+    if ( iCurrentRequest.OutstandingRequest() == ECreateKey )
+        {
+        Cancel();
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::ImportKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::ImportKey(const TDesC8& aKey, CCTKeyInfo*& aReturnedKey, TRequestStatus& aStatus)
+    {
+    DoImportKey(EImportKey, aKey, aReturnedKey, aStatus);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::CancelImportKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::CancelImportKey()
+    {
+    if ( iCurrentRequest.OutstandingRequest() == EImportKey )
+        {
+        Cancel();
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::ImportEncryptedKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::ImportEncryptedKey(const TDesC8& aKey, 
+                                          CCTKeyInfo*& aReturnedKey, 
+                                          TRequestStatus& aStatus)
+    {
+    DoImportKey(EImportEncryptedKey, aKey, aReturnedKey, aStatus);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::CancelImportEncryptedKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::CancelImportEncryptedKey()
+    {
+    if (iCurrentRequest.OutstandingRequest() == EImportEncryptedKey)
+		{
+		Cancel();
+		}
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::DoImportKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::DoImportKey(TDevTokenMessages aMessage, 
+                                   const TDesC8& aKey, 
+                                   CCTKeyInfo*& aReturnedKey, 
+                                   TRequestStatus& aStatus)
+    { 
+    // [in] CCTKeyInfo, caller fills with data required to create the key,
+    // [out] TKeyUpdate, key iId and iHandle members from the server
+    TInt r = AllocKeyBuffer(aKey.Size());
+    if ( KErrNone!=r )
+        {
+        TRequestStatus* stat = &aStatus;
+        User::RequestComplete(stat, r);
+        return;
+        }
+
+    TPtr8 keyPtr(iKey->Des());
+    keyPtr.Copy(aKey);
+    
+    r = MarshalKeyInfo(*aReturnedKey);
+    if ( KErrNone!=r )
+        {
+        FreeKeyBuffer();
+        TRequestStatus* stat = &aStatus;
+        User::RequestComplete(stat, r);
+        return;
+        }
+
+    iClientPtr.iKeyInfo = &aReturnedKey;
+    SetActive();
+    iCurrentRequest(aMessage, &aStatus);
+    iClientSession.SendAsyncRequest(aMessage, TIpcArgs(iKey, &iRequestPtr), &iStatus);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::MarshalKeyInfo()
+// -----------------------------------------------------------------------------
+//
+TInt CDevCertKeyStore::MarshalKeyInfo(CCTKeyInfo& aKey)
+    {
+    TInt r = AllocRequestBuffer(DevTokenDataMarshaller::Size(aKey));
+    if ( KErrNone==r )  //  OOM or some catastrophe, no point continuing
+        {
+        DevTokenDataMarshaller::Write(aKey, iRequestPtr);
+        }
+    
+    return (r);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::ExportKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::ExportKey(TCTTokenObjectHandle aHandle, 
+                                 HBufC8*& aKey, 
+                                 TRequestStatus& aStatus)
+    {
+    TUint keySize=0;
+    TRAPD(r, keySize = GetKeySizeL(aHandle.iObjectId));
+    if ( KErrNone!=r )
+        {
+        TRequestStatus* stat = &aStatus;
+        User::RequestComplete(stat, r);
+        return; 
+        }
+
+    ASSERT(keySize);  
+
+    iClientPtr.iBuffer = &aKey;
+    iObjectId = aHandle.iObjectId;
+
+    r = AllocRequestBuffer((keySize/8)*6);   
+    // Heuristic, pkcs8 cleartext format is about 6 times the keysize in bytes...
+
+    if ( KErrNone!=r )  //  OOM or some catastrophe, no point continuing
+        {
+        TRequestStatus* stat = &aStatus;
+        User::RequestComplete(stat, r); 
+        }
+    else
+        {     
+        SetActive();
+        iCurrentRequest(EExportKey, &aStatus);
+        iClientSession.SendAsyncRequest(iCurrentRequest.OutstandingRequest(), TIpcArgs(iObjectId,  &iRequestPtr), &iStatus);    
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::CancelExportKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::CancelExportKey()
+    {
+    if ( iCurrentRequest.OutstandingRequest() == EExportKey )
+        {
+        Cancel();
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::ExportEncryptedKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::ExportEncryptedKey(TCTTokenObjectHandle /*aHandle*/, 
+                                          const CPBEncryptParms& /*aParams*/,  
+                                          HBufC8*& /*aKey*/, 
+                                          TRequestStatus& aStatus)
+    {
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete( status, KErrNotSupported );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertKeyStore::CancelExportEncryptedKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::CancelExportEncryptedKey()
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::RepudiableDSASign()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::RepudiableDSASign(const TCTTokenObjectHandle& aHandle,
+                      const TDesC8& aDigest,
+                      CDSASignature*& aSignature,
+                      TRequestStatus& aStatus)
+    { 
+    if ( aDigest.Length() > KMaxDSADigestSize )
+        {
+        TRequestStatus* stat = &aStatus;
+        User::RequestComplete(stat, KErrOverflow);  
+        }
+    else
+        {// Calls the same DSA digest function server side for DSA
+        iClientPtr.iDSASignature = &aSignature; 
+        Process(aHandle,aDigest,ERepudiableDSASign,aStatus,KMaxDSASignatureSize);
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::RepudiableRSASign()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::RepudiableRSASign(const TCTTokenObjectHandle& aHandle,
+                      const TDesC8& aDigest,
+                      CRSASignature*& aSignature,
+                      TRequestStatus& aStatus)
+    {
+    if ( aDigest.Length() > KMaxRSADigestSize )
+        {
+        TRequestStatus* stat = &aStatus;
+        User::RequestComplete(stat, KErrOverflow);  
+        }
+    else
+        {
+        iClientPtr.iRSASignature = &aSignature; 
+        Process(aHandle,aDigest,ERepudiableRSASign,aStatus,KMaxRSASignatureSize);
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::Process()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::Process(const TCTTokenObjectHandle& aHandle,
+                const TDesC8& aText,
+                TDevTokenMessages aMessage,
+                TRequestStatus& aStatus, TInt aBuffSize)
+    {
+    TInt err = AllocRequestBuffer(aBuffSize); //Assuming the buf is large enough
+    if (KErrNone!=err)  //  OOM or some catastrophe, no point continuing
+        {
+        TRequestStatus* stat = &aStatus;
+        User::RequestComplete(stat, err);
+        return;
+        } 
+    iObjectId = aHandle.iObjectId;  
+    iText = aText.Alloc();
+    if ( iText == NULL )
+        {
+        FreeRequestBuffer();
+        TRequestStatus* stat = &aStatus;
+        User::RequestComplete(stat, KErrNoMemory);
+        return;
+        }
+    SetActive();
+    iCurrentRequest(aMessage, &aStatus);
+    iClientSession.SendAsyncRequest(aMessage, TIpcArgs(iObjectId, iText, &iRequestPtr), &iStatus);
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::Decrypt()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::Decrypt(const TCTTokenObjectHandle& aHandle,
+                const TDesC8& aCiphertext,
+                TDes8& aDecryptedText,
+                TRequestStatus& aStatus)
+    {
+    iClientPtr.iDecryptedText = &aDecryptedText;
+    Process(aHandle,aCiphertext,EDecryptText,aStatus, KMaxRSAPlaintextSize);
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::DHPublicKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::DHPublicKey(const TCTTokenObjectHandle& aHandle, const TInteger& aN, const TInteger& aG,
+                  CDHPublicKey*& aX, TRequestStatus& aStatus)
+    {
+    TRAPD(err, DoDHPublicKeyL(aHandle, aN, aG, aX, aStatus));
+    if ( err != KErrNone )
+        {
+        delete iDHParams;
+        iDHParams = NULL;
+        FreeRequestBuffer();
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete(status, err);
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::DoDHPublicKeyL()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::DoDHPublicKeyL(const TCTTokenObjectHandle& aHandle, 
+                                      const TInteger& aN, const TInteger& aG,
+                     CDHPublicKey*& aX, TRequestStatus& aStatus)
+    {
+    iDHParams = CDevTokenDHParams::NewL(aN, aG);
+    
+    TInt sizeReqd = DevTokenDataMarshaller::Size(*iDHParams);
+    User::LeaveIfError(AllocRequestBuffer(sizeReqd));
+
+    DevTokenDataMarshaller::WriteL(*iDHParams, iRequestPtr);
+    
+    iObjectId = aHandle.iObjectId;
+    iClientPtr.iDHPublicKey = &aX;
+    iCurrentRequest(EDHPublicKey, &aStatus);
+    iClientSession.SendAsyncRequest(EDHPublicKey, TIpcArgs(iObjectId, &iRequestPtr), &iStatus); 
+    SetActive();
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::DHAgree()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::DHAgree(const TCTTokenObjectHandle& aHandle, 
+                               const CDHPublicKey& iY,
+                 HBufC8*& aAgreedKey, TRequestStatus& aStatus)
+    { 
+    TInt sizeReqd = DevTokenDataMarshaller::Size(iY);
+    TInt err = AllocRequestBuffer(sizeReqd);
+    if ( err != KErrNone )
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete(status, err);
+        return;
+        }
+
+    TRAP(err, DevTokenDataMarshaller::WriteL(iY, iRequestPtr));
+    if ( err != KErrNone )
+        {
+        FreeRequestBuffer();
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete(status, err);
+        return;   
+        }
+  
+    iObjectId = aHandle.iObjectId;
+    iClientPtr.iBuffer = &aAgreedKey;
+    iCurrentRequest(EDHAgree, &aStatus);
+    iClientSession.SendAsyncRequest(EDHAgree, TIpcArgs(iObjectId, &iRequestPtr), &iStatus); 
+    SetActive();
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::DeleteKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::DeleteKey(TCTTokenObjectHandle aHandle, TRequestStatus& aStatus)
+    {
+    TInt err = iClientSession.SendRequest(EDeleteKey, TIpcArgs(aHandle.iObjectId));
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::CancelDeleteKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::CancelDeleteKey()
+    {
+    // synchronous, nothing to do
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::SetUsePolicy()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::SetUsePolicy(TCTTokenObjectHandle aHandle, 
+                   const TSecurityPolicy& aPolicy,
+                   TRequestStatus& aStatus)
+    {
+    TPckgC<TSecurityPolicy> policyPckg(aPolicy);
+    TInt err = iClientSession.SendRequest(ESetUsePolicy, TIpcArgs(aHandle.iObjectId, &policyPckg));
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::CancelSetUsePolicy()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::CancelSetUsePolicy()
+    {
+    // synchronous, nothing to do
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::SetManagementPolicy()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::SetManagementPolicy(TCTTokenObjectHandle aHandle, 
+                      const TSecurityPolicy& aPolicy,
+                      TRequestStatus& aStatus)
+    {
+    TPckgC<TSecurityPolicy> policyPckg(aPolicy);
+    TInt err = iClientSession.SendRequest(ESetManagementPolicy, TIpcArgs(aHandle.iObjectId, &policyPckg));
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, err);
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::CancelSetManagementPolicy()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::CancelSetManagementPolicy()
+    {
+    // synchronous, nothing to do
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::UpdateKey()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::UpdateKey()
+    {
+    __ASSERT_DEBUG((iRequestPtr.Ptr()), DevTokenPanic(ENoDataMarshalled));
+    CCTKeyInfo& keyInfo = **iClientPtr.iKeyInfo;
+
+    // Set handle and key id returned from server
+    TDevTokenKeyUpdate update;
+    TPckg<TDevTokenKeyUpdate> pckg(update);
+    pckg.Copy(iRequestPtr);
+    keyInfo.SetHandle(update.iReference);
+    keyInfo.SetIdentifier(update.iId);
+    // Set size and algorithm - only strictly necessary for import
+    keyInfo.SetSize(update.iSize);
+    keyInfo.SetAlgorithm(update.iAlgorithm);
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::SetPassphraseTimeout()
+// -----------------------------------------------------------------------------
+//
+void CDevCertKeyStore::SetPassphraseTimeout(TInt /*aTimeout*/, TRequestStatus& aStatus) 
+    { 
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, KErrNone);
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::CancelSetPassphraseTimeout()
+// -----------------------------------------------------------------------------
+//    
+void CDevCertKeyStore::CancelSetPassphraseTimeout()
+    { 
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::Relock()
+// -----------------------------------------------------------------------------
+// 
+void CDevCertKeyStore::Relock(TRequestStatus& aStatus )
+    {
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete(status, KErrNone);
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CDevCertKeyStore::CancelRelock()
+// -----------------------------------------------------------------------------
+//     
+void CDevCertKeyStore::CancelRelock()
+    { 
+    }
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/KeyStore/Client/DevCertOpenedKeys.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,531 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevCertOpenedKey
+*
+*/
+
+
+
+#include <e32base.h>
+#include <ct.h>
+#include <mctkeystore.h>
+#include <mctkeystoreuids.h>
+#include <hash.h>
+#include "DevCertOpenedKeys.h"
+#include "DevCertKeyStore.h"
+
+
+// ======== MEMBER FUNCTIONS ========
+
+//CDevCertOpenedKey
+
+// -----------------------------------------------------------------------------
+// CDevCertOpenedKey::~CDevCertOpenedKey()
+// -----------------------------------------------------------------------------
+//
+CDevCertOpenedKey::~CDevCertOpenedKey()
+    {
+    if ( iClient )
+        {
+        iClient->ReleaseObject(iHandle);
+    	  }	
+    delete iLabel;
+    }
+
+// CDevCertRSARepudiableSigner
+
+// -----------------------------------------------------------------------------
+// CDevCertRSARepudiableSigner::New()
+// -----------------------------------------------------------------------------
+//
+CDevCertRSARepudiableSigner* CDevCertRSARepudiableSigner::New(CDevCertKeyStore* aClient)
+    {
+    return new CDevCertRSARepudiableSigner(aClient);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSARepudiableSigner::CDevCertRSARepudiableSigner()
+// -----------------------------------------------------------------------------
+//
+CDevCertRSARepudiableSigner::CDevCertRSARepudiableSigner(CDevCertKeyStore* aClient)
+    : MCTSigner<CRSASignature*>(aClient->Token())
+    {
+    iClient = aClient;
+    iHandle.iTokenHandle = aClient->Token().Handle();
+    iHandle.iObjectId = 0;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSARepudiableSigner::~CDevCertRSARepudiableSigner()
+// -----------------------------------------------------------------------------
+//
+CDevCertRSARepudiableSigner::~CDevCertRSARepudiableSigner()
+    {
+    delete iDigest;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSARepudiableSigner::Release()
+// -----------------------------------------------------------------------------
+//
+void CDevCertRSARepudiableSigner::Release()
+    {
+    MCTTokenObject::Release();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSARepudiableSigner::Label()
+// -----------------------------------------------------------------------------
+//
+const TDesC& CDevCertRSARepudiableSigner::Label() const
+    {
+    return iLabel ? static_cast<const TDesC&>(*iLabel) : static_cast<const TDesC&>(KNullDesC);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSARepudiableSigner::Token()
+// -----------------------------------------------------------------------------
+//
+MCTToken& CDevCertRSARepudiableSigner::Token() const
+    {
+    return iClient->Token();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSARepudiableSigner::Type()
+// -----------------------------------------------------------------------------
+//
+TUid CDevCertRSARepudiableSigner::Type() const
+    {
+    return KRSARepudiableSignerUID;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSARepudiableSigner::Handle()
+// -----------------------------------------------------------------------------
+//
+TCTTokenObjectHandle CDevCertRSARepudiableSigner::Handle() const
+    {
+    return iHandle;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSARepudiableSigner::SignMessage()
+// -----------------------------------------------------------------------------
+//
+void CDevCertRSARepudiableSigner::SignMessage(const TDesC8& aPlaintext, 
+          CRSASignature*& aSignature, 
+          TRequestStatus& aStatus)
+    {
+    // Hash the data on the client side
+    TRAPD(err, iDigest = CSHA1::NewL());
+    if (err != KErrNone)
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete(status, err);
+        }
+    else
+        {
+        iDigest->Update(aPlaintext);  
+        Sign(iDigest->Final(), aSignature, aStatus);
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSARepudiableSigner::Sign()
+// -----------------------------------------------------------------------------
+//
+void CDevCertRSARepudiableSigner::Sign(const TDesC8& aPlaintext, 
+          CRSASignature*& aSignature, 
+          TRequestStatus& aStatus)
+    {
+    iClient->RepudiableRSASign(Handle(),aPlaintext, aSignature, aStatus);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSARepudiableSigner::CancelSign()
+// -----------------------------------------------------------------------------
+//
+void CDevCertRSARepudiableSigner::CancelSign()
+    {
+    // Synchronous, no need to cancel
+    }
+
+
+// CDevCertDSARepudiableSigner 
+
+// -----------------------------------------------------------------------------
+// CDevCertDSARepudiableSigner::New()
+// -----------------------------------------------------------------------------
+//
+CDevCertDSARepudiableSigner* CDevCertDSARepudiableSigner::New(CDevCertKeyStore* aClient)
+    {
+    return new CDevCertDSARepudiableSigner(aClient);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDSARepudiableSigner::CDevCertDSARepudiableSigner()
+// -----------------------------------------------------------------------------
+//
+CDevCertDSARepudiableSigner::CDevCertDSARepudiableSigner(CDevCertKeyStore* aClient)
+    : MCTSigner<CDSASignature*>(aClient->Token())
+    {
+    iClient = aClient;
+    iHandle.iTokenHandle = aClient->Token().Handle();
+    iHandle.iObjectId = 0;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDSARepudiableSigner::~CDevCertDSARepudiableSigner()
+// -----------------------------------------------------------------------------
+//
+CDevCertDSARepudiableSigner::~CDevCertDSARepudiableSigner()
+    {
+    delete iDigest;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDSARepudiableSigner::Release()
+// -----------------------------------------------------------------------------
+//
+void CDevCertDSARepudiableSigner::Release()
+    {
+    MCTTokenObject::Release();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDSARepudiableSigner::Label()
+// -----------------------------------------------------------------------------
+//
+const TDesC& CDevCertDSARepudiableSigner::Label() const
+    {
+    return iLabel ? static_cast<const TDesC&>(*iLabel) : static_cast<const TDesC&>(KNullDesC);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDSARepudiableSigner::Token()
+// -----------------------------------------------------------------------------
+//
+MCTToken& CDevCertDSARepudiableSigner::Token() const
+    {
+    return iClient->Token();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDSARepudiableSigner::Type()
+// -----------------------------------------------------------------------------
+//
+TUid CDevCertDSARepudiableSigner::Type() const
+    {
+    return KDSARepudiableSignerUID;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDSARepudiableSigner::Handle()
+// -----------------------------------------------------------------------------
+//
+TCTTokenObjectHandle CDevCertDSARepudiableSigner::Handle() const
+    {
+    return iHandle;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDSARepudiableSigner::SignMessage()
+// -----------------------------------------------------------------------------
+//
+void CDevCertDSARepudiableSigner::SignMessage(const TDesC8& aPlaintext, 
+          CDSASignature*& aSignature, 
+        TRequestStatus& aStatus)
+    {
+    // Hash the data on the client side
+    TRAPD(err, iDigest = CSHA1::NewL());
+    if (err != KErrNone)
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete(status, err);
+        }
+    else
+        {
+        iDigest->Update(aPlaintext);
+        Sign(iDigest->Final(), aSignature, aStatus);
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDSARepudiableSigner::Sign()
+// -----------------------------------------------------------------------------
+//
+void CDevCertDSARepudiableSigner::Sign(const TDesC8& aPlaintext, 
+          CDSASignature*& aSignature, 
+        TRequestStatus& aStatus)
+    {
+    iClient->RepudiableDSASign(Handle(),aPlaintext, aSignature, aStatus);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDSARepudiableSigner::CancelSign()
+// -----------------------------------------------------------------------------
+//
+void CDevCertDSARepudiableSigner::CancelSign()
+    {
+    // Synchronous, no need to cancel
+    }
+
+
+// CDevCertRSADecryptor
+
+// -----------------------------------------------------------------------------
+// CDevCertRSADecryptor::New()
+// -----------------------------------------------------------------------------
+//
+CDevCertRSADecryptor* CDevCertRSADecryptor::New(CDevCertKeyStore* aClient)
+    {
+    return new CDevCertRSADecryptor(aClient);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSADecryptor::CDevCertRSADecryptor()
+// -----------------------------------------------------------------------------
+//
+CDevCertRSADecryptor::CDevCertRSADecryptor(CDevCertKeyStore* aClient)
+    : MCTDecryptor(aClient->Token())
+    {
+    iClient = aClient;
+    iHandle.iTokenHandle = aClient->Token().Handle();
+    iHandle.iObjectId = 0;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSADecryptor::~CDevCertRSADecryptor()
+// -----------------------------------------------------------------------------
+//
+CDevCertRSADecryptor::~CDevCertRSADecryptor()
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSADecryptor::Release()
+// -----------------------------------------------------------------------------
+//
+void CDevCertRSADecryptor::Release()
+    {
+    MCTTokenObject::Release();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSADecryptor::Label()
+// -----------------------------------------------------------------------------
+//
+const TDesC& CDevCertRSADecryptor::Label() const
+    {
+    return iLabel ? static_cast<const TDesC&>(*iLabel) : static_cast<const TDesC&>(KNullDesC);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSADecryptor::Token()
+// -----------------------------------------------------------------------------
+//
+MCTToken& CDevCertRSADecryptor::Token() const
+    {
+    return iClient->Token();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSADecryptor::Type()
+// -----------------------------------------------------------------------------
+//
+TUid CDevCertRSADecryptor::Type() const
+    {
+    return KPrivateDecryptorUID;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSADecryptor::Handle()
+// -----------------------------------------------------------------------------
+//
+TCTTokenObjectHandle CDevCertRSADecryptor::Handle() const
+    {
+    return iHandle;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSADecryptor::Decrypt()
+// -----------------------------------------------------------------------------
+//
+void CDevCertRSADecryptor::Decrypt(const TDesC8& aCiphertext,
+      TDes8& aPlaintext, 
+      TRequestStatus& aStatus)
+    {
+    iClient->Decrypt(Handle(),aCiphertext,aPlaintext, aStatus);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertRSADecryptor::CancelDecrypt()
+// -----------------------------------------------------------------------------
+//
+void CDevCertRSADecryptor::CancelDecrypt()
+    {
+    // Synchronous, no need to cancel
+    }
+
+
+// CDevCertDHAgreement
+
+// -----------------------------------------------------------------------------
+// CDevCertDHAgreement::New()
+// -----------------------------------------------------------------------------
+//
+CDevCertDHAgreement* CDevCertDHAgreement::New(CDevCertKeyStore* aClient)
+    {
+    return new CDevCertDHAgreement(aClient);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDHAgreement::CDevCertDHAgreement()
+// -----------------------------------------------------------------------------
+//
+CDevCertDHAgreement::CDevCertDHAgreement(CDevCertKeyStore* aClient)
+  : MCTDH(aClient->Token())
+    {
+    iClient = aClient;
+    iHandle.iTokenHandle = aClient->Token().Handle();
+    iHandle.iObjectId = 0;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDHAgreement::~CDevCertDHAgreement()
+// -----------------------------------------------------------------------------
+//
+CDevCertDHAgreement::~CDevCertDHAgreement()
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDHAgreement::Release()
+// -----------------------------------------------------------------------------
+//
+void CDevCertDHAgreement::Release()
+    {
+    MCTTokenObject::Release();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDHAgreement::Label()
+// -----------------------------------------------------------------------------
+//
+const TDesC& CDevCertDHAgreement::Label() const
+    {
+    return iLabel ? static_cast<const TDesC&>(*iLabel) : static_cast<const TDesC&>(KNullDesC);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDHAgreement::Token()
+// -----------------------------------------------------------------------------
+//
+MCTToken& CDevCertDHAgreement::Token() const
+    {
+    return iClient->Token();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDHAgreement::Type()
+// -----------------------------------------------------------------------------
+//
+TUid CDevCertDHAgreement::Type() const
+    {
+    return KKeyAgreementUID;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDHAgreement::Handle()
+// -----------------------------------------------------------------------------
+//
+TCTTokenObjectHandle CDevCertDHAgreement::Handle() const
+    {
+    return iHandle;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDHAgreement::PublicKey()
+// Returns the public key ('Big X') for the supplied set of parameters
+// -----------------------------------------------------------------------------
+//
+void CDevCertDHAgreement::PublicKey(const TInteger& aN, const TInteger& aG, 
+               CDHPublicKey*& aX, TRequestStatus& aStatus)
+    {
+    iClient->DHPublicKey(Handle(), aN, aG, aX, aStatus);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDHAgreement::Agree()
+// Agrees a session key given the public key of the other party
+// -----------------------------------------------------------------------------
+//
+void CDevCertDHAgreement::Agree(const CDHPublicKey& iY, HBufC8*& aAgreedKey,
+             TRequestStatus& aStatus)
+    {
+    iClient->DHAgree(Handle(), iY, aAgreedKey, aStatus);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CDevCertDHAgreement::CancelAgreement()
+// Cancels either a PublicKey or Agree operation
+// -----------------------------------------------------------------------------
+//
+void CDevCertDHAgreement::CancelAgreement()
+    {
+    // Synchronous, no need to cancel
+    }
+    
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/KeyStore/EComPlugin/DevTokenKeyStorePlugin.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,66 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenKeyStorePlugin
+*
+*/
+
+
+
+#include <e32std.h>
+#include <ecom/implementationproxy.h>
+#include <ct.h>
+#include "DevTokenImplementationUID.hrh"
+#include "DevTokenType.h"
+
+static CCTTokenType* NewFunctionL();
+
+// ======== LOCAL FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CCTTokenType* NewFunctionL()
+// ---------------------------------------------------------------------------
+//
+CCTTokenType* NewFunctionL()
+    {
+    CCTTokenType* DevCertKeyStore = NULL;
+    //Implementation UID of Device Token KeyStore
+    TUid uid;
+    uid.iUid = DEVCERTKEYSTORE_IMPLEMENTATION_UID;
+    DevCertKeyStore = CDevTokenType::NewL(uid);
+    return (DevCertKeyStore);
+    }
+
+
+// -----------------------------------------------------------------------------
+// TImplementationProxy ImplementationTable[] 
+// -----------------------------------------------------------------------------
+//
+const TImplementationProxy ImplementationTable[] =
+    {
+    IMPLEMENTATION_PROXY_ENTRY(DEVCERTKEYSTORE_IMPLEMENTATION_UID, NewFunctionL)
+    };
+
+
+// -----------------------------------------------------------------------------
+// TImplementationProxy* ImplementationGroupProxy()
+// This function is needed by ECom and is the only one exported function
+// -----------------------------------------------------------------------------
+//
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+    {
+    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
+    return (ImplementationTable);
+    }
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertCreateKey.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,311 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevCertKeyDataManager
+*
+*/
+
+
+#include <bigint.h>
+#include "DevCertCreateKey.h"
+#include "DevTokenServerDebug.h"
+#include "SimpleDHKey.h"
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CSimpleDHKey::NewL()
+// ---------------------------------------------------------------------------
+//
+CSimpleDHKey* CSimpleDHKey::NewL(TInt aSize)
+    {
+    CSimpleDHKey* me = new (ELeave) CSimpleDHKey();
+    CleanupStack::PushL(me);
+    me->ConstructL(aSize);
+    CleanupStack::Pop(me);
+    return (me);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CSimpleDHKey::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CSimpleDHKey::ConstructL(TInt aSize)
+    {
+    iKey = RInteger::NewRandomL(aSize - 1);             
+    }
+
+
+// ---------------------------------------------------------------------------
+// CSimpleDHKey::~CSimpleDHKey()
+// ---------------------------------------------------------------------------
+//
+CSimpleDHKey::~CSimpleDHKey()
+    {
+    iKey.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyCreator::CDevCertKeyCreator()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyCreator::CDevCertKeyCreator()
+: CActive(EPriorityStandard), iAction(EIdle)
+    {
+    CActiveScheduler::Add(this);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyCreator::~CDevCertKeyCreator()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyCreator::~CDevCertKeyCreator()
+    {
+    Cancel(); 
+    iCreatorThread.LogonCancel(iStatus);
+    iCreatorThread.Close();
+    delete iCreateData;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyCreator::DoCreateKeyAsyncL()
+//  Spin a thread to create an appropriate key, if successful, 
+// left on CleanupStack
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyCreator::DoCreateKeyAsyncL(CDevTokenKeyInfo::EKeyAlgorithm aAlgorithm, TInt aSize, TRequestStatus& aStatus)
+    {
+    if ( (aSize <= 0) ||
+    (aAlgorithm==CDevTokenKeyInfo::EInvalidAlgorithm) || 
+    ((aAlgorithm!=CDevTokenKeyInfo::ERSA) && (aAlgorithm!=CDevTokenKeyInfo::EDSA) && (aAlgorithm!=CDevTokenKeyInfo::EDH)) )
+    User::Leave(KErrArgument);
+
+    iClientStatus = &aStatus;
+    *iClientStatus = KRequestPending;
+
+    iCreateData = new (ELeave) CDevCertKeyCreatorData(aAlgorithm, aSize);
+
+    //  OK, ready to start the async operation...do it in RunL
+    iAction = EReadyToCreateKey;
+    iStatus = KRequestPending;
+    SetActive();
+    TRequestStatus* stat = &iStatus;
+    User::RequestComplete(stat, KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyCreator::CreatorThreadEntryPoint()
+// HERE'S THE THREAD TO CREATE THE KEY
+// Code cannot leave in here, but not as many traps as it looks
+// ---------------------------------------------------------------------------
+//
+TInt CDevCertKeyCreator::CreatorThreadEntryPoint(TAny* aParameters)
+    {
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+    if (!cleanup)
+    User::Exit(KErrNoMemory);
+
+    #ifdef _DEBUG
+    DevTokenServerDebug::PauseOOMTest();
+    #endif
+
+    ASSERT(aParameters);
+    TInt result = KErrNone;
+    CDevCertKeyCreatorData* createData = static_cast<CDevCertKeyCreatorData*>(aParameters);
+    switch (createData->iKeyAlgorithm)
+        {
+        case(CDevTokenKeyInfo::ERSA):
+            {// Currently, CRT signing is not supported, in case the key is to be used
+            //  for such, create a standard (private) key as part of the pair
+            TRAP(result, createData->iKey.iRSAKey = CRSAKeyPair::NewL(createData->iSize));
+            }
+        break;
+        case (CDevTokenKeyInfo::EDSA):
+            {
+            TRAP(result, createData->iKey.iDSAKey = CDSAKeyPair::NewL(createData->iSize));
+            }
+        break;
+        case (CDevTokenKeyInfo::EDH):
+            {// Generate a number that's less than N. The snag is that
+            //  we don't know what N is. We do know that it'll be of a
+            //  particular size, so we can safely generate any number
+            //  with less than iSize digits
+            TRAP(result, createData->iKey.iDHKey = CSimpleDHKey::NewL(createData->iSize));        
+            }
+        break;
+        default:
+        ASSERT(EFalse);
+        result = KErrArgument;
+        }
+
+    #ifdef _DEBUG
+    DevTokenServerDebug::ResumeOOMTest();
+    #endif
+
+    delete cleanup;
+    User::Exit(result);
+    return (KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyCreator::GetCreatedRSAKey()
+// ---------------------------------------------------------------------------
+//
+CRSAKeyPair* CDevCertKeyCreator::GetCreatedRSAKey()
+    {// Check algorithm is as expected, return NULL if no key or wrong type
+    if ( (!iCreateData) || (CDevTokenKeyInfo::ERSA!=iCreateData->iKeyAlgorithm) )
+    return (NULL);
+    else
+    return (iCreateData->iKey.iRSAKey);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyCreator::GetCreatedDSAKey()
+// ---------------------------------------------------------------------------
+//
+CDSAKeyPair* CDevCertKeyCreator::GetCreatedDSAKey()
+    {// Check algorithm is as expected, return NULL if no key or wrong type
+    if ( (!iCreateData) || (CDevTokenKeyInfo::EDSA!=iCreateData->iKeyAlgorithm) )
+    return (NULL);
+    else
+    return (iCreateData->iKey.iDSAKey);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyCreator::GetCreatedDHKey()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyCreator::GetCreatedDHKey(RInteger& aDHKey)
+    {
+    ASSERT(iCreateData);
+    ASSERT(CDevTokenKeyInfo::EDH==iCreateData->iKeyAlgorithm);    
+    aDHKey = iCreateData->iKey.iDHKey->DHKey();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyCreator::DoCancel()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyCreator::DoCancel()
+    {// Only do the cancel if in the middle of creating a key.  Kill the thread.
+    if (iAction!=EIdle)
+        {
+        TExitType exitType = iCreatorThread.ExitType();
+        if (EExitPending==exitType) //  Still alive, so kill it
+        iCreatorThread.Kill(KErrCancel);
+
+        iAction = EIdle;
+        }
+
+    ASSERT(iClientStatus);
+    User::RequestComplete(iClientStatus, KErrCancel);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyCreator::RunL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyCreator::RunL()
+    {
+    ASSERT(iClientStatus);
+
+    switch (iAction)
+        {
+        case (EReadyToCreateKey):
+            {// Spin off the thread and pass it the parameter data, then stand by
+            User::LeaveIfError(iCreatorThread.Create(KCreateKeyName, CreatorThreadEntryPoint, KDefaultStackSize, NULL, (TAny*)iCreateData));
+            iStatus = KRequestPending;
+            iCreatorThread.Logon(iStatus);
+            iAction = ECreatedKey;
+            SetActive();
+            iCreatorThread.Resume();
+            }
+        break;
+        case (ECreatedKey):
+            {// Notify the caller
+            ASSERT(iClientStatus);
+
+            // May be OOM creating logon, in which case we should kill thread
+            if (iStatus.Int() == KErrNoMemory)
+                {
+                TExitType exitType = iCreatorThread.ExitType();
+                if (EExitPending==exitType) //  Still alive, so kill it
+                iCreatorThread.Kill(KErrNone);
+                }
+
+            User::RequestComplete(iClientStatus, iStatus.Int());
+            iAction = EIdle;
+            }
+        break;
+        default:
+        ASSERT(EFalse);
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyCreator::RunError()
+// ---------------------------------------------------------------------------
+//
+TInt CDevCertKeyCreator::RunError(TInt anError)
+    {
+    if (iClientStatus)
+        {
+        User::RequestComplete(iClientStatus, anError);
+        }
+    return (KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyCreator::CDevCertKeyCreatorData::CDevCertKeyCreatorData()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyCreator::CDevCertKeyCreatorData::CDevCertKeyCreatorData(CDevTokenKeyInfo::EKeyAlgorithm aAlgorithm, TInt aSize)
+: iSize(aSize), iKeyAlgorithm(aAlgorithm)
+    {}
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyCreator::CDevCertKeyCreatorData::~CDevCertKeyCreatorData()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyCreator::CDevCertKeyCreatorData::~CDevCertKeyCreatorData()
+    {
+    if (iKeyAlgorithm==CDevTokenKeyInfo::ERSA)
+        {
+    	delete iKey.iRSAKey;
+        }
+    else if (iKeyAlgorithm==CDevTokenKeyInfo::EDSA)
+        {
+        delete iKey.iDSAKey;	
+        }
+    else if (iKeyAlgorithm==CDevTokenKeyInfo::EDH)
+        {
+    	delete iKey.iDHKey;
+        }
+    }
+    
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertKeyDataManager.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,693 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevCertKeyDataManager
+*
+*/
+
+
+
+#include "DevCertKeyDataManager.h"
+#include "DevTokenDataTypes.h"
+#include "DevTokenCliServ.h"
+#include "DevTokenUtil.h"
+
+_LIT(KDevCertKeyStoreFilename,"DevCertKeys.dat");
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager::NewL()
+// Key store data manager - maintains array of objects representing keys
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyDataManager* CDevCertKeyDataManager::NewL()
+    {
+    CDevCertKeyDataManager* self = new (ELeave) CDevCertKeyDataManager();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager::~CDevCertKeyDataManager()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyDataManager::~CDevCertKeyDataManager()
+    {
+    if (iFileStore)
+        {
+        CompactStore();
+        delete iFileStore;
+        }
+
+    iFile.Close(); // May already have been closed by store
+    iFs.Close();
+
+    iKeys.ResetAndDestroy();
+    iKeys.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager::CDevCertKeyDataManager()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyDataManager::CDevCertKeyDataManager() :
+  iRootStreamId(KNullStreamId),
+  iInfoStreamId(KNullStreamId)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyDataManager::ConstructL()
+    {
+    User::LeaveIfError(iFs.Connect());
+    OpenStoreL();
+
+    RStoreReadStream lookupStream;
+    lookupStream.OpenLC(*iFileStore, iInfoStreamId);
+
+    TInt count = lookupStream.ReadInt32L();
+    for (TInt index = 0; index < count; index++)
+        {
+        const CDevCertKeyData* keyData = CDevCertKeyData::NewL(lookupStream);
+
+        if (keyData->Handle() > iKeyIdentifier)
+        iKeyIdentifier = keyData->Handle();
+
+        iKeys.Append(keyData);
+        }
+
+    CleanupStack::PopAndDestroy(&lookupStream);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager::OpenStoreL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyDataManager::OpenStoreL()
+    {
+    //  Tries to locate a key store file on the default drive and then from ROM
+    //  If it cannot find one, tries to create a file with permanent file store
+    //  inside it In all cases, should initialise iFileStore unless it cannot
+    //  create the file/store/streams
+
+    __ASSERT_DEBUG(!iFileStore, PanicServer(EPanicStoreInitialised));
+
+    TFileName fullPath;
+    FileUtils::MakePrivateFilenameL(iFs, KDevCertKeyStoreFilename, fullPath);
+
+    FileUtils::EnsurePathL(iFs, fullPath);
+    TRAPD(result, OpenStoreInFileL(fullPath));
+
+    if (result == KErrInUse) 
+        {   
+        // Cannot access the file now. Abort server startup rather than wiping the keystore.
+        User::Leave(result); 
+        }
+
+    if (result != KErrNone)
+        {   
+        // Not yet opened a valid store, either no file to be found, or no valid
+        // store in it. Copy the original one stored in the ROM.
+        delete iFileStore;
+        iFileStore = NULL;
+
+        TFileName romPath;
+        FileUtils::MakePrivateROMFilenameL(iFs, KDevCertKeyStoreFilename, romPath);
+
+        if (result != KErrNotFound)
+            {
+            // Wipe the keystore if we can't open it (it's corrupt anyway)
+            User::LeaveIfError(iFs.Delete(fullPath));
+            }
+
+        // Copy data from rom and open it 
+        TRAPD(err,
+        FileUtils::CopyL(iFs, romPath, fullPath);
+        OpenStoreInFileL(fullPath)
+        );
+
+        if (KErrNone != err)
+            {
+            // We tried to copy the keystore from ROM. For some reason this
+            // failed and we still cannot open the file. Create a new one from
+            // scratch.
+            CreateStoreInFileL(fullPath);
+            }
+        }
+
+    __ASSERT_DEBUG(iFileStore, PanicServer(EPanicStoreInitialised));
+    __ASSERT_DEBUG((KNullStreamId!=iRootStreamId), PanicServer(EPanicRootStreamNotReady));
+    __ASSERT_DEBUG((KNullStreamId!=iInfoStreamId), PanicServer(EPanicManagerStreamNotReady));
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager::CreateStoreInFileL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyDataManager::CreateStoreInFileL(const TDesC& aFile)
+    {
+    TInt r = iFs.MkDirAll(aFile);
+    if ( (r!=KErrNone) && (r!=KErrAlreadyExists) )
+    User::Leave(r);
+
+    iFileStore = CPermanentFileStore::ReplaceL(iFs, aFile, EFileRead | EFileWrite | EFileShareExclusive);
+    iFileStore->SetTypeL(KPermanentFileStoreLayoutUid);
+
+    TCleanupItem cleanupStore(RevertStore, iFileStore);
+    CleanupStack::PushL(cleanupStore);
+
+    // Create info stream - Currently no passphrase created, and no keys
+    RStoreWriteStream managerStream;
+    iInfoStreamId = managerStream.CreateLC(*iFileStore);
+    managerStream.WriteUint32L(0); // Write key count of zero
+    managerStream.CommitL();
+    CleanupStack::PopAndDestroy(&managerStream);
+
+    // Create root stream - just contains id of info stream
+    RStoreWriteStream rootStream;
+    iRootStreamId = rootStream.CreateLC(*iFileStore);
+    iFileStore->SetRootL(iRootStreamId);
+    rootStream.WriteUint32L(iInfoStreamId.Value());   
+    rootStream.CommitL();
+    CleanupStack::PopAndDestroy(&rootStream);
+
+    WriteKeysToStoreL();
+
+    iFileStore->CommitL();
+    CleanupStack::Pop(); // cleanupStore
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager::OpenStoreInFileL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyDataManager::OpenStoreInFileL(const TDesC& aFile)
+    {
+    // Make sure the file isn't write protected
+    User::LeaveIfError(iFs.SetAtt(aFile, 0, KEntryAttReadOnly));
+
+    User::LeaveIfError(iFile.Open(iFs, aFile, EFileRead | EFileWrite | EFileShareExclusive));
+
+    iFileStore = CPermanentFileStore::FromL(iFile);   
+
+    // Get the salt, root and manager TStreamIds
+    iRootStreamId = iFileStore->Root();
+    if (iRootStreamId == KNullStreamId)
+        {
+        User::Leave(KErrCorrupt);
+        }
+
+    RStoreReadStream rootStream;
+    rootStream.OpenLC(*iFileStore, iRootStreamId);
+    iInfoStreamId = (TStreamId)(rootStream.ReadUint32L());
+    CleanupStack::PopAndDestroy(&rootStream);
+    }
+
+
+// Methods dealing with atomic updates to key data file 
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager::RevertStore()
+// This is a cleanup item that reverts the store
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyDataManager::RevertStore(TAny* aStore)
+    {
+    CPermanentFileStore* store = reinterpret_cast<CPermanentFileStore*>(aStore);
+    TRAP_IGNORE(store->RevertL());
+    // We're ignoring the leave code from this becuase there's no way we can
+    // handle this sensibly.  This shouldn't be a problem in practice - this
+    // will leave if for example the file store is on removable which is
+    // unexpectedly remove, and this is never the case for us.
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager::RevertStore()
+// Rewrites the info stream (ie the array of key data info) to the store
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyDataManager::WriteKeysToStoreL()
+    {
+    RStoreWriteStream lookupStream;
+    lookupStream.ReplaceLC(*iFileStore, iInfoStreamId);
+
+    TInt keyCount = iKeys.Count();
+    lookupStream.WriteInt32L(keyCount);
+
+    for (TInt index = 0; index < keyCount; index++)
+        {
+        const CDevCertKeyData* key = iKeys[index];
+        key->ExternalizeL(lookupStream);
+        }
+
+    lookupStream.CommitL();
+    CleanupStack::PopAndDestroy(&lookupStream);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager::AddL()
+// Add a key to the store.  Assumes that the key data streams (info, public key
+// and private key) have already been written.
+// ---------------------------------------------------------------------------
+// 
+void CDevCertKeyDataManager::AddL(const CDevCertKeyData* aKeyData)
+    {
+    ASSERT(aKeyData);
+
+    // Add the key to to the array, rewrite the infostream and 
+    // ONLY THEN commit the store
+    User::LeaveIfError(iKeys.Append(aKeyData));
+
+    TRAPD(err, WriteKeysToStoreL());
+
+    // Release ownership of key data and reset default passphrase id if store
+    // can't be written
+    TCleanupItem cleanupStore(RevertStore, iFileStore);
+    CleanupStack::PushL(cleanupStore);
+
+    if (err != KErrNone)
+        {
+        iKeys.Remove(iKeys.Count() - 1);
+        User::Leave(err);
+        }
+
+    iFileStore->CommitL();
+
+    CleanupStack::Pop(); // cleanupStore
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager::RemoveL()
+// "Transaction safe" key removal - only removes the key in memory and file if
+//  all operations are successful.
+// ---------------------------------------------------------------------------
+// 
+void CDevCertKeyDataManager::RemoveL(TInt aObjectId)
+    {
+    TInt index;
+    const CDevCertKeyData* key = NULL;
+    for (index = 0 ; index < iKeys.Count() ; ++index)
+        {
+        if (iKeys[index]->Handle() == aObjectId)
+            {
+            key = iKeys[index];
+            break;
+            }
+        }
+
+    if (!key)
+        {
+        User::Leave(KErrNotFound);
+        }
+
+    TCleanupItem cleanupStore(RevertStore, iFileStore);
+    CleanupStack::PushL(cleanupStore);  
+
+    iFileStore->DeleteL(key->PrivateDataStreamId());
+    iFileStore->DeleteL(key->PublicDataStreamId());
+    iFileStore->DeleteL(key->InfoDataStreamId());
+
+    // Remove the key
+    iKeys.Remove(index);
+
+    TRAPD(res, WriteKeysToStoreL());
+    if (res != KErrNone)
+        {
+        User::LeaveIfError(iKeys.Append(key)); // Put it back, shouldn't leave
+        User::Leave(res);
+        }
+    else 
+        {
+        delete key;   // Cannot leave from the point it's removed to here, so no cleanup stack!
+        }   
+    iFileStore->CommitL();
+
+    CleanupStack::Pop(); // cleanupStore
+    CompactStore();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager::IsKeyAlreadyInStore().
+// ---------------------------------------------------------------------------
+// 
+TBool CDevCertKeyDataManager::IsKeyAlreadyInStore(const TDesC& aKeyLabel) const
+    {// Check each key in the store to determine if aKeyLabel already exists
+    TInt keyCount = iKeys.Count();
+    TBool isInStore = EFalse;
+    for (TInt index = 0; index < keyCount; index++)
+        {
+        const TDesC& keyLabel = iKeys[index]->Label();
+        if (keyLabel.Compare(aKeyLabel)==0)
+            {
+            isInStore = ETrue;
+            break;
+            }
+        }
+
+    return (isInStore);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager::Count().
+// ---------------------------------------------------------------------------
+//
+TInt CDevCertKeyDataManager::Count() const
+    {
+    return iKeys.Count();
+    } 
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager:::operator[](TInt aIndex) const
+// ---------------------------------------------------------------------------
+//
+const CDevCertKeyData* CDevCertKeyDataManager::operator[](TInt aIndex) const
+    {
+    return iKeys[aIndex];
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager:::Lookup()
+// ---------------------------------------------------------------------------
+//
+const CDevCertKeyData* CDevCertKeyDataManager::Lookup(TInt aObjectId) const
+    {
+    TInt count = Count();
+    for (TInt i = 0; i < count; ++i)
+        {
+        if ((*this)[i]->Handle() == aObjectId)
+            {
+            return (*this)[i];
+            }
+        }
+    return NULL;
+    }
+
+
+//  Management of file and store therein
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager:::CreateKeyDataLC()
+// ---------------------------------------------------------------------------
+//
+const CDevCertKeyData* CDevCertKeyDataManager::CreateKeyDataLC( const TDesC& aLabel )
+    {
+    TInt objectId = ++iKeyIdentifier;
+    TStreamId infoData = CreateWriteStreamL();
+    TStreamId publicKeyData = CreateWriteStreamL();
+    TStreamId privateKeyData = CreateWriteStreamL();
+    return CDevCertKeyData::NewLC(objectId, aLabel, infoData, publicKeyData, privateKeyData);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager:::CreateWriteStreamL()
+//  Creates a new write stream in the store (which it then closes)
+//  Returns the TStreamId associated with it
+// ---------------------------------------------------------------------------
+//
+TStreamId CDevCertKeyDataManager::CreateWriteStreamL()
+    {
+    __ASSERT_DEBUG(iFileStore, PanicServer(EPanicStoreInitialised));
+    if (!iFileStore)
+    User::Leave(KErrNotReady);
+
+    RStoreWriteStream newStream;
+    TStreamId result = newStream.CreateLC(*iFileStore);
+    if (KNullStreamId == result)
+    User::Leave(KErrBadHandle);
+
+    newStream.CommitL();
+    CleanupStack::PopAndDestroy(&newStream);
+
+    return result;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager:::ReadKeyInfoLC()
+// ---------------------------------------------------------------------------
+//
+CDevTokenKeyInfo* CDevCertKeyDataManager::ReadKeyInfoLC(const CDevCertKeyData& aKeyData) const
+    {
+    __ASSERT_ALWAYS(iFileStore, PanicServer(EPanicStoreInitialised));
+    RStoreReadStream stream;
+    stream.OpenLC(*iFileStore, aKeyData.InfoDataStreamId());
+    CDevTokenKeyInfo* info = CDevTokenKeyInfo::NewL(stream);
+    CleanupStack::PopAndDestroy(&stream);
+    info->CleanupPushL();
+    if (info->Handle() != aKeyData.Handle())
+        {
+        User::Leave(KErrCorrupt); // is this appropriate?
+        }
+    return info;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager:::WriteKeyInfoL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyDataManager::WriteKeyInfoL(const CDevCertKeyData& aKeyData, const CDevTokenKeyInfo& aKeyInfo)
+    {
+    RStoreWriteStream infoStream;
+    OpenInfoDataStreamLC(aKeyData, infoStream);
+    infoStream << aKeyInfo;
+    infoStream.CommitL();
+    CleanupStack::PopAndDestroy(&infoStream);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager:::SafeWriteKeyInfoL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyDataManager::SafeWriteKeyInfoL(const CDevCertKeyData& aKeyData, const CDevTokenKeyInfo& aKeyInfo)
+    {
+    TCleanupItem cleanupStore(RevertStore, iFileStore);
+    CleanupStack::PushL(cleanupStore);  
+
+    WriteKeyInfoL(aKeyData, aKeyInfo);
+    iFileStore->CommitL();
+
+    CleanupStack::Pop(); // cleanupStore  
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager:::OpenInfoDataStreamLC()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyDataManager::OpenInfoDataStreamLC(const CDevCertKeyData& aKeyData, RStoreWriteStream& aStream)
+    {
+    __ASSERT_ALWAYS(iFileStore, PanicServer(EPanicStoreInitialised));
+    aStream.ReplaceLC(*iFileStore, aKeyData.InfoDataStreamId());
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager:::OpenPublicDataStreamLC()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyDataManager::OpenPublicDataStreamLC(const CDevCertKeyData& aKeyData, RStoreWriteStream& aStream)
+    {
+    __ASSERT_ALWAYS(iFileStore, PanicServer(EPanicStoreInitialised));
+    aStream.ReplaceLC(*iFileStore, aKeyData.PublicDataStreamId());
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager:::OpenPublicDataStreamLC()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyDataManager::OpenPublicDataStreamLC(const CDevCertKeyData& aKeyData, RStoreReadStream& aStream) const
+    {
+    __ASSERT_ALWAYS(iFileStore, PanicServer(EPanicStoreInitialised));
+    aStream.OpenLC(*iFileStore, aKeyData.PublicDataStreamId());
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager:::OpenPrivateDataStreamLC()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyDataManager::OpenPrivateDataStreamLC(const CDevCertKeyData& aKeyData, 
+                          RStoreWriteStream& aStream)
+    {
+    __ASSERT_DEBUG(iFileStore, PanicServer(EPanicStoreInitialised));
+    aStream.ReplaceLC(*iFileStore, aKeyData.PrivateDataStreamId());
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager:::OpenPrivateDataStreamLC()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyDataManager::OpenPrivateDataStreamLC(const CDevCertKeyData& aKeyData, 
+                          RStoreReadStream& aStream) 
+    {
+    __ASSERT_DEBUG(iFileStore, PanicServer(EPanicStoreInitialised));
+    aStream.OpenLC(*iFileStore, aKeyData.PrivateDataStreamId());
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyDataManager:::CompactStore()
+// Attempt to compact the store - it doesn't matter if these calls leave, it
+// will only mean that the store takes up more space than necessary.
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyDataManager::CompactStore()
+    {
+    ASSERT(iFileStore);
+    TRAP_IGNORE(iFileStore->ReclaimL(); iFileStore->CompactL());
+    }
+
+
+// CDevCertKeyData
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyData::NewLC()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyData* CDevCertKeyData::NewLC(TInt aObjectId, const TDesC& aLabel, TStreamId aInfoData,
+                  TStreamId aPublicData, TStreamId aPrivateData)
+    {
+    CDevCertKeyData* self = new (ELeave) CDevCertKeyData(aObjectId, aInfoData, aPublicData, aPrivateData);
+    CleanupStack::PushL(self);
+    self->ConstructL(aLabel);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyData::NewL()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyData* CDevCertKeyData::NewL(RStoreReadStream& aReadStream)
+    {
+    CDevCertKeyData* self = new (ELeave) CDevCertKeyData();
+    CleanupStack::PushL(self);
+    self->InternalizeL(aReadStream);
+    CleanupStack::Pop(self);
+    return (self);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyData::~CDevCertKeyData()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyData::~CDevCertKeyData()
+    {
+    delete iLabel;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyData::CDevCertKeyData()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyData::CDevCertKeyData(TInt aObjectId, TStreamId aInfoData,
+               TStreamId aPublicData, TStreamId aPrivateData) :
+  iObjectId(aObjectId), iInfoData(aInfoData), 
+  iPublicKeyData(aPublicData), iPrivateKeyData(aPrivateData)
+    {
+    ASSERT(iObjectId);
+    ASSERT(iInfoData != KNullStreamId);
+    ASSERT(iPublicKeyData != KNullStreamId);
+    ASSERT(iPrivateKeyData != KNullStreamId);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyData::CDevCertKeyData()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyData::CDevCertKeyData()
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyData::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyData::ConstructL(const TDesC& aLabel)
+    {
+    TInt labelLen = aLabel.Length();
+    iLabel = HBufC::NewMaxL(labelLen);
+    TPtr theLabel(iLabel->Des());
+    theLabel.FillZ();
+    theLabel.Copy(aLabel);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyData::InternalizeL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyData::InternalizeL(RReadStream& aReadStream)
+    {
+    iObjectId = aReadStream.ReadInt32L();
+    iInfoData.InternalizeL(aReadStream);
+    iPublicKeyData.InternalizeL(aReadStream);
+    iPrivateKeyData.InternalizeL(aReadStream);
+
+    TInt labelLen = aReadStream.ReadInt32L();
+    iLabel = HBufC::NewMaxL(labelLen);
+    TPtr theLabel((TUint16*)iLabel->Ptr(), labelLen, labelLen);
+    theLabel.FillZ(labelLen);
+    aReadStream.ReadL(theLabel);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyData::ExternalizeL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyData::ExternalizeL(RWriteStream& aWriteStream) const
+    {
+    aWriteStream.WriteInt32L(iObjectId);
+    iInfoData.ExternalizeL(aWriteStream);
+    iPublicKeyData.ExternalizeL(aWriteStream);
+    iPrivateKeyData.ExternalizeL(aWriteStream);
+
+    TInt labelLen = iLabel->Length();
+    aWriteStream.WriteInt32L(labelLen);
+    TPtr theLabel(iLabel->Des());
+    theLabel.SetLength(labelLen);
+    aWriteStream.WriteL(theLabel);
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertKeyEncryptor.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,118 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevCertKeyEncryptor
+*
+*/
+
+
+#include <ecom/ecom.h>
+#include "DevCertKeyEncryptor.h"
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyEncryptor::NewL()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyEncryptor* CDevCertKeyEncryptor::NewL()
+    {
+    CDevCertKeyEncryptor* self = NewLC();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyEncryptor::NewLC()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyEncryptor* CDevCertKeyEncryptor::NewLC()
+    {
+    CDevCertKeyEncryptor* self = new(ELeave)CDevCertKeyEncryptor();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyEncryptor::~CDevCertKeyEncryptor()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyEncryptor::~CDevCertKeyEncryptor()
+    {
+    REComSession::DestroyedImplementation(iDtorIDKey);  
+
+    if(iKeyEncryptor)
+        {
+        iKeyEncryptor->Release(); 
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyEncryptor::CreateImplementationL()
+// ---------------------------------------------------------------------------
+//
+MKeyEncryptor* CDevCertKeyEncryptor::CreateImplementationL()
+    {
+    TAny* ptr = REComSession::CreateImplementationL(iImplementationUID, iDtorIDKey);
+    iKeyEncryptor = static_cast<MKeyEncryptor*>(ptr);
+    return iKeyEncryptor;   
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyEncryptor::IsPluginExistL()
+// ---------------------------------------------------------------------------
+//
+TBool CDevCertKeyEncryptor::IsPluginExistL()
+    {
+    RImplInfoPtrArray array;    
+    REComSession::ListImplementationsL(KKeyEncryptorInterfaceUID, array);
+
+    if( array.Count())
+        { 
+        iImplementationUID  = array[0]->ImplementationUid();
+        array.ResetAndDestroy();
+        return ETrue;
+        }
+    else
+        {
+        array.ResetAndDestroy();  
+        return EFalse;
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyEncryptor::CDevCertKeyEncryptor()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyEncryptor::CDevCertKeyEncryptor()
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyEncryptor::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyEncryptor::ConstructL()
+    {
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertKeyStoreConduit.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1075 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevCertKeyStoreConduit
+*
+*/
+
+
+
+#ifdef SYMBIAN_ENABLE_SPLIT_HEADERS
+#include <mctkeystoreuids.h>
+#endif
+#include "DevCertKeyStoreConduit.h"
+#include "DevCertKeyStoreServer.h"
+#include "DevCertKeyStoreSession.h"
+#include "DevCertOpenedKeysSrv.h"
+#include "DevTokenDataTypes.h"
+#include "DevTokenMarshaller.h"
+#include "DevTokenUtil.h"
+#include <asymmetric.h>
+#include <mctkeystoremanager.h>
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// CDevCertKeyStoreConduit
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::NewL()
+// ---------------------------------------------------------------------------
+// 
+CDevCertKeyStoreConduit* CDevCertKeyStoreConduit::NewL(CDevCertKeyStoreServer& aServer)
+    {
+    CDevCertKeyStoreConduit* self = new (ELeave) CDevCertKeyStoreConduit(aServer);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::~CDevCertKeyStoreConduit()
+// ---------------------------------------------------------------------------
+// 
+CDevCertKeyStoreConduit::~CDevCertKeyStoreConduit()
+    {
+    Cancel();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::CDevCertKeyStoreConduit()
+// ---------------------------------------------------------------------------
+// 
+CDevCertKeyStoreConduit::CDevCertKeyStoreConduit(CDevCertKeyStoreServer& aServer)
+  : CActive(EPriorityHigh), iServer(aServer), iCurrentRequest(iStatus)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::ConstructL()
+    {
+    CActiveScheduler::Add(this);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::ServiceRequestL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::ServiceRequestL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession)
+    {
+    TDevTokenMessages request = static_cast<TDevTokenMessages>(aMessage.Function());
+
+    if (iCurrentRequest.OutstandingRequest()!=EIdle)
+        {
+        //  There is currently a request outstanding, only allow this one if it's a cancel
+        if ( (request!=ECancelCreateKey) &&
+        (request!=ECancelImportKey) &&
+        (request!=ECancelImportEncryptedKey) &&
+        (request!=ECancelExportKey) &&
+        (request!=ECancelRSASign) &&
+        (request!=ECancelDSASign) &&
+        (request!=ECancelDecrypt) )
+            {
+            User::Leave(KErrServerBusy);
+            }
+        }
+
+    switch (request)
+        {
+        case EListKeys:
+            ListL(aMessage);
+            break;
+        case EGetKeyInfo:
+            GetKeyInfoL(aMessage);
+            break;
+        case ECreateKey:
+            CreateKeyL(aMessage);
+            break;
+        case ECancelCreateKey:
+            CancelCreateKey(aMessage);
+            break;
+        case EImportKey:
+        case EImportEncryptedKey:
+            ImportKeyL(aMessage);
+            break;
+        case ECancelImportKey:
+        case ECancelImportEncryptedKey:
+            CancelImportKey(aMessage);
+            break;
+        case EExportKey:
+            ExportKeyL(aMessage);
+            break;
+        case ECancelExportKey:
+            CancelExportKey(aMessage);
+            break;
+        case EExportPublic:
+            ExportPublicL(aMessage);
+            break;
+        case EGetKeyLength:
+            GetKeyLengthL(aMessage);
+            break;
+        case EDeleteKey:
+            DeleteKeyL(aMessage);
+            break;
+        case ESetUsePolicy:
+            SetUsePolicyL(aMessage);
+            break;
+        case ESetManagementPolicy:
+            SetManagementPolicyL(aMessage);
+            break;
+        case EOpenKeyRepudiableRSASign:
+            OpenKeyL(aMessage, aSession, KRSARepudiableSignerUID);
+            break;
+        case EOpenKeyRepudiableDSASign:
+            OpenKeyL(aMessage, aSession, KDSARepudiableSignerUID);
+            break;
+        case EOpenKeyDecrypt:
+            OpenKeyL(aMessage, aSession, KPrivateDecryptorUID);
+            break;
+        case EOpenKeyAgree:
+            OpenKeyL(aMessage, aSession, KKeyAgreementUID);
+            break;
+        case ECloseObject:
+            CloseObjectL(aMessage, aSession);
+            break;
+        case ERepudiableDSASign:
+            RepudiableDSASignL(aMessage, aSession);
+            break;
+        case ECancelDSASign:
+            CancelDSASign(aMessage);
+            break;         
+        case ERepudiableRSASign:
+            RepudiableRSASignL(aMessage, aSession);
+            break;
+        case ECancelRSASign:
+            CancelRSASign(aMessage);
+            break;         
+        case EDecryptText:
+            DecryptL(aMessage, aSession);
+            break;
+        case ECancelDecrypt:
+            CancelDecrypt(aMessage);
+            break;         
+        case EDHPublicKey:
+            DHPublicKeyL(aMessage, aSession);
+            break;
+        case EDHAgree:
+            DHAgreeL(aMessage, aSession);
+            break;
+        case ECancelDH:
+            CancelDH(aMessage);
+            break;         
+
+        default:  //  Should not reach here
+            __ASSERT_DEBUG(EFalse, PanicServer(EPanicInvalidRequest));
+            User::Leave(KErrNotSupported);
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::ListL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::ListL(const RMessage2& aMessage)
+    {
+    //  p[0] has the filter to use
+    RCPointerArray<CDevTokenKeyInfo> keyInfos;
+    CleanupClosePushL(keyInfos);
+
+    TPckgBuf<TCTKeyAttributeFilter> filter;
+    aMessage.ReadL(0, filter);
+
+    iServer.ListL(filter(), keyInfos);
+
+    TInt bufSize = User::LeaveIfError(aMessage.GetDesMaxLength(2)); 
+    TInt reqdSize = DevTokenDataMarshaller::Size(keyInfos);
+    if (bufSize >= reqdSize)
+        {
+        HBufC8* buffer = HBufC8::NewMaxLC(reqdSize);
+        TPtr8 thePtr(buffer->Des());
+        DevTokenDataMarshaller::Write(keyInfos, thePtr);
+        aMessage.WriteL(2, thePtr);
+        CleanupStack::PopAndDestroy(buffer);
+        }
+    else
+        {
+        TPckg<TInt> sizePckg(reqdSize);
+        aMessage.WriteL(2, sizePckg);
+        User::Leave(KErrOverflow);
+        }
+
+    CleanupStack::PopAndDestroy(&keyInfos); // keyInfos
+    aMessage.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::GetKeyInfoL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::GetKeyInfoL(const RMessage2& aMessage)
+    {
+    //  Token object to delete is in p[0]
+    TInt objectId = aMessage.Int0();
+    CDevTokenKeyInfo* info = NULL;
+    iServer.GetKeyInfoL(objectId, info);
+    info->CleanupPushL();
+
+    TInt bufferSize = User::LeaveIfError(aMessage.GetDesMaxLength(2));
+    TInt requiredSize = DevTokenDataMarshaller::Size(*info);
+
+    if (bufferSize >= requiredSize)
+        {
+        HBufC8* buffer = HBufC8::NewMaxLC(requiredSize);
+        TPtr8 thePtr(buffer->Des());
+        DevTokenDataMarshaller::Write(*info, thePtr);
+        aMessage.WriteL(2, thePtr);
+        CleanupStack::PopAndDestroy(buffer);
+        }
+    else
+        {
+        TPckg<TInt> theSize(requiredSize);
+        aMessage.WriteL(2, theSize);
+        User::Leave(KErrOverflow);
+        }
+
+    CleanupStack::PopAndDestroy(info);
+    aMessage.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::GetClientUidL()
+// Work out the UID of the client process.
+// ---------------------------------------------------------------------------
+//
+TUid CDevCertKeyStoreConduit::GetClientUidL(const RMessage2& aMessage) const
+    {
+    RThread clientThread;
+    User::LeaveIfError(aMessage.Client(clientThread));
+    CleanupClosePushL(clientThread);  
+    RProcess clientProcess;
+    User::LeaveIfError(clientThread.Process(clientProcess));
+    CleanupClosePushL(clientProcess);
+    TUid uid = clientProcess.Type()[2];
+    CleanupStack::PopAndDestroy(2); // clientProcess, clientThread
+    return uid;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::CreateKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::CreateKeyL(const RMessage2& aMessage)
+    {
+    ASSERT(!iKeyInfo);
+    //  p[0] has the length of the buffer. Check our buffer is big
+    //  enough, to cope with requests for keys with very long labels.
+
+    TInt bufLength = User::LeaveIfError(aMessage.GetDesLength(1));
+    HBufC8* keyInfoBuf = HBufC8::NewMaxLC(bufLength);
+
+    //  p[1] has the CDevTokenKeyInfo structure required to create a key
+    //  Read it and convert from descriptor back to a CDevTokenKeyInfo
+    TPtr8 thePtr(keyInfoBuf->Des());
+    thePtr.FillZ();
+
+    aMessage.ReadL(1, thePtr);
+    DevTokenDataMarshaller::ReadL(*keyInfoBuf, iKeyInfo);
+    CleanupStack::PopAndDestroy(keyInfoBuf);
+
+    iCurrentRequest.Set(ECreateKey, aMessage);
+    iStatus = KRequestPending;
+    SetActive();
+    iServer.CreateKey(*iKeyInfo, iStatus);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::CancelCreateKey()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::CancelCreateKey(const RMessage2& aMessage)
+    {
+    if (iCurrentRequest.OutstandingRequest() == ECreateKey)
+        {
+        Cancel();
+        }
+    aMessage.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::ImportKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::ImportKeyL(const RMessage2& aMessage)
+    {
+    ASSERT(!iImportKey);
+    ASSERT(!iKeyInfo);
+
+    // p[0] has the descriptor containing the PKCS8 object (not be encrypted)
+    TInt keyLen = User::LeaveIfError(aMessage.GetDesLength(0));
+
+    HBufC8* importBuf = HBufC8::NewMaxLC(keyLen);
+    TPtr8 theKeyData(importBuf->Des());
+    theKeyData.FillZ();
+    aMessage.ReadL(0, theKeyData);
+
+    TInt bufLen = User::LeaveIfError(aMessage.GetDesLength(1));
+    HBufC8* keyInfoBuf = HBufC8::NewMaxLC(bufLen);
+
+    // p[1] has the CDevTokenKeyInfo structure required to create a key
+    // Read it and convert from descriptor back to a CDevTokenKeyInfo
+    TPtr8 thePtr(keyInfoBuf->Des());
+    thePtr.FillZ();
+    aMessage.ReadL(1, thePtr);
+
+    DevTokenDataMarshaller::ReadL(*keyInfoBuf, iKeyInfo);
+    CleanupStack::PopAndDestroy(keyInfoBuf);
+
+    iImportKey = importBuf;
+    CleanupStack::Pop(importBuf);
+
+    iCurrentRequest.Set(static_cast<TDevTokenMessages>(aMessage.Function()), aMessage);
+    iStatus = KRequestPending;
+    SetActive();
+    
+    TBool isEncrypted = (aMessage.Function() == EImportEncryptedKey);
+	iServer.ImportKey(*iImportKey, *iKeyInfo, isEncrypted, iStatus);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::CancelImportKey()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::CancelImportKey(const RMessage2& aMessage)
+    {
+    if (iCurrentRequest.OutstandingRequest() == EImportKey ||
+		iCurrentRequest.OutstandingRequest() == EImportEncryptedKey)
+        {
+        Cancel();
+        }
+    aMessage.Complete(KErrNone); 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::GetKeyLengthL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::GetKeyLengthL(const RMessage2& aMessage)
+    {
+    TInt length = iServer.GetKeyLengthL(aMessage.Int0());
+    ASSERT(length > 0);
+    aMessage.Complete(length);    
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::CancelExportKey()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::CancelExportKey(const RMessage2& aMessage)
+    {
+    if (iCurrentRequest.OutstandingRequest() == EExportKey ||
+        iCurrentRequest.OutstandingRequest() == EImportEncryptedKey)
+        {
+        Cancel();
+        }
+    aMessage.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::ExportKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::ExportKeyL(const RMessage2& aMessage)
+    {
+    ASSERT(!iExportBuf);
+
+    TInt objectId = aMessage.Int0();
+    TInt bufLen = User::LeaveIfError(aMessage.GetDesMaxLength(1));  // #1 IPC argument is the request Ptr
+
+    HBufC8* exportBuf =  HBufC8::NewMaxLC(bufLen);
+    TPtr8 temp(exportBuf->Des());
+    temp.FillZ();
+
+    // No more leaves
+    iExportBuf = exportBuf;
+    CleanupStack::Pop(exportBuf);
+
+    iCurrentRequest.Set(static_cast<TDevTokenMessages>(aMessage.Function()), aMessage); 
+    iStatus = KRequestPending;
+    SetActive();    
+
+    if (aMessage.Function() == EExportKey) 
+        {
+        iServer.ExportKey(objectId, temp, iStatus);
+        }    
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::ExportPublicL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::ExportPublicL(const RMessage2& aMessage)
+    {
+    TInt objectId = aMessage.Int0();
+    TInt bufLen = User::LeaveIfError(aMessage.GetDesMaxLength(1));
+
+    HBufC8* exportBuf = HBufC8::NewMaxLC(bufLen);
+    TPtr8 ptr(exportBuf->Des());
+    ptr.FillZ();
+    iServer.ExportPublicL(objectId, ptr);
+    aMessage.WriteL(1, ptr);
+
+    CleanupStack::PopAndDestroy(exportBuf);
+    aMessage.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::DeleteKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::DeleteKeyL(const RMessage2& aMessage)
+    {
+    TInt objectId = aMessage.Int0();
+    iServer.DeleteKeyL(objectId);
+    aMessage.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::SetUsePolicyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::SetUsePolicyL(const RMessage2& aMessage)
+    {
+    TInt objectId = aMessage.Int0();
+    TSecurityPolicyBuf policyBuf;
+
+    aMessage.ReadL(1, policyBuf);
+
+    iServer.SetUsePolicyL(objectId, policyBuf());
+    aMessage.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::SetManagementPolicyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::SetManagementPolicyL(const RMessage2& aMessage)
+    {
+    TInt objectId = aMessage.Int0();
+    TSecurityPolicyBuf policyBuf;
+
+    aMessage.ReadL(1, policyBuf);
+
+    iServer.SetManagementPolicyL(objectId, policyBuf());
+    aMessage.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::OpenKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::OpenKeyL(const RMessage2& aMessage, 
+                                       CDevCertKeyStoreSession& aSession, 
+                                       TUid aType)
+    { 
+    CDevCertOpenedKeySrv* openedKey = iServer.OpenKeyL(aMessage.Int0(), aType);
+    CleanupStack::PushL(openedKey);
+
+    const TDesC& label = openedKey->Label();
+
+    TInt writeBufLen = User::LeaveIfError(aMessage.GetDesMaxLength(3));
+    TInt reqdLength = label.Length();
+    if (writeBufLen < reqdLength)
+        {
+        // We're writing into a TDes16 so we can't use TPckg<TInt>
+        TPtrC sizePtr(reinterpret_cast<TUint16*>(&reqdLength), 2);
+        aMessage.WriteL(3, sizePtr);
+        User::Leave(KErrOverflow);
+        }
+
+    aMessage.WriteL(3, label);
+
+    TInt handle = aSession.AddOpenedKeyL(*openedKey);
+
+    TPckg<TInt> handlePckg(handle);
+    TRAPD(err, aMessage.WriteL(1, handlePckg));
+
+    if (err != KErrNone)
+        {
+        aSession.RemoveOpenedKeyL(handle);
+        User::Leave(err);
+        }
+
+    CleanupStack::Pop(openedKey); // now owned by session
+    aMessage.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::RepudiableRSASignL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::RepudiableRSASignL(const RMessage2& aMessage, 
+                                         CDevCertKeyStoreSession& aSession)
+    {
+    ASSERT( iOpenedKey == NULL );
+    TPtr8 thePtr(0,0);
+    iOpenedKey = ProcessL(aMessage, aSession, KRSARepudiableSignerUID, ERepudiableRSASign, thePtr);
+    static_cast<CDevCertRSARepudiableSignerSrv*>(iOpenedKey)->Sign(thePtr, iRSASignature, iStatus);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::CancelRSASign()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::CancelRSASign(const RMessage2& aMessage)
+    {
+    if (iCurrentRequest.OutstandingRequest() == ERepudiableRSASign)
+        {
+        Cancel();
+        }
+    aMessage.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::RepudiableDSASignL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::RepudiableDSASignL(const RMessage2& aMessage, 
+                                          CDevCertKeyStoreSession& aSession)
+    {
+    ASSERT( iOpenedKey == NULL );
+    TPtr8 thePtr(0,0);
+    iOpenedKey = ProcessL(aMessage, aSession, KDSARepudiableSignerUID, ERepudiableDSASign, thePtr);
+    static_cast<CDevCertDSARepudiableSignerSrv*>(iOpenedKey)->Sign(thePtr, iDSASignature, iStatus);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::CancelDSASign()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::CancelDSASign(const RMessage2& aMessage)
+    {
+    if (iCurrentRequest.OutstandingRequest() == ERepudiableDSASign)
+        {
+        Cancel();
+        }
+    aMessage.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::DecryptL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::DecryptL(const RMessage2& aMessage, 
+                                       CDevCertKeyStoreSession& aSession)
+    {
+    ASSERT( iOpenedKey == NULL );
+    TPtr8 thePtr(0,0);
+    iOpenedKey = ProcessL(aMessage, aSession, KPrivateDecryptorUID, EDecryptText, thePtr);
+    static_cast<CDevCertRSADecryptorSrv*>(iOpenedKey)->Decrypt(thePtr, iPlaintext, iStatus);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::CancelDecrypt()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::CancelDecrypt(const RMessage2& aMessage)
+    {
+    if (iCurrentRequest.OutstandingRequest() == EDecryptText)
+        {
+        Cancel();
+        }
+    aMessage.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::ProcessL()
+// ---------------------------------------------------------------------------
+//
+CDevCertOpenedKeySrv* CDevCertKeyStoreConduit::ProcessL(
+                     const RMessage2& aMessage,
+                     CDevCertKeyStoreSession& aSession,
+                     const TUid& aCKeyInfoID,
+                     const TDevTokenMessages& aState,
+                     TPtr8& aTextPtr)
+    {
+    CDevCertOpenedKeySrv* object = aSession.OpenedKey(aMessage.Int0());
+    if (!object)
+        {
+        User::Leave(KErrNotFound);
+        }
+
+    if (aCKeyInfoID != object->Type())
+        {
+        User::Leave(KErrAccessDenied);
+        }
+
+    TInt length = User::LeaveIfError(aMessage.GetDesLength(1));
+    iText = HBufC8::NewL(length);
+    aTextPtr.Set(iText->Des());
+    aMessage.ReadL(1, aTextPtr);
+
+    iCurrentRequest.Set(aState, aMessage);
+    iStatus=KRequestPending;
+    SetActive();
+
+    return object;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::DHPublicKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::DHPublicKeyL(const RMessage2& aMessage, 
+                                      CDevCertKeyStoreSession& aSession)
+    {
+    // 0: Object id
+    // 1: DH paramters
+
+    ASSERT(iDHParams == NULL );
+    ASSERT(iOpenedKey == NULL );
+    TRAPD(err, DoDHPublicKeyL(aMessage, aSession));
+    if (err != KErrNone)
+        {
+        iOpenedKey = NULL;
+        delete iDHParams;
+        iDHParams = NULL;
+        User::Leave(err);
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::DoDHPublicKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::DoDHPublicKeyL(const RMessage2& aMessage, 
+                                      CDevCertKeyStoreSession& aSession)
+    {
+    iOpenedKey = aSession.OpenedKey(aMessage.Int0());
+    if (!iOpenedKey)
+        {
+        User::Leave(KErrNotFound);
+        }
+
+    //Check that this is a DH object
+    if (KKeyAgreementUID != iOpenedKey->Type())
+        {
+        iOpenedKey = NULL;
+        User::Leave(KErrAccessDenied);
+        }
+
+    HBufC8* clientBuf = HBufC8::NewMaxLC(User::LeaveIfError(aMessage.GetDesLength(1)));
+    TPtr8 clientPtr = clientBuf->Des();
+    aMessage.ReadL(1, clientPtr);
+    DevTokenDataMarshaller::ReadL(*clientBuf, iDHParams);
+    CleanupStack::PopAndDestroy(clientBuf);
+
+    static_cast<CDevCertDHAgreementSrv*>(iOpenedKey)->PublicKey(*iDHParams, iDHPublicKeyOut, iStatus);
+
+    iCurrentRequest.Set(EDHPublicKey, aMessage);
+    iStatus=KRequestPending;
+    SetActive();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::FinishDHPublicKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::FinishDHPublicKeyL()
+    {
+    // Client buffer must be big enough for result because it had the DH
+    // parameters in it
+    TInt reqdSize = DevTokenDataMarshaller::Size(iDHPublicKeyOut);
+    ASSERT(reqdSize <= iCurrentRequest.Message().GetDesMaxLength(1));
+
+    HBufC8* clientBuf = HBufC8::NewMaxLC(reqdSize);
+    TPtr8 clientPtr = clientBuf->Des();
+    DevTokenDataMarshaller::WriteL(iDHPublicKeyOut, clientPtr);
+    iCurrentRequest.Message().WriteL(1, clientPtr);
+    CleanupStack::PopAndDestroy(clientBuf);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::DHAgreeL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::DHAgreeL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession)
+    {
+    // 0: Object id
+    // 1: DH public key
+
+    ASSERT( iOpenedKey == NULL );
+    ASSERT( iDHPublicKey == NULL );
+    TRAPD(err, DoDHAgreeL(aMessage, aSession));
+    if (err != KErrNone)
+        {
+        iOpenedKey = NULL;
+        delete iDHPublicKey;
+        iDHPublicKey = NULL;
+        User::Leave(err);
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::DoDHAgreeL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::DoDHAgreeL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession)
+    {
+    CDevCertOpenedKeySrv* iOpenedKey = aSession.OpenedKey(aMessage.Int0());
+    if (!iOpenedKey)
+        {
+        User::Leave(KErrNotFound);
+        }
+
+    //Check that this is a DH object
+    if (KKeyAgreementUID != iOpenedKey->Type())
+        {
+        iOpenedKey = NULL;
+        User::Leave(KErrAccessDenied);
+        }
+
+    HBufC8* clientBuf = HBufC8::NewMaxLC(User::LeaveIfError(aMessage.GetDesLength(1)));
+    TPtr8 clientPtr = clientBuf->Des();
+    aMessage.ReadL(1, clientPtr);
+    DevTokenDataMarshaller::ReadL(*clientBuf, iDHPublicKey);
+    CleanupStack::PopAndDestroy(clientBuf);
+
+    static_cast<CDevCertDHAgreementSrv*>(iOpenedKey)->Agree(*iDHPublicKey, iDHAgreedKeyOut, iStatus);
+
+    iCurrentRequest.Set(EDHAgree, aMessage);
+    iStatus=KRequestPending;
+    SetActive();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::FinishDHAgreeL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::FinishDHAgreeL()
+    {
+    // Client buffer must be big enough for result because it had the DH
+    // public key in it
+    ASSERT(iDHAgreedKeyOut->Length() <= iCurrentRequest.Message().GetDesMaxLength(1));
+
+    iCurrentRequest.Message().WriteL(1, *iDHAgreedKeyOut);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::CancelDH()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::CancelDH(const RMessage2& aMessage)
+    {
+    if (iCurrentRequest.OutstandingRequest() == EDHPublicKey ||
+    iCurrentRequest.OutstandingRequest() == EDHAgree)
+        {
+        Cancel();
+        }
+    aMessage.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::CloseObjectL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::CloseObjectL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession)
+    {
+    aSession.RemoveOpenedKeyL(aMessage.Int0());
+    aMessage.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::DoCancel()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::DoCancel()
+    {
+    switch (iCurrentRequest.OutstandingRequest())
+        {
+        case ECreateKey:
+            iServer.CancelCreateKey();
+            break;
+
+        case ERepudiableRSASign:
+        case ERepudiableDSASign:
+        case EDecryptText:
+        case EDHAgree:
+        case EDHPublicKey:
+            if (iOpenedKey)
+                {       
+                iOpenedKey->Cancel();
+                }
+            break;
+
+        case EImportKey:
+            iServer.CancelImportKey();
+            break;
+
+        case EExportKey:
+            iServer.CancelExportKey();
+            break;
+
+        default:
+            // Nothing to do
+            break;
+        }
+
+    Cleanup();
+    iCurrentRequest.Cancel();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::RunL()
+// The token interface has completed the request - munge any return parameters
+// and write back to client.
+// ---------------------------------------------------------------------------
+// 
+void CDevCertKeyStoreConduit::RunL()
+    {
+    // Handle errors from server
+    User::LeaveIfError(iStatus.Int());
+
+    switch (iCurrentRequest.OutstandingRequest())
+        {
+        case ECreateKey:
+        case EImportKey:
+        case EImportEncryptedKey:
+            {
+            //  Marshal TKeyUpdate to client - the client's buffer will be large
+            //  enough as it passed us a CCTKeyInfo in the first place
+            ASSERT(iKeyInfo);
+            TDevTokenKeyUpdate update;
+            update.iReference = iKeyInfo->HandleID();
+            update.iId = iKeyInfo->ID();
+            update.iSize = iKeyInfo->Size();
+            update.iAlgorithm = iKeyInfo->Algorithm();
+            TPckg<TDevTokenKeyUpdate> pckg(update);
+            iCurrentRequest.Message().WriteL(1, pckg);
+            break;
+            }
+        case EExportKey:
+            {
+            ASSERT(iExportBuf);
+            TPtr8 clientPtr(iExportBuf->Des());
+            iCurrentRequest.Message().WriteL(1, clientPtr);
+            break;
+            }
+        case ERepudiableDSASign:
+            {
+            ASSERT(iDSASignature);
+
+            TInt length = User::LeaveIfError(iCurrentRequest.Message().GetDesMaxLength(2));
+            TInt reqdLength = DevTokenDataMarshaller::Size(*iDSASignature);
+            if (length < reqdLength)
+                {
+                User::Leave(KErrOverflow);
+                }
+
+            HBufC8* clientBuffer = HBufC8::NewLC(reqdLength);
+            TPtr8 ptr(clientBuffer->Des());
+            DevTokenDataMarshaller::WriteL(*iDSASignature, ptr);
+            iCurrentRequest.Message().WriteL(2, ptr);
+            CleanupStack::PopAndDestroy(clientBuffer);
+            break;
+            }
+        case ERepudiableRSASign:
+            {
+            ASSERT(iRSASignature);
+            TInt length = User::LeaveIfError(iCurrentRequest.Message().GetDesMaxLength(2));
+            TInt reqdLength = DevTokenDataMarshaller::Size(*iRSASignature);
+            if (length < reqdLength)
+                {
+                User::Leave(KErrOverflow);
+                }
+
+            HBufC8* clientBuffer = HBufC8::NewLC(reqdLength);
+            TPtr8 ptr(clientBuffer->Des());
+            DevTokenDataMarshaller::WriteL(*iRSASignature, ptr);
+            iCurrentRequest.Message().WriteL(2, ptr);
+            CleanupStack::PopAndDestroy(clientBuffer);
+            break;
+            }
+        case EDecryptText:
+            {
+            ASSERT(iPlaintext);
+            TInt length = User::LeaveIfError(iCurrentRequest.Message().GetDesMaxLength(2));
+            if (length < iPlaintext->Length())
+                {
+                User::Leave(KErrOverflow);
+                }
+            iCurrentRequest.Message().WriteL(2, *iPlaintext);
+            break;
+            }
+
+        case EDHPublicKey:
+            FinishDHPublicKeyL();
+            break;
+        case EDHAgree:
+            FinishDHAgreeL();
+            break;
+
+        default:
+            __ASSERT_DEBUG(EFalse, PanicServer(EPanicInvalidRequest));
+            User::Leave(KErrNotSupported);
+        }
+
+    Cleanup();
+    iCurrentRequest.Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::Cleanup()
+// Cleans up data members used in processing a client request.  Called whenenver a
+// request is completed, either from RunL, RunError or indirectly from DoCancel.
+// ---------------------------------------------------------------------------
+// 
+void CDevCertKeyStoreConduit::Cleanup()
+    {
+    delete iKeyInfo;     iKeyInfo = NULL;
+    delete iImportKey;     iImportKey = NULL;
+    delete iText;        iText = NULL;
+    delete iDSASignature;  iDSASignature = NULL;
+    delete iRSASignature;  iRSASignature = NULL;
+    delete iExportBuf;     iExportBuf = NULL;
+    delete iDHParams;    iDHParams = NULL;
+    iDHPublicKeyOut.Close();
+    delete iDHPublicKey;   iDHPublicKey = NULL;
+    delete iDHAgreedKeyOut;  iDHAgreedKeyOut = NULL;
+    delete iPlaintext;     iPlaintext = NULL;
+    iOpenedKey = NULL;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::RunError()
+// ---------------------------------------------------------------------------
+// 
+TInt CDevCertKeyStoreConduit::RunError(TInt aError)
+    {
+    Cleanup();
+    //  Handle error by completing client appropriately
+    iCurrentRequest.Complete(aError);
+    return (KErrNone);
+    }
+
+
+// CDevCertKeyStoreConduit::TAsyncRequest 
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::TAsyncRequest::TAsyncRequest()
+// ---------------------------------------------------------------------------
+// 
+CDevCertKeyStoreConduit::TAsyncRequest::TAsyncRequest(TRequestStatus& aStatus) :
+  iOwnerStatus(aStatus)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::TAsyncRequest::~TAsyncRequest()
+// ---------------------------------------------------------------------------
+// 
+CDevCertKeyStoreConduit::TAsyncRequest::~TAsyncRequest()
+    {
+    __ASSERT_DEBUG(EIdle==iRequest, PanicServer(EPanicRequestOutstanding));
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::TAsyncRequest::Set()
+// ---------------------------------------------------------------------------
+// 
+void CDevCertKeyStoreConduit::TAsyncRequest::Set(TDevTokenMessages aRequest, const RMessage2& aMessage)
+    {
+    __ASSERT_DEBUG(EIdle==iRequest, PanicServer(EPanicRequestOutstanding));
+
+    iOwnerStatus = KRequestPending;
+    iRequest = aRequest;
+    iMessage = aMessage;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::TAsyncRequest::Complete()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::TAsyncRequest::Complete(TInt aResult)
+    {
+    iMessage.Complete(aResult);
+    iRequest = EIdle;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreConduit::TAsyncRequest::Cancel()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreConduit::TAsyncRequest::Cancel()
+    {// Complete outstanding request with KErrCancel
+    iMessage.Complete(KErrCancel);
+    iRequest = EIdle;
+    }
+    
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertKeyStoreServer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1268 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevCertKeyStoreServer
+*
+*/
+
+
+#include <securityerr.h>
+#include <asnpkcs.h>
+#include <asn1enc.h>
+#ifndef SYMBIAN_ENABLE_SPLIT_HEADERS
+#include <x509keys.h>
+#else
+#include <x509keys.h>
+#include <x509keyencoder.h>
+#endif
+#include <keyidentifierutil.h>
+#include <mctauthobject.h>
+#include <utf.h>
+
+#include "DevCertKeyStoreServer.h"
+#include "DevCertKeyStoreSession.h"
+#include "DevCertKeyDataManager.h"
+#include "DevCertKeyStoreConduit.h"
+#include "DevCertKeyStoreSession.h"
+#include "DevCertOpenedKeysSrv.h"
+#include "DevTokenCliServ.h"
+#include "DevCertCreateKey.h"
+#include "DevCertOpenedKeys.h"
+#include "DevTokenDataTypes.h"
+#include "DevCertKeyStreamUtils.h"
+#include "DevTokenUtil.h"
+#include "DevCertKeyEncryptor.h"
+#include "DevTokenPWManager.h"
+
+// We don't currently allow any keys larger than 2048 bits.  It may be necessary to
+// increase this limit in the future. 
+const TUint KTheMinKeySize = 512;
+const TUint KTheMaxKeySize = 2048;
+
+// Security policies
+_LIT_SECURITY_POLICY_C1(KImportRemoveSecurityPolicy, ECapabilityWriteDeviceData);
+_LIT_SECURITY_POLICY_C1(KCreateSecurityPolicy, ECapabilityReadDeviceData);
+_LIT_SECURITY_POLICY_C1(KOpenSecurityPolicy, ECapabilityReadDeviceData);
+_LIT_SECURITY_POLICY_C1(KListSecurityPolicy, ECapabilityReadUserData);
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::NewL()
+// ---------------------------------------------------------------------------
+// 
+CDevCertKeyStoreServer* CDevCertKeyStoreServer::NewL()
+    {
+    CDevCertKeyStoreServer* me = new (ELeave) CDevCertKeyStoreServer();
+    CleanupStack::PushL(me);
+    me->ConstructL();
+    CleanupStack::Pop(me);
+    return (me);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::CDevCertKeyStoreServer()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyStoreServer::CDevCertKeyStoreServer() :
+	CActive(EPriorityStandard),
+	iAction(EIdle),
+	iExportBuf(NULL, 0)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::ConstructL()
+    {
+    iKeyDataManager = CDevCertKeyDataManager::NewL();
+    iConduit = CDevCertKeyStoreConduit::NewL(*this);
+    CActiveScheduler::Add(this);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::~CDevCertKeyStoreServer()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyStoreServer::~CDevCertKeyStoreServer()
+    {
+    Cancel();
+
+    delete iKeyDataManager;
+    delete iConduit;
+    delete iKeyCreator;
+    iSessions.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::CreateSessionL()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyStoreSession* CDevCertKeyStoreServer::CreateSessionL()
+    {
+    CDevCertKeyStoreSession* session = CDevCertKeyStoreSession::NewL(*this );
+    CleanupStack::PushL(session);
+    User::LeaveIfError(iSessions.Append(session));
+    CleanupStack::Pop(session);
+    return session;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::RemoveSession()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::RemoveSession(CDevCertKeyStoreSession& aSession)
+    {
+    if (iSession == &aSession) // just in case
+        {
+        iSession = NULL; 
+        }
+
+    for (TInt index = 0 ; index < iSessions.Count() ; ++index)
+        {
+        if (iSessions[index] == &aSession)
+            {
+            iSessions.Remove(index);
+            return;
+            }
+        }
+    User::Invariant();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::ServiceRequestL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::ServiceRequestL(const RMessage2& aMessage, CDevCertKeyStoreSession& aSession)
+    {
+    iMessage = &aMessage;
+    iSession = &aSession;
+    iConduit->ServiceRequestL(aMessage, aSession);
+    }
+
+
+//	From MCTKeyStore
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::ListL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::ListL(const TCTKeyAttributeFilter& aFilter,
+							  RPointerArray<CDevTokenKeyInfo>& aKeys)
+    {
+    ASSERT(iMessage);
+
+    // Check the calling process has ReadUserData capability
+    if (!KListSecurityPolicy.CheckPolicy(*iMessage))
+        {
+        User::Leave(KErrPermissionDenied);
+        }
+
+    TInt count = iKeyDataManager->Count();
+
+    for (TInt i = 0; i < count; ++i)
+        {
+        const CDevCertKeyData* data = (*iKeyDataManager)[i];
+        CDevTokenKeyInfo* info = iKeyDataManager->ReadKeyInfoLC(*data);
+        if (KeyMatchesFilterL(*info, aFilter))
+            {
+            User::LeaveIfError(aKeys.Append(info));
+            CleanupStack::Pop(info);
+            }
+        else
+            {
+            CleanupStack::PopAndDestroy(info);
+            }
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::KeyMatchesFilterL()
+// ---------------------------------------------------------------------------
+//
+TBool CDevCertKeyStoreServer::KeyMatchesFilterL(const CDevTokenKeyInfo& aInfo,
+										   const TCTKeyAttributeFilter& aFilter)
+    {
+    ASSERT(iMessage);
+
+    if (aFilter.iKeyId.Length() && aFilter.iKeyId != aInfo.ID())
+        {
+        return EFalse;
+        }
+
+    if (aFilter.iUsage != EPKCS15UsageAll)
+        {
+        if ((aInfo.Usage() & aFilter.iUsage) == 0)
+        return EFalse;
+        }
+
+    if (aFilter.iKeyAlgorithm != CCTKeyInfo::EInvalidAlgorithm && 
+    aFilter.iKeyAlgorithm != aInfo.Algorithm())
+        {
+        return EFalse;
+        }
+
+    switch (aFilter.iPolicyFilter)
+        {
+        case TCTKeyAttributeFilter::EAllKeys:
+        // All keys pass
+        break;
+
+        case TCTKeyAttributeFilter::EUsableKeys:
+        if (!aInfo.UsePolicy().CheckPolicy(*iMessage))
+            {
+            return EFalse;
+            }
+        break;
+
+        case TCTKeyAttributeFilter::EManageableKeys:
+        if (!aInfo.ManagementPolicy().CheckPolicy(*iMessage))
+            {
+            return EFalse;
+            }
+        break;
+
+        case TCTKeyAttributeFilter::EUsableOrManageableKeys:
+        if (!aInfo.UsePolicy().CheckPolicy(*iMessage) &&
+        !aInfo.ManagementPolicy().CheckPolicy(*iMessage))
+            {
+            return EFalse;
+            }
+        break;
+
+        default:
+        User::Leave(KErrArgument);
+        }
+
+    return ETrue;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::GetKeyInfoL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::GetKeyInfoL(TInt aObjectId, CDevTokenKeyInfo*& aInfo)
+    {
+    const CDevCertKeyData* keyData = iKeyDataManager->Lookup(aObjectId);
+    if (!keyData)
+        {
+        User::Leave(KErrNotFound);
+        }
+
+    CDevTokenKeyInfo* result = iKeyDataManager->ReadKeyInfoLC(*keyData);
+    if (!result->UsePolicy().CheckPolicy(*iMessage))
+        {
+        User::Leave(KErrPermissionDenied);
+        }
+
+    aInfo = result;
+    CleanupStack::Pop(aInfo);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::GetKeyLengthL()
+// ---------------------------------------------------------------------------
+//
+TInt CDevCertKeyStoreServer::GetKeyLengthL(TInt aObjectId)
+    {
+    const CDevCertKeyData* keyData = iKeyDataManager->Lookup(aObjectId);
+    if (!keyData)
+        {
+        User::Leave(KErrNotFound);
+        }
+
+    // this could be cached in memory (would break file format though)
+    CDevTokenKeyInfo* keyInfo = iKeyDataManager->ReadKeyInfoLC(*keyData);
+    TInt result = keyInfo->Size();
+    CleanupStack::PopAndDestroy(keyInfo);
+
+    return result;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::OpenKeyL()
+// ---------------------------------------------------------------------------
+//
+CDevCertOpenedKeySrv* CDevCertKeyStoreServer::OpenKeyL(TInt aHandle, TUid aOpenedKeyType)
+    {
+    ASSERT(iMessage);
+
+    if (!KOpenSecurityPolicy.CheckPolicy(*iMessage))
+        {
+        User::Leave(KErrPermissionDenied);
+        }
+
+
+    const CDevCertKeyData *keyData = iKeyDataManager->Lookup(aHandle);
+    if (!keyData)
+        {
+        User::Leave(KErrNotFound);
+        }
+
+    return CDevCertOpenedKeySrv::NewL( *keyData, aOpenedKeyType, *iMessage,*iKeyDataManager );						
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::ExportPublicL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::ExportPublicL(TInt aObjectId,
+									  TDes8& aOut)
+    {
+    const CDevCertKeyData* keyData = iKeyDataManager->Lookup(aObjectId);
+    if (!keyData)
+        {
+        User::Leave(KErrNotFound);
+        }
+
+    CDevTokenKeyInfo* keyInfo = iKeyDataManager->ReadKeyInfoLC(*keyData);
+
+    RStoreReadStream stream;
+    iKeyDataManager->OpenPublicDataStreamLC(*keyData, stream);
+
+    CDevTokenKeyInfo::EKeyAlgorithm keyAlgorithm = keyInfo->Algorithm();
+
+    switch(keyAlgorithm)
+        {
+        case (CDevTokenKeyInfo::ERSA):
+            {
+            CRSAPublicKey* publicKey = NULL;
+
+            CreateL(stream, publicKey);
+            ASSERT(publicKey);
+            CleanupStack::PushL(publicKey);
+
+            TX509RSAKeyEncoder encoder(*publicKey, ESHA1);
+            CASN1EncBase* encoded = encoder.EncodeKeyLC();
+
+            if (encoded->LengthDER() > static_cast<TUint>(aOut.MaxLength()))
+                {
+                User::Leave(KErrOverflow);
+                }
+
+            //	Get the Public key DER encoding
+            TUint pos=0;
+            encoded->WriteDERL(aOut, pos);
+
+            // WriteDERL does not set the length of the buffer, we do it ourselves			
+            aOut.SetLength(encoded->LengthDER());			
+
+            CleanupStack::PopAndDestroy(2, publicKey);
+            }
+        break;
+
+        case (CDevTokenKeyInfo::EDSA):
+            {
+            CDSAPublicKey* publicKey = NULL;
+
+            CreateL(stream, publicKey);
+            ASSERT(publicKey);
+            CleanupStack::PushL(publicKey);
+
+            TX509DSAKeyEncoder encoder(*publicKey, ESHA1);
+            CASN1EncBase* encoded = encoder.EncodeKeyLC();
+
+            if (encoded->LengthDER() > static_cast<TUint>(aOut.MaxLength()))
+                {
+                User::Leave(KErrOverflow);
+                }
+
+            //	Get the Public key DER encoding
+            TUint pos=0;
+            encoded->WriteDERL(aOut, pos);
+
+            // WriteDERL does not set the length of the buffer, we do it ourselves			
+            aOut.SetLength(encoded->LengthDER());						
+
+            CleanupStack::PopAndDestroy(2, publicKey);
+            }
+        break;
+
+        case (CDevTokenKeyInfo::EDH):
+        default:
+        User::Leave(KErrKeyAlgorithm);
+        break;
+        }
+
+    CleanupStack::PopAndDestroy(2, keyInfo); //stream, keyinfo
+    }
+
+
+//	From MCTKeyStoreManager
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::CheckKeyAttributes()
+// ---------------------------------------------------------------------------
+//
+TInt CDevCertKeyStoreServer::CheckKeyAttributes(CDevTokenKeyInfo& aKey, TNewKeyOperation aOp)
+    {
+    ASSERT(iMessage);
+
+    // Sort out the access rights
+    TInt access = aKey.AccessType(); 
+
+    // Only allow sensitive and extractable to be sepcified
+    if (access & ~(CDevTokenKeyInfo::ESensitive | CDevTokenKeyInfo::EExtractable))
+        {
+        return KErrKeyAccess;
+        }	
+
+    // If it's sensitive and either created internally 
+    // or imported from an encrypted source then it's always been sensitive
+    if ((access & CDevTokenKeyInfo::ESensitive) &&
+        (aOp == ENewKeyCreate))
+        {
+        access |= CDevTokenKeyInfo::EAlwaysSensitive;		
+        }
+
+    // If it's not extractable and it's created internally
+    // then it's never been extractable
+    if ((!(access & CDevTokenKeyInfo::EExtractable)) && aOp == ENewKeyCreate)
+        {
+        access |= CDevTokenKeyInfo::ENeverExtractable;		
+        }
+
+    aKey.SetAccessType(access);
+
+    // check management policy allows the calling process to manage the key
+    if (!aKey.ManagementPolicy().CheckPolicy(*iMessage))
+        {
+        return KErrArgument;
+        }
+
+    // check end date is not in the past
+    TTime timeNow;
+    timeNow.UniversalTime();
+    if (aKey.EndDate().Int64() != 0 && aKey.EndDate() <= timeNow)
+        {
+        return KErrKeyValidity;
+        }
+
+    // We don't support non-repudiation, however we currently allow keys
+    // to be created with this usage
+
+    return KErrNone;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::CheckKeyAlgorithmAndSize()
+// ---------------------------------------------------------------------------
+//
+TInt CDevCertKeyStoreServer::CheckKeyAlgorithmAndSize(CDevTokenKeyInfo& aKey)
+    {
+    CDevTokenKeyInfo::EKeyAlgorithm keyAlgorithm = aKey.Algorithm();
+    if ( ((keyAlgorithm!=CDevTokenKeyInfo::ERSA) && (keyAlgorithm!=CDevTokenKeyInfo::EDSA) && (keyAlgorithm!=CDevTokenKeyInfo::EDH) ))
+        {
+        return KErrKeyAlgorithm;
+        }
+
+    if (aKey.Size() < KTheMinKeySize || aKey.Size() > KTheMaxKeySize)
+        {
+        return KErrKeySize;
+        }
+
+    return KErrNone;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::CreateKey()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::CreateKey(CDevTokenKeyInfo& aReturnedKey, TRequestStatus& aStatus)
+    {
+    ASSERT(iSession);
+    ASSERT(iMessage);
+
+    TInt err = KErrNone;
+
+    // Check the calling process has WriteUserData capability
+    if (!KCreateSecurityPolicy.CheckPolicy(*iMessage))
+        {
+        err = KErrPermissionDenied;
+        }
+
+    // Check the incoming information has been initialised correctly
+    if (err == KErrNone)
+        {
+        err = CheckKeyAttributes(aReturnedKey, ENewKeyCreate);
+        }
+
+    if (err == KErrNone)
+        {
+        err = CheckKeyAlgorithmAndSize(aReturnedKey);
+        }
+
+    if (err != KErrNone)
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete(status, err);
+        return;
+        }
+
+    // should make it local only if it's created in the keystore
+    aReturnedKey.SetAccessType(aReturnedKey.AccessType() | CDevTokenKeyInfo::ELocal);
+
+    if (iKeyDataManager->IsKeyAlreadyInStore(aReturnedKey.Label()))
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete(status, KErrAlreadyExists);
+        return;
+        }
+
+    iCallerRequest = &aStatus;
+    iKeyInfo = &aReturnedKey;
+
+    iStatus = KRequestPending;
+    iAction = ECreateKeyCreate;
+    SetActive();
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete(status, KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::CancelCreateKey()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::CancelCreateKey()
+    {
+    if (iAction == ECreateKeyCreate ||
+    iAction == ECreateKeyFinal)
+        {
+        Cancel();
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::DoCreateKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::DoCreateKeyL()
+    {
+    __ASSERT_DEBUG(iAction==ECreateKeyCreate, PanicServer(EPanicECreateKeyNotReady));
+    __ASSERT_DEBUG(iKeyInfo, PanicServer(EPanicNoClientData));
+
+    if (iKeyCreator)
+        {
+        delete iKeyCreator;
+        iKeyCreator = NULL;
+        }
+
+    iKeyCreator = new (ELeave) CDevCertKeyCreator();
+    iStatus = KRequestPending;
+    iAction = EKeyCreated;
+    iKeyCreator->DoCreateKeyAsyncL(iKeyInfo->Algorithm(), iKeyInfo->Size(), iStatus);
+    SetActive(); 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::DoStoreKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::DoStoreKeyL()
+    {
+    __ASSERT_DEBUG(iAction==ECreateKeyFinal, PanicServer(EPanicECreateKeyNotReady));
+    __ASSERT_DEBUG(iKeyInfo, PanicServer(EPanicNoClientData));
+    __ASSERT_DEBUG(iKeyCreator, PanicServer(ENoCreatedKeyData));
+
+    const CDevCertKeyData* keyData = iKeyDataManager->CreateKeyDataLC(iKeyInfo->Label());	   
+
+    RStoreWriteStream privateStream;
+    iKeyDataManager->OpenPrivateDataStreamLC(*keyData, privateStream);
+
+    CDevTokenKeyInfo::EKeyAlgorithm keyAlgorithm = iKeyInfo->Algorithm();
+
+    // 	Get key identifier and externalize private key 
+    TKeyIdentifier theKeyId;
+    switch (keyAlgorithm)
+        {
+        case (CDevTokenKeyInfo::ERSA):
+            {
+            CRSAKeyPair* newKey = iKeyCreator->GetCreatedRSAKey();
+            KeyIdentifierUtil::RSAKeyIdentifierL(newKey->PublicKey(), theKeyId);			
+            privateStream << newKey->PrivateKey();
+            break;
+            }
+
+        case (CDevTokenKeyInfo::EDSA):
+            {
+            CDSAKeyPair* newKey = iKeyCreator->GetCreatedDSAKey();			
+            KeyIdentifierUtil::DSAKeyIdentifierL(newKey->PublicKey(), theKeyId);
+            privateStream << newKey->PrivateKey();
+            break;
+            }
+
+        case (CDevTokenKeyInfo::EDH):
+            {
+            CDevCertKeyEncryptor* encryptor = CDevCertKeyEncryptor::NewLC();
+            if( encryptor->IsPluginExistL() )
+                {
+                //SetEncryptor( encryptor->CreateImplementationL() );
+                MKeyEncryptor* encrypt = encryptor->CreateImplementationL();
+
+                RInteger newKey; 
+                iKeyCreator->GetCreatedDHKey(newKey);			
+                KeyIdentifierUtil::DHKeyIdentifierL(newKey, theKeyId);
+
+                if (newKey.IsZero())
+                User::Leave(KErrArgument);
+
+                //privateStream << newKey;
+                EncryptAndStoreL(newKey, privateStream, encrypt );
+
+                privateStream.CommitL();
+
+                }
+            else
+                {
+                RInteger newKey; 
+                iKeyCreator->GetCreatedDHKey(newKey);			
+                KeyIdentifierUtil::DHKeyIdentifierL(newKey, theKeyId);
+
+                if (newKey.IsZero())
+                User::Leave(KErrArgument);
+
+                privateStream << newKey;
+                privateStream.CommitL();
+                } 
+            CleanupStack::PopAndDestroy( encryptor );      
+            break;
+            }
+
+        default:
+        __ASSERT_DEBUG(EFalse, PanicServer(EPanicInvalidKeyCreateReq));
+        break;
+        }
+
+    privateStream.CommitL();
+    CleanupStack::PopAndDestroy(); // privateStream
+
+    //	Fill in the CCTKeyInfo data currently missing (TKeyIdentifier and handle)
+    iKeyInfo->SetHandle(keyData->Handle());
+    iKeyInfo->SetIdentifier(theKeyId);	
+
+    // 	Externalize public key
+
+    RStoreWriteStream publicStream;
+    iKeyDataManager->OpenPublicDataStreamLC(*keyData, publicStream);
+
+    switch (keyAlgorithm)
+        {
+        case (CDevTokenKeyInfo::ERSA):
+        publicStream << iKeyCreator->GetCreatedRSAKey()->PublicKey();			
+        break;
+
+        case (CDevTokenKeyInfo::EDSA):
+        publicStream << iKeyCreator->GetCreatedDSAKey()->PublicKey();
+        break;
+
+        case (CDevTokenKeyInfo::EDH):
+        // Nothing to do for DH
+        break;
+
+        default:
+        __ASSERT_DEBUG(EFalse, PanicServer(EPanicInvalidKeyCreateReq));
+        break;
+        }
+
+    publicStream.CommitL();
+    CleanupStack::PopAndDestroy(); // publicStream
+
+    //	Finished with the key creator
+    if (iKeyCreator)
+        {
+        delete iKeyCreator;
+        iKeyCreator = NULL;
+        }
+
+    //	Externalize the CDevTokenKeyInfo data associated with the key,
+    iKeyDataManager->WriteKeyInfoL(*keyData, *iKeyInfo);
+
+    //	Now add the new key to the data manager (which adds it to the store)
+    iKeyDataManager->AddL(keyData);
+    CleanupStack::Pop(); // keydata
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::ImportKey()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::ImportKey(const TDesC8& aKey, CDevTokenKeyInfo& aReturnedKey, TBool aIsEncrypted, TRequestStatus& aStatus)
+    {
+    ASSERT(iMessage);
+
+    TInt err = KErrNone;
+
+    // Check the calling process has WriteUserData capability
+    if (!KImportRemoveSecurityPolicy.CheckPolicy(*iMessage))
+        {
+        err = KErrPermissionDenied;
+        }
+
+    if (err == KErrNone)
+        {
+        err = CheckKeyAttributes(aReturnedKey, ENewKeyImportPlaintext);
+        }
+
+    if (err == KErrNone && iKeyDataManager->IsKeyAlreadyInStore(aReturnedKey.Label()))
+        {
+        err = KErrAlreadyExists;
+        }
+
+    if (err != KErrNone)
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete(status, err);
+        return;
+        }
+
+    iPKCS8Data.Set(aKey);
+    
+    iImportingEncryptedKey = aIsEncrypted;
+    
+    iCallerRequest = &aStatus;
+    iKeyInfo = &aReturnedKey;
+
+    iAction = EImportKey;
+    SetActive();
+    
+    if ( aIsEncrypted )
+	    {
+		TDevTokenPWManager::ImportPassword( iPassword, iStatus );
+	    }
+	else
+		{
+		TRequestStatus* status = &iStatus;
+		User::RequestComplete(status, KErrNone);
+		}
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::CancelImportKey()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::CancelImportKey()
+    {
+    if (iAction == EImportOpenPrivateStream ||
+    iAction == EImportKey)
+        {
+        Cancel();
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::DoImportKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::DoImportKeyL()
+    {
+    // Generate a decode PKCS8 data object from the incoming descriptor of PKCS8
+    // data Creation of this will parse the DER stream and generate the
+    // appropriate key representation based on the algorithm
+
+    ASSERT(iPKCS8Data.Ptr());
+
+    CDecPKCS8Data* pkcs8Data = NULL;
+
+    if ( iImportingEncryptedKey )
+	    {
+	    // Convert import passphrase to 8 bit representation
+		TBuf8<32> password;
+		
+		CnvUtfConverter::ConvertFromUnicodeToUtf8(password, iPassword);
+		pkcs8Data = TASN1DecPKCS8::DecodeEncryptedDERL(iPKCS8Data, password);
+	    }
+	else
+		{
+		pkcs8Data = TASN1DecPKCS8::DecodeDERL(iPKCS8Data);
+		}
+    
+    CleanupStack::PushL(pkcs8Data);	
+    PKCS8ToKeyL(pkcs8Data);
+    CleanupStack::PopAndDestroy(pkcs8Data);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::PKCS8ToKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::PKCS8ToKeyL(CDecPKCS8Data* aPKCS8Data)
+    { 
+    ASSERT(aPKCS8Data);
+
+    MPKCS8DecodedKeyPairData* keyPairData = aPKCS8Data->KeyPairData();
+
+    // Set algorithm and size from pkcs8 data, and sanity check them
+    if (aPKCS8Data->Algorithm() != ERSA && aPKCS8Data->Algorithm() != EDSA)
+        {
+        User::Leave(KErrKeyAlgorithm);
+        }
+    iKeyInfo->SetAlgorithm((aPKCS8Data->Algorithm() == ERSA) ? CKeyInfoBase::ERSA : CKeyInfoBase::EDSA);
+    iKeyInfo->SetSize(keyPairData->KeySize());
+    User::LeaveIfError(CheckKeyAlgorithmAndSize(*iKeyInfo));
+
+    // Retrieve and store any PKCS8 attributes (in DER encoded descriptor)
+    // These will form part of CDevTokenKeyInfo & available for callers to decode	
+    TPtrC8 theAttributes(aPKCS8Data->PKCS8Attributes());
+    if (theAttributes != KNullDesC8)
+        {
+        iKeyInfo->SetPKCS8AttributeSet(theAttributes.AllocL());
+        }
+
+    const CDevCertKeyData* keyData = iKeyDataManager->CreateKeyDataLC(iKeyInfo->Label());
+    RStoreWriteStream privateStream;
+    iKeyDataManager->OpenPrivateDataStreamLC(*keyData, privateStream);
+
+    // Generate the key identifier
+    TKeyIdentifier theKeyId;
+    keyPairData->GetKeyIdentifierL(theKeyId);
+
+    // Fill in the CDevTokenKeyInfo data currently missing (TKeyIdentifier and handle)
+    iKeyInfo->SetHandle(keyData->Handle());
+    iKeyInfo->SetIdentifier(theKeyId);	
+
+    CDevTokenKeyInfo::EKeyAlgorithm keyAlgorithm = iKeyInfo->Algorithm();
+
+    // Externalize private key data
+    switch (keyAlgorithm)
+        {
+        case (CDevTokenKeyInfo::ERSA):
+        privateStream << static_cast<CPKCS8KeyPairRSA*>(keyPairData)->PrivateKey();
+        break;
+
+        case (CDevTokenKeyInfo::EDSA):
+        privateStream << static_cast<CPKCS8KeyPairDSA*>(keyPairData)->PrivateKey();
+        break;
+
+        default:
+        __ASSERT_DEBUG(EFalse, PanicServer(EPanicInvalidKeyCreateReq));
+        break;
+        }
+
+    privateStream.CommitL();
+    CleanupStack::PopAndDestroy(&privateStream);
+
+    // Externalize public key data
+    RStoreWriteStream publicStream;
+    iKeyDataManager->OpenPublicDataStreamLC(*keyData, publicStream);
+
+    switch (keyAlgorithm)
+        {
+        case (CDevTokenKeyInfo::ERSA):
+        publicStream << static_cast<CPKCS8KeyPairRSA*>(keyPairData)->PublicKey();
+        break;
+
+        case (CDevTokenKeyInfo::EDSA):
+        publicStream << static_cast<CPKCS8KeyPairDSA*>(keyPairData)->PublicKey();
+        break;
+
+        default:
+        __ASSERT_DEBUG(EFalse, PanicServer(EPanicInvalidKeyCreateReq));
+        break;
+        }
+
+    publicStream.CommitL();
+    CleanupStack::PopAndDestroy(&publicStream);
+
+    // Externalize the CDevTokenKeyInfo data associated with the key,
+    iKeyDataManager->WriteKeyInfoL(*keyData, *iKeyInfo);
+
+    // Now add the new key to the data manager (which adds it to the store)
+    iKeyDataManager->AddL(keyData);
+    CleanupStack::Pop(const_cast<CDevCertKeyData*>(keyData));
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::ExportKey()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::ExportKey(TInt aObjectId, const TPtr8& aKey, TRequestStatus& aStatus)
+    {				
+    TRAPD(err, DoExportKeyL(aObjectId, aKey, aStatus));
+    if (err != KErrNone)
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete(status, err);
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::CancelExportKey()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::CancelExportKey()
+    {
+    if ( iAction == EExportKey )
+        {
+        Cancel();
+        }
+    }	
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::DoExportKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::DoExportKeyL(TInt aObjectId, const TPtr8& aKey, TRequestStatus& aStatus)
+    {
+    ASSERT(iMessage);
+    ASSERT(!iKeyData);
+    ASSERT(!iKeyInfo);
+
+    const CDevCertKeyData* keyData = iKeyDataManager->Lookup(aObjectId);
+    if (!keyData)
+        {
+        User::Leave(KErrNotFound);
+        }
+
+    CDevTokenKeyInfo* keyInfo = iKeyDataManager->ReadKeyInfoLC(*keyData);
+
+    // Check access flags allow key to be exported
+    if (!(keyInfo->AccessType() & CCTKeyInfo::EExtractable) ||
+    ((keyInfo->AccessType() & CCTKeyInfo::ESensitive)))
+        {
+        User::Leave(KErrKeyAccess);
+        }
+
+    // Check this isn't a DH key
+    if (keyInfo->Algorithm() != CDevTokenKeyInfo::ERSA &&
+    keyInfo->Algorithm() != CDevTokenKeyInfo::EDSA)
+        {
+        User::Leave(KErrNotSupported);
+        }
+
+    // Check the caller is allowed by the management policy
+    if (!keyInfo->ManagementPolicy().CheckPolicy(*iMessage))
+        {
+        User::Leave(KErrPermissionDenied);
+        }
+
+    iKeyData = keyData;
+    iKeyInfo = keyInfo;
+    CleanupStack::Pop(keyInfo);
+    iExportBuf.Set(aKey);		
+    iCallerRequest = &aStatus;
+
+    iAction = EExportKey;
+
+    SetActive();				
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete(status, KErrNone);		
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::CompleteKeyExportL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::CompleteKeyExportL()
+    {
+    ASSERT(iKeyData);
+    ASSERT(iExportBuf.Ptr());
+
+    CDevTokenKeyInfo::EKeyAlgorithm keyAlgorithm = iKeyInfo->Algorithm();
+    RStoreReadStream privStream;		
+    iKeyDataManager->OpenPrivateDataStreamLC(*iKeyData, privStream);
+
+    CASN1EncSequence* encoded = NULL;
+
+    switch(keyAlgorithm)
+        {
+        case (CDevTokenKeyInfo::ERSA):
+            {
+            RStoreReadStream pubStream;
+            iKeyDataManager->OpenPublicDataStreamLC(*iKeyData, pubStream);
+            CRSAPublicKey* publicKey = NULL;
+            CreateL(pubStream, publicKey);
+            ASSERT(publicKey);
+            CleanupStack::PushL(publicKey);
+
+            CRSAPrivateKey* privateKey = NULL;
+            CreateL(privStream, privateKey);
+            ASSERT(privateKey);
+            CleanupStack::PushL(privateKey);			
+            
+            encoded = TASN1EncPKCS8::EncodeL(*(static_cast<CRSAPrivateKeyCRT*>(privateKey)), *publicKey, iKeyInfo->PKCS8AttributeSet());					
+            
+            CleanupStack::PopAndDestroy(3, &pubStream);          // privateKey,  publicKey, pubStream
+            }
+        break;
+
+        case (CDevTokenKeyInfo::EDSA):
+            {
+            CDSAPrivateKey* privateKey = NULL;
+
+            CreateL(privStream, privateKey);
+            ASSERT(privateKey);
+            CleanupStack::PushL(privateKey);
+
+            encoded = TASN1EncPKCS8::EncodeL(*privateKey, iKeyInfo->PKCS8AttributeSet());					
+            					
+            CleanupStack::PopAndDestroy(privateKey);
+            }
+        break;
+
+        case (CDevTokenKeyInfo::EInvalidAlgorithm):
+        default:
+        User::Leave(KErrKeyAlgorithm);		
+        break;
+        }
+
+    // common to all algorithms			
+    ASSERT(encoded);
+    CleanupStack::PushL(encoded);
+    if (encoded->LengthDER() > static_cast<TUint>(iExportBuf.MaxLength()))
+        {
+        User::Leave(KErrOverflow);
+        }
+    TUint pos=0;
+    encoded->WriteDERL(iExportBuf, pos);
+
+    // WriteDERL does not set the length of the buffer, we do it ourselves			
+    iExportBuf.SetLength(encoded->LengthDER());
+
+    CleanupStack::PopAndDestroy(encoded); 
+    CleanupStack::PopAndDestroy(&privStream); 
+    RunError(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::DeleteKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::DeleteKeyL(TInt aObjectId)
+    {
+    ASSERT(iMessage);
+
+    const CDevCertKeyData* keyData = iKeyDataManager->Lookup(aObjectId);
+    if (!keyData)
+        {
+        User::Leave(KErrNotFound);
+        }
+
+    CDevTokenKeyInfo* keyInfo = iKeyDataManager->ReadKeyInfoLC(*keyData);
+
+    // Check the caller is allowed by the management policy
+    if (!KImportRemoveSecurityPolicy.CheckPolicy(*iMessage))
+        {
+        User::Leave(KErrPermissionDenied);
+        }
+
+    CleanupStack::PopAndDestroy(keyInfo);
+
+    // Check if any session has this key open
+    for (TInt i = 0 ; i < iSessions.Count() ; ++i)
+        {
+        CDevCertKeyStoreSession& session = *iSessions[i];
+        if (session.HasOpenKey(aObjectId))
+            {
+            User::Leave(KErrInUse);
+            }	
+        }
+
+    iKeyDataManager->RemoveL(aObjectId);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::SetUsePolicyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::SetUsePolicyL(TInt aObjectId, const TSecurityPolicy& aPolicy)
+    {
+    ASSERT(iMessage);
+
+    const CDevCertKeyData* keyData = iKeyDataManager->Lookup(aObjectId);
+    if (!keyData)
+        {
+        User::Leave(KErrNotFound);
+        }
+
+    CDevTokenKeyInfo* keyInfo = iKeyDataManager->ReadKeyInfoLC(*keyData);
+
+    // Check the caller is allowed by the management policy
+    if (!keyInfo->ManagementPolicy().CheckPolicy(*iMessage))
+        {
+        User::Leave(KErrPermissionDenied);
+        }
+
+    // should revert change if write fails
+    keyInfo->SetUsePolicy(aPolicy); 
+    iKeyDataManager->SafeWriteKeyInfoL(*keyData, *keyInfo);	
+
+    CleanupStack::PopAndDestroy(keyInfo);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::SetManagementPolicyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::SetManagementPolicyL(TInt aObjectId, const TSecurityPolicy& aPolicy)
+    {
+    ASSERT(iMessage);
+
+    const CDevCertKeyData* keyData = iKeyDataManager->Lookup(aObjectId);
+    if (!keyData)
+        {
+        User::Leave(KErrNotFound);
+        }
+
+    CDevTokenKeyInfo* keyInfo = iKeyDataManager->ReadKeyInfoLC(*keyData);
+
+    // Check the caller is allowed by current management policy
+    if (!keyInfo->ManagementPolicy().CheckPolicy(*iMessage))
+        {
+        User::Leave(KErrPermissionDenied);
+        }
+
+    // Check the caller is allowed by new management policy
+    if (!aPolicy.CheckPolicy(*iMessage))
+        {
+        User::Leave(KErrArgument);
+        }
+
+    // should revert change if write fails
+    keyInfo->SetManagementPolicy(aPolicy);
+    iKeyDataManager->SafeWriteKeyInfoL(*keyData, *keyInfo);	
+
+    CleanupStack::PopAndDestroy(keyInfo);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::RunError()
+// ---------------------------------------------------------------------------
+//
+TInt CDevCertKeyStoreServer::RunError(TInt aError)
+    { 
+    // Delete anything we might have created
+    delete iKeyCreator; iKeyCreator = NULL;
+
+    if ( iAction == EExportKey )
+        {
+        // we only own iKeyInfo for export operations
+        delete iKeyInfo;
+        iKeyInfo = NULL;
+        }
+
+    // Zero pointers to things we don't own
+    iKeyInfo = NULL;
+    iKeyData = NULL;
+    iExportBuf.Set(NULL, 0, 0);
+    iPKCS8Data.Set(NULL, 0);
+    iSession = NULL;
+    iMessage = NULL;
+
+    if (iCallerRequest)
+    User::RequestComplete(iCallerRequest, aError);
+
+    iAction = EIdle;		//	Reset action
+    return (KErrNone);		//	Handled
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::DoCancel()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::DoCancel()
+    {
+    switch (iAction)
+        {
+        case ECreateKeyFinal:
+        ASSERT(iKeyCreator);
+        iKeyCreator->Cancel();
+        break;
+
+        default:
+        // Nothing to do
+        break;
+        }
+
+    RunError(KErrCancel);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreServer::RunL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreServer::RunL()
+    {
+    User::LeaveIfError(iStatus.Int()); 
+
+    switch (iAction)
+        {
+        case ECreateKeyCreate:
+            DoCreateKeyL();	
+            iAction = ECreateKeyFinal;
+            break;
+        case ECreateKeyFinal:
+            DoStoreKeyL();			 
+            //	Check iKeyInfo was initialised for the caller
+            ASSERT(iKeyInfo->HandleID() != 0);						
+            RunError(KErrNone);
+            break;
+        case EImportKey:
+            {
+            TRAPD(err, DoImportKeyL());
+            if (err == KErrTooBig)
+                {
+                // Returned by ASN library if data is unexpected probably as a result of
+                // bad import data
+                err = KErrArgument;
+                }
+            User::LeaveIfError(err);
+            RunError(KErrNone);
+            break;
+            }
+            	
+        case EExportKey:
+            {
+            CompleteKeyExportL();
+            break;
+            }
+   				
+        default:
+            ASSERT(EFalse);
+        }
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertKeyStoreSession.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,136 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevCertKeyStoreSession
+*
+*/
+
+
+
+#include "DevCertKeyStoreSession.h"
+#include "DevCertKeyStoreServer.h"
+#include "DevCertOpenedKeysSrv.h"
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreSession::NewL()
+// ---------------------------------------------------------------------------
+// 
+CDevCertKeyStoreSession* CDevCertKeyStoreSession::NewL( CDevCertKeyStoreServer& aServer )
+    {
+    return new (ELeave) CDevCertKeyStoreSession( aServer );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreSession::CDevCertKeyStoreSession()
+// ---------------------------------------------------------------------------
+// 
+CDevCertKeyStoreSession::CDevCertKeyStoreSession(CDevCertKeyStoreServer& aServer )
+  : iServer(aServer)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreSession::~CDevCertKeyStoreSession()
+// ---------------------------------------------------------------------------
+//
+CDevCertKeyStoreSession::~CDevCertKeyStoreSession()
+    {
+    iServer.RemoveSession(*this);
+
+    for (TInt i = 0 ; i < iOpenedKeys.Count() ; ++i)
+        {
+        CDevCertOpenedKeySrv* object = iOpenedKeys[i].iObject;
+        delete object;
+        }
+    iOpenedKeys.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreSession::DoServiceL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreSession::DoServiceL(const RMessage2& aMessage)
+    {
+    iServer.ServiceRequestL(aMessage, *this);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreSession::AddOpenedKeyL()
+// ---------------------------------------------------------------------------
+//
+TInt CDevCertKeyStoreSession::AddOpenedKeyL(CDevCertOpenedKeySrv& aObject)
+    {
+    TObjectIndex oi;
+    oi.iObject = &aObject;
+    oi.iHandle = ++iLastHandle;
+    User::LeaveIfError(iOpenedKeys.InsertInSignedKeyOrder(oi));
+    return oi.iHandle;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreSession::RemoveOpenedKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertKeyStoreSession::RemoveOpenedKeyL(TInt aHandle)
+    {
+    TObjectIndex oi;
+    oi.iHandle = aHandle;
+    TInt pos = iOpenedKeys.Find(oi);
+    User::LeaveIfError(pos);
+    delete iOpenedKeys[pos].iObject;
+    iOpenedKeys.Remove(pos);  
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreSession::OpenedKey()
+// ---------------------------------------------------------------------------
+//
+CDevCertOpenedKeySrv* CDevCertKeyStoreSession::OpenedKey(TInt aHandle)
+    {
+    TObjectIndex oi;
+    oi.iHandle = aHandle;
+    TInt pos = iOpenedKeys.Find(oi);
+    return (pos != KErrNotFound) ? iOpenedKeys[pos].iObject : NULL;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertKeyStoreSession::HasOpenKey()
+// ---------------------------------------------------------------------------
+//
+TBool CDevCertKeyStoreSession::HasOpenKey(TInt aHandle)
+    {
+    TBool result = EFalse;
+    for (TInt i = 0 ; i < iOpenedKeys.Count() ; ++i)
+        {
+        CDevCertOpenedKeySrv* object = iOpenedKeys[i].iObject;
+        if (object->Handle() == aHandle)
+            {
+            result = ETrue;
+            break;
+            }
+        }
+    return result;
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertKeyStreamUtils.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,300 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevCertKeyStreamUtils
+*
+*/
+
+
+#include <asymmetrickeys.h>
+#include "DevCertKeyStreamUtils.h"
+#include "DevCertKeyEncryptor.h"
+
+// ======== GLOBAL FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// ExternalizeL()
+// RSA Public Key
+// ---------------------------------------------------------------------------
+//
+void ExternalizeL(const CRSAPublicKey& aKey, RWriteStream& aStream)
+    {
+    aStream << aKey.N() << aKey.E();
+    }
+
+
+// ---------------------------------------------------------------------------
+// ExternalizeL()
+// RSA Private Key
+// ---------------------------------------------------------------------------
+//
+void ExternalizeL(const CRSAPrivateKey& aData, RWriteStream& aStream)
+    {
+    CDevCertKeyEncryptor* encryptor = CDevCertKeyEncryptor::NewLC();
+    if( encryptor->IsPluginExistL() )
+        {
+        MKeyEncryptor* encrypt = encryptor->CreateImplementationL();  
+
+        //aStream << aData.N();
+        EncryptAndStoreL(aData.N(), aStream, encrypt );
+
+        // Check the incoming RSA private key (standard or CRT) 
+        TRSAPrivateKeyType keyType = aData.PrivateKeyType();
+        aStream.WriteInt32L((TInt32)keyType);
+
+        if (EStandard==keyType)
+            {
+            const CRSAPrivateKeyStandard& key = static_cast<const CRSAPrivateKeyStandard&>(aData);
+            //aStream << key.D();
+            EncryptAndStoreL(key.D(), aStream, encrypt );
+            }
+        else if (EStandardCRT==keyType)
+            {
+            const CRSAPrivateKeyCRT& key = static_cast<const CRSAPrivateKeyCRT&>(aData);
+            //aStream << key.P() << key.Q() << key.DP() << key.DQ() << key.QInv();
+            EncryptAndStoreL(key.P(), aStream, encrypt );
+            EncryptAndStoreL(key.Q(), aStream, encrypt );
+            EncryptAndStoreL(key.DP(), aStream, encrypt );
+            EncryptAndStoreL(key.DQ(), aStream, encrypt );
+            EncryptAndStoreL(key.QInv(), aStream, encrypt );
+            }
+        else
+            { 
+            User::Leave(KErrNotSupported);
+            }   
+        }
+    else
+        {
+        aStream << aData.N();
+
+        // Check the incoming RSA private key (standard or CRT) 
+        TRSAPrivateKeyType keyType = aData.PrivateKeyType();
+        aStream.WriteInt32L((TInt32)keyType);
+
+        if (EStandard==keyType)
+            {
+            const CRSAPrivateKeyStandard& key = static_cast<const CRSAPrivateKeyStandard&>(aData);
+            aStream << key.D();
+            }
+        else if (EStandardCRT==keyType)
+            {
+            const CRSAPrivateKeyCRT& key = static_cast<const CRSAPrivateKeyCRT&>(aData);
+            aStream << key.P() << key.Q() << key.DP() << key.DQ() << key.QInv();
+            }
+        else
+            { 
+            User::Leave(KErrNotSupported);
+            }
+        } 
+    CleanupStack::PopAndDestroy( encryptor );        
+    }
+
+
+// ---------------------------------------------------------------------------
+// ExternalizeL()
+// DSA Public Key
+// ---------------------------------------------------------------------------
+//
+void ExternalizeL(const CDSAPublicKey& aKey, RWriteStream& aStream)
+    {
+    aStream << aKey.P() << aKey.Q() << aKey.G() << aKey.Y();
+    }
+
+
+// ---------------------------------------------------------------------------
+// ExternalizeL()
+// DSA Private Key
+// ---------------------------------------------------------------------------
+//
+void ExternalizeL(const CDSAPrivateKey& aKey, RWriteStream& aStream)
+    {
+    CDevCertKeyEncryptor* encryptor = CDevCertKeyEncryptor::NewLC();
+    if( encryptor->IsPluginExistL() )
+        {
+        MKeyEncryptor* encrypt = encryptor->CreateImplementationL();  
+        //aStream << aKey.P() << aKey.Q() << aKey.G() << aKey.X();
+        EncryptAndStoreL(aKey.P(), aStream, encrypt );
+        EncryptAndStoreL(aKey.Q(), aStream, encrypt );
+        EncryptAndStoreL(aKey.G(), aStream, encrypt );
+        EncryptAndStoreL(aKey.X(), aStream, encrypt );
+        }
+    else
+        {
+        aStream << aKey.P() << aKey.Q() << aKey.G() << aKey.X();  
+        }
+    CleanupStack::PopAndDestroy(encryptor);        
+    }
+
+
+// ---------------------------------------------------------------------------
+// CreateL()
+// RSA Public key
+// ---------------------------------------------------------------------------
+//
+void CreateL(RReadStream& aStream, CRSAPublicKey*& aOut)
+    {
+    RInteger N, keyPublicExp;
+    CreateLC(aStream, N);
+    CreateLC(aStream, keyPublicExp);
+
+    aOut = CRSAPublicKey::NewL(N, keyPublicExp);
+
+    CleanupStack::Pop(2, &N); // keyPublicExp, N
+    }
+
+
+// ---------------------------------------------------------------------------
+// CreateL()
+// RSA Private key
+// ---------------------------------------------------------------------------
+//
+void CreateL(RReadStream& aStream, CRSAPrivateKey*& aOut)
+    {
+    CDevCertKeyEncryptor* encryptor = CDevCertKeyEncryptor::NewLC();
+    if( encryptor->IsPluginExistL() )
+        {
+        MKeyEncryptor* encrypt = encryptor->CreateImplementationL();
+
+        RInteger privateN;
+        DecryptAndCreateLC(aStream, privateN, encrypt);
+
+        TRSAPrivateKeyType keyType = EStandard;
+        keyType = (TRSAPrivateKeyType)aStream.ReadInt32L();
+
+        if (EStandard==keyType)
+            {
+            RInteger D;
+            DecryptAndCreateLC(aStream, D, encrypt);
+
+            aOut = CRSAPrivateKeyStandard::NewL(privateN, D);
+
+            CleanupStack::Pop(&D);
+            }
+        else if (EStandardCRT==keyType)
+            {
+            RInteger p, q, dP, dQ, qInv;
+            DecryptAndCreateLC(aStream, p, encrypt);
+            DecryptAndCreateLC(aStream, q, encrypt);
+            DecryptAndCreateLC(aStream, dP, encrypt);
+            DecryptAndCreateLC(aStream, dQ, encrypt);
+            DecryptAndCreateLC(aStream, qInv, encrypt);
+
+            aOut = CRSAPrivateKeyCRT::NewL(privateN, p, q, dP, dQ, qInv);
+
+            CleanupStack::Pop(5, &p);
+            }
+        else
+            {
+            User::Leave(KErrNotSupported);
+            }
+
+        CleanupStack::Pop(&privateN);
+        }
+    else
+        {
+        RInteger privateN;
+        CreateLC(aStream, privateN);
+
+        TRSAPrivateKeyType keyType = EStandard;
+        keyType = (TRSAPrivateKeyType)aStream.ReadInt32L();
+
+        if (EStandard==keyType)
+            {
+            RInteger D;
+            CreateLC(aStream, D);
+
+            aOut = CRSAPrivateKeyStandard::NewL(privateN, D);
+
+            CleanupStack::Pop(&D);
+            }
+        else if (EStandardCRT==keyType)
+            {
+            RInteger p, q, dP, dQ, qInv;
+            CreateLC(aStream, p);
+            CreateLC(aStream, q);
+            CreateLC(aStream, dP);
+            CreateLC(aStream, dQ);
+            CreateLC(aStream, qInv);
+
+            aOut = CRSAPrivateKeyCRT::NewL(privateN, p, q, dP, dQ, qInv);
+
+            CleanupStack::Pop(5, &p);
+            }
+        else
+            {
+            User::Leave(KErrNotSupported);
+            }
+
+        CleanupStack::Pop(&privateN); 
+        } 
+    CleanupStack::PopAndDestroy(encryptor);       
+    }
+
+
+// ---------------------------------------------------------------------------
+// CreateL()
+// DSA Public key
+// ---------------------------------------------------------------------------
+//
+void CreateL(RReadStream& aStream, CDSAPublicKey*& aOut)
+    {
+    RInteger P, Q, G, Y;
+    CreateLC(aStream, P);
+    CreateLC(aStream, Q);
+    CreateLC(aStream, G);
+    CreateLC(aStream, Y);
+
+    aOut = CDSAPublicKey::NewL(P, Q, G, Y);
+
+    CleanupStack::Pop(4, &P);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CreateL()
+// DSA Private key
+// ---------------------------------------------------------------------------
+//
+void CreateL(RReadStream& aStream, CDSAPrivateKey*& aOut)
+    {
+    CDevCertKeyEncryptor* encryptor = CDevCertKeyEncryptor::NewLC();
+    if( encryptor->IsPluginExistL() )
+        {
+        MKeyEncryptor* encrypt = encryptor->CreateImplementationL();
+        RInteger P, Q, G, X;
+        DecryptAndCreateLC(aStream, P, encrypt);
+        DecryptAndCreateLC(aStream, Q, encrypt);
+        DecryptAndCreateLC(aStream, G, encrypt);
+        DecryptAndCreateLC(aStream, X, encrypt);
+
+        aOut = CDSAPrivateKey::NewL(P, Q, G, X);
+
+        CleanupStack::Pop(4, &P);
+        }
+    else
+        {
+        RInteger P, Q, G, X;
+        CreateLC(aStream, P);
+        CreateLC(aStream, Q);
+        CreateLC(aStream, G);
+        CreateLC(aStream, X);
+
+        aOut = CDSAPrivateKey::NewL(P, Q, G, X);
+
+        CleanupStack::Pop(4, &P); 
+        }
+    CleanupStack::PopAndDestroy(encryptor);        
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/KeyStore/Server/DevCertOpenedKeysSrv.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,754 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevCertOpenedKeySrv
+*
+*/
+
+
+#ifdef SYMBIAN_ENABLE_SPLIT_HEADERS
+#include <mctkeystoreuids.h>
+#endif
+#include <asymmetric.h>
+#include <asymmetrickeys.h>
+#include <bigint.h>
+#include <ct.h>
+#include <securityerr.h>
+#include <e32base.h>
+
+#include "DevCertOpenedKeysSrv.h"
+#include "DevCertKeyStoreServer.h"
+#include "DevCertKeyStreamUtils.h"
+#include "DevTokenDataTypes.h"
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// CDevCertOpenedKeySrv
+
+// ---------------------------------------------------------------------------
+// CDevCertOpenedKeySrv::NewL()
+// ---------------------------------------------------------------------------
+//
+CDevCertOpenedKeySrv* CDevCertOpenedKeySrv::NewL(const CDevCertKeyData& aKeyData, 
+                                                 TUid aType, 
+                                                 const RMessage2& aMessage,
+                                                 CDevCertKeyDataManager& aKeyDataMan )
+    {
+    CDevCertOpenedKeySrv* self = NULL;
+
+    if (aType == KRSARepudiableSignerUID)
+        {
+        self = new (ELeave) CDevCertRSARepudiableSignerSrv(aKeyData, aKeyDataMan );
+        }
+    else if (aType == KDSARepudiableSignerUID)
+        {
+        self = new (ELeave) CDevCertDSARepudiableSignerSrv(aKeyData, aKeyDataMan );
+        }
+    else if (aType == KPrivateDecryptorUID)
+        {
+        self = new (ELeave) CDevCertRSADecryptorSrv(aKeyData, aKeyDataMan );
+        }
+    else if (aType == KKeyAgreementUID)
+        {
+        self = new (ELeave) CDevCertDHAgreementSrv(aKeyData, aKeyDataMan );
+        }
+    else
+        {
+        User::Invariant();
+        }
+
+    CleanupStack::PushL(self);
+    self->ConstructL(aMessage);
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertOpenedKeySrv::CDevCertOpenedKeySrv()
+// ---------------------------------------------------------------------------
+//
+CDevCertOpenedKeySrv::CDevCertOpenedKeySrv(const CDevCertKeyData& aKeyData, CDevCertKeyDataManager& aKeyDataMan ) :
+  CActive(EPriorityStandard),
+  iKeyData(aKeyData),
+  iKeyDataMan(aKeyDataMan)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertOpenedKeySrv::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertOpenedKeySrv::ConstructL(const RMessage2& aMessage)
+    {
+    CDevTokenKeyInfo* keyInfo = iKeyDataMan.ReadKeyInfoLC(iKeyData);  
+    CheckKeyL(*keyInfo, aMessage);
+    iLabel = keyInfo->Label().AllocL();
+    CleanupStack::PopAndDestroy(keyInfo);
+    CActiveScheduler::Add(this);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertOpenedKeySrv::~CDevCertOpenedKeySrv()
+// ---------------------------------------------------------------------------
+//
+CDevCertOpenedKeySrv::~CDevCertOpenedKeySrv()
+    {
+    Cancel();
+    delete iLabel;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertOpenedKeySrv::Label()
+// ---------------------------------------------------------------------------
+//
+const TDesC& CDevCertOpenedKeySrv::Label() const
+    {
+    return *iLabel;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertOpenedKeySrv::Handle()
+// ---------------------------------------------------------------------------
+//
+TInt CDevCertOpenedKeySrv::Handle() const
+    {
+    return iKeyData.Handle();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertOpenedKeySrv::CheckKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertOpenedKeySrv::CheckKeyL(const CDevTokenKeyInfo& aKeyInfo, const RMessage2& aMessage)
+    {
+    // Check the client is allowed to use the key
+    if (!aKeyInfo.UsePolicy().CheckPolicy(aMessage))
+        {
+        User::Leave(KErrPermissionDenied);
+        }
+
+    // Check that the operation represented by this object is supported for this
+    // type of key
+    if (aKeyInfo.Algorithm() != Algorithm())
+        {
+        User::Leave(KErrKeyAlgorithm);
+        }
+
+    // Check the key usage allows the operation
+    if ((aKeyInfo.Usage() & RequiredUsage()) == 0)
+        {
+        User::Leave(KErrKeyUsage);
+        }
+
+    // Check current time is after start date (if set) and before end date (if
+    // set)
+    TTime timeNow;
+    timeNow.UniversalTime();
+    if (aKeyInfo.StartDate().Int64() != 0 && timeNow < aKeyInfo.StartDate())
+        {
+        User::Leave(KErrKeyValidity);
+        }
+    if (aKeyInfo.EndDate().Int64() != 0 && timeNow >= aKeyInfo.EndDate())
+        {
+        User::Leave(KErrKeyValidity);
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertOpenedKeySrv::DoOperation()
+// ---------------------------------------------------------------------------
+//
+void CDevCertOpenedKeySrv::DoOperation( TRequestStatus& aStatus )
+    {
+    ASSERT(iState == EIdle);
+    iStatus = KRequestPending;
+    iClientStatus = &aStatus;
+    TRequestStatus* status = &iStatus;
+    iState = EOperation;
+    SetActive();
+    User::RequestComplete( status, KErrNone );
+    }   
+
+
+// ---------------------------------------------------------------------------
+// CDevCertOpenedKeySrv::RunL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertOpenedKeySrv::RunL()
+    {
+    User::LeaveIfError(iStatus.Int());
+
+    switch (iState)
+        {
+        case EOperation:
+        if (!iKeyRead)
+            {
+            RStoreReadStream stream;
+            iKeyDataMan.OpenPrivateDataStreamLC(iKeyData, stream);
+            ReadPrivateKeyL(stream);
+            CleanupStack::PopAndDestroy(&stream);
+            iKeyRead = ETrue;
+            }
+        PerformOperationL();
+        break;
+
+        default:
+        ASSERT(EFalse);
+        }
+
+    Complete(KErrNone);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertOpenedKeySrv::RunError()
+// ---------------------------------------------------------------------------
+//
+TInt CDevCertOpenedKeySrv::RunError(TInt aError)
+    {
+    Complete(aError);
+    return KErrNone;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertOpenedKeySrv::DoCancel()
+// ---------------------------------------------------------------------------
+//
+void CDevCertOpenedKeySrv::DoCancel()
+    {
+    Complete(KErrCancel);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertOpenedKeySrv::Complete()
+// ---------------------------------------------------------------------------
+//
+void CDevCertOpenedKeySrv::Complete(TInt aError)
+    {
+    Cleanup();
+    if (iClientStatus)
+        {
+        User::RequestComplete(iClientStatus, aError);
+        }
+    iState = EIdle;
+    }
+
+
+
+// CDevCertRSARepudiableSignerSrv 
+
+// ---------------------------------------------------------------------------
+// CDevCertRSARepudiableSignerSrv::CDevCertRSARepudiableSignerSrv()
+// ---------------------------------------------------------------------------
+//
+CDevCertRSARepudiableSignerSrv::CDevCertRSARepudiableSignerSrv(const CDevCertKeyData& aKeyData, CDevCertKeyDataManager& aKeyDataMan ) :
+  CDevCertOpenedKeySrv(aKeyData, aKeyDataMan )
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSARepudiableSignerSrv::~CDevCertRSARepudiableSignerSrv()
+// ---------------------------------------------------------------------------
+//
+CDevCertRSARepudiableSignerSrv::~CDevCertRSARepudiableSignerSrv()
+    {
+    delete iPrivateKey;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSARepudiableSignerSrv::Type()
+// ---------------------------------------------------------------------------
+//
+TUid CDevCertRSARepudiableSignerSrv::Type() const
+    {
+    return KRSARepudiableSignerUID;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSARepudiableSignerSrv::Algorithm()
+// ---------------------------------------------------------------------------
+//
+CDevTokenKeyInfo::EKeyAlgorithm CDevCertRSARepudiableSignerSrv::Algorithm() const
+    {
+    return CDevTokenKeyInfo::ERSA;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSARepudiableSignerSrv::RequiredUsage()
+// ---------------------------------------------------------------------------
+//
+TKeyUsagePKCS15 CDevCertRSARepudiableSignerSrv::RequiredUsage() const
+    {
+    return EPKCS15UsageSignSignRecover;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSARepudiableSignerSrv::Sign()
+// ---------------------------------------------------------------------------
+//
+void CDevCertRSARepudiableSignerSrv::Sign(const TDesC8& aPlaintext,
+                CRSASignature*& aSignature,
+                TRequestStatus& aStatus)
+    {
+    ASSERT( iPlaintext.Ptr() == NULL );
+    ASSERT( iSignaturePtr == NULL );
+    iPlaintext.Set(aPlaintext);
+    iSignaturePtr = &aSignature;
+    DoOperation( aStatus );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSARepudiableSignerSrv::ReadPrivateKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertRSARepudiableSignerSrv::ReadPrivateKeyL(RReadStream& aStream)
+    {
+    ASSERT( iPrivateKey == NULL );
+    CreateL(aStream, iPrivateKey);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSARepudiableSignerSrv::PerformOperationL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertRSARepudiableSignerSrv::PerformOperationL()
+    {
+    ASSERT(iPrivateKey);
+
+    CRSAPKCS1v15Signer* signer = CRSAPKCS1v15Signer::NewLC(*iPrivateKey);
+    const CRSASignature* signature = signer->SignL(iPlaintext);
+    CleanupStack::PopAndDestroy(signer);
+    *iSignaturePtr = const_cast<CRSASignature*>(signature);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSARepudiableSignerSrv::Cleanup()
+// ---------------------------------------------------------------------------
+//
+void CDevCertRSARepudiableSignerSrv::Cleanup()
+    {
+    iPlaintext.Set(NULL, 0);
+    iSignaturePtr = NULL;
+    }
+
+
+// CDevCertDSARepudiableSignerSrv 
+
+// ---------------------------------------------------------------------------
+// CDevCertDSARepudiableSignerSrv::CDevCertDSARepudiableSignerSrv()
+// ---------------------------------------------------------------------------
+//
+CDevCertDSARepudiableSignerSrv::CDevCertDSARepudiableSignerSrv(const CDevCertKeyData& aKeyData, CDevCertKeyDataManager& aKeyDataMan ) :
+  CDevCertOpenedKeySrv(aKeyData, aKeyDataMan )
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDSARepudiableSignerSrv::~CDevCertDSARepudiableSignerSrv()
+// ---------------------------------------------------------------------------
+//
+CDevCertDSARepudiableSignerSrv::~CDevCertDSARepudiableSignerSrv()
+    {
+    delete iPrivateKey;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDSARepudiableSignerSrv::Type()
+// ---------------------------------------------------------------------------
+//
+TUid CDevCertDSARepudiableSignerSrv::Type() const
+    {
+    return KDSARepudiableSignerUID;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDSARepudiableSignerSrv::Algorithm()
+// ---------------------------------------------------------------------------
+//
+CDevTokenKeyInfo::EKeyAlgorithm CDevCertDSARepudiableSignerSrv::Algorithm() const
+    {
+    return CDevTokenKeyInfo::EDSA;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDSARepudiableSignerSrv::RequiredUsage()
+// ---------------------------------------------------------------------------
+//
+TKeyUsagePKCS15 CDevCertDSARepudiableSignerSrv::RequiredUsage() const
+    {
+    return EPKCS15UsageSignSignRecover;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDSARepudiableSignerSrv::Sign()
+// ---------------------------------------------------------------------------
+//
+void CDevCertDSARepudiableSignerSrv::Sign(const TDesC8& aPlaintext,
+                CDSASignature*& aSignature,
+                TRequestStatus& aStatus)
+    {
+    ASSERT( iPlaintext.Ptr() == NULL );
+    ASSERT( iSignaturePtr == NULL );
+    iPlaintext.Set(aPlaintext);
+    iSignaturePtr = &aSignature;
+    DoOperation( aStatus );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDSARepudiableSignerSrv::ReadPrivateKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertDSARepudiableSignerSrv::ReadPrivateKeyL(RReadStream& aStream)
+    {
+    ASSERT( iPrivateKey == NULL );
+    CreateL(aStream, iPrivateKey);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDSARepudiableSignerSrv::PerformOperationL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertDSARepudiableSignerSrv::PerformOperationL()
+    {
+    ASSERT( iPrivateKey );
+
+    CDSASigner* signer = CDSASigner::NewLC(*iPrivateKey);
+    const CDSASignature* signature = signer->SignL(iPlaintext);
+    CleanupStack::PopAndDestroy(signer);
+    *iSignaturePtr = const_cast<CDSASignature*>(signature);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDSARepudiableSignerSrv::Cleanup()
+// ---------------------------------------------------------------------------
+//
+void CDevCertDSARepudiableSignerSrv::Cleanup()
+    {
+    iPlaintext.Set(NULL, 0);
+    iSignaturePtr = NULL;
+    }
+
+
+// CDevCertRSADecryptorSrv 
+
+// ---------------------------------------------------------------------------
+// CDevCertRSADecryptorSrv::CDevCertRSADecryptorSrv()
+// ---------------------------------------------------------------------------
+//
+CDevCertRSADecryptorSrv::CDevCertRSADecryptorSrv(const CDevCertKeyData& aKeyData, CDevCertKeyDataManager& aKeyDataMan ) :
+  CDevCertOpenedKeySrv(aKeyData, aKeyDataMan )
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSADecryptorSrv::~CDevCertRSADecryptorSrv()
+// ---------------------------------------------------------------------------
+//
+CDevCertRSADecryptorSrv::~CDevCertRSADecryptorSrv()
+    {
+    delete iPrivateKey;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSADecryptorSrv::Type()
+// ---------------------------------------------------------------------------
+//
+TUid CDevCertRSADecryptorSrv::Type() const
+    {
+    return KPrivateDecryptorUID;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSADecryptorSrv::Algorithm()
+// ---------------------------------------------------------------------------
+//
+CDevTokenKeyInfo::EKeyAlgorithm CDevCertRSADecryptorSrv::Algorithm() const
+    {
+    return CDevTokenKeyInfo::ERSA;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSADecryptorSrv::RequiredUsage()
+// ---------------------------------------------------------------------------
+//
+TKeyUsagePKCS15 CDevCertRSADecryptorSrv::RequiredUsage() const
+    {
+    return EPKCS15UsageDecryptUnwrap;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSADecryptorSrv::Decrypt()
+// ---------------------------------------------------------------------------
+//
+void CDevCertRSADecryptorSrv::Decrypt(const TDesC8& aCiphertext,
+                HBufC8*& aPlaintext,
+                TRequestStatus& aStatus)
+    {
+    ASSERT( iCiphertext.Ptr() == NULL );
+    ASSERT( iPlaintextPtr == NULL );
+    iCiphertext.Set(aCiphertext);
+    iPlaintextPtr = &aPlaintext;
+    DoOperation( aStatus );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSADecryptorSrv::ReadPrivateKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertRSADecryptorSrv::ReadPrivateKeyL(RReadStream& aStream)
+    {
+    ASSERT( iPrivateKey == NULL );
+    CreateL(aStream, iPrivateKey);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSADecryptorSrv::PerformOperationL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertRSADecryptorSrv::PerformOperationL()
+    {
+    ASSERT(iPrivateKey);
+
+    CRSAPKCS1v15Decryptor* decryptor = CRSAPKCS1v15Decryptor::NewLC(*iPrivateKey);
+    HBufC8* plaintext = HBufC8::NewMaxLC(decryptor->MaxOutputLength());
+    TPtr8 ptr = plaintext->Des();
+    decryptor->DecryptL(iCiphertext, ptr);
+
+    *iPlaintextPtr = plaintext;
+    CleanupStack::Pop(plaintext); // now owned by client
+    CleanupStack::PopAndDestroy(decryptor);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertRSADecryptorSrv::Cleanup()
+// ---------------------------------------------------------------------------
+//
+void CDevCertRSADecryptorSrv::Cleanup()
+    {
+    iCiphertext.Set(NULL, 0);
+    iPlaintextPtr = NULL;
+    }
+
+
+// CDevCertDHAgreementSrv 
+
+// ---------------------------------------------------------------------------
+// CDevCertDHAgreementSrv::CDevCertDHAgreementSrv()
+// ---------------------------------------------------------------------------
+//
+CDevCertDHAgreementSrv::CDevCertDHAgreementSrv(const CDevCertKeyData& aKeyData, CDevCertKeyDataManager& aKeyDataMan ) :
+  CDevCertOpenedKeySrv(aKeyData, aKeyDataMan )
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDHAgreementSrv::~CDevCertDHAgreementSrv()
+// ---------------------------------------------------------------------------
+//
+CDevCertDHAgreementSrv::~CDevCertDHAgreementSrv()
+    {
+    iKey.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDHAgreementSrv::Type()
+// ---------------------------------------------------------------------------
+//
+TUid CDevCertDHAgreementSrv::Type() const
+    {
+    return KKeyAgreementUID;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDHAgreementSrv::Algorithm()
+// ---------------------------------------------------------------------------
+//
+CDevTokenKeyInfo::EKeyAlgorithm CDevCertDHAgreementSrv::Algorithm() const
+    {
+    return CDevTokenKeyInfo::EDH;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDHAgreementSrv::RequiredUsage()
+// ---------------------------------------------------------------------------
+//
+TKeyUsagePKCS15 CDevCertDHAgreementSrv::RequiredUsage() const
+    {
+    return EPKCS15UsageDerive;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDHAgreementSrv::PublicKey()
+// ---------------------------------------------------------------------------
+//
+void CDevCertDHAgreementSrv::PublicKey(CDevTokenDHParams& aParameters, RInteger& aPublicKey, TRequestStatus& aStatus)
+    {
+    ASSERT( iPKParams == NULL );
+    ASSERT( iPKPublicKeyPtr == NULL );
+    iPKParams = &aParameters;
+    iPKPublicKeyPtr = &aPublicKey;
+    iDHState = EPublicKey;
+    DoOperation( aStatus );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDHAgreementSrv::Agree()
+// ---------------------------------------------------------------------------
+//
+void CDevCertDHAgreementSrv::Agree(CDHPublicKey& aY, HBufC8*& aAgreedKey, TRequestStatus& aStatus)
+    {
+    ASSERT( iAKPublicKey == NULL );
+    ASSERT( iAKAgreedKeyPtr == NULL );
+    iAKPublicKey = &aY;
+    iAKAgreedKeyPtr = &aAgreedKey;
+    iDHState = EAgree;
+    DoOperation( aStatus );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDHAgreementSrv::ReadPrivateKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertDHAgreementSrv::ReadPrivateKeyL(RReadStream& aStream)
+    {
+    CreateLC(aStream, iKey);
+    CleanupStack::Pop(&iKey);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDHAgreementSrv::PerformOperationL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertDHAgreementSrv::PerformOperationL()
+    {
+    switch (iDHState)
+        {
+        case EPublicKey:
+        DoPublicKeyL();
+        break;
+        case EAgree:
+        DoAgreeL();
+        break;
+        default:
+        ASSERT(FALSE);
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDHAgreementSrv::DoPublicKeyL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertDHAgreementSrv::DoPublicKeyL()
+    {
+    ASSERT(iPKParams);
+    ASSERT(iPKPublicKeyPtr);
+
+    RInteger n = iPKParams->TakeN();
+    CleanupStack::PushL(n);
+    RInteger g = iPKParams->TakeG();
+    CleanupStack::PushL(g);
+    RInteger x = RInteger::NewL(iKey);
+    CleanupStack::PushL(x);
+    CDHKeyPair* keyPair = CDHKeyPair::NewL(n, g, x);
+    CleanupStack::Pop(3); // x, g, n
+    CleanupStack::PushL(keyPair);
+
+    const CDHPublicKey& pubKey = keyPair->PublicKey();
+    *iPKPublicKeyPtr = RInteger::NewL(pubKey.X());
+    CleanupStack::PopAndDestroy(keyPair);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDHAgreementSrv::DoAgreeL()
+// ---------------------------------------------------------------------------
+//
+void CDevCertDHAgreementSrv::DoAgreeL()
+    {
+    ASSERT(iAKPublicKey);
+    ASSERT(iAKAgreedKeyPtr);
+
+    RInteger n = RInteger::NewL(iAKPublicKey->N());
+    CleanupStack::PushL(n);
+    RInteger g = RInteger::NewL(iAKPublicKey->G());
+    CleanupStack::PushL(g);
+    RInteger x = RInteger::NewL(iKey);
+    CleanupStack::PushL(x);
+    CDHPrivateKey* privKey = CDHPrivateKey::NewL(n, g, x);
+    CleanupStack::Pop(3); // x, g, n
+    CleanupStack::PushL(privKey);
+    CDH* dh = CDH::NewLC(*privKey);
+    *iAKAgreedKeyPtr = const_cast<HBufC8*>(dh->AgreeL(*iAKPublicKey));
+    CleanupStack::PopAndDestroy(2, privKey);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevCertDHAgreementSrv::Cleanup()
+// ---------------------------------------------------------------------------
+//
+void CDevCertDHAgreementSrv::Cleanup()
+    {
+    iPKParams = NULL;
+    iPKPublicKeyPtr = NULL;
+    iAKPublicKey = NULL;
+    iAKAgreedKeyPtr = NULL;
+    iDHState = EIdle;
+    }
+
+//EOF
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/KeyStore/Server/DevTokenPWManager.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevToken Password manager
+*
+*/
+
+
+
+#include "DevTokenPWManager.h"
+#include "DevTokenDialog.h"
+#include <pbedata.h>
+#include <mctauthobject.h>
+#include <securityerr.h>
+
+//CONST
+_LIT( KKeyStoreImportKeyLabel, "Passphrase of the imported key file" );
+
+void TDevTokenPWManager::GetPassword( TPINValue& aValue, 
+									  TRequestStatus& aStatus,
+									  TBool aRetry)
+    {
+	  TPINParams params;
+    //CTSecDlg will check the key label to decide the show-up dialog
+	  params.iPINLabel.Copy(KKeyStoreImportKeyLabel);
+	  params.iMinLength = 0;
+	  params.iMaxLength = KMaxPINLength;
+	  
+	  DevTokenDialog::Dialog()->EnterPIN(params, aRetry, aValue, aStatus);
+	  }
+
+	
+void TDevTokenPWManager::ImportPassword(TPINValue& aValue, 
+												 TRequestStatus& aStatus)
+	  {
+	  GetPassword( aValue, aStatus );
+	  }
+	  
+
+void TDevTokenPWManager::Cancel()
+      {
+	  DevTokenDialog::Dialog()->Cancel();
+	  }
+
+//EOF
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Shared/DevTokenCertInfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,213 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenCertInfo
+*
+*/
+
+
+
+#include "DevTokenDataTypes.h"
+
+// ======== MEMBER FUNCTIONS ========
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenCertInfo::NewLC(const CDevTokenCertInfo& aOther)
+// ---------------------------------------------------------------------------
+// 
+EXPORT_C CDevTokenCertInfo* CDevTokenCertInfo::NewLC(const CDevTokenCertInfo& aOther)
+    {
+    CDevTokenCertInfo* self = NewL(aOther);
+    CleanupStack::PushL(self);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenCertInfo::NewL(const CDevTokenCertInfo& aOther)
+// ---------------------------------------------------------------------------
+// 
+EXPORT_C CDevTokenCertInfo* CDevTokenCertInfo::NewL(const CDevTokenCertInfo& aOther)
+    {
+    return new (ELeave) CDevTokenCertInfo(aOther);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenCertInfo::CDevTokenCertInfo(const CDevTokenCertInfo& aOther)
+// ---------------------------------------------------------------------------
+//
+CDevTokenCertInfo::CDevTokenCertInfo(const CDevTokenCertInfo& aOther) :
+    MCertInfo(aOther)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenCertInfo* CDevTokenCertInfo::NewL()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CDevTokenCertInfo* CDevTokenCertInfo::NewL(const TDesC& aLabel,
+               TCertificateFormat aFormat,
+               TCertificateOwnerType aCertificateOwnerType,
+               TInt aSize,
+               const TKeyIdentifier* aSubjectKeyId,   
+               const TKeyIdentifier* aIssuerKeyId,
+               TInt aCertificateId)
+    {
+    CDevTokenCertInfo* self = new(ELeave) CDevTokenCertInfo(
+        aLabel,
+        aFormat, 
+        aCertificateOwnerType, 
+        aSize, 
+        aSubjectKeyId, 
+        aIssuerKeyId,
+        aCertificateId);
+    self->ConstructL(NULL);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenCertInfo* CDevTokenCertInfo::NewL()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CDevTokenCertInfo* CDevTokenCertInfo::NewL(const TDesC& aLabel,
+               TCertificateFormat aFormat,
+               TCertificateOwnerType aCertificateOwnerType,
+               TInt aSize,
+               const TKeyIdentifier* aSubjectKeyId,   
+               const TKeyIdentifier* aIssuerKeyId,
+               TInt aCertificateId,
+               const TBool aDeletable)
+    {
+    CDevTokenCertInfo* self = new(ELeave) CDevTokenCertInfo(
+        aLabel,
+        aFormat, 
+        aCertificateOwnerType, 
+        aSize, 
+        aSubjectKeyId,  
+        aIssuerKeyId,
+        aCertificateId, 
+        aDeletable);
+    self->ConstructL(NULL);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenCertInfo* CDevTokenCertInfo::NewLC()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CDevTokenCertInfo* CDevTokenCertInfo::NewLC(const TDesC& aLabel,
+              TCertificateFormat aFormat,
+              TCertificateOwnerType aCertificateOwnerType,
+              TInt aSize,
+              const TKeyIdentifier* aSubjectKeyId,
+              const TKeyIdentifier* aIssuerKeyId,
+              TInt aCertificateId)
+    {
+    CDevTokenCertInfo* self = CDevTokenCertInfo::NewL(
+        aLabel,
+        aFormat, 
+        aCertificateOwnerType, 
+        aSize, 
+        aSubjectKeyId, 
+        aIssuerKeyId,
+        aCertificateId);
+    CleanupStack::PushL(self);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenCertInfo* CDevTokenCertInfo::NewLC()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CDevTokenCertInfo* CDevTokenCertInfo::NewLC(const TDesC& aLabel,
+              TCertificateFormat aFormat,
+              TCertificateOwnerType aCertificateOwnerType,
+              TInt aSize,
+              const TKeyIdentifier* aSubjectKeyId,
+              const TKeyIdentifier* aIssuerKeyId,
+              TInt aCertificateId,
+                const TBool aDeletable)
+    {
+    CDevTokenCertInfo* self = CDevTokenCertInfo::NewL(
+        aLabel,
+        aFormat, 
+        aCertificateOwnerType, 
+        aSize, 
+        aSubjectKeyId, 
+        aIssuerKeyId,
+        aCertificateId, 
+        aDeletable);
+    CleanupStack::PushL(self);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenCertInfo::CDevTokenCertInfo()
+// ---------------------------------------------------------------------------
+//
+CDevTokenCertInfo::CDevTokenCertInfo(const TDesC& aLabel, 
+           TCertificateFormat aFormat,
+           TCertificateOwnerType aCertificateOwnerType,
+           TInt aSize,
+           const TKeyIdentifier* aSubjectKeyId,
+           const TKeyIdentifier* aIssuerKeyId,
+           TInt aCertificateId,
+           const TBool aDeletable) :
+  MCertInfo(aLabel, aFormat, aCertificateOwnerType, aSize, aSubjectKeyId,
+        aIssuerKeyId, aCertificateId, aDeletable)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenCertInfo* CDevTokenCertInfo::NewL(RReadStream& aStream)
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CDevTokenCertInfo* CDevTokenCertInfo::NewL(RReadStream& aStream)
+    {
+    CDevTokenCertInfo* me = NewLC(aStream);
+    CleanupStack::Pop(me);
+    return me;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenCertInfo* CDevTokenCertInfo::NewLC(RReadStream& aStream)
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CDevTokenCertInfo* CDevTokenCertInfo::NewLC(RReadStream& aStream)
+    {
+    CDevTokenCertInfo* self = new (ELeave) CDevTokenCertInfo();
+    CleanupStack::PushL(self);
+    self->InternalizeL(aStream);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenCertInfo::CDevTokenCertInfo() 
+// ---------------------------------------------------------------------------
+//
+CDevTokenCertInfo::CDevTokenCertInfo() :
+    MCertInfo()
+    {
+    }
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Shared/DevTokenDHParams.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,86 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenDHParams
+*
+*/
+
+
+
+#include "DevTokenDataTypes.h"
+
+// ======== MEMBER FUNCTIONS ========
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenDHParams::~CDevTokenDHParams()
+// ---------------------------------------------------------------------------
+// 
+EXPORT_C CDevTokenDHParams::~CDevTokenDHParams()
+    {
+    iN.Close();
+    iG.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenDHParams::CDevTokenDHParams(RInteger aN, RInteger aG)
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CDevTokenDHParams::CDevTokenDHParams(RInteger aN, RInteger aG)
+    : iN(aN), iG(aG)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenDHParams::NewL(const TInteger& aN, const TInteger& aG)
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CDevTokenDHParams* CDevTokenDHParams::NewL(const TInteger& aN, const TInteger& aG)
+    {
+    RInteger n = RInteger::NewL(aN);
+    CleanupStack::PushL(n);
+    RInteger g = RInteger::NewL(aG);
+    CleanupStack::PushL(g);
+    CDevTokenDHParams* self = new (ELeave) CDevTokenDHParams(n, g);
+    CleanupStack::Pop(2); // g, n
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenDHParams::TakeN()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C RInteger CDevTokenDHParams::TakeN()
+    {
+    RInteger result = iN;
+    iN = RInteger();
+    return result;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenDHParams::TakeG()
+// ---------------------------------------------------------------------------
+//
+EXPORT_C RInteger CDevTokenDHParams::TakeG()
+    {
+    RInteger result = iG;
+    iG = RInteger();
+    return result;
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Shared/DevTokenDataMarshaller.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,780 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenDataMarshaller
+*
+*/
+
+
+
+#include <asymmetric.h>
+#include <bigint.h>
+#include <s32mem.h>
+#include <certificateapps.h>
+#include <ccertattributefilter.h>
+#include <s32strm.h>
+#include <e32test.h>
+#include "DevTokenMarshaller.h"
+#include "DevTokenDataTypes.h"
+#include "DevTokenNullStream.h"
+#include "DevCertKeyEncryptor.h"
+#include "DevtokenLog.h"
+
+
+// ======== LOCAL FUNCTIONS ========
+
+// Generic externalization stuff
+
+// ---------------------------------------------------------------------------
+// Determine how many bytes are taked up by the externalized representation of
+// an object.
+// ---------------------------------------------------------------------------
+//
+template <class T>
+TInt Size(const T& aObject)
+    {
+    RNullWriteStream stream;
+    TRAPD(err, stream << aObject);
+    if ( err != KErrNone )
+    {
+    _LIT(KPanicCategory, "InValid Size");
+    User::Panic(KPanicCategory,ESerialisationPanic);
+    }
+    stream.Close();
+    return stream.BytesWritten();
+    }
+
+
+// ---------------------------------------------------------------------------
+// Externalize an object to a buffer.  Leaves if an error occurs.
+// ---------------------------------------------------------------------------
+// 
+template <class T>
+void WriteL(const T& aIn, TDes8& aOut)
+    {
+    RDesWriteStream stream(aOut);
+    stream << aIn;
+    stream.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// Externalize an object to a buffer.  In debug mode, it will panics if an error
+// occurs - eg buffer is too short.  In release mode, errors are ignored.
+// ---------------------------------------------------------------------------
+//  
+template <class T>
+void Write(const T& aIn, TDes8& aOut)
+    {
+    TRAPD(err, WriteL(aIn, aOut));
+    if ( err != KErrNone )
+        {
+        _LIT(KPanicCategory, "Writing Error");
+        User::Panic(KPanicCategory,ESerialisationPanic);
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// Implement Externalization selector for RPointerArrays to use a function.
+// ---------------------------------------------------------------------------
+// 
+template <class T>
+EXTERNALIZE_FUNCTION(RPointerArray<T>)
+
+
+// ---------------------------------------------------------------------------
+// Function to externalize RPointerArrays.Although this is generic, 
+// it's currently only instantiated for CDevTokenKeyInfo.
+// ---------------------------------------------------------------------------
+// 
+template <class T>
+void ExternalizeL(const RPointerArray<T>& aIn, RWriteStream& aOut)
+    {
+    TInt count = aIn.Count();
+    aOut.WriteInt32L(count);
+    for ( TInt i = 0 ; i < count ; ++i )
+        {
+        T* object = aIn[i];
+        if ( object == NULL )
+            {
+            User::Leave(KErrArgument);
+            }
+        aOut << *object;
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// Implement Externalization selector for RArrays to use a function.
+// ---------------------------------------------------------------------------
+//  
+template <class T>
+EXTERNALIZE_FUNCTION(RArray<T>)
+
+
+// ---------------------------------------------------------------------------
+// Function to externalize RArrays.
+// ---------------------------------------------------------------------------
+//  
+template <class T>
+void ExternalizeL(const RArray<T>& aIn, RWriteStream& aOut)
+    {
+    TInt count = aIn.Count();
+    aOut.WriteInt32L(count);
+    for ( TInt i = 0 ; i < count ; ++i )
+        {
+        aOut << aIn[i];
+        }
+    }
+
+
+// No-so-generic internalization stuff 
+
+// ---------------------------------------------------------------------------
+// Internalize an object from a descriptor.
+// ---------------------------------------------------------------------------
+//  
+template <class T>
+void ReadL(const TDesC8& aIn, T& aOut)
+    {
+    RDesReadStream stream(aIn);
+    stream >> aOut;
+    stream.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// Implement Internalization selector for RArrays to use a function.
+// ---------------------------------------------------------------------------
+//  
+template <class T>
+inline Internalize::Function Internalization(const RArray<T>*)
+    {
+    return Internalize::Function();
+    }
+
+
+// ---------------------------------------------------------------------------
+// Function to internalize an RArray.
+// ---------------------------------------------------------------------------
+//  
+template <class T>
+void InternalizeL(RArray<T>& aOut, RReadStream& aIn)
+    {
+    ASSERT(aOut.Count() == 0);
+    TInt count = aIn.ReadInt32L();
+    for (TInt i = 0 ; i < count ; ++i)
+        {
+        T t;
+        aIn >> t;
+        User::LeaveIfError(aOut.Append(t));
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// Internalize an object from a stream.  Creates an instance by calling the
+// class' NewL(RReadStream&) method.
+// ---------------------------------------------------------------------------
+//  
+template <class T>
+inline void CreateL(RReadStream& aIn, T*& aOut)
+    {
+    aOut = T::NewL(aIn);
+    }
+
+
+// ---------------------------------------------------------------------------
+// Internalize an object from a descriptor.
+// ---------------------------------------------------------------------------
+//  
+template <class T>
+void CreateL(const TDesC8& aIn, T& aOut)
+    {
+    RDesReadStream stream(aIn);
+    CreateL(stream, aOut);
+    stream.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// Internalize an object from a descriptor leaving the result on the cleanup
+// stack.  This is generic, but is only instantiated for RInteger.
+// ---------------------------------------------------------------------------
+//  
+template <class T>
+void CreateLC(const TDesC8& aIn, T& aOut)
+    {
+    RDesReadStream stream(aIn);
+    CreateLC(stream, aOut);
+    stream.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// Internalize a cryptotokens object from a descriptor.
+// ---------------------------------------------------------------------------
+// 
+template <class T>
+void CreateL(const TDesC8& aIn, MCTToken& aToken, T& aOut)
+    {
+    RDesReadStream stream(aIn);
+    CreateL(stream, aToken, aOut);
+    stream.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// Internalize a cryptotoken object from a stream.  Creates an instance by
+// calling the class' NewL(RReadStream&, MCTToken&) method.
+// ---------------------------------------------------------------------------
+// 
+template <class T>
+inline void CreateL(RReadStream& aIn, MCTToken& aToken, T*& aOut)
+    {
+    aOut = T::NewL(aIn, aToken);
+    }
+
+
+// ---------------------------------------------------------------------------
+// Internalize an array of of key info objects from a stream. 
+// ---------------------------------------------------------------------------
+// 
+void CreateL(RReadStream& aIn, MCTToken& aToken, MDevTokenKeyInfoArray& aOut)
+    {
+    //No need to check this
+    //ASSERT(aOut.Count() == 0);
+    TInt count = aIn.ReadInt32L();
+    for (TInt i = 0 ; i < count ; ++i)
+        {
+        CCTKeyInfo* t;
+        CreateL(aIn, aToken, t);
+        CleanupReleasePushL(*t);
+        User::LeaveIfError(aOut.Append(t));
+        CleanupStack::Pop();
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// Internalize an RMPointerArray of cryptotoken objects from a stream.
+// ---------------------------------------------------------------------------
+//  
+template <class T>
+void CreateL(RReadStream& aIn, MCTToken& aToken, RMPointerArray<T>& aOut)
+    {
+    TInt count = aIn.ReadInt32L();
+    for (TInt i = 0 ; i < count ; ++i)
+        {
+        T* t;
+        CreateL(aIn, aToken, t);
+        CleanupReleasePushL(*t);
+        User::LeaveIfError(aOut.Append(t));
+        CleanupStack::Pop();
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// Internalize an RPointerArray from a stream.
+// ---------------------------------------------------------------------------
+//
+template <class T>
+void CreateL(RReadStream& aIn, RPointerArray<T>& aOut)
+    {
+    TInt count = aIn.ReadInt32L();
+    for (TInt i = 0 ; i < count ; ++i)
+        {
+        T* t;
+        CreateL(aIn, t);
+        CleanupStack::PushL(t);
+        User::LeaveIfError(aOut.Append(t));
+        CleanupStack::Pop();
+        }
+    }
+
+// Serialization for RIntegers 
+// This is exported as it is useful itself in the server
+
+
+// ---------------------------------------------------------------------------
+// Implement a CreateL function for internalizing HBufC8s.
+// ---------------------------------------------------------------------------
+// 
+inline void CreateL(RReadStream& aIn, HBufC8*& aOut)
+    {
+    aOut = HBufC8::NewL(aIn, KMaxIntegerSize);
+    }
+
+
+// ---------------------------------------------------------------------------
+// Implement a CreateL function for internalizing HBufCs.
+// ---------------------------------------------------------------------------
+// 
+inline void CreateL(RReadStream& aIn, HBufC*& aOut )
+    {
+    aOut = HBufC::NewL(aIn, KMaxSiteName );
+    }
+
+
+// ---------------------------------------------------------------------------
+// Implement a CreateLC function for internalizing RIntegers.
+// ---------------------------------------------------------------------------
+// 
+EXPORT_C void CreateLC(RReadStream& aIn, RInteger& aOut)
+    {
+    HBufC8* rBuf;
+    CreateL(aIn, rBuf);
+    CleanupStack::PushL(rBuf);
+    TPtr8 rPtr(rBuf->Des());
+    aOut = RInteger::NewL(rPtr);
+    CleanupStack::PopAndDestroy(rBuf);
+    CleanupStack::PushL(aOut);
+    }
+
+
+// ---------------------------------------------------------------------------
+// Decrypt and create a RInteger
+// ---------------------------------------------------------------------------
+// 
+EXPORT_C void DecryptAndCreateLC(RReadStream& aIn, RInteger& aOut, MKeyEncryptor* aEncryptor)
+    {
+    TRACE_PRINT( "DecryptAndCreateL   ->>>")
+    HBufC8* rBuf;
+    HBufC8* decryptedBuf = NULL;
+    CreateL(aIn, rBuf);
+    CleanupStack::PushL(rBuf);
+
+    TRACE_PRINT( "DecryptAndCreateL encrypted buf:" )
+    TRACE_PRINT_RAW(*rBuf);
+    if ( aEncryptor )
+        {
+        decryptedBuf = aEncryptor->DecryptL( *rBuf );
+
+        TRACE_PRINT( "DecryptAndCreateL decrypted buf:" )
+        TRACE_PRINT_RAW(*decryptedBuf);
+
+        TPtr8 decryptedPtr(decryptedBuf->Des());
+        aOut = RInteger::NewL(decryptedPtr);
+        }
+
+    TRACE_PRINT( "DecryptAndCreatL   <<<-")
+    CleanupStack::PopAndDestroy(rBuf);
+    CleanupStack::PushL(aOut);
+    }
+
+
+// ---------------------------------------------------------------------------
+// Externalize an RInteger.
+// ---------------------------------------------------------------------------
+//  
+EXPORT_C void ExternalizeL(const TInteger& aIn, RWriteStream& aOut )
+    {
+    HBufC8* sBuf = aIn.BufferLC();
+    aOut << *sBuf;  
+    CleanupStack::PopAndDestroy(sBuf);
+    }
+
+
+// ---------------------------------------------------------------------------
+// Encrypt and Store an RInteger 
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void EncryptAndStoreL(const TInteger& aIn, RWriteStream& aOut, MKeyEncryptor* aEncryptor )
+    {
+    TRACE_PRINT( "EncryptAndStoreL   ->>>" )
+    
+    HBufC8* sBuf = aIn.BufferLC();
+    HBufC8* encryptedBuf = NULL;
+
+    TRACE_PRINT( "EncryptAndStoreL plain buf ;")
+    TRACE_PRINT_RAW( *sBuf );
+    if ( aEncryptor )
+        {
+        encryptedBuf = aEncryptor->EncryptL( *sBuf ); 
+        
+        TRACE_PRINT( "EncryptAndStoreL encrypted buf ;" )
+        TRACE_PRINT_RAW( *encryptedBuf );
+        aOut << *encryptedBuf;
+        }
+
+    TRACE_PRINT( "EncryptAndStoreL   <<<-" )    
+    CleanupStack::PopAndDestroy(sBuf);
+    }
+
+
+// Externalization for signature objects 
+
+// ---------------------------------------------------------------------------
+// Implement Externalization selector for CDSASignature to use a function.
+// ---------------------------------------------------------------------------
+//
+EXTERNALIZE_FUNCTION(CDSASignature)
+
+
+// ---------------------------------------------------------------------------
+// Externalise a DSA signature object.
+// ---------------------------------------------------------------------------
+// 
+void ExternalizeL(const CDSASignature& aIn, RWriteStream& aOut)
+    {
+    aOut << aIn.R();
+    aOut << aIn.S();
+    }
+
+
+// ---------------------------------------------------------------------------
+// Implement Externalization selector for CRSASignature to use a function.
+// ---------------------------------------------------------------------------
+// 
+EXTERNALIZE_FUNCTION(CRSASignature)
+
+
+// ---------------------------------------------------------------------------
+// Externalize an RSA signature object.
+// ---------------------------------------------------------------------------
+//  
+void ExternalizeL(const CRSASignature& aIn, RWriteStream& aOut)
+    {
+    aOut << aIn.S();
+    }
+
+// Internalization for signature objects ///////////////////////////////////////
+
+// ---------------------------------------------------------------------------
+// Specialise CreateL for CRSASignature.
+// ---------------------------------------------------------------------------
+// 
+template <>
+void CreateL(RReadStream& aIn, CRSASignature*& aOut)
+    {
+    RInteger r;
+    CreateLC(aIn, r);
+    aOut = CRSASignature::NewL(r);
+    CleanupStack::Pop(); // r
+    }
+
+
+// ---------------------------------------------------------------------------
+// Specialise CreateL for CDSASignature.
+// ---------------------------------------------------------------------------
+// 
+template <>
+void CreateL(RReadStream& aIn, CDSASignature*& aOut)
+  {
+    RInteger r;
+    CreateLC(aIn, r);
+    RInteger s;
+    CreateLC(aIn, s);
+    aOut = CDSASignature::NewL(r, s);
+    CleanupStack::Pop(2); // s, r
+    }
+
+// Serialization for DH ojects 
+
+
+// ---------------------------------------------------------------------------
+// Implement Externalization selector for CDevTokenDHParams to use a function.
+// ---------------------------------------------------------------------------
+// 
+EXTERNALIZE_FUNCTION(CDevTokenDHParams)
+
+
+// ---------------------------------------------------------------------------
+// Externalise a CDevTokenDHParams object.
+// ---------------------------------------------------------------------------
+//  
+void ExternalizeL(const CDevTokenDHParams& aIn, RWriteStream& aOut)
+    {
+    aOut << aIn.N();
+    aOut << aIn.G();
+    }
+
+
+// ---------------------------------------------------------------------------
+// Specialise CreateL for CDevTokenDHParams.
+// ---------------------------------------------------------------------------
+// 
+template <>
+void CreateL(RReadStream& aIn, CDevTokenDHParams*& aOut)
+    {
+    RInteger n;
+    CreateLC(aIn, n);
+    RInteger g;
+    CreateLC(aIn, g);
+    aOut = CDevTokenDHParams::NewL(n, g);
+    CleanupStack::PopAndDestroy(2, &n); // g, n
+    }
+
+
+// ---------------------------------------------------------------------------
+// Implement Externalization selector for CDHPublicKey to use a function.
+// ---------------------------------------------------------------------------
+// 
+EXTERNALIZE_FUNCTION(CDHPublicKey)
+
+
+// ---------------------------------------------------------------------------
+// Externalise a CDHPublicKey object.
+// ---------------------------------------------------------------------------
+//  
+void ExternalizeL(const CDHPublicKey& aIn, RWriteStream& aOut)
+    {
+    aOut << aIn.N();
+    aOut << aIn.G();
+    aOut << aIn.X();
+    }
+
+
+// ---------------------------------------------------------------------------
+// Specialise CreateL for CDHPublicKey.
+// ---------------------------------------------------------------------------
+// 
+template <>
+void CreateL(RReadStream& aIn, CDHPublicKey*& aOut)
+    {
+    RInteger n;
+    CreateLC(aIn, n);
+    RInteger g;
+    CreateLC(aIn, g);
+    RInteger X;
+    CreateLC(aIn, X);
+    aOut = CDHPublicKey::NewL(n, g, X);
+    CleanupStack::Pop(3); // X, g, n
+    }
+
+// ======== MEMBER FUNCTIONS ========
+
+// Common 
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, RArray<TUid>& aOut)
+    {
+    ::ReadL(aIn, aOut);
+    }
+
+EXPORT_C TInt DevTokenDataMarshaller::Size(const CKeyInfoBase& aIn)
+    {
+    return ::Size(aIn);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::Write(const CKeyInfoBase& aIn, TDes8& aOut)
+    {
+    ::Write(aIn, aOut);
+    }
+
+EXPORT_C TInt DevTokenDataMarshaller::Size(const RArray<TUid>& aIn)
+    {
+    return ::Size(aIn);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::Write(const RArray<TUid>& aIn, TDes8& aOut)
+    {
+    ::Write(aIn, aOut);
+    }
+
+EXPORT_C TInt DevTokenDataMarshaller::Size(const MCertInfo& aIn)
+    {
+    return ::Size(aIn);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::Write(const MCertInfo& aIn, TDes8& aOut)
+    {
+    ::Write(aIn, aOut);
+    }
+
+// Client 
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, MCTToken& aToken, MDevTokenKeyInfoArray& aOut)
+    {
+    ::CreateL(aIn, aToken, aOut);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, MCTToken& aToken, CCTKeyInfo*& aOut)
+    {
+    ::CreateL(aIn, aToken, aOut);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, CDSASignature*& aOut)
+    {
+    ::CreateL(aIn, aOut);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, CRSASignature*& aOut)
+    {
+    ::CreateL(aIn, aOut);
+    }
+
+EXPORT_C TInt DevTokenDataMarshaller::Size(const CDevTokenDHParams& aIn)
+    {
+    return Size(aIn.N()) + Size(aIn.G());
+    }
+
+EXPORT_C void DevTokenDataMarshaller::WriteL(const CDevTokenDHParams& aIn, TDes8& aOut)
+    {
+    ::WriteL(aIn, aOut);
+    }
+
+EXPORT_C TInt DevTokenDataMarshaller::Size(const CDHPublicKey& aIn)
+    {
+    return Size(aIn.N()) + Size(aIn.G()) + Size(aIn.X());
+    }
+
+EXPORT_C void DevTokenDataMarshaller::WriteL(const CDHPublicKey& aIn, TDes8& aOut)
+    {
+    ::WriteL(aIn, aOut);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, RInteger& aInteger)
+    {
+    ::CreateLC(aIn, aInteger);
+    CleanupStack::Pop();
+    }
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, MCTToken& aToken, RMPointerArray<CCTCertInfo>& aOut)
+    {
+    ::CreateL(aIn, aToken, aOut);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, MCTToken& aToken, CCTCertInfo*& aOut)
+    {
+    ::CreateL(aIn, aToken, aOut);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, RArray<TCertificateAppInfo>& aOut)
+    {
+    ::ReadL(aIn, aOut);
+    }
+
+EXPORT_C TInt DevTokenDataMarshaller::Size(const CCertAttributeFilter& aIn)
+    {
+    return ::Size(aIn);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::WriteL(const CCertAttributeFilter& aIn, TDes8& aOut)
+    {
+    ::WriteL(aIn, aOut);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, RPointerArray<HBufC>& aOut)
+    {
+    ::CreateL(aIn, aOut);
+    }
+
+// Server 
+
+EXPORT_C TInt DevTokenDataMarshaller::Size(const RPointerArray<CDevTokenKeyInfo>& aIn)
+    {
+    return ::Size(aIn);
+    }
+
+EXPORT_C TInt DevTokenDataMarshaller::Size(const RPointerArray<HBufC>& aIn)
+    {
+    return ::Size(aIn);
+    } 
+
+EXPORT_C void DevTokenDataMarshaller::Write(const RPointerArray<HBufC>& aIn, TDes8& aOut )
+    {
+    return ::Write(aIn, aOut);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::Write(const RPointerArray<CDevTokenKeyInfo>& aIn, TDes8& aOut)
+    {
+    ::Write(aIn, aOut);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, CDevTokenKeyInfo*& aOut)
+    {
+    ::CreateL(aIn, aOut);
+    }
+
+
+// ---------------------------------------------------------------------------
+// Determine the size of an externalized big integer.  This assumes that the
+// size of the buffer returned by TInteger::BufferLC() is the same as the size
+// of the integer as returned by TInteger::ByteCount().  This is done to avoid
+// allocating the buffer just so we can tell how big it is.
+// ---------------------------------------------------------------------------
+// 
+EXPORT_C TInt DevTokenDataMarshaller::Size(const TInteger& aIn)
+    {
+    // This is an overestimate as the length is encoded with a TCardinality
+    return sizeof(TInt32) + aIn.ByteCount();
+    }
+
+EXPORT_C TInt DevTokenDataMarshaller::Size(const CDSASignature& aIn)
+    {
+    return Size(aIn.R()) + Size(aIn.S());
+    }
+
+EXPORT_C void DevTokenDataMarshaller::WriteL(const CDSASignature& aIn, TDes8& aOut)
+    {
+    ::WriteL(aIn, aOut);
+    }
+
+EXPORT_C TInt DevTokenDataMarshaller::Size(const CRSASignature& aIn)
+    {
+    return Size(aIn.S());
+    }
+
+EXPORT_C void DevTokenDataMarshaller::WriteL(const CRSASignature& aIn, TDes8& aOut)
+    {
+    ::WriteL(aIn, aOut);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, CDevTokenDHParams*& aOut)
+    {
+    ::CreateL(aIn, aOut);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, CDHPublicKey*& aOut)
+    {
+    ::CreateL(aIn, aOut);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::WriteL(const TInteger& aIn, TDes8& aOut)
+    {
+    ::WriteL(aIn, aOut);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, CDevTokenCertInfo*& aOut)
+    {
+    ::CreateL(aIn, aOut);
+    }
+
+EXPORT_C TInt DevTokenDataMarshaller::Size(const RPointerArray<CDevTokenCertInfo>& aIn)
+    {
+    return ::Size(aIn);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::Write(const RPointerArray<CDevTokenCertInfo>& aIn, TDes8& aOut)
+    {
+    ::Write(aIn, aOut);
+    }
+
+EXPORT_C TInt DevTokenDataMarshaller::Size(const RArray<TCertificateAppInfo>& aIn)
+    {
+    return ::Size(aIn);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::Write(const RArray<TCertificateAppInfo>& aIn, TDes8& aOut)
+    {
+    ::Write(aIn, aOut);
+    }
+
+EXPORT_C void DevTokenDataMarshaller::ReadL(const TDesC8& aIn, CCertAttributeFilter*& aOut)
+    {
+    ::CreateL(aIn, aOut);
+    }
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Shared/DevTokenKeyInfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,69 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenKeyInfo
+*
+*/
+
+
+
+#include "DevTokenDataTypes.h"
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CDevTokenKeyInfo* CDevTokenKeyInfo::NewL(RReadStream& aStream)
+// ---------------------------------------------------------------------------
+// 
+EXPORT_C CDevTokenKeyInfo* CDevTokenKeyInfo::NewL(RReadStream& aStream)
+    {
+    CDevTokenKeyInfo* me = new (ELeave) CDevTokenKeyInfo();
+    me->CleanupPushL();
+    me->ConstructL(aStream);
+    CleanupStack::Pop(me);
+    return me;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenKeyInfo::SetUsePolicy(const TSecurityPolicy& aPolicy)
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CDevTokenKeyInfo::SetUsePolicy(const TSecurityPolicy& aPolicy)
+    {
+    iUsePolicy = aPolicy;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenKeyInfo::SetManagementPolicy(const TSecurityPolicy& aPolicy)
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CDevTokenKeyInfo::SetManagementPolicy(const TSecurityPolicy& aPolicy)
+    {
+    iManagementPolicy = aPolicy;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CDevTokenKeyInfo::SetPKCS8AttributeSet(HBufC8* aPKCS8AttributeSet)
+// ---------------------------------------------------------------------------
+//
+EXPORT_C void CDevTokenKeyInfo::SetPKCS8AttributeSet(HBufC8* aPKCS8AttributeSet)
+    {
+    delete iPKCS8AttributeSet;
+    iPKCS8AttributeSet = aPKCS8AttributeSet;
+    }
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/Shared/DevTokenNullStream.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,77 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of DevTokenNullStream
+*
+*/
+
+
+
+#include "DevTokenNullStream.h"
+
+// ======== MEMBER FUNCTIONS ========
+
+// TNullBuf 
+
+// ---------------------------------------------------------------------------
+// TNullBuf::TNullBuf()
+// ---------------------------------------------------------------------------
+// 
+TNullBuf::TNullBuf() :
+    iBytesWritten(0)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// TNullBuf::DoWriteL(const TAny* /*aPtr*/,TInt aLength)
+// ---------------------------------------------------------------------------
+//
+void TNullBuf::DoWriteL(const TAny* /*aPtr*/,TInt aLength)
+    {
+    iBytesWritten += aLength;
+    }
+
+
+// ---------------------------------------------------------------------------
+// TNullBuf::BytesWritten()
+// ---------------------------------------------------------------------------
+//
+TUint TNullBuf::BytesWritten()
+    {
+    return iBytesWritten;
+    }
+
+
+// RNullWriteStream 
+
+// ---------------------------------------------------------------------------
+// RNullWriteStream::RNullWriteStream()
+// ---------------------------------------------------------------------------
+//
+RNullWriteStream::RNullWriteStream()
+    {
+    Attach(&iSink);
+    }
+
+
+// ---------------------------------------------------------------------------
+// RNullWriteStream::BytesWritten()
+// ---------------------------------------------------------------------------
+//
+TUint RNullWriteStream::BytesWritten()
+    {
+    return iSink.BytesWritten();
+    }
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/TruSitesStore/Client/TrustedSitesStore.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,315 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of TrustedSitesStore
+*
+*/
+
+
+
+#include <x509cert.h>
+#include "TrustedSitesStore.h"
+#include "DevandTruSrvCertStore.h"
+#include "DevTokenType.h"
+#include "DevToken.h"
+#include "DevTokenUtils.h"
+#include "DevTokenImplementationUID.hrh"
+
+const TInt KSHA1Length = 20;
+
+// Define the default size. If overflow, the function 
+// SendSyncRequestAndHandleOverflowL() will handle.
+const TInt KDefaultBufferSize = 256;
+
+// ======== MEMBER FUNCTIONS ========
+
+// -----------------------------------------------------------------------------
+// CTrustSitesStore::NewL()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CTrustSitesStore* CTrustSitesStore::NewL()
+    {
+    CTrustSitesStore* me = new (ELeave) CTrustSitesStore();
+    CleanupStack::PushL(me);
+    me->ConstructL();
+    CleanupStack::Pop(me);
+    return (me);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CTrustSitesStore::CTrustSitesStore()
+// -----------------------------------------------------------------------------
+//
+CTrustSitesStore::CTrustSitesStore() :
+  iRequestPtr(NULL, 0, 0) 
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CTrustSitesStore::~CTrustSitesStore()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CTrustSitesStore::~CTrustSitesStore()
+    {
+    FreeRequestBuffer();  
+    if ( iClientSession )
+        {
+        iClientSession->Close();
+        delete iClientSession;
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CTrustSitesStore::ConstructL()
+// -----------------------------------------------------------------------------
+//
+void CTrustSitesStore::ConstructL()
+    { 
+    iClientSession = RDevTokenClientSession::ClientSessionL();
+    User::LeaveIfError(iClientSession->Connect(ETruSitesStore));
+    }
+
+
+// -----------------------------------------------------------------------------
+// CTrustSitesStore::AddL()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CTrustSitesStore::AddL( const TDesC8& aCertificate, const TDesC& aTrustedSite )
+    {
+    if( !(aCertificate.Length() > KSHA1Length) || !( aTrustedSite.Length() > 0) )
+        {
+        User::LeaveIfError(KErrArgument);
+        }
+
+    CX509Certificate* cert = CX509Certificate::NewL(aCertificate);
+    TBuf8<KSHA1Length> certHash;
+    certHash.Copy(cert->Fingerprint());
+    delete cert;
+
+    TIpcArgs args(&certHash, &aTrustedSite, NULL, NULL);
+    TInt r = iClientSession->SendRequest(EAddTrustSite, args);  
+    return r; 
+    }
+
+
+// -----------------------------------------------------------------------------
+// CTrustSitesStore::AddForgivenSiteL()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CTrustSitesStore::AddForgivenSiteL( const TDesC& aSite, const TBool& aIsOutOfDateAllowed )
+    {
+    if( !( aSite.Length() > 0) )
+        {
+        User::LeaveIfError(KErrArgument);
+        }
+
+    TIpcArgs args( &aSite, aIsOutOfDateAllowed );
+    TInt r = iClientSession->SendRequest(EAddForgivenSite, args);  
+    return r; 	
+    }
+
+
+// -----------------------------------------------------------------------------
+// CTrustSitesStore::RemoveForgivenSiteL()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CTrustSitesStore::RemoveForgivenSiteL( const TDesC& aSite )
+	{
+	TIpcArgs args( &aSite );
+	TInt r = iClientSession->SendRequest(ERemoveForgivenSite, args);  
+	return r;
+	}
+
+
+// -----------------------------------------------------------------------------
+// CTrustSitesStore::IsOutOfDateAllowedL()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TBool CTrustSitesStore::IsOutOfDateAllowedL( const TDesC8& aCertificate, const TDesC& aTrustedSite )
+    {
+    if( !(aCertificate.Length() > 0) || !( aTrustedSite.Length() > 0) )
+        {
+        User::LeaveIfError(KErrArgument);
+        }
+
+    CX509Certificate* cert = CX509Certificate::NewL(aCertificate);
+    TBuf8<KSHA1Length> certHash;
+    certHash.Copy(cert->Fingerprint());
+    delete cert;
+    cert = NULL;
+
+    TIpcArgs args(&certHash, &aTrustedSite );
+    TInt r = iClientSession->SendRequest(EIsOutOfDateAllowed, args); 
+    if( r > 0 )
+        {
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;  
+        } 	
+   }
+
+// -----------------------------------------------------------------------------
+// CTrustSitesStore::IsTrustedSiteL()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TBool CTrustSitesStore::IsTrustedSiteL( const TDesC8& aCertificate, const TDesC& aTrustedSite )
+    {
+    if( !(aCertificate.Length() > 0) || !( aTrustedSite.Length() > 0) )
+        {
+        User::LeaveIfError(KErrArgument);
+        }
+
+    CX509Certificate* cert = CX509Certificate::NewL(aCertificate);
+    TBuf8<KSHA1Length> certHash;
+    certHash.Copy(cert->Fingerprint());
+    delete cert;
+    cert = NULL;
+
+    TIpcArgs args(&certHash, &aTrustedSite, &aCertificate );
+    TInt r = iClientSession->SendRequest(EIsTrustedSite, args); 
+    if( r > 0 )
+        {
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;  
+        } 
+    }
+
+
+// -----------------------------------------------------------------------------
+// CTrustSitesStore::GetTrustedSitesL()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CTrustSitesStore::GetTrustedSitesL( const TDesC8& aCertificate, RPointerArray<HBufC>& aListOfSites )       
+    {
+    if( !(aCertificate.Length() > 0 ) ) 
+        {
+        User::LeaveIfError(KErrArgument);
+        }
+
+    CX509Certificate* cert = CX509Certificate::NewL(aCertificate);
+    TBuf8<KSHA1Length> certHash;
+    certHash.Copy(cert->Fingerprint()); 
+    delete cert;
+    cert = NULL;
+
+    TIpcArgs args( &certHash, &iRequestPtr, NULL, NULL );
+
+    TRAPD(err, SendSyncRequestAndHandleOverflowL(KDefaultBufferSize, args));
+    if(err!=KErrNone)
+        {
+        return err;
+        }
+
+    TRAP(err, DevTokenDataMarshaller::ReadL( iRequestPtr, aListOfSites ));
+    if( err!= KErrNone )
+        {
+        return err;
+        }
+    return KErrNone;    
+    }
+
+
+// -----------------------------------------------------------------------------
+// CTrustSitesStore::RemoveL()
+// -----------------------------------------------------------------------------
+//
+/*EXPORT_C TInt CTrustSitesStore::RemoveL( const TDesC8& aCertificate )
+    {
+    if( !(aCertificate.Length() > 0 ) )
+        {
+        User::LeaveIfError(KErrArgument);
+        }
+
+    CX509Certificate* cert = CX509Certificate::NewL(aCertificate);
+    TBuf8<KSHA1Length> certHash;
+    certHash.Copy(cert->Fingerprint()); 
+
+    TIpcArgs args( &certHash, NULL, NULL, NULL );
+
+    TInt r = iClientSession->SendRequest(ERemove, args);  
+    return r; 
+    }*/
+
+
+// -----------------------------------------------------------------------------
+// CTrustSitesStore::FreeRequestBuffer()
+// -----------------------------------------------------------------------------
+//
+void CTrustSitesStore::FreeRequestBuffer() 
+    {
+    delete iRequestDataBuf; 
+    iRequestDataBuf = NULL;
+    iRequestPtr.Set(NULL, 0, 0);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CTrustSitesStore::AllocRequestBuffer()
+// -----------------------------------------------------------------------------
+//
+TInt CTrustSitesStore::AllocRequestBuffer(TInt aReqdSize) 
+    {
+    ASSERT(aReqdSize > 0);
+    TInt result = KErrNoMemory;
+
+    FreeRequestBuffer();
+    iRequestDataBuf = HBufC8::NewMax(aReqdSize);
+    if (iRequestDataBuf)
+        {
+        iRequestPtr.Set(iRequestDataBuf->Des());
+        iRequestPtr.FillZ();
+        result = KErrNone;
+        }
+
+    return result;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CTrustSitesStore::SendSyncRequestAndHandleOverflowL()
+// -----------------------------------------------------------------------------
+//
+void CTrustSitesStore::SendSyncRequestAndHandleOverflowL(TInt aInitialBufSize,
+                          const TIpcArgs& aArgs) 
+    {
+
+    TDevTokenMessages message;
+    message = EGetTrustedSites; 
+
+    User::LeaveIfError(AllocRequestBuffer(aInitialBufSize));
+
+    TInt err = iClientSession->SendRequest(message, aArgs);
+    if (err == KErrOverflow)
+        {
+        TInt sizeReqd = 0;
+        TPckg<TInt> theSize(sizeReqd);
+        theSize.Copy(iRequestPtr);
+        User::LeaveIfError(AllocRequestBuffer(sizeReqd));     
+        err = iClientSession->SendRequest(message, aArgs);
+        }
+
+    User::LeaveIfError(err);
+    }
+ 
+//EOF
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/TruSitesStore/Server/TrustedSitesConduit.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,268 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of TrustedSitesStoreConduit
+*
+*/
+
+
+
+#include "TrustedSitesConduit.h"
+#include "TrustedSitesServer.h"
+#include "DevTokenMarshaller.h"
+#include "DevTokenUtil.h"
+#include "DevTokenDataTypes.h"
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesConduit::NewL()
+// ---------------------------------------------------------------------------
+//
+CTrustedSitesConduit* CTrustedSitesConduit::NewL(CTrustedSitesServer& aServer)
+    {
+    return new (ELeave) CTrustedSitesConduit(aServer);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesConduit::CTrustedSitesConduit()
+// ---------------------------------------------------------------------------
+//
+CTrustedSitesConduit::CTrustedSitesConduit(CTrustedSitesServer& aServer) :
+  iServer(aServer)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesConduit::~CTrustedSitesConduit()
+// ---------------------------------------------------------------------------
+//
+CTrustedSitesConduit::~CTrustedSitesConduit()
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesConduit::AllocResponseBufferLC()
+// ---------------------------------------------------------------------------
+//
+HBufC8* CTrustedSitesConduit::AllocResponseBufferLC(TInt aSize, const RMessage2& aMessage)
+    {
+    TInt writeBufLen = aMessage.GetDesLengthL(1);
+
+    if (aSize > writeBufLen)
+        {
+        TPckg<TInt> theRequiredLength(aSize);
+        aMessage.WriteL(1, theRequiredLength);
+        User::Leave(KErrOverflow);
+        }
+
+    HBufC8* result = HBufC8::NewMaxLC(aSize);
+    TPtr8 ptr = result->Des();
+    ptr.FillZ();
+
+    return result;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesConduit::ServiceTrustedSitesRequestL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesConduit::ServiceTrustedSitesRequestL(const RMessage2& aMessage)
+    {
+    TDevTokenMessages request = (TDevTokenMessages) aMessage.Function();
+    TInt result = KErrNone;
+
+    switch (request)
+        {
+        case EAddTrustSite:
+            AddL(aMessage);   
+            break;
+            
+        case EAddForgivenSite:
+            AddForgivenSiteL( aMessage );
+            break;
+        
+        case ERemoveForgivenSite:
+            RemoveForgivenSiteL( aMessage );
+            break;
+            
+        case EIsTrustedSite:
+            result = IsTrustedSiteL( aMessage );
+            break;
+        case EGetTrustedSites:
+            GetTrustedSitesL( aMessage );
+            break;
+            
+        case EIsOutOfDateAllowed:
+            result = IsOutOfDateAllowedL( aMessage ); 
+            break;
+        default:
+        // Client made an illegal request
+        PanicClient(aMessage, EPanicInvalidRequest);
+        return;
+        }
+
+    aMessage.Complete(result);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesConduit::AddL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesConduit::AddL( const RMessage2& aMessage )
+    {
+    HBufC8* certHash = HBufC8::NewLC(20);
+    TPtr8 ptrCertHash = certHash->Des();
+    aMessage.ReadL(0,ptrCertHash);  
+
+    TInt bufLen = aMessage.GetDesLengthL(1);
+    HBufC* siteName = HBufC::NewLC(bufLen);
+    TPtr ptrSiteName = siteName->Des();
+    aMessage.ReadL(1,ptrSiteName);
+
+    iServer.AddL( *certHash, *siteName, aMessage );    
+
+    CleanupStack::PopAndDestroy(2);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesConduit::AddForgivenSiteL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesConduit::AddForgivenSiteL( const RMessage2& aMessage )
+    {
+    TInt bufLen = aMessage.GetDesLengthL(0);
+    HBufC* forgivenSite = HBufC::NewLC(bufLen);
+    TPtr ptrSite = forgivenSite->Des();
+    aMessage.ReadL(0,ptrSite);
+    
+    TInt outofdateallowed = aMessage.Int1();
+    iServer.AddForgivenSiteL( *forgivenSite, (TBool)outofdateallowed, aMessage );    
+
+    CleanupStack::PopAndDestroy(1);
+    }
+    
+// ---------------------------------------------------------------------------
+// CTrustedSitesConduit::RemoveForgivenSiteL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesConduit::RemoveForgivenSiteL( const RMessage2& aMessage )
+    {
+    TInt bufLen = aMessage.GetDesLengthL(0);
+    
+    if ( bufLen == 0 )
+    	{
+    	iServer.RemoveAllForgivenSitesL( aMessage ); 
+    	}
+    else
+    	{
+        HBufC* forgivenSite = HBufC::NewLC( bufLen );
+        TPtr ptrSite = forgivenSite->Des();
+        aMessage.ReadL(0,ptrSite);
+        
+        iServer.RemoveThisForgivenSiteL( *forgivenSite, aMessage );    
+
+        CleanupStack::PopAndDestroy(1);
+    	}
+    }
+
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesConduit::IsTrustedSiteL()
+// ---------------------------------------------------------------------------
+//
+TInt CTrustedSitesConduit::IsTrustedSiteL( const RMessage2& aMessage ) 
+    {
+    HBufC8* certHash = HBufC8::NewLC(20);
+    TPtr8 ptrCertHash = certHash->Des();
+    aMessage.ReadL(0,ptrCertHash);  
+
+    TInt bufLen = aMessage.GetDesLengthL(1);
+    HBufC* siteName = HBufC::NewLC(bufLen);
+    TPtr ptrSiteName = siteName->Des();
+    aMessage.ReadL(1,ptrSiteName);
+    
+    //get the certifcate
+    bufLen = aMessage.GetDesLength(2);
+    HBufC8* cert = HBufC8::NewLC( bufLen );
+    TPtr8 ptrCert = cert->Des();
+    aMessage.ReadL(2, ptrCert );
+    
+    TBool result = iServer.IsTrustedSiteL( *certHash, *siteName, *cert, aMessage );
+
+    CleanupStack::PopAndDestroy(3); //certHash, siteName, cert
+
+    return result? 1 : 0; 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesConduit::IsOutOfDateAllowedL()
+// ---------------------------------------------------------------------------
+//
+TInt CTrustedSitesConduit::IsOutOfDateAllowedL( const RMessage2& aMessage )
+    {
+    HBufC8* certHash = HBufC8::NewLC(20);
+    TPtr8 ptrCertHash = certHash->Des();
+    aMessage.ReadL(0,ptrCertHash);  
+
+    TInt bufLen = aMessage.GetDesLengthL(1);
+    HBufC* siteName = HBufC::NewLC(bufLen);
+    TPtr ptrSiteName = siteName->Des();
+    aMessage.ReadL(1,ptrSiteName);
+
+    
+    TBool result = iServer.IsOutOfDateAllowedL( *certHash, *siteName, aMessage );
+
+    CleanupStack::PopAndDestroy(2); //certHash, siteName
+
+    return result? 1 : 0; 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesConduit::GetTrustedSitesL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesConduit::GetTrustedSitesL( const RMessage2& aMessage )
+    {
+    HBufC8* certHash = HBufC8::NewLC(20);
+    TPtr8 ptrCertHash = certHash->Des();
+    aMessage.ReadL(0,ptrCertHash);
+
+    RPointerArray<HBufC> sites;
+
+    iServer.GetTrustedSitesL(*certHash, sites, aMessage );
+
+    HBufC8* clientBuffer = AllocResponseBufferLC(DevTokenDataMarshaller::Size(sites), aMessage);  
+    TPtr8 theData(clientBuffer->Des());
+
+    DevTokenDataMarshaller::Write(sites, theData);
+
+    aMessage.WriteL(1, theData);
+
+    sites.ResetAndDestroy();
+
+    CleanupStack::PopAndDestroy(2); //certhash, clientbuffer
+    }
+  
+
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/TruSitesStore/Server/TrustedSitesServer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1436 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of TrustedSitesStoreServer
+*
+*/
+
+
+
+#include "TrustedSitesServer.h"
+#include "TrustedSitesConduit.h"
+#include "TrustedSitesSession.h"
+#include "DevTokenCliServ.h"
+#include "DevTokenUtil.h"
+#include "DevTokenDataTypes.h"
+#include "DevTokenServer.h"
+#include "DevandTruSrvCertStoreServer.h"
+#include <x509cert.h>
+#include <ccertattributefilter.h>
+#include <e32cmn.h>
+#include <badesca.h>
+
+_LIT(KTrustedSitesStoreFilename,"TrustedSitesStore.dat");
+// Maximum length of SQL query clause
+const TInt KMaxSQLLength = 256;
+
+// API policing
+_LIT_SECURITY_POLICY_C1(KReadSecurityPolicy, ECapabilityReadUserData);
+_LIT_SECURITY_POLICY_C1(KWriteSecurityPolicy, ECapabilityWriteDeviceData);
+
+// ======== MEMBER FUNCTIONS ========
+
+//CTrustedSitesServer
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::NewL()
+// ---------------------------------------------------------------------------
+//
+CTrustedSitesServer* CTrustedSitesServer::NewL( CDevTokenServer* aServer )
+    {
+    CTrustedSitesServer* self = new (ELeave) CTrustedSitesServer( aServer );
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::CTrustedSitesServer()
+// ---------------------------------------------------------------------------
+//
+CTrustedSitesServer::CTrustedSitesServer( CDevTokenServer* aServer ) :
+    iServer ( aServer )
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::ConstructL()
+    {
+    iConduit = CTrustedSitesConduit::NewL(*this);
+
+    User::LeaveIfError( iFs.Connect() );
+
+    TBuf<KMaxFilenameLength> filename;
+
+    FileUtils::MakePrivateFilenameL(iFs, KTrustedSitesStoreFilename, filename);
+
+    TInt err = iDatabase.Open( iFs, filename );
+
+    if ( err != KErrNone ) 
+        {
+        CreateDBL(); // Create DB
+        User::LeaveIfError( iDatabase.Open( iFs, filename ) );
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::CreateDBL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::CreateDBL()
+    {
+
+    RFs fsSession;
+    User::LeaveIfError( fsSession.Connect() ); // Connect to file server
+
+    CleanupClosePushL( fsSession );
+
+    RDbNamedDatabase database;
+
+    TBuf<KMaxFilenameLength> filename;
+
+    FileUtils::MakePrivateFilenameL(fsSession, KTrustedSitesStoreFilename, filename);
+
+    FileUtils::EnsurePathL(fsSession, filename);
+    CleanupClosePushL( database );
+
+    User::LeaveIfError( database.Create( fsSession, filename ) );
+
+    // Create tables
+
+    // Trusted sites table
+    _LIT( KSQLCreateTable1, "CREATE TABLE Certificates (\
+    CertID COUNTER NOT NULL,\
+    CertHash CHAR(20) NOT NULL)");
+
+    _LIT( KSQLCreateTable2, "CREATE TABLE TrustedSites (\
+    CertID INTEGER,\
+    SiteName VARCHAR(100) NOT NULL,\
+    Forgiven INTEGER NOT NULL,\
+    OutOfDate INTEGER NOT NULL,\
+    ClientUID INTEGER NOT NULL )");                                      
+    
+    User::LeaveIfError( database.Execute( KSQLCreateTable1 ) );
+    User::LeaveIfError( database.Execute( KSQLCreateTable2 ) );
+
+    CleanupStack::PopAndDestroy( 2 ); // database, fsSession
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::~CTrustedSitesServer()
+// ---------------------------------------------------------------------------
+//
+CTrustedSitesServer::~CTrustedSitesServer()
+    {
+    delete iConduit;
+    iDatabase.Close();  // Close database
+    iFs.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::CreateSessionL()
+// ---------------------------------------------------------------------------
+//
+CTrustedSitesSession* CTrustedSitesServer::CreateSessionL()
+    {
+    return CTrustedSitesSession::NewL(*iConduit);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::AddL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::AddL(const TDesC8& aCertHash, const TDesC& aSiteName, const RMessage2& aMessage )
+    {
+    // API policing
+    if (!KWriteSecurityPolicy.CheckPolicy(aMessage))
+        {
+        User::Leave(KErrPermissionDenied);
+        }
+
+    TInt certID;
+    GetCertIDL( aCertHash, certID ); // Get certificate ID
+
+    if ( certID == KErrNotFound ) // Not found
+        {
+        iDatabase.Begin(); // Begin transaction
+
+        TRAPD( err, DoAddCertL( aCertHash ));
+
+        if ( err ) // Some error occurred
+            {
+            iDatabase.Rollback(); // Rollback changes
+            User::Leave ( err );
+            }
+        else
+            {
+            iDatabase.Commit(); // Commit changes
+            }
+
+        GetCertIDL( aCertHash, certID );
+
+        if( certID == KErrNotFound )
+            {
+            User::Leave( KErrNotFound );
+            }
+
+        iDatabase.Begin();
+
+        TRAP( err, DoAddSiteNameL( certID, aSiteName ));
+
+        if ( err ) // Some error occurred
+            {
+            iDatabase.Rollback(); // Rollback changes
+            User::Leave ( err );
+            }
+        else
+            {
+            iDatabase.Commit(); // Commit changes
+            }    
+        }
+    else
+        {
+        if(IsSiteAlreadyExistL( certID, aSiteName ))
+            {
+            return; 
+            }
+        else
+            {
+            iDatabase.Begin(); // Begin transaction
+
+            TRAPD( err, DoAddSiteNameL( certID, aSiteName ));
+
+            if ( err ) // Some error occurred
+                {
+                iDatabase.Rollback(); // Rollback changes
+                User::Leave ( err );
+                }
+            else
+                {
+                iDatabase.Commit(); // Commit changes
+                }
+            return;   
+            } 
+        }  
+
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::AddL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::AddL(const TDesC8& aCertHash, const TDesC& aSiteName )
+    {
+    TInt certID;
+    GetCertIDL( aCertHash, certID ); // Get certificate ID
+
+    if ( certID == KErrNotFound ) // Not found
+        {
+        iDatabase.Begin(); // Begin transaction
+
+        TRAPD( err, DoAddCertL( aCertHash ));
+
+        if ( err ) // Some error occurred
+            {
+            iDatabase.Rollback(); // Rollback changes
+            User::Leave ( err );
+            }
+        else
+            {
+            iDatabase.Commit(); // Commit changes
+            }
+
+        GetCertIDL( aCertHash, certID );
+
+        if( certID == KErrNotFound )
+            {
+            User::Leave( KErrNotFound );
+            }
+
+        iDatabase.Begin();
+
+        TRAP( err, DoAddSiteNameL( certID, aSiteName ));
+
+        if ( err ) // Some error occurred
+            {
+            iDatabase.Rollback(); // Rollback changes
+            User::Leave ( err );
+            }
+        else
+            {
+            iDatabase.Commit(); // Commit changes
+            }    
+        }
+    else
+        {
+        if(IsSiteAlreadyExistL( certID, aSiteName ))
+            {
+            return; 
+            }
+        else
+            {
+            iDatabase.Begin(); // Begin transaction
+
+            TRAPD( err, DoAddSiteNameL( certID, aSiteName ));
+
+            if ( err ) // Some error occurred
+                {
+                iDatabase.Rollback(); // Rollback changes
+                User::Leave ( err );
+                }
+            else
+                {
+                iDatabase.Commit(); // Commit changes
+                }
+            return;   
+            } 
+        }  
+    }
+    
+    
+// ---------------------------------------------------------------------------    
+// CTrustedSitesServer::GetCertIDL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::GetCertIDL( const TDesC8& aCertHash, TInt& aCertID )
+    {   
+    _LIT( KSQLQuery, "SELECT CertID,\
+    CertHash\
+    FROM Certificates" );
+
+    RDbView view;
+
+    User::LeaveIfError( view.Prepare( iDatabase, TDbQuery( KSQLQuery ) ) );
+
+    CleanupClosePushL( view );
+
+    // Get data
+    TInt i = 0;
+
+    while ( i == 0 && view.NextL() ) // Should find only one ID
+        {
+        view.GetL();
+
+        if ( !view.ColDes8( 2 ).Compare( aCertHash ) )
+            {
+            aCertID = view.ColUint32( 1 );
+            i++;
+            }
+        }
+
+    if ( i == 0 ) // Not found any matching rows
+        {
+        aCertID = KErrNotFound;
+        }
+
+    CleanupStack::PopAndDestroy( 1 ); // view
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::DoAddSiteNameL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::DoAddSiteNameL(const TInt& aCertID, const TDesC& aSiteName )   
+    {
+    //insert the normal trusted site record,not for forgiven site
+    TBuf<KMaxSQLLength> SQL;
+
+    _LIT( KSQLInsert1,
+    "INSERT INTO TrustedSites (CertID,SiteName,Forgiven,OutOfDate,ClientUID) VALUES (" );
+
+    SQL.Copy(KSQLInsert1);
+    SQL.AppendNum(aCertID);
+    SQL.Append(_L(",'"));
+    
+    SQL.Append( aSiteName );
+    SQL.Append(_L("',"));
+    //not forgiven
+    SQL.AppendNum(0);
+    SQL.Append(_L(","));
+    //not allowed out of date
+    SQL.AppendNum(0); 
+    //set the UID to -1 since in the normal case we don't need the information
+    SQL.Append(_L(","));
+    SQL.AppendNum(-1);
+    SQL.Append(_L(")"));
+    
+    User::LeaveIfError( iDatabase.Execute( SQL ) );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::DoAddCertL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::DoAddCertL( const TDesC8& aCertHash )
+    {   
+    RDbView view;
+
+    _LIT( KSQLInsertCert, "SELECT CertHash\
+    FROM Certificates" );
+
+    User::LeaveIfError( view.Prepare( iDatabase, TDbQuery( KSQLInsertCert ),
+    TDbWindow::EUnlimited, RDbView::EInsertOnly ) );
+
+    CleanupClosePushL( view );
+
+    view.InsertL();
+    view.SetColL( 1, aCertHash );
+    view.PutL();
+
+    CleanupStack::PopAndDestroy( 1 ); 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::IsSiteAlreadyExistL()
+// ---------------------------------------------------------------------------
+//
+TBool CTrustedSitesServer::IsSiteAlreadyExistL(const TInt& aCertID, const TDesC& aSiteName)
+    {
+    RDbView view;   
+    _LIT( KSQLQuery, 
+    "SELECT SiteName FROM TrustedSites WHERE certID = " );
+
+    TBuf<KMaxSQLLength> SQLStatement;
+    SQLStatement.Copy( KSQLQuery );
+
+    SQLStatement.AppendNum( aCertID );
+
+    TPtrC sqlStat( SQLStatement.PtrZ() );
+
+    TInt err = view.Prepare( iDatabase, TDbQuery( sqlStat ), TDbWindow::EUnlimited );
+
+    if ( err != KErrNone )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    err = view.EvaluateAll();
+
+    CleanupClosePushL( view );
+
+    TBool alreadyExist = EFalse;
+    // Get data
+    while ( view.NextL() ) // Should find only one certificate
+        {
+        TRAPD(error, view.GetL());
+        error = error;
+        if(!aSiteName.Compare(view.ColDes( 1 )))
+            {
+            alreadyExist = ETrue;
+            break;
+            }
+        }
+    CleanupStack::PopAndDestroy( 1 ); 
+    return alreadyExist;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::IsOutOfDateAllowedForTheSiteL()
+// ---------------------------------------------------------------------------
+//
+TBool CTrustedSitesServer::IsOutOfDateAllowedForTheSiteL( const TInt& aCertID, const TDesC& aSiteName )
+    {
+    RDbView view;   
+    _LIT( KSQLQuery, 
+    "SELECT SiteName,OutOfDate FROM TrustedSites WHERE certID = " );
+
+    TBuf<KMaxSQLLength> SQLStatement;
+    SQLStatement.Copy( KSQLQuery );
+
+    SQLStatement.AppendNum( aCertID );
+
+    TPtrC sqlStat( SQLStatement.PtrZ() );
+
+    TInt err = view.Prepare( iDatabase, TDbQuery( sqlStat ), TDbWindow::EUnlimited );
+
+    if ( err != KErrNone )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    err = view.EvaluateAll();
+
+    CleanupClosePushL( view );
+
+    TBool outofdate = EFalse;
+    // Get data
+    while ( view.NextL() ) // Should find only one certificate
+        {
+        TRAPD(error, view.GetL());
+        error = error;
+        
+        if ( (!aSiteName.Compare( view.ColDes( 1 ) ) ) && ( view.ColInt( 2 ) == 1 ) )
+            {
+            outofdate = ETrue;
+            break;
+            }
+        }
+        
+    CleanupStack::PopAndDestroy( 1 ); //view
+    return outofdate; 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::IsTrustedSiteL()
+// ---------------------------------------------------------------------------
+//
+TBool CTrustedSitesServer::IsTrustedSiteL( const TDesC8& aCertHash, const TDesC& aSiteName, const TDesC8& aCert, const RMessage2& aMessage )
+    {
+    // API policing
+    if (!KReadSecurityPolicy.CheckPolicy(aMessage))
+        {
+        User::Leave(KErrPermissionDenied);
+        }
+    
+    //is it a forgiven site 
+    if ( IsForgivenSiteAlreadyL( aSiteName ) )
+        {
+        // Insert the certificate into database
+        DoOverWriteCertL( aSiteName, aCertHash );
+        
+        //check if the certificate is already existing
+        CCertAttributeFilter* filter = CCertAttributeFilter::NewL();
+        CleanupStack::PushL(filter);
+        filter->SetOwnerType(EPeerCertificate);
+        RPointerArray<CDevTokenCertInfo> certs;
+        RMessage2 message;             
+        iServer->CertStoreServerL().ListL( *filter,certs,message, ETrue  );            
+      
+        CleanupStack::PopAndDestroy(); //filter
+      
+        TBool exist = EFalse;
+        if ( certs.Count() )
+            {
+            for (TInt i= 0; i<certs.Count();i++)
+                {
+                HBufC8* certData = iServer->CertStoreServerL().RetrieveLC( certs[i]->CertificateId(),message,ETrue );
+                TPtr8 certPtr = certData->Des();
+                
+                //certificate from trusted server certstore
+                CX509Certificate* cert = CX509Certificate::NewLC( certPtr );
+                //certificate from client
+                CX509Certificate* cert2 = CX509Certificate::NewLC( aCert );
+              
+                if ( cert->Fingerprint() == cert2->Fingerprint() )
+                    {
+                    exist = ETrue;
+                    CleanupStack::PopAndDestroy(3); //cert, cert2, certData
+                    break;
+                    }
+              
+                CleanupStack::PopAndDestroy(3); //cert, cert2, certData
+                }
+            }
+          
+        if ( exist )
+             {
+             //server certificate has saved already, no need to save again
+             return ETrue;  
+             }
+
+        TDevTokenAddCertDataStruct data;
+        data.iLabel.Zero();
+        data.iSubjectKeyId.Zero();
+        
+        CX509Certificate* cert = CX509Certificate::NewL(aCert);
+        data.iSubjectKeyId.Copy( cert->KeyIdentifierL() );
+        delete cert;
+        
+        data.iIssuerKeyId.Zero();   
+        data.iLabel.Copy(aSiteName);   
+        data.iFormat = EX509Certificate;
+        data.iCertificateOwnerType = EPeerCertificate;
+        
+        iServer->CertStoreServerL().AddL( data, aCert, aMessage, ETrue ) ;
+         
+        return ETrue;
+        }
+    
+    //It isn't a forgiven site, query in the normal way to check whether it is trusted by the user 
+    TInt certID;
+    GetCertIDL( aCertHash, certID ); // Get certificate ID
+
+    if ( certID == KErrNotFound ) // Not found
+        {
+        return EFalse;
+        }
+    else
+        {
+        if(IsSiteAlreadyExistL( certID, aSiteName ))
+            {
+            return ETrue; 
+            }
+        else
+            {
+            return EFalse;    
+            } 
+        }  
+    }
+
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::IsOutOfDateAllowedL()
+// ---------------------------------------------------------------------------
+//
+TBool CTrustedSitesServer::IsOutOfDateAllowedL( const TDesC8& aCertHash, const TDesC& aSiteName, const RMessage2& aMessage )
+    {
+    // API policing
+    if (!KReadSecurityPolicy.CheckPolicy(aMessage))
+        {
+        User::Leave(KErrPermissionDenied);
+        }
+
+    TInt certID;
+    GetCertIDL( aCertHash, certID ); // Get certificate ID
+
+    if ( certID == KErrNotFound ) // Not found
+        {
+        return EFalse;
+        }
+    else
+        {
+        if(IsOutOfDateAllowedForTheSiteL( certID, aSiteName ))
+            {
+            return ETrue; 
+            }
+        else
+            {
+            return EFalse;    
+            } 
+        }  
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::GetTrustedSitesL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::GetTrustedSitesL( const TDesC8& aCertHash, 
+                                           RPointerArray<HBufC>& aListOfSites,
+                                           const RMessage2& aMessage)
+    {
+    // API policing
+    if (!KReadSecurityPolicy.CheckPolicy(aMessage))
+        {
+        User::Leave(KErrPermissionDenied);
+        }
+
+    TInt certID;
+    GetCertIDL( aCertHash, certID );
+
+    if( certID == KErrNotFound )
+        {
+        User::Leave( KErrNotFound );
+        }
+    DoGetTrustedSitesL( certID, aListOfSites );     
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::DoGetTrustedSitesL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::DoGetTrustedSitesL( const TInt& aCertID, 
+                                              RPointerArray<HBufC>& aListOfSites)
+    {
+    RDbView view;   
+    _LIT( KSQLQuery, 
+    "SELECT SiteName FROM TrustedSites WHERE certID = " );
+
+    TBuf<KMaxSQLLength> SQLStatement;
+    SQLStatement.Copy( KSQLQuery );
+
+    SQLStatement.AppendNum( aCertID );
+
+    TPtrC sqlStat( SQLStatement.PtrZ() );
+
+    TInt err = view.Prepare( iDatabase, TDbQuery( sqlStat ), TDbWindow::EUnlimited );
+
+    if ( err != KErrNone )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    err = view.EvaluateAll();
+
+    CleanupClosePushL( view );
+
+    // Get data
+    while ( view.NextL() ) // Should find only one certificate
+        {
+        TRAPD(error, view.GetL());
+        error = error;
+        HBufC* temp = HBufC::NewL(KMaxSiteName);
+        TPtr ptrTemp = temp->Des();
+        ptrTemp.Copy(view.ColDes( 1 ));      
+        aListOfSites.Append(temp);
+        }
+    CleanupStack::PopAndDestroy( 1 ); 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::RemoveL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::RemoveL( const TDesC8& aCertHash )
+    {  
+    TInt certID;
+    GetCertIDL( aCertHash, certID );
+
+    if( certID == KErrNotFound )
+        {
+        User::Leave( KErrNotFound );
+        }
+    CCertAttributeFilter* filter = CCertAttributeFilter::NewL();
+    CleanupStack::PushL(filter);
+    filter->SetOwnerType(EPeerCertificate);
+    RPointerArray<CDevTokenCertInfo> certs;
+    RMessage2 message;             
+    iServer->CertStoreServerL().ListL(*filter,certs,message, ETrue  );            
+    
+    CleanupStack::PopAndDestroy(); //filter
+    
+    TBool stillexist = EFalse;
+    if ( certs.Count() )
+        {
+        for (TInt i= 0; i<certs.Count();i++)
+            {
+            HBufC8* certData = iServer->CertStoreServerL().RetrieveLC( certs[i]->CertificateId(),message,ETrue );
+
+            TPtr8 certPtr = certData->Des();
+        	
+            CX509Certificate* cert = CX509Certificate::NewLC( certPtr );
+            
+            if ( cert->Fingerprint() == aCertHash )
+                 {
+                 stillexist = ETrue;
+            	 CleanupStack::PopAndDestroy( 2 ); //certData, cert
+                 break;
+                 }
+
+            CleanupStack::PopAndDestroy( 2 ); //certData, cert
+            }
+        }
+        
+    if ( stillexist )
+        {
+        //there are still same server certificate saved in cert store
+        //with different label, doesn't delete information then
+        return;	
+        }
+    iDatabase.Begin(); // Begin transaction
+
+    TRAPD( err, DoRemoveL( certID ));
+
+    if ( err ) // Some error occurred
+        {
+        iDatabase.Rollback(); // Rollback changes
+        User::Leave ( err );
+        }
+    else
+        {
+        iDatabase.Commit(); // Commit changes
+        } 
+    }   
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::DoRemoveL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::DoRemoveL(const TInt& aCertID )
+    {  
+    _LIT( KSQLDelete1, "DELETE FROM Certificates WHERE CertID = " );
+    _LIT( KSQLDelete2, "DELETE FROM TrustedSites WHERE CertID = " );
+
+    TBuf<KMaxSQLLength> SQLStatement1;
+    TBuf<KMaxSQLLength> SQLStatement2;
+
+    SQLStatement1.Copy( KSQLDelete1 );
+    SQLStatement1.AppendNum( aCertID );
+    TPtrC sqlStat1( SQLStatement1.PtrZ() );
+
+    SQLStatement2.Copy( KSQLDelete2 );
+    SQLStatement2.AppendNum( aCertID );
+    TPtrC sqlStat2( SQLStatement2.PtrZ() );
+
+    User::LeaveIfError( iDatabase.Execute( sqlStat1) );
+    User::LeaveIfError( iDatabase.Execute( sqlStat2 ) );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::AddForgivenSiteL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::AddForgivenSiteL( const TDesC& aSite, const TBool& aOutOfDateAllowed, const RMessage2& aMessage )
+    {
+    // API policing,WriteDeviceData
+    if (!KWriteSecurityPolicy.CheckPolicy(aMessage))
+        {
+        User::Leave(KErrPermissionDenied);
+        }
+
+    if ( IsForgivenSiteAlreadyL( aSite ) )
+       {
+       //the hostname is in table already.
+       DoOverWriteOutOfDateL( aSite, aOutOfDateAllowed );
+       return;  
+       }
+    else
+       {
+       iDatabase.Begin(); // Begin transaction
+
+       TRAPD( err, DoAddForgivenSiteL( aSite, aOutOfDateAllowed, aMessage.SecureId().iId ));
+
+       if ( err ) // Some error occurred
+           {
+           iDatabase.Rollback(); // Rollback changes
+           User::Leave ( err );
+           }
+       else
+           {
+           iDatabase.Commit(); // Commit changes            
+           }
+       }    
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::RemoveAllForgivenSitesL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::RemoveAllForgivenSitesL( const RMessage2& aMessage )
+	{
+    // API policing,WriteDeviceData
+    if (!KWriteSecurityPolicy.CheckPolicy(aMessage))
+        {
+        User::Leave(KErrPermissionDenied);
+        }
+    
+    // get certid arrays for the ClientUID
+    RDbView view;   
+    _LIT( KSQLQuery, 
+    "SELECT SiteName,CertID FROM TrustedSites WHERE ClientUID = " );
+
+    TBuf<KMaxSQLLength> SQLStatement;
+    SQLStatement.Copy( KSQLQuery );
+
+    SQLStatement.AppendNum( aMessage.SecureId().iId );
+
+    TPtrC sqlStat( SQLStatement.PtrZ() );
+
+    TInt err = view.Prepare( iDatabase, TDbQuery( sqlStat ), TDbWindow::EUnlimited );
+
+    if ( err != KErrNone )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    err = view.EvaluateAll();
+
+    CleanupClosePushL( view );
+    
+    RArray<TInt> certIDs;
+    RArray<TInt> certIDs2;
+    if ( view.CountL() )
+    	{
+        // Get data
+        while ( view.NextL() ) // Should find only one certificate
+            {
+            TRAPD(error, view.GetL());
+            error = error;
+            certIDs.Append( view.ColInt( 2 ) );      
+            }
+        CleanupStack::PopAndDestroy( 1 ); //view
+    	}
+    else
+    	{
+    	CleanupStack::PopAndDestroy( 1 ); //view
+    	//no match found, nothing to delete 
+    	return;
+    	}
+    
+    if ( certIDs.Count() == 0 )
+    	{
+    	//no cert id, just return;
+    	return;
+    	}
+    
+    //the certID may contain -1, then no need to delete the certificate but go to delete the site directly
+    //filter the -1 out.
+    for ( TInt i = 0; i < certIDs.Count() ; i++ )
+    	{
+    	if ( certIDs[i] != -1 )
+    		{
+    		certIDs2.Append( certIDs[i] );
+    		}
+    	}
+    
+    // if certid2 is not empty, it means there are certificates associated with the sitename,
+    // we should delete it.
+    if ( certIDs2.Count() > 0 )
+    	{
+    	// get the certhash array for certid arrays
+        //the desc8 array to put the certhash
+        TInt num = certIDs2.Count();
+        CDesC8ArrayFlat* descarray = new (ELeave) CDesC8ArrayFlat( num );
+        CleanupStack::PushL( descarray );
+        
+        for ( TInt i = 0; i < certIDs2.Count(); i++ )
+        	{
+        	//empty the previous command
+        	SQLStatement.Zero();
+            _LIT( KSQLQuery, "SELECT CertHash FROM Certificates WHERE CertID =" );
+            SQLStatement.Append( KSQLQuery );
+            SQLStatement.AppendNum( certIDs2[i] );
+            
+           	TPtrC sqlStat1( SQLStatement.PtrZ() );
+        	
+            TInt err = view.Prepare( iDatabase, TDbQuery( sqlStat1 ), TDbWindow::EUnlimited );
+         
+            if ( err != KErrNone )
+                {
+                User::Leave( KErrArgument );
+                }
+
+            err = view.EvaluateAll();
+            
+            CleanupClosePushL( view );
+           
+            //put the hash into array
+            while ( view.NextL() ) // Should find only one certificate
+                {
+                TRAPD(error, view.GetL());
+                error = error;
+                descarray->AppendL( view.ColDes8( 1 ) );      
+                }
+            CleanupStack::PopAndDestroy( 1 ); //view
+        	}
+        
+        // List all of the certificate in trusted server certstore
+        // retrive them one by one to compare the certhash.
+        //if match found, remove the certificate from the trusted server certstore
+        
+        CCertAttributeFilter* filter = CCertAttributeFilter::NewL();
+        CleanupStack::PushL(filter);
+        filter->SetOwnerType(EPeerCertificate);
+        RPointerArray<CDevTokenCertInfo> certs;
+        RMessage2 message;             
+        iServer->CertStoreServerL().ListL(*filter,certs,message, ETrue  );            
+        
+        CleanupStack::PopAndDestroy(); //filter
+        
+        if ( certs.Count() )
+            {
+            for ( TInt i= 0; i < certs.Count(); i++ )
+                {
+                HBufC8* certData = iServer->CertStoreServerL().RetrieveLC( certs[i]->CertificateId(),message,ETrue );
+
+                TPtr8 certPtr = certData->Des();
+            	
+                CX509Certificate* cert = CX509Certificate::NewLC( certPtr );
+                
+                for ( TInt ii=0; ii < descarray->Count(); ii++ )
+                	{
+                	if ( (*descarray)[ii] == cert->Fingerprint() )
+                		{
+                           //match, then delete it 
+                		iServer->CertStoreServerL().RemoveL( certs[i]->CertificateId(),message,ETrue );
+                		break;
+                		}
+                	}
+                
+                CleanupStack::PopAndDestroy( 2 ); //certData, cert
+                }
+            }
+        descarray->Reset(); //clean the buffer for certhash
+        CleanupStack::PopAndDestroy(); //descarray
+        
+        //delete the cert record in Certificates Table
+        for ( TInt i = 0; i < certIDs2.Count(); i++ )
+        	{
+        	_LIT( KSQLDelete1, "DELETE FROM Certificates WHERE CertID = " );
+        	SQLStatement.Zero();
+
+        	SQLStatement.Copy( KSQLDelete1 );
+        	SQLStatement.AppendNum( certIDs2[i] );
+        	TPtrC sqlStat2( SQLStatement.PtrZ() );
+        	
+        	User::LeaveIfError( iDatabase.Execute( sqlStat2 ) );
+        	}
+    	}
+        
+    //now corresponding certificates are deleted,  it is time to delete the sitenames
+    // just delete all of the record where uid matched with the client uid
+    
+    _LIT( KSQLDelete2, "DELETE FROM TrustedSites WHERE ClientUID = " );
+
+    SQLStatement.Zero();
+    SQLStatement.Copy( KSQLDelete2 );
+    SQLStatement.AppendNum( aMessage.SecureId().iId  );
+    
+    TPtrC sqlStat3( SQLStatement.PtrZ() );
+
+    User::LeaveIfError( iDatabase.Execute( sqlStat3) );
+	}
+
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::RemoveThisForgivenSiteL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::RemoveThisForgivenSiteL( const TDesC& aSite, const RMessage2& aMessage )
+	{
+    // API policing,WriteDeviceData
+    if (!KWriteSecurityPolicy.CheckPolicy(aMessage))
+    	{
+        User::Leave(KErrPermissionDenied);
+        }
+    
+    // get certid arrays for the ClientUID
+    RDbView view;   
+    _LIT( KSQLQuery, 
+    "SELECT CertID FROM TrustedSites WHERE ClientUID = " );
+
+    TBuf<KMaxSQLLength> SQLStatement;
+    SQLStatement.Copy( KSQLQuery );
+
+    SQLStatement.AppendNum( aMessage.SecureId().iId );
+    SQLStatement.Append(_L(" AND SiteName = '") );
+    SQLStatement.Append( aSite );
+    SQLStatement.Append(_L("'"));
+    
+    
+    TPtrC sqlStat( SQLStatement.PtrZ() );
+
+    TInt err = view.Prepare( iDatabase, TDbQuery( sqlStat ), TDbWindow::EUnlimited );
+
+    if ( err != KErrNone )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    err = view.EvaluateAll();
+    
+    
+    CleanupClosePushL( view );
+    
+    RArray<TInt> certIDs;
+    RArray<TInt> certIDs2;
+    if ( view.CountL() )
+    	{
+        // Get data
+        while ( view.NextL() ) // Should find only one certificate
+            {
+            TRAPD(error, view.GetL());
+            error = error;
+            certIDs.Append( view.ColInt( 1 ) );      
+            }
+        CleanupStack::PopAndDestroy( 1 ); //view
+    	}
+    else
+    	{
+    	CleanupStack::PopAndDestroy( 1 ); //view
+    	//no match found, nothing to delete 
+    	return;
+    	}
+    
+    if ( certIDs.Count() == 0 )
+    	{
+    	//no cert id, just return;
+    	return;
+    	}
+    
+    //the certID may contain -1, then no need to delete the certificate but go to delete the site directly
+    //filter the -1 out.
+    for ( TInt i = 0; i < certIDs.Count() ; i++ )
+    	{
+    	if ( certIDs[i] != -1 )
+    		{
+    		certIDs2.Append( certIDs[i] );
+    		}
+    	}
+    // if certid2 is not empty, it means there are certificates associated with the sitename,
+    // we should delete it.
+    
+    if ( certIDs2.Count() > 0 )
+    	{
+    	// get the certhash array for certid arrays
+        //the desc8 array to put the certhash
+        TInt num = certIDs2.Count();
+        CDesC8ArrayFlat* descarray = new (ELeave) CDesC8ArrayFlat( num );
+        CleanupStack::PushL( descarray );
+        
+        for ( TInt i = 0; i < certIDs2.Count(); i++ )
+        	{
+        	//empty the previous command
+        	SQLStatement.Zero();
+            _LIT( KSQLQuery, "SELECT CertHash FROM Certificates WHERE CertID =" );
+            SQLStatement.Append( KSQLQuery );
+            SQLStatement.AppendNum( certIDs2[i] );
+            
+           	TPtrC sqlStat1( SQLStatement.PtrZ() );
+        	
+            TInt err = view.Prepare( iDatabase, TDbQuery( sqlStat1 ), TDbWindow::EUnlimited );
+         
+            if ( err != KErrNone )
+                {
+                User::Leave( KErrArgument );
+                }
+
+            err = view.EvaluateAll();
+            
+            CleanupClosePushL( view );
+           
+            //put the hash into array
+            while ( view.NextL() ) // Should find only one certificate
+                {
+                TRAPD(error, view.GetL());
+                error = error;
+                descarray->AppendL( view.ColDes8( 1 ) );      
+                }
+            CleanupStack::PopAndDestroy( 1 ); //view
+        	}
+        
+        // List all of the certificate in trusted server certstore
+        // retrive them one by one to compare the certhash.
+        //if match found, remove the certificate from the trusted server certstore
+        
+        CCertAttributeFilter* filter = CCertAttributeFilter::NewL();
+        CleanupStack::PushL(filter);
+        filter->SetOwnerType(EPeerCertificate);
+        RPointerArray<CDevTokenCertInfo> certs;
+        RMessage2 message;             
+        iServer->CertStoreServerL().ListL(*filter,certs,message, ETrue  );            
+        
+        CleanupStack::PopAndDestroy(); //filter
+        
+        if ( certs.Count() )
+            {
+            for ( TInt i= 0; i < certs.Count(); i++ )
+                {
+                HBufC8* certData = iServer->CertStoreServerL().RetrieveLC( certs[i]->CertificateId(),message,ETrue );
+
+                TPtr8 certPtr = certData->Des();
+            	
+                CX509Certificate* cert = CX509Certificate::NewLC( certPtr );
+                
+                for ( TInt ii=0; ii < descarray->Count(); ii++ )
+                	{
+                	if ( (*descarray)[ii] == cert->Fingerprint() )
+                		{
+                           //match, then delete it 
+                		iServer->CertStoreServerL().RemoveL( certs[i]->CertificateId(),message,ETrue );
+                		break;
+                		}
+                	}
+                
+                CleanupStack::PopAndDestroy( 2 ); //certData, cert
+                }
+            }
+        descarray->Reset(); //clean the buffer for certhash
+        CleanupStack::PopAndDestroy(); //descarray
+        
+        //delete the cert record in Certificates Table
+        for ( TInt i = 0; i < certIDs2.Count(); i++ )
+        	{
+        	_LIT( KSQLDelete1, "DELETE FROM Certificates WHERE CertID = " );
+        	SQLStatement.Zero();
+
+        	SQLStatement.Copy( KSQLDelete1 );
+        	SQLStatement.AppendNum( certIDs2[i] );
+        	TPtrC sqlStat2( SQLStatement.PtrZ() );
+        	
+        	User::LeaveIfError( iDatabase.Execute( sqlStat2 ) );
+        	}
+    	}
+    //now corresponding certificates are deleted,  it is time to delete the sitenames
+    // just delete all of the record where uid matched with the client uid
+    
+    _LIT( KSQLDelete2, "DELETE FROM TrustedSites WHERE ClientUID = " );
+
+    SQLStatement.Zero();
+    SQLStatement.Copy( KSQLDelete2 );
+    SQLStatement.AppendNum( aMessage.SecureId().iId  );
+    SQLStatement.Append(_L("AND SiteName = '"));
+    SQLStatement.Append( aSite );
+    SQLStatement.Append(_L("'"));
+    
+    TPtrC sqlStat3( SQLStatement.PtrZ() );
+    
+    //TInt errr = iDatabase.Execute( sqlStat3);
+    User::LeaveIfError( iDatabase.Execute( sqlStat3) );
+	}
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::DoAddForgivenSiteL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::DoAddForgivenSiteL(const TDesC& aSite, const TBool& aOutOfDateAllowed, const TUint32& aUID )
+    {
+    TBuf<KMaxSQLLength> SQLStatement;
+
+    _LIT( KSQLInsert1,
+    "INSERT INTO TrustedSites (CertID,SiteName,Forgiven,OutOfDate,ClientUID) VALUES (" );
+
+    SQLStatement.Copy(KSQLInsert1);
+    SQLStatement.AppendNum(-1);
+    SQLStatement.Append(_L(",'"));
+    
+    SQLStatement.Append( aSite );
+    SQLStatement.Append(_L("',"));
+    SQLStatement.AppendNum(1);
+    SQLStatement.Append(_L(","));
+    //add record for forgiven sites, check if outofdate is allowed also
+    if ( aOutOfDateAllowed )
+        {
+        SQLStatement.AppendNum(1);
+        }
+    else 
+        {
+        SQLStatement.AppendNum(0); 
+        }
+    SQLStatement.Append(_L(","));
+    //append the client UID.
+    SQLStatement.AppendNum( aUID );
+    SQLStatement.Append(_L(")"));
+    
+    User::LeaveIfError( iDatabase.Execute( SQLStatement ) );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::IsForgivenSiteAlreadyL()
+// ---------------------------------------------------------------------------
+//
+TBool CTrustedSitesServer::IsForgivenSiteAlreadyL( const TDesC& aSite )
+    {
+    RDbView view;   
+    _LIT( KSQLCheckForgivenSite, 
+    "SELECT SiteName, Forgiven, OutOfDate FROM TrustedSites" );
+
+    TInt err = view.Prepare( iDatabase, TDbQuery( KSQLCheckForgivenSite ) );
+    
+    if( err == KErrNotFound )
+        {
+        return EFalse; 
+        }
+    
+    if ( err != KErrNone )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    err = view.EvaluateAll();
+
+    CleanupClosePushL( view );
+
+    TBool alreadyExist = EFalse;
+    
+    // looking for a match
+    while ( view.NextL() ) // Should find only one certificate
+        {
+        TRAPD(error, view.GetL());
+        error = error;
+        
+        // sitename is matched and forgiven is set to 1
+        if(  (!aSite.Compare(view.ColDes( 1 ))) && ( view.ColInt( 2 ) == 1 )   )
+            {
+            alreadyExist = ETrue;
+            break;
+            }
+        }
+        
+    CleanupStack::PopAndDestroy( 1 ); 
+    return alreadyExist;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::DoOverWriteOutOfDateL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::DoOverWriteOutOfDateL(const TDesC& aSite, const TBool& aOutOfDateAllowed )
+    {
+    _LIT( KSQLOverWrite1, "UPDATE TrustedSites SET OutOfDate = ");
+    
+    _LIT( KSQLOverWrite2, " WHERE SiteName = '");
+
+    TBuf<KMaxSQLLength> SQLStatement;
+    SQLStatement.Copy(KSQLOverWrite1);
+    SQLStatement.AppendNum(aOutOfDateAllowed);
+    SQLStatement.Append(KSQLOverWrite2);
+    SQLStatement.Append(aSite);
+    SQLStatement.Append(_L("'"));
+    
+    User::LeaveIfError( iDatabase.Execute( SQLStatement ) ); 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesServer::DoOverWriteCertL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesServer::DoOverWriteCertL( const TDesC& aSiteName, const TDesC8& aCertHash )
+    {
+    TInt certID;
+    GetCertIDL( aCertHash, certID );
+    
+    if( certID == KErrNotFound )
+        {
+        DoAddCertL( aCertHash );
+        GetCertIDL(aCertHash, certID);
+        }
+    
+    RDbView view;
+    TBuf<KMaxSQLLength> SQLStatement;
+
+    _LIT( KSQLQuery2, "SELECT Forgiven, OutOfDate FROM TrustedSites WHERE CertID = ");
+    
+    _LIT( KSQLQuery3," AND SiteName ='" );
+  
+    SQLStatement.Copy( KSQLQuery2 );
+    SQLStatement.AppendNum(certID);
+    SQLStatement.Append( KSQLQuery3);
+    SQLStatement.Append( aSiteName );
+    SQLStatement.Append(_L("'"));
+    
+    TPtrC sqlStat( SQLStatement.PtrZ() );
+    TInt err = view.Prepare( iDatabase, TDbQuery( sqlStat ) );
+     
+    err = view.EvaluateAll();
+
+    CleanupClosePushL( view ); 
+     
+    //same sitename and same cert exists
+    if (view.FirstL())
+        {
+        //already exist, no need to add
+        CleanupStack::PopAndDestroy(); //view
+        return;
+        }
+   
+    CleanupStack::PopAndDestroy(); //view
+   
+    // no match found
+   
+    _LIT( KSQLQuery, 
+    "SELECT Forgiven,OutOfDate, CertID FROM TrustedSites WHERE CertId = -1 AND SiteName = '" );
+
+    SQLStatement.Zero(); 
+    SQLStatement.Copy( KSQLQuery );
+
+    SQLStatement.Append( aSiteName );
+    SQLStatement.Append(_L("'"));
+
+    sqlStat.Set( SQLStatement.PtrZ() );
+    err = view.Prepare( iDatabase, TDbQuery( sqlStat ) );
+    
+    err = view.EvaluateAll();
+
+    CleanupClosePushL( view );
+    
+    if ( view.CountL() )
+        {
+        //record is there but certid is empty, add the certid into the record
+        //Update the certid 
+        _LIT( KSQLOverWrite1, "UPDATE TrustedSites SET CertID = ");
+        _LIT( KSQLOverWrite2, " WHERE SiteName = '");
+   
+        SQLStatement.Zero();
+        SQLStatement.Copy(KSQLOverWrite1);
+        SQLStatement.AppendNum( certID );
+        SQLStatement.Append(KSQLOverWrite2);
+        SQLStatement.Append(aSiteName);
+        SQLStatement.Append(_L("'"));
+    
+        User::LeaveIfError( iDatabase.Execute(SQLStatement) );
+        }
+    else
+        {
+        //retrive the forgiven and outofdate, and make a same record for the certificate
+        TInt forgiven = 0;
+        TInt OutOfDate = 0;
+        TInt ClientUID  = 0;
+        _LIT( KSQLQuery, 
+         "SELECT Forgiven,OutOfDate,CertID,ClientUID FROM TrustedSites WHERE SiteName = '" );
+
+        SQLStatement.Zero(); 
+        SQLStatement.Copy( KSQLQuery );
+
+        SQLStatement.Append( aSiteName );
+        SQLStatement.Append(_L("'"));
+
+        sqlStat.Set( SQLStatement.PtrZ() );
+        err = view.Prepare( iDatabase, TDbQuery( sqlStat ) );
+      
+        err = view.EvaluateAll();
+
+        CleanupClosePushL( view );
+      
+        // looking for a match
+        if ( view.FirstL() ) // Should find only one certificate
+            {
+            TRAPD(error, view.GetL());
+            error = error;
+            //add a new record
+            forgiven = view.ColInt( 1 ); 
+            OutOfDate = view.ColInt( 2 );
+            ClientUID = view.ColInt( 4 );
+
+            //set the new record with new certid and same forgiven and outofdate settings
+            _LIT( KSQLInsert,
+            "INSERT INTO TrustedSites (CertID,SiteName,Forgiven,OutOfDate,ClientUID) VALUES(" );
+            SQLStatement.Zero();
+            SQLStatement.Copy(KSQLInsert);
+            SQLStatement.AppendNum(certID);
+            SQLStatement.Append(_L(",'"));
+      
+            SQLStatement.Append( aSiteName );
+            SQLStatement.Append(_L("',"));
+            SQLStatement.AppendNum(forgiven);
+            SQLStatement.Append(_L(","));
+            SQLStatement.AppendNum(OutOfDate);  
+            SQLStatement.Append(_L(","));
+            SQLStatement.AppendNum(ClientUID);
+            SQLStatement.Append(_L(")"));
+            
+            User::LeaveIfError( iDatabase.Execute( SQLStatement ) );  
+            } 
+        CleanupStack::PopAndDestroy();    
+        }
+    CleanupStack::PopAndDestroy(); //view 
+    }
+//EOF 
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/DeviceToken/Src/TruSitesStore/Server/TrustedSitesSession.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of TrustedSitesStoreSession
+*
+*/
+
+
+
+#include "TrustedSitesSession.h"
+#include "TrustedSitesConduit.h"
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesSession::NewL()
+// ---------------------------------------------------------------------------
+//
+CTrustedSitesSession* CTrustedSitesSession::NewL(CTrustedSitesConduit& aConduit)
+    {
+    return new (ELeave) CTrustedSitesSession(aConduit);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesSession::CTrustedSitesSession()
+// ---------------------------------------------------------------------------
+//
+CTrustedSitesSession::CTrustedSitesSession(CTrustedSitesConduit& aConduit) :
+    iConduit(aConduit)
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CTrustedSitesSession::DoServiceL()
+// ---------------------------------------------------------------------------
+//
+void CTrustedSitesSession::DoServiceL(const RMessage2& aMessage)
+    {
+    iConduit.ServiceTrustedSitesRequestL(aMessage);
+    }
+    
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/Include/securityuisvariant.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This file contains all the bit flag declarations to variate 
+*		 locally SecurityUis
+*
+*/
+
+
+
+#ifndef SECURITYUISVARIANT_HRH
+#define SECURITYUISVARIANT_HRH
+
+// SecurityUIs related values are in 101F8732.ini
+
+// Feature to prevent user to change Native application
+// trust setting for certificate during certificate installation
+// or from CertmanUI
+//
+#define KSecurityUIsNoNativeAppTrustSettingChange   0x01
+
+#endif // SECURITYUISVARIANT_HRH
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrBer/BMARM/CRBERU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,99 @@
+EXPORTS
+	"_._6CCrBer" @ 1 NONAME R3UNUSED ; CCrBer::~CCrBer(void)
+	AppendAndUpdateL__9CCrBerSetP6CCrBer @ 2 NONAME R3UNUSED ; CCrBerSet::AppendAndUpdateL(CCrBer *)
+	BufferL__6CCrBerP6HBufC8P7CCrDataUiUi @ 3 NONAME ; CCrBer::BufferL(HBufC8 *, CCrData *, unsigned int, unsigned int)
+	BufferL__6CCrBerP7HBufC16P7CCrDataUiUc @ 4 NONAME ; CCrBer::BufferL(HBufC16 *, CCrData *, unsigned int, unsigned char)
+	CloseLastSeqOrSet__9CCrBerSetUi @ 5 NONAME R3UNUSED ; CCrBerSet::CloseLastSeqOrSet(unsigned int)
+	Close__7CCrData @ 6 NONAME R3UNUSED ; CCrData::Close(void)
+	ContentBegin__6CCrBer @ 7 NONAME R3UNUSED ; CCrBer::ContentBegin(void)
+	ContentL__6CCrBerP7HBufC16 @ 8 NONAME R3UNUSED ; CCrBer::ContentL(HBufC16 *)
+	ContentLen__6CCrBer @ 9 NONAME R3UNUSED ; CCrBer::ContentLen(void)
+	Content__6CCrBerP6HBufC8 @ 10 NONAME R3UNUSED ; CCrBer::Content(HBufC8 *)
+	CreateBEREncodedObjectL__9CCrBerSetR6TDesC8 @ 11 NONAME R3UNUSED ; CCrBerSet::CreateBEREncodedObjectL(TDesC8 &)
+	CreateBoolL__9CCrBerSeti @ 12 NONAME R3UNUSED ; CCrBerSet::CreateBoolL(int)
+	CreateConstructedStartL__9CCrBerSetUci @ 13 NONAME R3UNUSED ; CCrBerSet::CreateConstructedStartL(unsigned char, int)
+	CreateEndL__9CCrBerSet @ 14 NONAME R3UNUSED ; CCrBerSet::CreateEndL(void)
+	CreateGenTimeL__9CCrBerSetR6TDesC8 @ 15 NONAME R3UNUSED ; CCrBerSet::CreateGenTimeL(TDesC8 &)
+	CreateGeneralL__9CCrBerSetR6TDesC8 @ 16 NONAME R3UNUSED ; CCrBerSet::CreateGeneralL(TDesC8 &)
+	CreateGraphicalL__9CCrBerSetR6TDesC8 @ 17 NONAME R3UNUSED ; CCrBerSet::CreateGraphicalL(TDesC8 &)
+	CreateIA5L__9CCrBerSetR6TDesC8 @ 18 NONAME R3UNUSED ; CCrBerSet::CreateIA5L(TDesC8 &)
+	CreateIntL__9CCrBerSeti @ 19 NONAME R3UNUSED ; CCrBerSet::CreateIntL(int)
+	CreateLongIntL__9CCrBerSetR8RInteger @ 20 NONAME R3UNUSED ; CCrBerSet::CreateLongIntL(RInteger &)
+	CreateNullL__9CCrBerSet @ 21 NONAME R3UNUSED ; CCrBerSet::CreateNullL(void)
+	CreateNumericL__9CCrBerSetR6TDesC8 @ 22 NONAME R3UNUSED ; CCrBerSet::CreateNumericL(TDesC8 &)
+	CreateOIdL__9CCrBerSetR6TDesC8 @ 23 NONAME R3UNUSED ; CCrBerSet::CreateOIdL(TDesC8 &)
+	CreateOctetL__9CCrBerSetP7CCrData @ 24 NONAME R3UNUSED ; CCrBerSet::CreateOctetL(CCrData *)
+	CreateOctetL__9CCrBerSetR6TDesC8 @ 25 NONAME R3UNUSED ; CCrBerSet::CreateOctetL(TDesC8 &)
+	CreatePrintableL__9CCrBerSetR6TDesC8 @ 26 NONAME R3UNUSED ; CCrBerSet::CreatePrintableL(TDesC8 &)
+	CreateSeqStartL__9CCrBerSeti @ 27 NONAME R3UNUSED ; CCrBerSet::CreateSeqStartL(int)
+	CreateSetStartL__9CCrBerSeti @ 28 NONAME R3UNUSED ; CCrBerSet::CreateSetStartL(int)
+	CreateT61L__9CCrBerSetR6TDesC8 @ 29 NONAME R3UNUSED ; CCrBerSet::CreateT61L(TDesC8 &)
+	CreateUTCL__9CCrBerSetR6TDesC8 @ 30 NONAME R3UNUSED ; CCrBerSet::CreateUTCL(TDesC8 &)
+	CreateVideoTexL__9CCrBerSetR6TDesC8 @ 31 NONAME R3UNUSED ; CCrBerSet::CreateVideoTexL(TDesC8 &)
+	CreateVisibleL__9CCrBerSetR6TDesC8 @ 32 NONAME R3UNUSED ; CCrBerSet::CreateVisibleL(TDesC8 &)
+	Data__6CCrBer @ 33 NONAME R3UNUSED ; CCrBer::Data(void)
+	Delete__7CCrDataii @ 34 NONAME R3UNUSED ; CCrData::Delete(int, int)
+	FindEndOfContent__6CCrBerP7CCrData @ 35 NONAME R3UNUSED ; CCrBer::FindEndOfContent(CCrData *)
+	FlushL__9CCrBerSetP7CCrData @ 36 NONAME R3UNUSED ; CCrBerSet::FlushL(CCrData *)
+	GetBooleanL__6CCrBer @ 37 NONAME R3UNUSED ; CCrBer::GetBooleanL(void)
+	GetContentStringLC__6CCrBer @ 38 NONAME R3UNUSED ; CCrBer::GetContentStringLC(void)
+	GetGeneralStringL__6CCrBer @ 39 NONAME R3UNUSED ; CCrBer::GetGeneralStringL(void)
+	GetGeneralizedTimeL__6CCrBer @ 40 NONAME R3UNUSED ; CCrBer::GetGeneralizedTimeL(void)
+	GetGraphicsStringL__6CCrBer @ 41 NONAME R3UNUSED ; CCrBer::GetGraphicsStringL(void)
+	GetIA5StringL__6CCrBer @ 42 NONAME R3UNUSED ; CCrBer::GetIA5StringL(void)
+	GetIntegerL__6CCrBer @ 43 NONAME R3UNUSED ; CCrBer::GetIntegerL(void)
+	GetLongIntegerL__6CCrBer @ 44 NONAME R3UNUSED ; CCrBer::GetLongIntegerL(void)
+	GetNumericStringL__6CCrBer @ 45 NONAME R3UNUSED ; CCrBer::GetNumericStringL(void)
+	GetOctetStringL__6CCrBer @ 46 NONAME R3UNUSED ; CCrBer::GetOctetStringL(void)
+	GetOctetStringL__6CCrBerR7CCrData @ 47 NONAME R3UNUSED ; CCrBer::GetOctetStringL(CCrData &)
+	GetOidL__6CCrBer @ 48 NONAME R3UNUSED ; CCrBer::GetOidL(void)
+	GetPrintStringL__6CCrBer @ 49 NONAME R3UNUSED ; CCrBer::GetPrintStringL(void)
+	GetSequenceL__6CCrBer @ 50 NONAME R3UNUSED ; CCrBer::GetSequenceL(void)
+	GetTeletextStringL__6CCrBer @ 51 NONAME R3UNUSED ; CCrBer::GetTeletextStringL(void)
+	GetUTCTimeL__6CCrBer @ 52 NONAME R3UNUSED ; CCrBer::GetUTCTimeL(void)
+	GetVideoStringL__6CCrBer @ 53 NONAME R3UNUSED ; CCrBer::GetVideoStringL(void)
+	GetVisibleStringL__6CCrBer @ 54 NONAME R3UNUSED ; CCrBer::GetVisibleStringL(void)
+	Indefinite__6CCrBer @ 55 NONAME R3UNUSED ; CCrBer::Indefinite(void)
+	IsFile__7CCrData @ 56 NONAME R3UNUSED ; CCrData::IsFile(void)
+	IsKnownType__6CCrBerUc @ 57 NONAME R3UNUSED ; CCrBer::IsKnownType(unsigned char)
+	IsSeqOrSet__6CCrBerUc @ 58 NONAME R3UNUSED ; CCrBer::IsSeqOrSet(unsigned char)
+	LenLen__6CCrBer @ 59 NONAME R3UNUSED ; CCrBer::LenLen(void)
+	Level__6CCrBer @ 60 NONAME R3UNUSED ; CCrBer::Level(void)
+	LineL__7CCrDataR5TDes8 @ 61 NONAME R3UNUSED ; CCrData::LineL(TDes8 &)
+	NewLC__10CCrDataSeti @ 62 NONAME R3UNUSED ; CCrDataSet::NewLC(int)
+	NewLC__6CCrBeri @ 63 NONAME R3UNUSED ; CCrBer::NewLC(int)
+	NewLC__7CCrDatai @ 64 NONAME R3UNUSED ; CCrData::NewLC(int)
+	NewLC__9CCrBerSeti @ 65 NONAME R3UNUSED ; CCrBerSet::NewLC(int)
+	NewL__10CCrDataSeti @ 66 NONAME R3UNUSED ; CCrDataSet::NewL(int)
+	NewL__6CCrBeri @ 67 NONAME R3UNUSED ; CCrBer::NewL(int)
+	NewL__7CCrDatai @ 68 NONAME R3UNUSED ; CCrData::NewL(int)
+	NewL__9CCrBerSeti @ 69 NONAME R3UNUSED ; CCrBerSet::NewL(int)
+	ObjectBegin__6CCrBer @ 70 NONAME R3UNUSED ; CCrBer::ObjectBegin(void)
+	ObjectL__6CCrBerP7HBufC16 @ 71 NONAME R3UNUSED ; CCrBer::ObjectL(HBufC16 *)
+	ObjectLen__6CCrBer @ 72 NONAME R3UNUSED ; CCrBer::ObjectLen(void)
+	Object__6CCrBerP6HBufC8 @ 73 NONAME R3UNUSED ; CCrBer::Object(HBufC8 *)
+	OpenConstructedEncodingL__6CCrBerR7CCrData @ 74 NONAME R3UNUSED ; CCrBer::OpenConstructedEncodingL(CCrData &)
+	OpenConstructedEncodingWithTagL__6CCrBerP7CCrDataR6CCrBerP6HBufC8 @ 75 NONAME ; CCrBer::OpenConstructedEncodingWithTagL(CCrData *, CCrBer &, HBufC8 *)
+	OpenL__9CCrBerSetP7CCrDataUc @ 76 NONAME R3UNUSED ; CCrBerSet::OpenL(CCrData *, unsigned char)
+	Open__7CCrDataR3RFsRC7TDesC16Ui @ 77 NONAME ; CCrData::Open(RFs &, TDesC16 const &, unsigned int)
+	Open__7CCrDataR3RFsUi @ 78 NONAME R3UNUSED ; CCrData::Open(RFs &, unsigned int)
+	Path__7CCrData @ 79 NONAME R3UNUSED ; CCrData::Path(void)
+	ReadLen__6CCrBerP7CCrDataRiPUc @ 80 NONAME ; CCrBer::ReadLen(CCrData *, int &, unsigned char *)
+	ReadType__6CCrBerP7CCrData @ 81 NONAME R3UNUSED ; CCrBer::ReadType(CCrData *)
+	Read__6CCrBerP7CCrData @ 82 NONAME R3UNUSED ; CCrBer::Read(CCrData *)
+	Read__7CCrDataR5TDes8 @ 83 NONAME R3UNUSED ; CCrData::Read(TDes8 &)
+	Read__7CCrDataR5TDes8i @ 84 NONAME R3UNUSED ; CCrData::Read(TDes8 &, int)
+	Read__7CCrDataiR5TDes8i @ 85 NONAME ; CCrData::Read(int, TDes8 &, int)
+	Replace__7CCrDataR3RFsRC7TDesC16Ui @ 86 NONAME ; CCrData::Replace(RFs &, TDesC16 const &, unsigned int)
+	Seek__7CCrData5TSeekRi @ 87 NONAME R3UNUSED ; CCrData::Seek(TSeek, int &)
+	SetLevel__6CCrBerUi @ 88 NONAME R3UNUSED ; CCrBer::SetLevel(unsigned int)
+	SetObjectLen__6CCrBer @ 89 NONAME R3UNUSED ; CCrBer::SetObjectLen(void)
+	SetPathL__7CCrDataRC7TDesC16 @ 90 NONAME R3UNUSED ; CCrData::SetPathL(TDesC16 const &)
+	Size__7CCrDataRi @ 91 NONAME R3UNUSED ; CCrData::Size(int &)
+	Type__6CCrBer @ 92 NONAME R3UNUSED ; CCrBer::Type(void)
+	Update__9CCrBerSetP6CCrBer @ 93 NONAME R3UNUSED ; CCrBerSet::Update(CCrBer *)
+	Write__7CCrDataRC6TDesC8 @ 94 NONAME R3UNUSED ; CCrData::Write(TDesC8 const &)
+	Write__7CCrDataRC6TDesC8i @ 95 NONAME R3UNUSED ; CCrData::Write(TDesC8 const &, int)
+	Zero__7CCrDataii @ 96 NONAME R3UNUSED ; CCrData::Zero(int, int)
+	AddToContentLen__6CCrBeri @ 97 NONAME R3UNUSED ; CCrBer::AddToContentLen(int)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrBer/BWINS/CRBERU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,108 @@
+EXPORTS
+	??0CCrData@@QAE@H@Z @ 1 NONAME ; public: __thiscall CCrData::CCrData(int)
+	??0CCrData@@QAE@XZ @ 2 NONAME ; public: __thiscall CCrData::CCrData(void)
+	??1CCrBer@@UAE@XZ @ 3 NONAME ; public: virtual __thiscall CCrBer::~CCrBer(void)
+	??1CCrBerSet@@UAE@XZ @ 4 NONAME ; public: virtual __thiscall CCrBerSet::~CCrBerSet(void)
+	??1CCrData@@UAE@XZ @ 5 NONAME ; public: virtual __thiscall CCrData::~CCrData(void)
+	?AddToContentLen@CCrBer@@QAEXH@Z @ 6 NONAME ; public: void __thiscall CCrBer::AddToContentLen(int)
+	?AppendAndUpdateL@CCrBerSet@@QAEXPAVCCrBer@@@Z @ 7 NONAME ; public: void __thiscall CCrBerSet::AppendAndUpdateL(class CCrBer *)
+	?BufferL@CCrBer@@SAHPAVHBufC16@@PAVCCrData@@IE@Z @ 8 NONAME ; public: static int __cdecl CCrBer::BufferL(class HBufC16 *,class CCrData *,unsigned int,unsigned char)
+	?BufferL@CCrBer@@SAHPAVHBufC8@@PAVCCrData@@II@Z @ 9 NONAME ; public: static int __cdecl CCrBer::BufferL(class HBufC8 *,class CCrData *,unsigned int,unsigned int)
+	?Close@CCrData@@QAEXXZ @ 10 NONAME ; public: void __thiscall CCrData::Close(void)
+	?CloseLastSeqOrSet@CCrBerSet@@QAEXI@Z @ 11 NONAME ; public: void __thiscall CCrBerSet::CloseLastSeqOrSet(unsigned int)
+	?Content@CCrBer@@QAEHPAVHBufC8@@@Z @ 12 NONAME ; public: int __thiscall CCrBer::Content(class HBufC8 *)
+	?ContentBegin@CCrBer@@QAEHXZ @ 13 NONAME ; public: int __thiscall CCrBer::ContentBegin(void)
+	?ContentL@CCrBer@@QAEHPAVHBufC16@@@Z @ 14 NONAME ; public: int __thiscall CCrBer::ContentL(class HBufC16 *)
+	?ContentLen@CCrBer@@QAEHXZ @ 15 NONAME ; public: int __thiscall CCrBer::ContentLen(void)
+	?CreateBEREncodedObjectL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 16 NONAME ; public: void __thiscall CCrBerSet::CreateBEREncodedObjectL(class TDesC8 &)
+	?CreateBoolL@CCrBerSet@@QAEXH@Z @ 17 NONAME ; public: void __thiscall CCrBerSet::CreateBoolL(int)
+	?CreateConstructedStartL@CCrBerSet@@QAEXEH@Z @ 18 NONAME ; public: void __thiscall CCrBerSet::CreateConstructedStartL(unsigned char,int)
+	?CreateEndL@CCrBerSet@@QAEXXZ @ 19 NONAME ; public: void __thiscall CCrBerSet::CreateEndL(void)
+	?CreateGenTimeL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 20 NONAME ; public: void __thiscall CCrBerSet::CreateGenTimeL(class TDesC8 &)
+	?CreateGeneralL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 21 NONAME ; public: void __thiscall CCrBerSet::CreateGeneralL(class TDesC8 &)
+	?CreateGraphicalL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 22 NONAME ; public: void __thiscall CCrBerSet::CreateGraphicalL(class TDesC8 &)
+	?CreateIA5L@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 23 NONAME ; public: void __thiscall CCrBerSet::CreateIA5L(class TDesC8 &)
+	?CreateIntL@CCrBerSet@@QAEXH@Z @ 24 NONAME ; public: void __thiscall CCrBerSet::CreateIntL(int)
+	?CreateLongIntL@CCrBerSet@@QAEXAAVRInteger@@@Z @ 25 NONAME ; public: void __thiscall CCrBerSet::CreateLongIntL(class RInteger &)
+	?CreateNullL@CCrBerSet@@QAEXXZ @ 26 NONAME ; public: void __thiscall CCrBerSet::CreateNullL(void)
+	?CreateNumericL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 27 NONAME ; public: void __thiscall CCrBerSet::CreateNumericL(class TDesC8 &)
+	?CreateOIdL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 28 NONAME ; public: void __thiscall CCrBerSet::CreateOIdL(class TDesC8 &)
+	?CreateOctetL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 29 NONAME ; public: void __thiscall CCrBerSet::CreateOctetL(class TDesC8 &)
+	?CreateOctetL@CCrBerSet@@QAEXPAVCCrData@@@Z @ 30 NONAME ; public: void __thiscall CCrBerSet::CreateOctetL(class CCrData *)
+	?CreatePrintableL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 31 NONAME ; public: void __thiscall CCrBerSet::CreatePrintableL(class TDesC8 &)
+	?CreateSeqStartL@CCrBerSet@@QAEXH@Z @ 32 NONAME ; public: void __thiscall CCrBerSet::CreateSeqStartL(int)
+	?CreateSetStartL@CCrBerSet@@QAEXH@Z @ 33 NONAME ; public: void __thiscall CCrBerSet::CreateSetStartL(int)
+	?CreateT61L@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 34 NONAME ; public: void __thiscall CCrBerSet::CreateT61L(class TDesC8 &)
+	?CreateUTCL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 35 NONAME ; public: void __thiscall CCrBerSet::CreateUTCL(class TDesC8 &)
+	?CreateVideoTexL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 36 NONAME ; public: void __thiscall CCrBerSet::CreateVideoTexL(class TDesC8 &)
+	?CreateVisibleL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 37 NONAME ; public: void __thiscall CCrBerSet::CreateVisibleL(class TDesC8 &)
+	?Data@CCrBer@@QAEPAVCCrData@@XZ @ 38 NONAME ; public: class CCrData * __thiscall CCrBer::Data(void)
+	?Delete@CCrData@@QAEHHH@Z @ 39 NONAME ; public: int __thiscall CCrData::Delete(int,int)
+	?FindEndOfContent@CCrBer@@QAEIPAVCCrData@@@Z @ 40 NONAME ; public: unsigned int __thiscall CCrBer::FindEndOfContent(class CCrData *)
+	?FlushL@CCrBerSet@@QAEHPAVCCrData@@@Z @ 41 NONAME ; public: int __thiscall CCrBerSet::FlushL(class CCrData *)
+	?GetBigInt@CCrBer@@QAE?AVRInteger@@XZ @ 42 NONAME ; public: class RInteger  __thiscall CCrBer::GetBigInt(void)
+	?GetBooleanL@CCrBer@@QAEHXZ @ 43 NONAME ; public: int __thiscall CCrBer::GetBooleanL(void)
+	?GetContentStringLC@CCrBer@@QAEPAVHBufC8@@XZ @ 44 NONAME ; public: class HBufC8 * __thiscall CCrBer::GetContentStringLC(void)
+	?GetGeneralStringL@CCrBer@@QAEPAVHBufC16@@XZ @ 45 NONAME ; public: class HBufC16 * __thiscall CCrBer::GetGeneralStringL(void)
+	?GetGeneralizedTimeL@CCrBer@@QAE?AVTTime@@XZ @ 46 NONAME ; public: class TTime  __thiscall CCrBer::GetGeneralizedTimeL(void)
+	?GetGraphicsStringL@CCrBer@@QAEPAVHBufC16@@XZ @ 47 NONAME ; public: class HBufC16 * __thiscall CCrBer::GetGraphicsStringL(void)
+	?GetIA5StringL@CCrBer@@QAEPAVHBufC16@@XZ @ 48 NONAME ; public: class HBufC16 * __thiscall CCrBer::GetIA5StringL(void)
+	?GetIntegerL@CCrBer@@QAEHXZ @ 49 NONAME ; public: int __thiscall CCrBer::GetIntegerL(void)
+	?GetLongIntegerL@CCrBer@@QAE?AVRInteger@@XZ @ 50 NONAME ; public: class RInteger  __thiscall CCrBer::GetLongIntegerL(void)
+	?GetNumericStringL@CCrBer@@QAEPAVHBufC16@@XZ @ 51 NONAME ; public: class HBufC16 * __thiscall CCrBer::GetNumericStringL(void)
+	?GetOctetStringL@CCrBer@@QAEPAVHBufC8@@XZ @ 52 NONAME ; public: class HBufC8 * __thiscall CCrBer::GetOctetStringL(void)
+	?GetOctetStringL@CCrBer@@QAEXAAVCCrData@@@Z @ 53 NONAME ; public: void __thiscall CCrBer::GetOctetStringL(class CCrData &)
+	?GetOidL@CCrBer@@QAEPAVHBufC16@@XZ @ 54 NONAME ; public: class HBufC16 * __thiscall CCrBer::GetOidL(void)
+	?GetPrintStringL@CCrBer@@QAEPAVHBufC16@@XZ @ 55 NONAME ; public: class HBufC16 * __thiscall CCrBer::GetPrintStringL(void)
+	?GetSequenceL@CCrBer@@QAEPAVHBufC8@@XZ @ 56 NONAME ; public: class HBufC8 * __thiscall CCrBer::GetSequenceL(void)
+	?GetTeletextStringL@CCrBer@@QAEPAVHBufC16@@XZ @ 57 NONAME ; public: class HBufC16 * __thiscall CCrBer::GetTeletextStringL(void)
+	?GetUTCTimeL@CCrBer@@QAE?AVTTime@@XZ @ 58 NONAME ; public: class TTime  __thiscall CCrBer::GetUTCTimeL(void)
+	?GetVideoStringL@CCrBer@@QAEPAVHBufC16@@XZ @ 59 NONAME ; public: class HBufC16 * __thiscall CCrBer::GetVideoStringL(void)
+	?GetVisibleStringL@CCrBer@@QAEPAVHBufC16@@XZ @ 60 NONAME ; public: class HBufC16 * __thiscall CCrBer::GetVisibleStringL(void)
+	?Indefinite@CCrBer@@QAEHXZ @ 61 NONAME ; public: int __thiscall CCrBer::Indefinite(void)
+	?IsFile@CCrData@@QAEHXZ @ 62 NONAME ; public: int __thiscall CCrData::IsFile(void)
+	?IsKnownType@CCrBer@@SAHE@Z @ 63 NONAME ; public: static int __cdecl CCrBer::IsKnownType(unsigned char)
+	?IsSeqOrSet@CCrBer@@SAHE@Z @ 64 NONAME ; public: static int __cdecl CCrBer::IsSeqOrSet(unsigned char)
+	?LenLen@CCrBer@@QAEHXZ @ 65 NONAME ; public: int __thiscall CCrBer::LenLen(void)
+	?Level@CCrBer@@QAEIXZ @ 66 NONAME ; public: unsigned int __thiscall CCrBer::Level(void)
+	?LineL@CCrData@@QAEHAAVTDes8@@@Z @ 67 NONAME ; public: int __thiscall CCrData::LineL(class TDes8 &)
+	?NewL@CCrBer@@SAPAV1@H@Z @ 68 NONAME ; public: static class CCrBer * __cdecl CCrBer::NewL(int)
+	?NewL@CCrBerSet@@SAPAV1@H@Z @ 69 NONAME ; public: static class CCrBerSet * __cdecl CCrBerSet::NewL(int)
+	?NewL@CCrData@@SAPAV1@H@Z @ 70 NONAME ; public: static class CCrData * __cdecl CCrData::NewL(int)
+	?NewL@CCrDataSet@@SAPAV1@H@Z @ 71 NONAME ; public: static class CCrDataSet * __cdecl CCrDataSet::NewL(int)
+	?NewLC@CCrBer@@SAPAV1@H@Z @ 72 NONAME ; public: static class CCrBer * __cdecl CCrBer::NewLC(int)
+	?NewLC@CCrBerSet@@SAPAV1@H@Z @ 73 NONAME ; public: static class CCrBerSet * __cdecl CCrBerSet::NewLC(int)
+	?NewLC@CCrData@@SAPAV1@H@Z @ 74 NONAME ; public: static class CCrData * __cdecl CCrData::NewLC(int)
+	?NewLC@CCrDataSet@@SAPAV1@H@Z @ 75 NONAME ; public: static class CCrDataSet * __cdecl CCrDataSet::NewLC(int)
+	?Object@CCrBer@@QAEHPAVHBufC8@@@Z @ 76 NONAME ; public: int __thiscall CCrBer::Object(class HBufC8 *)
+	?ObjectBegin@CCrBer@@QAEHXZ @ 77 NONAME ; public: int __thiscall CCrBer::ObjectBegin(void)
+	?ObjectL@CCrBer@@QAEHPAVHBufC16@@@Z @ 78 NONAME ; public: int __thiscall CCrBer::ObjectL(class HBufC16 *)
+	?ObjectLen@CCrBer@@QAEHXZ @ 79 NONAME ; public: int __thiscall CCrBer::ObjectLen(void)
+	?Open@CCrData@@QAEHAAVRFs@@ABVTDesC16@@I@Z @ 80 NONAME ; public: int __thiscall CCrData::Open(class RFs &,class TDesC16 const &,unsigned int)
+	?Open@CCrData@@QAEHAAVRFs@@I@Z @ 81 NONAME ; public: int __thiscall CCrData::Open(class RFs &,unsigned int)
+	?OpenConstructedEncodingL@CCrBer@@QAEHAAVCCrData@@@Z @ 82 NONAME ; public: int __thiscall CCrBer::OpenConstructedEncodingL(class CCrData &)
+	?OpenConstructedEncodingWithTagL@CCrBer@@QAEIPAVCCrData@@AAV1@PAVHBufC8@@@Z @ 83 NONAME ; public: unsigned int __thiscall CCrBer::OpenConstructedEncodingWithTagL(class CCrData *,class CCrBer &,class HBufC8 *)
+	?OpenL@CCrBerSet@@QAEIPAVCCrData@@E@Z @ 84 NONAME ; public: unsigned int __thiscall CCrBerSet::OpenL(class CCrData *,unsigned char)
+	?Path@CCrData@@QAEPAVHBufC16@@XZ @ 85 NONAME ; public: class HBufC16 * __thiscall CCrData::Path(void)
+	?Read@CCrBer@@QAEEPAVCCrData@@@Z @ 86 NONAME ; public: unsigned char __thiscall CCrBer::Read(class CCrData *)
+	?Read@CCrData@@QAEHAAVTDes8@@@Z @ 87 NONAME ; public: int __thiscall CCrData::Read(class TDes8 &)
+	?Read@CCrData@@QAEHAAVTDes8@@H@Z @ 88 NONAME ; public: int __thiscall CCrData::Read(class TDes8 &,int)
+	?Read@CCrData@@QAEHHAAVTDes8@@H@Z @ 89 NONAME ; public: int __thiscall CCrData::Read(int,class TDes8 &,int)
+	?ReadLen@CCrBer@@QAEIPAVCCrData@@AAHPAE@Z @ 90 NONAME ; public: unsigned int __thiscall CCrBer::ReadLen(class CCrData *,int &,unsigned char *)
+	?ReadType@CCrBer@@SAEPAVCCrData@@@Z @ 91 NONAME ; public: static unsigned char __cdecl CCrBer::ReadType(class CCrData *)
+	?Replace@CCrData@@QAEHAAVRFs@@ABVTDesC16@@I@Z @ 92 NONAME ; public: int __thiscall CCrData::Replace(class RFs &,class TDesC16 const &,unsigned int)
+	?Seek@CCrData@@QAEHW4TSeek@@AAH@Z @ 93 NONAME ; public: int __thiscall CCrData::Seek(enum TSeek,int &)
+	?SetLevel@CCrBer@@QAEII@Z @ 94 NONAME ; public: unsigned int __thiscall CCrBer::SetLevel(unsigned int)
+	?SetObjLenWithOutContent@CCrBer@@QAEXI@Z @ 95 NONAME ; public: void __thiscall CCrBer::SetObjLenWithOutContent(unsigned int)
+	?SetObjectLen@CCrBer@@QAEXXZ @ 96 NONAME ; public: void __thiscall CCrBer::SetObjectLen(void)
+	?SetPathL@CCrData@@QAEXABVTDesC16@@@Z @ 97 NONAME ; public: void __thiscall CCrData::SetPathL(class TDesC16 const &)
+	?SetValue@CCrBer@@QAEXH@Z @ 98 NONAME ; public: void __thiscall CCrBer::SetValue(int)
+	?Size@CCrData@@QAEHAAH@Z @ 99 NONAME ; public: int __thiscall CCrData::Size(int &)
+	?Type@CCrBer@@QAEEXZ @ 100 NONAME ; public: unsigned char __thiscall CCrBer::Type(void)
+	?Update@CCrBerSet@@QAEXPAVCCrBer@@@Z @ 101 NONAME ; public: void __thiscall CCrBerSet::Update(class CCrBer *)
+	?Value@CCrBer@@QAEHXZ @ 102 NONAME ; public: int __thiscall CCrBer::Value(void)
+	?ValuePtr@CCrBer@@QAEPAVTDesC8@@XZ @ 103 NONAME ; public: class TDesC8 * __thiscall CCrBer::ValuePtr(void)
+	?Write@CCrData@@QAEHABVTDesC8@@@Z @ 104 NONAME ; public: int __thiscall CCrData::Write(class TDesC8 const &)
+	?Write@CCrData@@QAEHABVTDesC8@@H@Z @ 105 NONAME ; public: int __thiscall CCrData::Write(class TDesC8 const &,int)
+	?Zero@CCrData@@QAEHHH@Z @ 106 NONAME ; public: int __thiscall CCrData::Zero(int,int)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrBer/Inc/crber.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,598 @@
+/*
+* Copyright (c) 2000, 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:    This file contains the headers of CCrBer and CCrBerSet classes.
+*                 These classes are used to encode and decode BER object(s).
+*
+*/
+
+
+
+#ifndef CR_BER
+#define CR_BER
+
+//  INCLUDES
+#include <e32base.h>        // CBase
+#include <asn1dec.h>       // ASN1 (Symbian)
+#include "crdata.h"         // CCrData
+#include "crdefs.h"         // Definitions
+
+#include <bigint.h>
+
+//  MACROS
+#define LEN_BYTES_MAX    4  // Max amount of length bytes in BER encoded
+                            // object. Probably this never changes, but
+                            // you'll never know.
+//  DATA TYPES
+typedef TUint8 TBerTag;
+
+//  CONSTANTS  
+//////////////////////////////////////////////////////////////////////////
+// BER types.
+const TBerTag KBerEndOfContent  = 0x00;     // End of contents tag
+const TBerTag KBerBoolean       = 0x01;     // Boolean tag
+const TBerTag KBerInteger       = 0x02;     // Integer tag
+const TBerTag KBerBitString     = 0x03;     // Bit string tag
+const TBerTag KBerOctetString   = 0x04;     // Octet string tag
+const TBerTag KBerNull          = 0x05;     // NULL tag
+const TBerTag KBerOid           = 0x06;     // Object identifier tag
+const TBerTag KBerNumS          = 0x12;	    // Numeric string		
+const TBerTag KBerPrS           = 0x13;     // Printable string tag
+const TBerTag KBerT61S          = 0x14;     // T61 string tag
+const TBerTag KBerVideoS        = 0x15;	    // Video string tag				 
+const TBerTag KBerIA5S          = 0x16;     // IA5 string tag
+const TBerTag KBerUtc           = 0x17;     // UTC time tag
+const TBerTag KBerGenTime       = 0x18;	    // Generalized Time tag					
+const TBerTag KBerGraphS        = 0x19;	    // Graphics string tag			
+const TBerTag KBerVisibleS      = 0x1A;     // Visible string					
+const TBerTag KBerGeneralS      = 0x1B;     // Generalised string	
+const TBerTag KBerBmpS          = 0x1E;     // Bmp string
+const TBerTag KBerSeq           = 0x30;     // Sequence tag
+const TBerTag KBerSet           = 0x31;     // Set tag
+
+const TBerTag KBerUnknown       = 0xff;     // Unknown tag
+
+const TBerTag KBerEncodedObject = 0xfe;     // Tag for ready-made
+                                            // BER encoded objects
+
+const TBerTag KBerLongLengthBit = 0x80;     // Long length bit
+const TBerTag KBerConstructedBit= 0x20;     // Constructed bit
+const TBerTag KBerConstructed   = 0x20;
+
+const TBerTag KBerImplicit = 0x80;   // Implicit tag
+const TBerTag KBerExplicit = 0x80;   // Explicit tag
+
+const TBerTag KBerImplicitConstructed = 0xA0;   // Implicit constructed tag
+const TBerTag KBerExplicitConstructed = 0xA0;   // Explicit constructed tag
+
+const TBerTag KBerBooleanTrue   = 0xFF;     // Boolean true value   (DER)
+const TBerTag KBerBooleanFalse  = 0x00;     // Boolean false value  (DER)
+const TBerTag KBerNullContent   = 0x00;     // Null objects content
+
+const TBerTag KBerBooleanLen    = 0x03;     // Boolean object length
+const TBerTag KBerNullLen       = 0x02;     // Null object length
+const TBerTag KBerShortLen      = 0x02;     // Tag + (short) length byte
+const TBerTag KBerIndefiniteLen = 0x04;     // Indefinite length (xx 80 00 00)
+
+const TInt KReadBufMax          = 256;      // Length of buffer used
+								            // when reading from files.
+const TUint KOpenAllLevels      = 255;      // OpenL(....) function
+const TInt KOctetWidth          = 8;        
+const TInt KObjectIDDot         = 1;        // object id encoding
+const TInt KObjectIDFirstFactor = 4;        // object id encoding
+const TInt KObjectIDSecondFactor = 10;      // object id encoding
+
+const TInt KIntBufSize          = 6;        // Integer encoding buffer size 
+
+// CLASS DECLARATION
+
+/**
+*  Class CCrBer is able to contain a BER encoded object of any type.
+*
+*  @lib crber.lib
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CCrBer ): public CBase
+    {
+    /////////////////////////////////////////////
+    // Constructors and destructors.
+    private:
+        CCrBer(TInt aLevel = 0);
+        
+        TAny ConstructL();
+        
+    public:
+        IMPORT_C static CCrBer* NewLC(TInt aLevel = 0); 
+        IMPORT_C static CCrBer* NewL(TInt aLevel = 0);
+        IMPORT_C ~CCrBer();
+
+
+        /////////////////////////////////////////////
+        // Functions to open BER object.
+
+        /**
+        * Read next BER encoded object from the current position of
+        * given CCrData to this object. Return the type of the BER
+        * object, or KBerUnknown, if not of any known type. Only pointer
+        * to aData is stored into this object, so Get* functions are
+        * meaningful only if original data object is still existing,
+        * when these functions are used.
+        */
+        IMPORT_C TBerTag Read(CCrData* aData);
+
+        /**
+        * Read type tag from current position in given CCrData.
+        * Returns type tag or KBerUnknown, if not of any known type.
+        */
+        IMPORT_C static TBerTag ReadType(CCrData* aData);
+
+        /**
+        * Read length tags from current position in given CCrData.
+        * Returns length. If length is indefinite, aIndefinite is set
+        * to true, otherwise to false. In indefinite case length is 0.
+        * Also sets amount of length bytes in aLenLen, if given.
+        */
+        IMPORT_C TUint ReadLen(
+            CCrData* aData,
+            TBool&   aIndefinite,
+            TUint8*  aLenLen = 0);
+
+        /**
+        * Returns true if given BER tag is identified one.
+        */
+        IMPORT_C static TBool IsKnownType(TBerTag aTag);
+
+        /**
+        * Returns true if given BER tag is sequence, set,
+        * implicit contructed, or explicit constructed tag.
+        */
+        IMPORT_C static TBool IsSeqOrSet(TBerTag aTag);
+        
+        /**
+        * Finds next end-of-content (00 00) tag from given data.
+        * Returns the distance between current place and the tag,
+        * or 0, if not found. Moves data pointer to the next byte
+        * _after_ the tag, i.e. two bytes longer than you might
+        * except from the return value.
+        */
+        IMPORT_C TUint FindEndOfContent(CCrData* aData);
+
+        /**
+        * Open constructed encoding from this object.  
+        * Parameters: aTarget; target for contentbytes.
+        * Return Values:  Number of objects. 
+        */
+        IMPORT_C TInt OpenConstructedEncodingL(CCrData& aTarget);
+
+        IMPORT_C TUint OpenConstructedEncodingWithTagL(
+            CCrData* aData,
+            CCrBer&  parentObj,
+            HBufC8*  buf = 0);
+
+        /////////////////////////////////////////////
+        // Functions to get info about this BER object.
+			
+        // Return type of the object.
+        IMPORT_C TBerTag Type();
+    
+        // Return value of the object (int or boolean object).
+        // Only to encoding..
+        IMPORT_C TInt Value();
+        IMPORT_C RInteger GetBigInt();
+        IMPORT_C TDesC8* ValuePtr();
+        IMPORT_C TAny SetValue(TInt aInt);
+
+        // Return amount of length bytes.
+        IMPORT_C TInt LenLen();
+
+        // Return begin of the whole object.
+        IMPORT_C TInt ObjectBegin();
+
+        // Return begin of the content.
+        IMPORT_C TInt ContentBegin();
+
+        // Return length of the content.
+        IMPORT_C TInt ContentLen();
+
+        // Return length of the whole object.
+        IMPORT_C TInt ObjectLen();
+
+        // Return true if this object is indefinite length, else false.
+        IMPORT_C TBool Indefinite();
+
+        // Return pointer to data object.
+        IMPORT_C CCrData* Data();
+
+        // Return whole BER object with tag and stuff. For implementation
+        // reasons ObjectL returns only max 255 bytes of data.
+
+        IMPORT_C TInt Object(HBufC8* aBuf);
+        IMPORT_C TInt ObjectL(HBufC* aBuf);
+
+        // Return content of this object. For implementation reasons
+        // ContentL returns only max 255 bytes of data.
+        IMPORT_C TInt Content(HBufC8* aBuf);
+        IMPORT_C TInt ContentL(HBufC* aBuf);
+
+        // Read aAmount of data starting from begin to the buffer.
+        // Return amount of data read. For implementation reasons
+        // BufferL can be used only to read max 255 bytes of data.
+        static IMPORT_C TInt BufferL(
+            HBufC8*   aBuf,
+            CCrData*  aData,
+            TUint     aBegin = 0,
+            TUint     aAmount = KReadBufMax);
+        static IMPORT_C TInt BufferL(
+            HBufC*    aBuf,
+            CCrData*  aData,
+            TUint     aBegin = 0,
+            TUint8    aAmount = 255);
+
+        // Return nesting level of this object.
+        IMPORT_C TUint Level();
+
+        // Set nesting level of this object.
+        IMPORT_C TUint SetLevel(TUint aLevel);
+      
+        ///////////////////////////////////////////
+        // Get content 
+
+        // Return value of integer object.
+        // e.g. 21
+		IMPORT_C TInt GetIntegerL();
+		IMPORT_C RInteger GetLongIntegerL();
+
+        // Return value of boolean object.
+        // e.g. ETrue
+        IMPORT_C TBool GetBooleanL();
+
+		// Return content of object identifier object.
+        // e.g. 1.2.3.4.5
+        IMPORT_C HBufC* GetOidL();
+		
+        // Return content of octet string object.
+        // e.g. 45 53 65 77 
+        IMPORT_C HBufC8* GetOctetStringL();
+        IMPORT_C TAny GetOctetStringL(CCrData& Trg);
+
+        // Return content of content string object.
+        IMPORT_C HBufC8* GetContentStringLC();
+		
+        // Return content of IA5 string object.
+        // e.g. "hello"
+        IMPORT_C HBufC* GetIA5StringL();
+		
+        // Return content of UTC time object.
+        IMPORT_C TTime GetUTCTimeL();
+		
+        // Return content of printable string object.
+        // e.g. "hello"
+        IMPORT_C HBufC* GetPrintStringL();
+		
+        // Return content of teletext string object.
+        IMPORT_C HBufC* GetTeletextStringL();
+		
+        // Return content of sequence object.
+        // e.g. 02 01 01 01 01 FF 
+        IMPORT_C HBufC8* GetSequenceL();
+		
+        // Return content of videotext string object.
+        IMPORT_C HBufC* GetVideoStringL();
+		
+        // Return content of generalised string object.
+        IMPORT_C HBufC* GetGeneralStringL();
+		
+        // Return content of visible characters string object.
+        IMPORT_C HBufC* GetVisibleStringL();
+		
+        // Return content of a generalised graphical string obj.
+        IMPORT_C HBufC* GetGraphicsStringL();
+		
+        // Basically, TIME+ century
+        // Return content of a generalized time string obj.
+        IMPORT_C TTime GetGeneralizedTimeL();
+		
+        // Return content of numeric string object
+        // only for numbers. 
+        IMPORT_C HBufC* GetNumericStringL();
+
+
+        /////////////////////////////////////////////
+        // Functions to modify info about this BER object.
+
+        // Add given integer to content length of this object.
+        IMPORT_C TAny AddToContentLen(TInt iLen);
+
+        // Calculate object length from tag, length's length, and
+        // content's length. Used to 'close' indefinite objects, meaning
+        // that their end-of-contents tag is finally found, so their
+        // length can be calculated.
+        IMPORT_C TAny SetObjectLen();
+
+        // Set object length to object length - content length. = Length of tag 
+        // and lenbits (+lenlen).
+        IMPORT_C TAny SetObjLenWithOutContent(TUint aContentLen);        
+    
+    public:
+        // Encoding
+        // These functions are used by CCrBerSet::Create*
+        // Save type,length and value. 
+        TAny CreateBool(TBool aBool);
+        // Save type,length and value.
+        TAny CreateInt(TInt aInt);
+        TAny CreateLongInt(RInteger& aData);
+        // Save type and value of object.
+        TAny CreateNull();
+        // Save type, length and pointer to string
+        TAny CreateOIdL(TDesC8* aString);
+        TAny CreateString(TBerTag aTag, TDesC8* aString);
+        TAny CreateString(TBerTag aTag, CCrData* aData);
+
+        // Save tag and value of constructed type.
+        TAny CreateStart(TBerTag aTag, TBool aDefinite);
+        // Save type.
+        TAny CreateEnd();
+
+        // This fuction can be used to create a BER object
+        // from buffer, which already contains a full BER
+        // encoded object.
+        TAny CreateBEREncodedObject(TDesC8* aBuffer);
+        
+        
+    public: // Data.
+        // Maximum sixe of TUint.
+        // static TUint iMaxUint;
+        TUint iMaxUint;
+
+        // Maximum sixe of TInt.
+        //static TInt iMaxInt;
+        TInt iMaxInt;
+
+    private: // Data
+        // Type.
+        TBerTag iType;
+
+        // iValue is used in encoding
+        TInt iValue;
+        // Pointer to value (encoding).
+        TDesC8* iValuePtr;
+        RInteger iInt;
+
+        // Amount of length bytes.
+        TUint8 iLenLen;
+
+        // Indefinite length or not.
+        TBool iIndefinite;
+
+        // These indexes indicate places in the CCrData
+        // object pointed by the member iData.
+        TUint iObjectBegin;     // Place where whole BER object begins.
+        TUint iContentBegin;    // Place where BER object's content begins.
+        TUint iContentLen;      // Length of the BER object's content.
+        TUint iObjectLen;       // Length of the whole BER object.
+
+        // Pointer to the object containing the actual object.
+		CCrData* iData;
+		
+
+        // Nesting level of this object. Not set in this object,
+        // but given by caller.
+        TInt iLevel;
+
+        // End of content bytes.
+        // static TUint8 iEOCBytes[2];
+        TUint8 iEOCBytes[2];
+
+    };
+
+/**
+*  Class CCrBerSet 
+*  CCrBerSet contains set of CCrBer objects.
+*
+*  @lib crber.lib
+*  @since Series 60 3.0
+*/
+class CCrBerSet : public CArrayPtrSeg<CCrBer>
+    {
+    /////////////////////////////////////////////
+    // Constructors and destructors.
+    private:
+        CCrBerSet(TInt aGranularity); 
+        TAny ConstructL();
+         
+        
+    public:
+        IMPORT_C static CCrBerSet* NewLC(TInt aGranularity);
+        IMPORT_C static CCrBerSet* NewL(TInt aGranularity);
+        IMPORT_C ~CCrBerSet();
+
+       
+    /////////////////////////////////////////////
+    // Functions.
+        
+        // Opens next BER encoded object from the current position of
+        // given CCrData to this object set. Opens also all nested BER
+        // objects as deep as aRecursionLevel tells. If it is zero, one
+        // object is read, if it is one, all objects at first level are
+        // read, if it is 255, all objects at 255 first levels are
+        // extracted, and if it is 256, all objects at any level are
+        // extracted. Returns the amount of extracted objects.
+        // The data pointer of CCrData points right after the
+        // opened BER object after this function is finished.
+        IMPORT_C TUint OpenL(
+            CCrData* aData,
+            TUint8   aRecursionLevel = 1);
+
+        // Appends given new object into this set. Updates all previous
+        // items in this set, which have indefinite length, with the
+        // length of the new object.
+        IMPORT_C TAny AppendAndUpdateL(CCrBer *aBerObject);
+
+        // Updates all previous items in this set, which have
+        // indefinite length, with the length of the new object.
+        IMPORT_C TAny Update(CCrBer *aBerObject);
+
+        // Finds last open indefinite length sequence
+        // or set from this set at given level and closes it.
+        IMPORT_C TAny CloseLastSeqOrSet(TUint aLevel);
+        
+
+    ////////////////////////////////////////////
+    // Encoding functions
+
+        // Function creates Ber boolean object (CCrBer object).
+        // Write a object to CCrData (file) by Flush(..)  
+        // (ETrue or EFalse) (Tag 01)
+        IMPORT_C TAny CreateBoolL(TBool aValue);
+
+        //   Function creates Ber integer object (CCrBer object).
+        // Write a object to CCrData (file) by Flush(..)  Parameter is either
+        // a positive whole number, or a negative whole number, or zero.
+        IMPORT_C TAny CreateIntL(TInt aValue);
+        IMPORT_C TAny CreateLongIntL(RInteger& aValue);
+
+        // Function creates Ber octet string object.
+        // The OCTET STRING  is an arbitrarily long binary value.
+        IMPORT_C TAny CreateOctetL(TDesC8& aString);
+        IMPORT_C TAny CreateOctetL(CCrData* aData);
+
+
+        // Function creates Ber null object (CCrBer object).
+        // (0x05 0x00).
+        IMPORT_C TAny CreateNullL();
+
+        // Function creates Ber object identifier object.
+        // type tag = (0x06)
+        // e.g. berSet->AppendObjectId(_L8("1.2.3.4.5")
+        IMPORT_C TAny CreateOIdL(TDesC8& aString);
+
+        // Function creates Ber Numeric string object (CCrBer object).
+        // The NumericString is defined to only contain the characters 0-9 
+        // and space. 
+        IMPORT_C TAny CreateNumericL(TDesC8& aString);
+
+        // Function creates Ber Printable string object (CCrBer object)
+        // The PrintableString is defined to only contain
+        // the characters A-Z, a-z, 0-9, space,
+        // and the punctuation characters ()-+=:',./?.
+        IMPORT_C TAny CreatePrintableL(TDesC8& aString);
+
+        // Function creates Ber T61 string object (CCrBer object).
+        // The TeletexString is a string, containing characters
+        // according to the T.61 character set. 
+        IMPORT_C TAny CreateT61L(TDesC8& aString);
+
+        // Function creates Ber Video text object (CCrBer object) 
+        // type tag = (0x15). 
+        IMPORT_C TAny CreateVideoTexL(TDesC8& aString);
+
+        // Function creates Ber IA5 string object (CCrBer object).
+        // IA5 (International Alphabet 5)
+        // is equivalent to US-ASCII.
+        IMPORT_C TAny CreateIA5L(TDesC8& aString);
+
+        // Function creates Ber UTC time object (CCrBer object).
+        // Note this value only represents years using two digits.
+        // e.g. berSet->AppendUTCTime(_L8("980801000000Z"));
+        IMPORT_C TAny CreateUTCL(TDesC8& aString);
+
+        // Function creates Ber generalised time object 
+        // (CCrBer object). type = (0x18). Unlike UTCTime
+        // it represents years using 4 digits.
+        IMPORT_C TAny CreateGenTimeL(TDesC8& aString);
+
+        // Function creates Ber graphical string object (CCrBer object)
+        // type byte = (0x19).
+        IMPORT_C TAny CreateGraphicalL(TDesC8& aString);
+
+        // Function creates Ber visible string object (CCrBer object)
+        // type = (0x1A).
+        IMPORT_C TAny CreateVisibleL(TDesC8& aString);
+
+        // Function creates Ber general string object (CCrBer object)
+        // type = (0x1B).       
+        IMPORT_C TAny CreateGeneralL(TDesC8& aString);
+
+        // Append start of sequence (30 xx, xx = length)
+        // True --> DefiniteLen, False --> IndefiniteLength. 
+        IMPORT_C TAny CreateSeqStartL(TBool aDefinite);
+
+        // Append start of set (31 xx, xx = length)
+        // True --> DefiniteLen, False --> IndefiniteLength. 
+        IMPORT_C TAny CreateSetStartL(TBool aDefinite);
+
+        // Append start of the constructed.
+        IMPORT_C TAny CreateConstructedStartL(TBerTag aTag, TBool aDefinite);
+
+        // Append end to last constructed (e.g. seq)
+        // type (definite or indefinite).
+        IMPORT_C TAny CreateEndL();
+
+        // This fuction can be used to create a BER object
+        // from buffer, which already contains a full BER
+        // encoded object.
+        IMPORT_C TAny CreateBEREncodedObjectL(TDesC8& aBuffer);
+
+        // Function writes all created crber objects (which are 
+        // AppendL to set) to file. Function also fix all definite
+        // lengths. Call this function then crberSet is ready 
+        // (all berObjects are delived).
+        IMPORT_C TInt FlushL(CCrData* aTarget);
+
+    public:
+
+        // Encode and write object identifier.
+        TInt AppendObjectIdL(const TDesC8& aString,TBool aOnlyLen = EFalse);
+
+    private:
+        // These functions are used by CCrBerSet::Flush(...)
+
+        // Write constructed type start.
+        TInt AppendConstructedL(TBerTag aTag, TUint aLength = 0);
+        
+        // close indefinite length. (= add 0x00 0x00) 
+        TInt CloseIndefinite(); 
+        
+        // Encode and write boolean object. 
+        TInt AppendBoolL(TBool aBool);   
+        
+        // Encode and write integer object.
+        TInt AppendIntL(TInt aData); 
+        TInt AppendLongIntL(RInteger& aData);
+        
+        // Encode and write null object. (0x05 0x00)
+        TInt AppendNull();
+        
+        // Encode and write string to CCrData (file).
+        TInt AppendStringL(TBerTag aTag, const TDesC8& aString);
+        TInt AppendStringL(TBerTag aTag, CCrData* const aData);
+
+        // Write BER encoded object to CCrData (file).
+        // Note that this function doesn't add any tags
+        // etc. it trusts that the given object already
+        // is a whole BER encoded object.
+        TInt AppendBerEncodedObject(const TDesC8& aString);    
+        
+    private: // Data
+
+        // Target file for objects (encoding). 
+        CCrData* iTarget;
+        
+        // Nesting level of object. (encoding).
+        TInt iLevel;
+        
+        // Max level which is used in encoding. (Flush(..))
+        TInt iMaxLevel;
+    };
+
+#endif CR_BER
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrBer/Inc/crdata.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,169 @@
+/*
+* Copyright (c) 2000, 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This file contains the header of CCrData class.
+*
+*/
+
+
+
+#ifndef CR_DATA
+#define CR_DATA
+
+
+//  INCLUDES
+
+#include <e32base.h>    // CArrayFixFlat
+#include <f32file.h>    // RFile
+
+#include "crdefs.h"     // Defines
+
+//  CONSTANTS         
+
+ _LIT8(KNewLine,"\r\n"); // New line for LineL method 
+
+// CLASS DECLARATION
+
+/**
+*  CCrData
+*  CCrData class handles file and stream I/O.
+*
+*  @lib crber.lib
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CCrData ): public CBase
+    {
+    /////////////////////////////////////////////
+    // Constructors and destructors.
+    public:
+        IMPORT_C CCrData();
+        // aIsFile set CCrData object either file (True) or buffer (False)
+        IMPORT_C CCrData(TBool aIsFile);            // EFalse for a buffer
+        IMPORT_C ~CCrData();
+        
+        TAny ConstructL();
+
+        IMPORT_C static CCrData* NewLC(TBool aIsFile = ETrue); 
+        IMPORT_C static CCrData* NewL(TBool aIsfile = ETrue);
+        
+    public: // Functions.
+
+        // Opens an existing file for reading or writing. If the file 
+        // does not already exist, an error is returned.
+        IMPORT_C TInt Open(RFs& aFs,const TDesC& aName,TUint aFileMode);
+        IMPORT_C TInt Open(RFs& aFs,TUint aFileMode);
+
+        // Replaces a file. If there is an existing file with the same
+        // name, this function will overwrite it. If the file does not 
+        // already exist, this function creates it.
+        IMPORT_C TInt Replace(RFs& aFs,const TDesC& aName,TUint aFileMode);
+
+        // Closes the file. Any open files are closed when the file server 
+        // session is closed. Close() is guaranteed to return, and provides 
+        // no indication of whether it completed successfully or not. When 
+        // closing a file that you have written to, you should ensure that
+        // data is committed to the file by invoking RFile::Flush() before 
+        // closing. If Flush() completes successfully, Close() is essentially 
+        // a no-operation.
+        IMPORT_C void Close();
+
+
+        // Reading transfers data from a file (or a buffer) to a descriptor.
+        // Íf CCrData object is created to be a file function only call 
+        // RFile::Read(.), but if CCrData is buffer, function makes same
+        // things to buffer as RFile::Read make to file.
+        // See EPOC documentation to get more information.
+        IMPORT_C TInt Read(TDes8& aDes);
+        IMPORT_C TInt Read(TDes8& aDes,TInt aLength);
+        IMPORT_C TInt Read(TInt aPos,TDes8& aDes,TInt aLength);
+
+        // Writing transfers data from a descriptor to a file or to a buffer.
+        // If CCrData object is created to be a file function only call 
+        // RFile::Write(.), but if CCrData is buffer, function makes same
+        // things to buffer as RFile::Write make to file.
+        // aLength must be more than zero or error is returned.
+        // See EPOC documentation to get more information.
+        IMPORT_C TInt Write(const TDesC8& aDes);
+        IMPORT_C TInt Write(const TDesC8& aDes,TInt aLength);
+
+        // Use this function to change the current buffer (or file) position.
+        // It can also be used to retrieve the current buffer (or file)
+        // position without changing it (ESeekCurrent, 0).
+        // The buffer (or file) position is the position at which 
+        // buffer (file) reads and writes take place.
+        // The start of the buffer(file) is position zero.
+        // If CCrData object is created to be a file function only call 
+        // RFile::Seek(.), but if CCrData is buffer, function makes same
+        // things to buffer as RFile::Seek make to file.
+        // aPos must be positive or error is returned. 
+        // See EPOC documentation to get more information (about Seek).
+        IMPORT_C TInt Seek(TSeek aMode,TInt& aPos);
+
+        IMPORT_C TInt Size(TInt& aSize);
+
+        // LineL sets data from the current place, where iPointer is, till
+        // next new line character to aLine. 
+        // iPointer moves to the following item from the found new line 
+        // character. If no new line character is found, aLine is the rest
+        // of the data and iPointer is moved to the end of the iBuffer or 
+        // the iFile.
+
+        IMPORT_C TInt LineL(TDes8& aLine);
+        IMPORT_C HBufC* Path();
+        IMPORT_C TAny SetPathL(const TDesC& aPath);
+        IMPORT_C TBool IsFile();
+        IMPORT_C TInt Delete(TInt aPos,TInt aLength);
+
+		IMPORT_C TInt Zero(const TInt aPos, const TInt aLength);
+
+
+    private: // Data
+        // Variable set CCrData object either file(1) or buffer(0)
+        TBool iIsFile;
+        // Index to iBuffer
+        TInt  iPointer;
+        // Buffer for data
+        HBufC8* iBuffer;
+        // File for data
+        RFile iFile;
+        // path of file
+        HBufC* iPath;
+    };
+
+// CLASS DECLARATION
+
+/**
+*  CCrDataSet
+*  CCrDataSet class is used to handle multiple CCrData objects.
+*
+*  @lib crber.lib
+*  @since Series 60 3.0
+*/
+class CCrDataSet : public CArrayPtrSeg<CCrData>
+    {
+    /////////////////////////////////////////////
+    // Constructors and destructors.
+    private:
+        CCrDataSet(TInt aGranularity);
+        
+        TAny ConstructL();
+        
+    public:
+        IMPORT_C static CCrDataSet* NewLC(TInt aGranularity); 
+        IMPORT_C static CCrDataSet* NewL(TInt aGranularity);
+
+        ~CCrDataSet();
+
+    };
+
+#endif CR_DATA
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrBer/Src/Crberset.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1367 @@
+/*
+* Copyright (c) 2000, 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This module contains the implementation of CCrBerSet class. 
+*
+*/
+
+
+
+//  INCLUDE FILES
+
+#include "crber.h"
+
+
+// -----------------------------------------------------------------------------
+//CCrBerSet
+//Constructor
+// -----------------------------------------------------------------------------
+CCrBerSet::CCrBerSet(TInt aGranularity)
+    : CArrayPtrSeg<CCrBer>(aGranularity), iLevel(0)
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet
+// Destructor
+// This function destructs CCrBerSet object
+// -----------------------------------------------------------------------------
+CCrBerSet::~CCrBerSet()
+    {
+    ResetAndDestroy();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::ConstructL
+// This function initializes CCrBerSet object's member objects.
+// -----------------------------------------------------------------------------
+TAny CCrBerSet::ConstructL()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::NewLC
+// -----------------------------------------------------------------------------
+EXPORT_C CCrBerSet* CCrBerSet::NewLC(TInt aGranularity)
+    {
+    CCrBerSet* self = new (ELeave) CCrBerSet(aGranularity);
+    CleanupStack::PushL(self);
+
+    self->ConstructL();
+
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::NewL
+// -----------------------------------------------------------------------------
+EXPORT_C CCrBerSet* CCrBerSet::NewL(TInt aGranularity)
+    {
+    CCrBerSet* self = NewLC(aGranularity);
+    CleanupStack::Pop();
+
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::OpenL
+// 
+// Opens next BER encoded object from the current position of
+// given CCrData to this object set. Opens also all nested BER
+// objects as deep as aRecursionLevel tells. If it is zero, one
+// object is read, if it is one, all objects at first level are
+// read, and if it is 0xff, all objects at 255 first levels are
+// extracted. This function cannot be used to extract deeper
+// structures than that, if you want to go deeper, implement
+// a function of your own. Returns the amount of extracted
+// objects. The data pointer of CCrData points right after the
+// opened BER object after this function is finished.
+// Parameters: CCrData* aData    Data object containing the BER
+//                               object to be opened.
+// Returns:    TUint             Amount of BER objects extracted.
+// -----------------------------------------------------------------------------
+EXPORT_C TUint CCrBerSet::OpenL(
+    CCrData* aData,
+    TUint8   aRecursionLevel /* = 1 */)
+    {
+    TInt    i       = 0;
+    TUint   level   = 0;
+    TUint8  amount  = 0;
+    TInt definiteObjectEnd [255]= {0};
+    TBerTag  type    = KBerEndOfContent;
+    CCrBer* newObject = 0;
+
+    while (type != KBerUnknown)
+        {
+        // Don't create new object if old is to be recycled.
+        if (newObject == 0)
+            {
+            newObject = CCrBer::NewLC(level);
+            }
+
+        // Read next BER object.
+        if ((type = newObject->Read(aData)) != KBerUnknown)
+            {                   
+            i = 0;
+            // check definite seq(e.g) end, and if so, take away 1 level. 
+            while (definiteObjectEnd[i] != 0)
+                {
+                if ((definiteObjectEnd[i]  <= newObject->ObjectLen() 
+                    + newObject->ObjectBegin()) &&
+                    (definiteObjectEnd[i]) &&
+                   !(newObject->IsSeqOrSet(type)))                                    
+                    {                
+                    level--;                
+                    definiteObjectEnd[i] = 0;
+                    }
+                i++;
+                }
+            // If type is explicit or implicit constructed or sequence
+            // or set with indefinite length, we are one level deeper.
+            if (CCrBer::IsSeqOrSet(type))
+                 {
+                if (newObject->Indefinite())
+                    {
+                    level++;
+                    }
+                else 
+                    {               
+                    level++;
+                    i = 0;
+                    while (definiteObjectEnd[i] != 0)
+                        {
+                        i++;
+                        }
+                    definiteObjectEnd[i] = newObject->ObjectLen() 
+                        + newObject->ObjectBegin();                                      
+                    }
+				// Changed by junuutin on 3.5.2004:				
+				if ((type == KBerImplicit) || (type == KBerExplicit))
+					{
+						// Don't try to parse the content of context-specified stuff
+			            // Jump to next object.
+						TInt currentPos = 0;
+						aData->Seek(ESeekCurrent, currentPos);
+                        TInt pos = currentPos + newObject->ContentLen(); 
+                        aData->Seek(ESeekStart, pos);
+                        level--;
+					} 
+				else if ((type == KBerImplicitConstructed) || (type == KBerExplicitConstructed))
+                    {
+                     TInt currentPos = 0;
+                     aData->Seek(ESeekCurrent, currentPos);
+                     CCrBer* tempObject = CCrBer::NewL();
+                     
+                     // Read next BER object.
+                     TBerTag tempType = tempObject->Read(aData);
+                     if (!(CCrBer::IsKnownType(tempType)))
+                        {
+                        // Jump to next object.
+                        TInt pos = currentPos + newObject->ContentLen(); 
+                        aData->Seek(ESeekStart, pos);
+                        level--;
+
+                        }
+                     else // return current position.
+                         {
+                         aData->Seek(ESeekStart, currentPos);
+                         }
+
+                    delete tempObject;
+                    tempObject = NULL;
+                    } 
+                } 
+
+            // If type is end-of-content tag, last constructed object,
+            // sequence or set with indefinite length has ended, we
+            // are one level lower.
+            if (type == KBerEndOfContent)
+                {
+                level--;
+
+                // Also set new object's level to current,
+                // because that's where it actually belongs.
+                newObject->SetLevel(level);
+            
+            
+                // Close last sequence or set.
+                CloseLastSeqOrSet(level);
+                }
+
+            // If it is of known type, append object to this set,
+            // null the pointer and continue to look for next objects.
+            // Append only if wanted recursion level not exceeded.
+            if ((level <= aRecursionLevel) || (aRecursionLevel == 255))
+                {
+                AppendAndUpdateL(newObject);
+                CleanupStack::Pop(); //newObject
+                newObject = NULL;
+                }
+            else
+                {
+                // Anyway previous open objects have to be
+                // updated with the length of this object.
+                Update(newObject);
+                }
+
+            // Anyway we have one item more.
+            
+            amount++;
+            }
+        else
+            {
+            // Otherwise delete object and stop the whole thing.
+            // Don't return those bloody errors, because we cannot
+            // know what the caller was looking for, let him evaluate
+            // the results and decide whether this was a failure or not.
+            //delete newObject;
+            CleanupStack::PopAndDestroy();
+
+            // go to return 
+            type = KBerUnknown;         
+            }
+        }
+
+    return amount;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::AppendAndUpdateL
+// Appends given new object into this set. Updates all previous
+// items in this set, which have indefinite length, with the
+// length of the new object.
+// Parameters: CCrBer* aBerObject    New BER object to be added to this set
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::AppendAndUpdateL(CCrBer* aBerObject)
+    {
+    Update(aBerObject);
+
+    AppendL(aBerObject);
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::Update
+// Updates all previous items in this set, which have
+// indefinite length, with the length of the new object.
+// Parameters: CCrBer* aBerObject    New BER object with whom
+//                                   this set is updated.
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::Update(CCrBer* aBerObject)
+    {
+    TInt  add = 0;
+    TInt  index = 0;
+    TInt  size = 0;
+    TUint berObjectLevel = 0; 
+
+    CCrBer* obj;
+
+    if (aBerObject == 0)
+        {
+        return;
+        }
+
+    // Loop backwards through set and append length of the new object
+    // to the lengths of each found upper constructed, sequence or set
+    // objects with indefinite lengths, until first 'closed' from upper
+    // level found.
+
+    // Use object length, unless this is an object, whose total length is
+    // not yet known. In that case use tag length (always 1) combined with
+    // the amount of the length bytes.
+    if ((add = aBerObject->ObjectLen()) == 0)
+        {
+        add = 1 + aBerObject->LenLen();
+
+        // If new object is of indefinite length, still
+        // add two more bytes for the end-of-content tag.
+        if (aBerObject->Indefinite())
+            {
+            add += 2;
+            }
+        }
+
+    berObjectLevel = aBerObject->Level();
+
+    size = Count();
+
+    for (index = size - 1; index >= 0; index--)
+        {
+        obj = At(index);
+
+        if ((obj != 0) &&
+            (obj->Level() < berObjectLevel) &&
+            (obj->Indefinite()))
+            {
+            if ((obj->Type() == KBerSeq) ||
+                (obj->Type() == KBerSet) ||
+                (obj->Type() == KBerImplicitConstructed) ||
+                (obj->Type() == KBerExplicitConstructed))
+                {
+                if (obj->ObjectLen() == 0)
+                    {
+                    obj->AddToContentLen(add);
+                    }
+                else
+                    {
+                    index = -1;                 // break;
+                    }
+                }
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CloseLastSeqOrSet
+// Finds last open indefinite length sequence
+// or set from this set at given level and closes it.
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CloseLastSeqOrSet(TUint aLevel)
+    {
+    TInt    index = 0;
+    TInt    size  = 0;
+    TBerTag type  = KBerUnknown;
+
+    CCrBer* obj = NULL;
+
+    // Loop backwards through set and find first sequence or set with
+    // indefinite length at same level. 'Close' it by setting its object
+    // length.
+    size = Count();
+
+    for (index = size - 1; index >= 0; index--)
+        {
+        obj = At(index);
+
+        if ((obj != 0) &&
+            (obj->Level() == aLevel) &&
+            (obj->Indefinite()))
+            {
+            type = obj->Type();
+
+            if ((type == KBerSeq) ||
+                (type == KBerSet) ||
+                (type == KBerImplicitConstructed) ||
+                (type == KBerExplicitConstructed))
+                {
+                obj->SetObjectLen();
+
+                // Update upper objects with closed object.
+                Update(obj);
+
+                index = -1;             // break;
+                }
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+//  Encoding
+// -----------------------------------------------------------------------------
+    
+// -----------------------------------------------------------------------------
+// CCrBerSet::AppendBool
+// Write boolean object to CCrData.
+// Parameters:     Boolean value. ETrue or EFalse ( 0 / 1 ).
+// Return Values:  Error code
+// -----------------------------------------------------------------------------
+TInt CCrBerSet::AppendBoolL(TBool aBool)
+    {
+    TInt err = KErrNone;
+    TBuf8<1> value;
+
+    if (aBool)           
+        {
+        value.Append(KBerBooleanTrue);            
+        }
+    else                  
+        {
+        value.Append(KBerBooleanFalse);
+        }
+
+    err = AppendStringL(KBerBoolean, value);                       
+
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::AppendInt
+// Write integer (0x02) object to CCrData. Parameter is either
+// a positive whole number, or a negative whole number, or zero.
+// value : from - 0xFFFFFFF to +0xFFF FFFF
+// Parameters:     Integer value e.g. 1024 or 0xABC. 
+// Return Values:  Error code
+// -----------------------------------------------------------------------------
+TInt CCrBerSet::AppendIntL(TInt aData)
+    {
+    TInt err = KErrNone;
+    TBuf8<8> indexBuf;
+    TUint len   = 0;
+ 
+    HBufC8* buf = NULL;
+    
+    buf = HBufC8::NewLC(KIntBufSize);
+    TPtr8 data  = buf->Des();
+              
+    if (aData >= 0)
+        { 
+        if (aData >= KBerLongLengthBit)
+            {      
+            while (aData > 0)                    
+                {
+                TInt8 byte;
+                byte = TInt8(aData);        // Take byte
+                indexBuf.Append(byte);      // and add it to indexBuf   
+                aData >>= KOctetWidth;      // Next byte
+                len++;                 
+                }       
+            if (indexBuf[len-1] >= KBerLongLengthBit)   // if high order bit=1
+                {
+                indexBuf.Append(0);         // e.g. content 00 FF no FF 
+                len++;                      // (FF = neg num)
+                }
+            }
+        else                                // only one byte
+            {
+            indexBuf.Append(aData);         // so add directly
+            len++;
+            }
+        }
+   
+    else
+        {
+        aData = -(aData + 1);               // convert to positive
+
+        while ((aData > 0) || (len < 1))    // (len < 1) because -1 -> 0 ->FF            
+            {
+            TInt8 byte;
+            byte = TInt8(aData);            // Take byte
+            indexBuf.Append(~byte);         // and add complement to buf
+            aData >>= KOctetWidth;          // Next byte
+            len++;                 
+            }
+        if (indexBuf[len-1] < KBerLongLengthBit) // if high order bit=0
+                {
+                indexBuf.Append(0xFF);  
+                len++;                  
+                }
+        }
+
+    for (TInt i=len ; i > 0 ; i--)
+        {
+        data.Append(indexBuf[i - 1]);       // add data to buffer
+        }
+
+    err = AppendStringL(KBerInteger, data);        // write data to file
+    
+    CleanupStack::PopAndDestroy();
+    buf = NULL;
+
+    return err;
+    }
+
+
+
+TInt CCrBerSet::AppendLongIntL(RInteger& aData)
+    {
+    TInt err = KErrNone;
+    
+    err = AppendStringL(KBerInteger, *aData.BufferLC());
+    
+    CleanupStack::PopAndDestroy(); 
+
+    return err;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::AppendNull
+// Write null (05 00) object to CCrData.
+// Parameters:     None
+// Return Values:  Error code
+// -----------------------------------------------------------------------------
+TInt CCrBerSet::AppendNull()
+    {
+    TInt err = KErrNone;
+    TBuf8<2> data;
+     
+    data.Append(KBerNull);                      // Add Null tag 05
+    data.Append(KBerNullContent);               // and null;    00
+    
+    err = iTarget->Write(data);                 // write data-buffer to CCrData 
+    
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CloseIndefinite
+// Write end of indefinite length (add 00 00) to CCrData.
+// Return Values:  Error code
+// -----------------------------------------------------------------------------
+TInt CCrBerSet::CloseIndefinite()
+    {   
+    TInt err = KErrNone;
+    TBuf8<2> data;                  
+    data.Append(KBerEndOfContent);              // add end of indefinite length 
+    data.Append(KBerEndOfContent);              // ( 00 00 )
+    err = iTarget->Write(data);                 // write data-buffer to file
+    
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::AppendConstructed
+// Write constructed type to CCrData.
+// Parameters:     First param is type of constructed tag
+//                 e.g. 04 for octetS.  Second parameter is length or 0 for
+//                 indefinite length. e.g. if params are 4 and 0 --> 24 00
+// Return Values:  Error code
+// -----------------------------------------------------------------------------
+TInt CCrBerSet::AppendConstructedL(TBerTag aTag, TUint aLength)
+    {
+    TInt err    = KErrNone;
+    HBufC8* buf = NULL; 
+    
+    buf = HBufC8::NewLC(8);
+    TPtr8 data  = buf->Des();
+
+    if (aTag < KBerConstructedBit)      // if tag not consist ConstructedBit
+        {
+        aTag += KBerConstructedBit;     // add ConstructedBit
+        }
+
+    if (aLength == KBerEndOfContent)            // indefinite length 
+        {
+        data.Append(aTag);                      // add Tag
+        data.Append(KBerLongLengthBit);         // add indefinite length
+        }
+
+    else if (aLength < KBerLongLengthBit)       // if short len
+        {
+        data.Append(aTag);                      // add Tag    
+        data.Append(aLength);                   // add len
+        }
+
+    else                                        // else we have long len
+        {
+        TBuf8<6> indexBuf;              
+        TInt lenlen = 0;                        // number of length bytes
+
+        while (aLength > 0)
+            {
+            TInt8 byte;           
+            byte = TInt8(aLength);                
+            indexBuf.Append(byte);
+            aLength >>= KOctetWidth;
+            lenlen++;
+            }
+
+        data.Append(aTag);                          // Add Tag 
+        data.Append(lenlen + KBerLongLengthBit);    // Lenlen byte
+            
+        for (TInt i = lenlen ; i > 0 ; i--)
+            {
+            data.Append(indexBuf[i - 1]);       // length bytes
+            }
+        }                                           
+        
+    err = iTarget->Write(data);                 // write to CCrData
+                  
+    CleanupStack::PopAndDestroy();
+    buf = NULL;
+
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::AppendObjectId
+// Write object id object to CCrData.
+// Parameters:     Object ID. e.g. _L8("1.2.3.4.5"). Second parameter is 
+//                 true if you don't want write object to CCrData.
+// Return Values:  Error code (or length of object if aOnlyLen is true).
+// -----------------------------------------------------------------------------
+TInt CCrBerSet::AppendObjectIdL(const TDesC8& aString, TBool aOnlyLen)
+    {
+    TChar ch   = NULL;
+    TUint num  = 0;
+    TUint sum  = 0; 
+    TInt index = 0;
+    TInt len   = 0;
+    TInt i     = 0;
+    TInt start = 0;
+    TInt err   = KErrNone;
+    TBuf8<16> outbuf;
+
+    HBufC8* fileBuf  = NULL;
+    HBufC8* str = NULL;
+
+    fileBuf = HBufC8::NewLC(aString.Length() + 1);
+    str = aString.AllocLC();
+  
+    TPtr8 ptrFileBuf = fileBuf->Des();
+    TPtr8 strptr = str->Des();
+    
+    // Check valid ( string must start "x.z.*", x < 10 and z < 10)
+    if ((len = strptr.Locate('.')) == KObjectIDDot)            
+        { 
+        ch  = strptr[i];                            // take first number
+        num = ch.GetNumericValue();                 // convert ascii to num                     
+
+        // First byte = (first number * 40) + second number  
+        sum = num * KObjectIDFirstFactor;           // num * 4                              
+       
+        strptr.Delete(start, len + 1);              // delete 'x.'
+
+        // also second num must be smaller than 10
+        if (!((strptr.Locate('.')) == KObjectIDDot))                   
+            {
+            err = KErrArgument;
+            }
+
+        while (strptr.Length() > 0)          
+            {
+            len = strptr.Locate('.');               // Find next dot
+            
+            if (len == KErrNotFound)                // if not found: take all 
+                {
+                len = strptr.Length();              // string len
+                } 
+
+            for (i = 0; i < len; i++)               
+                {
+                ch  = strptr[i];
+                num = ch.GetNumericValue();        
+                sum = sum * KObjectIDSecondFactor + num;    // sum * 10 + num           
+                num = 0;
+                }
+       
+            strptr.Delete(start, len + 1);          // delete also dot
+
+            for (index = 0; (sum >= KBerLongLengthBit); index++)
+                {   
+                outbuf.Append(sum % KBerLongLengthBit);        // add remainder 
+                sum = (sum - outbuf[index]) / KBerLongLengthBit;// take new 
+                }
+
+            outbuf.Append(sum);
+
+            for (; index >= 0 ; index--)
+                {
+                if (!index)                      
+                    {
+                    ptrFileBuf.Append(outbuf[index]);
+                    }
+                else                        
+                    {
+                    ptrFileBuf.Append(outbuf[index] + KBerLongLengthBit);
+                    }   
+                }
+            
+            sum = 0;
+            outbuf.Delete(start, outbuf.Length());       
+            }
+        
+        if ((!aOnlyLen && ptrFileBuf.Length()) && (err == KErrNone))
+            {
+            err = AppendStringL(KBerOid, ptrFileBuf);   // write object to CCrData
+            }
+        else if (err == KErrNone)
+            {
+            len = ptrFileBuf.Length();              // return object length 
+            err = len;
+            }                                       // else return error
+        }
+    else                                            
+        {                                           
+        err = KErrArgument;                         // return argument error
+        }
+
+    CleanupStack::PopAndDestroy(2);                  // delete fileBuf, str;
+    return err;                                     // return error code
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::AppendString
+// Write string object to CCrData.
+// Parameters:     Object type (tag) and string. e.g. (KBerIA5S, _L("Hello"))      
+// Return Values:  Error code
+// -----------------------------------------------------------------------------
+TInt CCrBerSet::AppendStringL(TBerTag aTag, const TDesC8& aString)
+    {
+    TInt err = KErrNone;
+    TInt len = aString.Length();
+
+    HBufC8* buf  = NULL;
+    
+    buf = HBufC8::NewLC(KBerShortLen + LEN_BYTES_MAX);
+    TPtr8   data = buf->Des();
+ 
+    if (len < KBerLongLengthBit)                    // If short len:
+        {
+        data.Append(aTag);                          // Add Tag
+        data.Append(len);                           // length 
+        }                                                  
+    else                                            // Else long
+        {
+        TBuf8<8> indexBuf;
+        TUint lenlen = 0;                           // number of len bytes
+              
+        while (len > 0)
+            {
+            TInt8 byte;                             
+            byte = TInt8(len);                      // Take byte
+            indexBuf.Append(byte);                  // append it to buf
+            len >>= KOctetWidth;                    // next byte
+            lenlen++;                                                        
+            }
+
+        data.Append(aTag);                          // Add tag
+        data.Append(lenlen + KBerLongLengthBit);    // now add lenlen byte
+                                                    // 0x80 + lenlen
+
+        for (TInt i=lenlen ; i > 0 ; i--)
+            {
+            data.Append(indexBuf[i - 1]);           // add len bytes
+            }
+
+        len = aString.Length();
+        }
+
+    err = iTarget->Write(data);                     // write buffer to file
+    err = iTarget->Write(aString);                     // write buffer to file
+                  
+    CleanupStack::PopAndDestroy();                  // delete buf;                         
+    buf = NULL;    
+
+    return err;
+    }
+ 
+// -----------------------------------------------------------------------------
+// CCrBerSet::AppendString
+// Write string object to CCrData.
+// Parameters:     Object type (tag) and CCrData      
+// Return Values:  Error code
+// -----------------------------------------------------------------------------
+TInt CCrBerSet::AppendStringL(TBerTag aTag, CCrData* const aData)
+    {
+    TInt err = KErrNone;
+    TInt len = 0;
+    aData->Size(len);
+
+    HBufC8* buf  = NULL;
+    buf = HBufC8::NewLC(KBerShortLen + LEN_BYTES_MAX);
+    TPtr8 data = buf->Des();
+ 
+    if (len < KBerLongLengthBit)                    // If short len:
+        {
+        data.Append(aTag);                          // Add Tag
+        data.Append(len);                           // length 
+
+        }                                                  
+    else                                            // Else long
+        {
+        TBuf8<8> indexBuf;
+        TUint lenlen = 0;                           // number of len bytes
+              
+        while (len > 0)
+            {
+            TInt8 byte;                             
+            byte = TInt8(len);                      // Take byte
+            indexBuf.Append(byte);                  // append it to buf
+            len >>= KOctetWidth;                    // next byte
+            lenlen++;                                                        
+            }
+
+        data.Append(aTag);                          // Add tag
+        data.Append(lenlen + KBerLongLengthBit);    // now add lenlen byte
+                                                    // 0x80 + lenlen
+
+        for (TInt i=lenlen ; i > 0 ; i--)
+            {
+            data.Append(indexBuf[i - 1]);           // add len bytes
+            }
+
+        aData->Size(len);
+
+        }
+
+    err = iTarget->Write(data);                     // write buffer to file
+    
+    // Write aData to iTarget
+    HBufC8* tempBuf = tempBuf = HBufC8::NewLC(KBufSize);
+    
+    // write aData to iTarget in loop.
+    TPtr8 ptr = tempBuf->Des();
+    TInt size = 0;
+    aData->Size(size);
+    TInt left = size;
+    TInt handleThisTime = 0;
+    TInt handled = 0;
+
+    while (left > 0)
+        {
+        if (left > KBufSize)
+            {
+            handleThisTime = KBufSize;
+            }
+        else
+            {
+            handleThisTime = left;
+            }
+        aData->Read(handled, ptr, handleThisTime);
+        iTarget->Write(ptr);
+        ptr.Zero();
+
+        handled = handled + handleThisTime;
+        left = size - handled;
+        }
+
+    CleanupStack::PopAndDestroy(2);
+    return err;
+    }
+ 
+// -----------------------------------------------------------------------------
+// CCrBerSet::AppendBerEncodedObject
+// Write BER encoded object to CCrData.
+// Parameters:     Buffer containing BER encoded object.      
+// Return Values:  Error code
+// -----------------------------------------------------------------------------
+TInt CCrBerSet::AppendBerEncodedObject(const TDesC8& aString)
+    {
+    TInt err = KErrNone;
+
+    err = iTarget->Write(aString); // write buffer to file
+                  
+    return err;
+    }
+ 
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateBoolL
+// Function creates Ber encoded boolean object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// Parameters:     Value of the object
+// Return Values:  None 
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateBoolL(TBool aValue)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateBool(aValue);
+    
+    AppendL(newObject);              // add to set
+    
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateIntL
+// Function creates Ber encoded integer object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// Parameters:     Value of the object
+// Return Values:  None 
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateIntL(TInt aValue)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateInt(aValue);
+    
+    AppendL(newObject);              // add to set
+    
+    CleanupStack::Pop();
+    }
+
+
+EXPORT_C TAny CCrBerSet::CreateLongIntL(RInteger& aValue)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    
+    newObject->CreateLongInt(aValue);
+    
+    AppendL(newObject);              // add to set
+    
+    CleanupStack::Pop();
+    }
+
+
+// -----------------------------------------------------------------------------        
+// CCrBerSet::CreateNullL
+// Function creates Ber encoded null object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateNullL()
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateNull();                
+    
+    AppendL(newObject);              // add to set
+    
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateIA5L
+// Function creates Ber encoded IA5 string object (CCrBer object).
+// Write a object to CCrData  by Flush(..) 
+// Parameters:     IA5 string
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateIA5L(TDesC8& aString)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateString(KBerIA5S, &aString);
+    
+    AppendL(newObject);              // add to set
+
+    CleanupStack::Pop();
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateNumericL
+// Function creates Ber encoded Numeric string object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// Parameters:     Numeric string
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateNumericL(TDesC8& aString)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateString(KBerNumS, &aString);
+        
+    AppendL(newObject);              // add to set
+
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreatePrintableL
+// Function creates Ber encoded Printable string object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// Parameters:     Printable string
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreatePrintableL(TDesC8& aString)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateString(KBerPrS, &aString);
+    AppendL(newObject);              // add to set
+
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateT61L
+// Function creates Ber encoded T61 string object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// Parameters:     T61 string (= a teletext string)
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateT61L(TDesC8& aString)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateString(KBerT61S, &aString);
+    AppendL(newObject);              // add to set
+
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateVideoTexL
+// Function creates Ber encoded Video text object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// Parameters:     VideoTex string
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateVideoTexL(TDesC8& aString)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateString(KBerVideoS, &aString);
+    AppendL(newObject);              // add to set
+
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateUTCL
+// Function creates Ber encoded UTC time object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// Parameters:     UTC time (string)
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateUTCL(TDesC8& aString)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateString(KBerUtc, &aString);
+    AppendL(newObject);              // add to set
+
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateGenTimeL
+// Function creates Ber encoded generalised time object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// Parameters:     Generalised time (string)
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateGenTimeL(TDesC8& aString)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateString(KBerGenTime, &aString);
+    AppendL(newObject);              // add to set
+
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateGraphicalL
+// Function creates Ber encoded graphical string object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// Parameters:     Graphical string
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateGraphicalL(TDesC8& aString)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateString(KBerGraphS, &aString);
+    AppendL(newObject);              // add to set
+
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateVisibleL
+// Function creates Ber encoded visible string object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// Parameters:     Visible string
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateVisibleL(TDesC8& aString)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateString(KBerVisibleS, &aString);    // save type & pointer
+    AppendL(newObject);              // add to set
+
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateGeneralL
+// Function creates Ber encoded general string object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// Parameters:     Generalised string
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateGeneralL(TDesC8& aString)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateString(KBerGeneralS, &aString);    // save type & pointer
+    AppendL(newObject);              // add to set
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateOctetL
+// Function creates Ber encoded octet string object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// Parameters:     Octet string
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateOctetL(TDesC8& aString)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateString(KBerOctetString, &aString); // save type & pointer
+    AppendL(newObject);              // add to set
+
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateOctetL
+// Function creates Ber encoded octet string object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// Parameters:     CCrData* 
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateOctetL(CCrData* aData)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateString(KBerOctetString, aData); // save type & pointer
+    AppendL(newObject);              // add to set
+
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateOIdL
+// Function creates Ber encoded object identifier object (CCrBer object).
+// Write a object to CCrData (file) by Flush(..) 
+// Parameters:     object identifier content e.g.(_L8("1.2.3.4445"))
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateOIdL(TDesC8& aString)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateOIdL(&aString);         // save type and pointer to data
+
+    AppendL(newObject);              // add to set
+
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateSeqStartL
+// Function creates start of sequence (0x30). End this by EndL().
+// Parameters:     True for definite length sequence, false for indefinite
+//                 length 
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateSeqStartL(TBool aDefinite)
+    {
+    CCrBer* newObject = CCrBer::NewLC(++iLevel);
+    newObject->CreateStart(KBerSeq, aDefinite); 
+        
+    if (iLevel > iMaxLevel) 
+        {
+        iMaxLevel = iLevel;                 // iMaxLevel is used in Flush(..)
+        }
+
+    AppendL(newObject);              // add to set
+
+    CleanupStack::Pop();
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateSetStartL
+// Start set (31 xx) object. End this set by EndL(). 
+// Parameters:     Parameter is true for definite length, false for
+//                 indefinite length. 
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateSetStartL(TBool aDefinite)
+    {
+    CCrBer* newObject = CCrBer::NewLC(++iLevel);
+    newObject->CreateStart(KBerSet, aDefinite);   
+        
+    if (iLevel > iMaxLevel) 
+        {
+        iMaxLevel = iLevel;                 // iMaxLevel is used in Flush(..)
+        }
+
+    AppendL(newObject);                     // add to set
+
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateConstructedStartL
+// Function creates start of constructed type object. End this by EndL(). 
+// Parameters:     First parameter is object type (tag), Second parameter is 
+//                 true for definite length, false for indefinite length. 
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateConstructedStartL(TBerTag aTag, TBool aDefinite)
+    {
+    CCrBer* newObject = CCrBer::NewLC(++iLevel);
+    if (aTag < KBerConstructed)
+        {
+        aTag += KBerConstructedBit;         // e.g. 0x04 --> 0x24
+        }
+
+    newObject->CreateStart(aTag, aDefinite);   
+        
+    if (iLevel > iMaxLevel) 
+        {
+        iMaxLevel = iLevel;                 // iMaxLevel is used in Flush(..)
+        }
+    AppendL(newObject);              // add to set
+    CleanupStack::Pop();
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateEndL
+// Function close last constructed (e.g. seq) object. 
+// (definite or indefinite). 
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateEndL()
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel--);
+    newObject->CreateEnd();
+
+    AppendL(newObject);              // add to set
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::CreateBEREncodedObjectL
+// This fuction can be used to create a BER object
+// from buffer, which already contains a full BER
+// encoded object.
+// Parameters:     Buffer containing BER encoded object.
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBerSet::CreateBEREncodedObjectL(TDesC8& aString)
+    {
+    CCrBer* newObject = CCrBer::NewLC(iLevel);
+    newObject->CreateBEREncodedObject(&aString); // save pointer
+    AppendL(newObject);                          // add to set
+    CleanupStack::Pop();                         // newObject
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBerSet::Flush
+// Function writes all created crber objects (which are AppendL to set)
+// to file. Function also set length for definite lengths.
+// Call this function then crberSet is ready (all berObjects are given).
+// Parameters:     Reference to target CCrData (file)
+// Return Values:  Number of written objects or error code. 
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrBerSet::FlushL(CCrData* aTarget)
+    {
+    TInt index = 0;
+    TInt i = 0;
+    TUint level = 0;
+    TUint8 type = 0;
+    TInt err = KErrNone;
+    CCrBer* berObject = NULL;
+    CCrBer* newObject = NULL;
+    TInt size = Count();                    // number of the ber-objects
+
+    iTarget = aTarget;
+
+    if (iLevel || !size)                    // end count != start count
+        {                                   // or if no CrBer objects 
+        return KErrArgument;
+        }
+    
+    // Set definite lengths  
+    for (level = iMaxLevel; level > 0; level--)     // check levels (except 0)
+        {                                           
+        for (index = 0 ; index < size ; index++)    // all objects
+            {
+            berObject = At(index);                  
+        
+            if ((berObject->Type() >= KBerConstructed) &&   // Constructed 
+                (!berObject->ObjectLen())              &&   // definite len
+                (berObject->Level() == level))              // same level
+                {
+                for (i = index + 1; i < size; i++)
+                    {
+                    newObject = At(i);
+ 
+                    if ((newObject->Type() == KBerEndOfContent) &&
+                        (newObject->Level() == berObject->Level()) &&
+                        (newObject->Value() >= 0))
+                        {
+                        berObject->SetObjLenWithOutContent(
+                            berObject->ContentLen());
+                        newObject->SetValue(-1);    // this end is now used
+                        i = size;                   // end found, go away
+                        }
+                    else                                
+                        {
+                        berObject->AddToContentLen(newObject->ObjectLen());
+                        }                       
+                    }
+                }
+            }
+        }
+
+
+    // Write objects to file
+    for (index = 0; index < size; index++)
+        {
+        berObject = At(index);
+        type = berObject->Type();
+
+        if (type > KBerConstructed && type != KBerEncodedObject )
+            {
+            type = KBerConstructed;
+            }
+        
+        switch (type)
+            {
+            case KBerBoolean:
+                {
+                err += AppendBoolL(berObject->Value());
+                break;
+                }
+            case KBerInteger:
+                {
+                if (!berObject->Value() && (berObject->GetBigInt() != NULL))
+                    {
+					RInteger integer = berObject->GetBigInt();
+                    err += AppendLongIntL(integer);
+                    }
+                else
+                    {
+                    err += AppendIntL(berObject->Value());
+                    }
+                break;
+                }  
+            case KBerNull:
+                {
+                err += AppendNull();
+                break;
+                }
+            case KBerOid:
+                {
+                err += AppendObjectIdL(*berObject->ValuePtr());
+                break;
+                }
+            case KBerBitString:
+            case KBerOctetString:             
+		    case KBerNumS:
+            case KBerPrS:
+            case KBerT61S:
+		    case KBerVideoS:
+            case KBerIA5S:
+            case KBerUtc:
+		    case KBerGenTime:                                
+		    case KBerGraphS: 
+		    case KBerVisibleS:
+		    case KBerGeneralS:
+                {
+                CCrData* tempData = berObject->Data();
+                if (tempData != NULL)
+                    {
+                    err += AppendStringL((berObject->Type()),
+                                    (berObject->Data()));
+                    }
+                else
+                    {
+                    err += AppendStringL((berObject->Type()),
+                                    (*berObject->ValuePtr()));
+                    }
+                break;
+                }
+            case KBerSeq:
+            case KBerSet:
+            case KBerConstructed:
+                {
+                err += AppendConstructedL((berObject->Type()), 
+                                         (berObject->ContentLen()));
+                break;
+                }
+            case KBerEncodedObject:
+                {
+                err += AppendBerEncodedObject(
+                    (*berObject->ValuePtr()));
+                break;
+                }
+            case KBerEndOfContent:
+                {
+                if (!berObject->Value())            // Indefinite len
+                    {   
+                    err += CloseIndefinite();
+                    }
+                break;
+                }
+            }
+        }
+    if (err < KErrNone)
+        {
+        return KErrGeneral;
+        }
+    else    
+        {
+        return size;
+        }
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrBer/Src/crber.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1735 @@
+/*
+* Copyright (c) 2000, 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This module contains the implementation of CCrBer class. 
+*
+*/
+
+
+
+//  INCLUDE FILES
+#include "crber.h"
+#include <e32math.h>    // Pow
+
+
+// -----------------------------------------------------------------------------
+// CCrBer
+// Constructor 
+// This function constructs CCrBer object
+// -----------------------------------------------------------------------------
+CCrBer::CCrBer(TInt aLevel /* = 0 */)
+    {
+    TReal size = 0;
+    
+    Math::Pow(size, 256, sizeof(TUint));
+    iMaxUint = STATIC_CAST(TUint, size - 1);
+    
+    Math::Pow(size, 128, sizeof(TInt));
+    iMaxInt = STATIC_CAST(TInt, size - 1);
+    
+    
+    iEOCBytes[0] = 0x00;
+    iEOCBytes[1] = 0x00;
+
+    iType = KBerUnknown;
+    
+    iIndefinite = EFalse;
+
+    iObjectBegin = 0;
+    iContentBegin = 0;
+    iContentLen = 0;
+    iObjectLen = 0;
+
+    iLevel = aLevel;
+
+    iData = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer
+// Destructor 
+// This function destructs CCrBer object
+// -----------------------------------------------------------------------------
+EXPORT_C CCrBer::~CCrBer()
+    {
+    iData = NULL;
+	iInt.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::ConstructL
+// This function initializes CCrBer object's member objects.
+// -----------------------------------------------------------------------------
+TAny CCrBer::ConstructL()
+    {
+    }
+// -----------------------------------------------------------------------------
+// CCrBer::NewLC
+// -----------------------------------------------------------------------------
+EXPORT_C CCrBer* CCrBer::NewLC(TInt aLevel /* = 0 */)
+    {
+    CCrBer* self = new (ELeave) CCrBer(aLevel);
+    CleanupStack::PushL(self);
+
+    self->ConstructL();
+
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::NewL
+// -----------------------------------------------------------------------------
+EXPORT_C CCrBer* CCrBer::NewL(TInt aLevel /* = 0 */)
+    {
+    CCrBer* self = NewLC(aLevel);
+    CleanupStack::Pop();
+
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::Read
+// Read next BER encoded object from the current position of
+// given CCrData to this object. Return the type of the BER
+// object, or KBerUnknown, if not of any known type. Only pointer
+// to aData is stored into this object, so Get* functions are
+// meaningful only if original data object is still existing,
+// when these functions are used.
+// -----------------------------------------------------------------------------
+EXPORT_C TUint8 CCrBer::Read(CCrData* aData)
+    {
+    if ((iType = ReadType(aData)) != KBerUnknown)
+        {
+        TInt  move;
+        TInt  pos = 0;
+        TBool conLenKnown;
+
+
+        // If type is known, this object begins right here,
+        // well, to be exact, one byte before this point.
+        if ((aData->Seek(ESeekCurrent, pos)) == KErrNone)
+            {
+            conLenKnown = ETrue;
+
+            // Now we have at least something sensible. Store pointer to
+            // the data object (and hope that the caller doesn't delete it :)
+            iData = aData;
+
+            iObjectBegin = pos - 1;
+
+            // Read length.
+            iContentLen = ReadLen(aData, iIndefinite, &iLenLen);
+
+            // Content begins right after type tag and length bytes.
+            iContentBegin = pos + iLenLen;
+
+            // If length is indefinite and type isn't set, sequence,
+            // or explicit/implicit constructed, find next end-of-content
+            // tag to define exact length.
+            if (iIndefinite)
+                {
+                if ((iType != KBerSeq) &&
+                    (iType != KBerSet) &&
+                    (iType != KBerImplicitConstructed) &&
+                    (iType != KBerExplicitConstructed))
+                    {
+                    // Give special treatment to constructed encoding.
+                    if ((iType & KBerConstructedBit) ||
+                        (iType & KBerImplicitConstructed))
+                        {
+                        iContentLen = OpenConstructedEncodingWithTagL(
+                                        aData, *this);
+                        
+                        }
+                    else
+                        {
+                        iContentLen = FindEndOfContent(aData);
+                        }
+                    }
+                else
+                    {
+                    // We really can't know what the length is,
+                    // until we open up the whole inner content.
+                    conLenKnown = EFalse;
+                    }
+                }
+
+            // Now, if we know content length, then we can calculate whole
+            // object's length; it is tag + length bytes + content length.
+            if (conLenKnown)
+                {
+                SetObjectLen();
+
+                // Also move data pointer at the end of this object, except
+                // if object was set or sequence, in which case don't move,
+                // because we still have to open inner items.
+                // At indefinite case this is already done (other than
+                // sequence or set) or this can't be done (sequence or
+                // set). So, if not indefinite and not sequence or set,
+                // move data pointer the amount of content length.
+                if (!(iIndefinite) && !(IsSeqOrSet(iType)))
+                    {
+                    move = iContentLen;
+
+                    aData->Seek(ESeekCurrent, move);
+                    }
+                }
+
+            // If tag was end-of-content tag, check that also length
+            // was 0 and not indefinite, this guarantees that we really
+            // have an end-of-content tag (00 00).
+            if (iType == KBerEndOfContent)
+                {
+                if ((iContentLen != 0) || (iIndefinite))
+                    {
+                    iType = KBerUnknown;
+                    }
+                }
+            }
+        
+	
+	 
+		}
+    return iType;
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CCrBer::ReadType
+// Read type tag from current position in given CCrData.
+// Returns type tag or KBerUnknown, if not of any known type.
+// -----------------------------------------------------------------------------
+EXPORT_C TUint8 CCrBer::ReadType(CCrData* aData)
+    {
+    TBuf8<1> byte;
+    TUint8   type = KBerUnknown;   // By default we are pessimists.
+
+    // Read type.
+    if ((aData != 0) &&
+        (aData->Read(byte, 1) == KErrNone) &&
+        (byte.Length() > 0))
+        {
+        type = byte[0];
+
+        if (!IsKnownType(type))
+            {
+            // Don't let type to be whatever byte happened to be
+            // at that place. Set it to unknown, which we all know.
+            type = KBerUnknown;
+            }
+        }
+
+    return type;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::ReadLen
+// Read length tags from current position in given CCrData.
+// Returns length. If length is indefinite, aIndefinite is set
+// to true, otherwise to false. In indefinite case length is 0.
+// Also sets amount of length bytes in aLenLen, if given.
+// -----------------------------------------------------------------------------
+EXPORT_C TUint CCrBer::ReadLen(
+    CCrData* aData,
+    TBool&   aIndefinite,
+    TUint8*  aLenLen/* = 0 */)
+    {
+    TBuf8<LEN_BYTES_MAX> bytes;
+    TUint8               byte = 0;
+    TUint                len = 0;
+
+    // Originally assume that length is definite,
+    aIndefinite = EFalse;
+
+    // First byte tells if the length bytes are in short or in long form.
+    if ((aData != 0) && (aData->Read(bytes, 1) == KErrNone))
+        {
+        if (bytes.Length() <= 0)        
+            {
+            User::Leave(KErrArgument);
+            }
+        byte = bytes[0];
+
+        // We have at least one length byte.
+        if (aLenLen != 0)
+            {
+            *aLenLen = 1;
+            }
+
+        if (byte & KBerLongLengthBit)
+            {
+            // We have length bytes, but how many?
+            TUint8 lenBytes = (TUint8)(byte & ~KBerLongLengthBit);
+
+            // If length is in long form, but there are zero
+            // length bytes, then length is indefinite.
+            if (lenBytes == 0)
+                {
+                aIndefinite = ETrue;
+                }
+            else
+                {
+                if (aLenLen != 0)
+                    {
+                    // Add amount of actual length bytes to one,
+                    // which was for long length form byte.
+                    for (TInt i = 0; i < lenBytes; i++)
+                        {
+                        (*aLenLen)++;
+                        }
+					}
+
+                // Otherwise we have to interpret length bytes and
+                // move the result into len variable. First check
+                // that there aren't more bytes than fits to
+                // unsigned integer, we don't want any troubles here.
+                if (lenBytes > sizeof(TUint))
+                    {
+                    // Return max uint, caller can then decide
+                    // what to do with this huge pile of...
+                    return iMaxUint;
+                    }
+
+                // Read length bytes
+                if (aData->Read(bytes, lenBytes) == KErrNone)
+                    {
+                    TUint8 i;
+
+                    // and move them to len.
+                    for (i = 0; i < lenBytes; i++)
+                        {
+                        len = len << 8;
+
+                        len += bytes[i];
+                        }
+                    }
+                }
+            }
+        else
+            {
+            // Otherwise length was in short form and length
+            // byte alone tells us the length of the contens.
+            len = byte;
+            }
+        }
+
+    return len;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCrBer::IsKnownType
+// Returns true if given BER tag is identified one.
+// Returns:  ETrue of EFalse.
+// -----------------------------------------------------------------------------
+EXPORT_C TBool CCrBer::IsKnownType(TBerTag aTag)
+    {
+    TBool isKnown = EFalse;
+
+    // Remove constructed bit, if it is on without other upper byte tags.
+    if ((aTag & 0xF0) == KBerConstructedBit)
+        {
+        aTag &= ~KBerConstructedBit;
+        }
+
+    // Remove implicit/explicit constructed bit, 
+    // if it is on without other upper byte tags.
+    if ((aTag & 0xF0) == KBerImplicitConstructed)
+        {
+        aTag &= ~KBerImplicitConstructed;
+        }
+
+    switch (aTag)
+        {
+        case KBerEndOfContent:
+        case KBerBoolean:
+        case KBerInteger:
+        case KBerBitString:
+        case KBerOctetString:
+        case KBerNull:
+        case KBerOid:
+		case KBerNumS:
+        case KBerPrS:
+        case KBerT61S:
+		case KBerVideoS:
+        case KBerIA5S:
+        case KBerUtc:
+		case KBerGenTime:                                
+		case KBerGraphS: 
+		case KBerVisibleS:
+		case KBerGeneralS:
+        case KBerBmpS:
+        case KBerSeq:
+        case KBerSet:
+        case KBerImplicitConstructed:
+        // Same as KBerExplicitConstructed
+        case KBerImplicit:
+        // Same as KBerExplicit
+            {
+            isKnown = ETrue;
+            break;
+            }
+        default:
+            {
+            isKnown = EFalse;
+            break;
+            }
+        }
+
+    return isKnown;
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CCrBer::IsSeqOrSet
+// Returns true if given BER tag is set, sequence,
+// implicit contructed, or explicit constructed tag.
+// -----------------------------------------------------------------------------
+EXPORT_C TBool CCrBer::IsSeqOrSet(TBerTag aTag)
+    {
+    TBool isSeqOrSet = EFalse;
+
+    if ((aTag == KBerSeq) ||
+        (aTag == KBerSet) ||
+        (aTag == KBerImplicit) ||
+        (aTag == KBerExplicit) ||
+        (aTag == KBerImplicitConstructed) ||
+        (aTag == KBerExplicitConstructed))
+
+        {
+        isSeqOrSet = ETrue;
+        }
+
+    return isSeqOrSet;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::FindEndOfContent
+// Finds next end-of-content (00 00) tag from given data.
+// Returns the distance between current place and the tag,
+// or 0, if not found. Moves data pointer to the next byte
+// _after_ the tag, i.e. two bytes longer than you might
+// except from the return value.
+// -----------------------------------------------------------------------------
+EXPORT_C TUint CCrBer::FindEndOfContent(CCrData* aData)
+    {
+    TBool go = ETrue;
+    TInt bufferOffset = 0;
+    TInt dataOffset = 0;
+    TInt move = 0;
+
+    TBuf8<KReadBufMax> bytes;
+
+    if (aData == 0)
+        {
+        return dataOffset;
+        }
+
+    // Read buffer of data. Go on, if there is something to go with.
+    while ((aData->Read(bytes, KReadBufMax) == KErrNone) &&
+           (bytes.Length() != 0) && go)
+        {
+        TBuf8<2> EOCBytes;
+
+        EOCBytes.Append(iEOCBytes[0]);
+        EOCBytes.Append(iEOCBytes[1]);
+
+        // Try to find end-of-content tag.
+        bufferOffset = bytes.Find(EOCBytes);
+
+        // If found, move data pointer right _after_
+        // the place of founded tag, and break.
+        if (bufferOffset != KErrNotFound)
+            {
+            move = bufferOffset -
+                       bytes.Length() +
+                       EOCBytes.Length();
+
+            aData->Seek(ESeekCurrent, move);
+
+            dataOffset += bufferOffset;
+
+            go = EFalse;                    //break;
+            }
+        else
+            {
+            // Otherwise keep searching. First check that the last
+            // character of the buffer isn't 00. If it is, move the
+            // data pointer one byte backwards to prevent us from
+            // missing end-of-content tag, if it is divided between
+            // buffers.
+            if (bytes[bytes.Length() - 1] == KBerEndOfContent)
+                {
+                move = -1;
+
+                aData->Seek(ESeekCurrent, move);
+
+                dataOffset--;
+                }
+
+            dataOffset += bytes.Length();
+            }
+        }
+
+    // If nothing was found, move data pointer back
+    // to where it was and return 0.
+    if (bytes.Length() == 0)
+        {
+        dataOffset = -dataOffset;
+
+        aData->Seek(ESeekCurrent, dataOffset);
+
+        dataOffset = 0;
+        }
+
+    return dataOffset;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::OpenConstructedEncodingL
+// Open constructed encoding from this object.  
+// Parameters: aTarget; target for contentbytes.
+// Return Values:  Number of objects in this contructed object.
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrBer::OpenConstructedEncodingL(CCrData& aTarget)
+    {      
+    TInt err = KErrNone;
+    TInt count = 0;
+    TInt offset = iContentBegin;
+    TInt objectNum = 0;
+    TInt type = Type();
+    CCrBer* object = NULL;
+
+    if (type <= KBerConstructed)        // not valid type
+        {
+        User::Leave(KErrArgument);
+        }
+    else  
+        {
+        type -= KBerConstructed;        // type what we are looking for
+        }
+
+    CCrBerSet* newSet = CCrBerSet::NewL(1);
+    CleanupStack::PushL(newSet);
+    iData->Seek(ESeekStart, offset);    // seek right place; content begin
+    newSet->OpenL(iData, KOpenAllLevels);
+    count = newSet->Count();            
+
+    HBufC8* obj = NULL;                 // buffer for CCrBer-objects
+
+    for (objectNum = 0; (objectNum < count); objectNum++)
+        {
+        object = newSet->At(objectNum); // select object
+        
+        if (object->Type() == type)
+            {
+            obj = HBufC8::NewLC(object->ContentLen());
+            TPtr8 pObj  = obj->Des();
+            
+            err = iData->Read(object->ContentBegin(), pObj, object->ContentLen());
+            
+            if (err < KErrNone)         // if error -> leave
+                {
+                CleanupStack::PopAndDestroy(2);  // delete newSet, obj;
+                User::Leave(err);
+                }    
+            err = aTarget.Write(pObj);  // write content to CCrData  
+            
+            CleanupStack::PopAndDestroy();  // delete obj;
+            obj = NULL;
+            
+            if (err < KErrNone)         // if error -> leave
+                {
+                CleanupStack::PopAndDestroy();  // delete newSet;
+                User::Leave(err);
+                }
+            
+            }
+        else 
+            {
+            count = objectNum;
+            }
+        }
+    CleanupStack::PopAndDestroy();      // delete newSet;
+
+    return count;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::OpenConstructedEncodingWithTagL
+// Open constructed encoding with given tag from given data.
+// Add all founded octets into the parameter string, if given.
+// Return amount of bytes read.
+// -----------------------------------------------------------------------------
+EXPORT_C TUint CCrBer::OpenConstructedEncodingWithTagL(
+    CCrData* aData,
+    CCrBer&  parentObj,
+    HBufC8*  aBuf /* = 0 */)
+    {
+    TInt    read = 0;
+    CCrBer  temp;
+    TBerTag parentTag = KBerUnknown;
+    TBerTag tempTag   = KBerUnknown;
+    HBufC8* tempBuf   = NULL;
+
+    parentTag = parentObj.Type();
+
+    // Check given object. It should have constructed tag.
+    if (parentTag & KBerConstructedBit)
+        {
+        TUint len = 0;
+        TUint totalLen = iMaxUint;
+        TBool isIndefinite = parentObj.Indefinite();
+
+        TBufC8<4> buf = _L8("Test");
+        TPtr8     ptr = buf.Des();
+
+        if (aBuf != 0)
+            {
+            ptr = aBuf->Des();
+            }
+
+        tempBuf = HBufC8::NewLC(KReadBufMax);
+
+        // After that we know that object either contains length or
+        // it is indefinite. Set max int to len even in the case of
+        // indefinite length to prevent this loop from going on forever.
+        if (!isIndefinite)
+            {
+            totalLen = parentObj.ContentLen();
+            }
+
+        while (len < totalLen)
+            {
+            // Read objects one by one, calculate content lengths together,
+            // add contents to target buffer, if given, and calculate also
+            // total object lengths together to know when stop. In indefinite
+            // case stop when end-of-content tag found.
+            temp.Read(aData);
+
+            tempTag = temp.Type();
+
+            if ((tempTag == KBerEndOfContent) ||
+                (tempTag == KBerUnknown) ||
+                (!(tempTag & parentTag)))
+                {
+                CleanupStack::PopAndDestroy();  // delete tempBuf;
+                return read;                // break
+                }
+
+            len += temp.ObjectLen();
+            read += temp.ContentLen();
+
+            if (aBuf != 0)
+                {
+                // Resize buffer, if needed, and append data to it.
+                if (aBuf->Length() < read)
+                    {
+                    // It is impossible to know how long buffer should be,
+                    // but add some extra space, so reallocation won't occur
+                    // each time.
+                    aBuf->ReAllocL(read + (read / 5));
+                    ptr = aBuf->Des();
+                    }
+
+                temp.Content(tempBuf);
+                ptr.Append(*tempBuf);
+                }
+            }
+
+        CleanupStack::PopAndDestroy();      // delete tempBuf;
+        }
+
+    return read;
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CCrBer::Type
+// Get type of the object.
+// -----------------------------------------------------------------------------
+EXPORT_C TBerTag CCrBer::Type()
+    {
+	return iType;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::Value
+// Get value of the object. Used in encoding.
+// -----------------------------------------------------------------------------
+TInt CCrBer::Value()
+    {
+    return iValue;
+    }
+// -----------------------------------------------------------------------------
+// CCrBer::GetBigInt
+// -----------------------------------------------------------------------------
+RInteger CCrBer::GetBigInt()
+    {
+    return iInt;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::SetValue
+// Set value of the object.
+// -----------------------------------------------------------------------------
+TAny CCrBer::SetValue(TInt aInt)
+    {
+    iValue = aInt;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::ValuePtr
+// Get valuePtr of the object. (encoding)
+// -----------------------------------------------------------------------------
+TDesC8* CCrBer::ValuePtr()
+    {
+    return iValuePtr;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::LenLen
+// Get amount of length bytes.
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrBer::LenLen()
+    {
+    return iLenLen;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::ObjectBegin
+// Return begin of the whole object.
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrBer::ObjectBegin()
+    {
+    return iObjectBegin;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::ContentBegin
+// Return begin of the content.
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrBer::ContentBegin()
+    {
+    return iContentBegin;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::ObjectLen
+// Get length of the whole object.
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrBer::ObjectLen()
+    {
+	return iObjectLen;
+	}
+
+// -----------------------------------------------------------------------------
+// CCrBer::ContentLen
+// Get length of the content.
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrBer::ContentLen()
+    {
+    return iContentLen;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::Indefinite
+// Returns true if this object is indefinite length.
+// -----------------------------------------------------------------------------
+EXPORT_C TBool CCrBer::Indefinite()
+    {
+    return iIndefinite;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::Data
+// Return pointer to data object.
+// -----------------------------------------------------------------------------
+EXPORT_C CCrData* CCrBer::Data()
+    {
+    return iData;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::Object
+// Return whole BER object with tag and stuff. For implementation
+// reasons ObjectL returns only max 255 bytes of data.
+// -----------------------------------------------------------------------------
+
+EXPORT_C TInt CCrBer::Object(HBufC8* aBuf)
+    {
+    return BufferL(aBuf, iData, iObjectBegin, iObjectLen);
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::Object
+// Return whole BER object with tag and stuff. For implementation
+// reasons ObjectL returns only max 255 bytes of data.
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrBer::ObjectL(HBufC* aBuf)
+    {
+    TUint8 len = 255;
+
+
+    if (iObjectLen < 255)
+        {
+        len = (TUint8)iObjectLen;
+        }
+	
+    return BufferL(aBuf, iData, iObjectBegin, len);
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::Content
+// Return content of this object. For implementation reasons
+// ContentL returns only max 255 bytes of data.
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrBer::Content(HBufC8* aBuf)
+    {
+    return BufferL(aBuf, iData, iContentBegin, iContentLen);
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::ContentL
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrBer::ContentL(HBufC* aBuf)
+    {
+    TUint8 len = 255;
+
+    if (iContentLen < 255)
+        {
+        len = (TUint8)iContentLen;
+        }
+
+    return BufferL(aBuf, iData, iContentBegin, len);
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::BufferL
+// Read aAmount of data starting from begin to the buffer.
+// Return amount of data read. For implementation reasons
+// BufferL can be used only to read max 256 bytes of data.
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrBer::BufferL(
+    HBufC8*   aBuf,
+    CCrData*  aData,
+    TUint     aBegin  /* = 0 */,
+    TUint     aAmount /* = KReadBufMax */)
+    {
+    TInt pos = 0;
+    TInt begin = aBegin;
+    TInt amount = aAmount;
+    TInt read = 0;
+
+    if ((aBuf == 0) || (aData == 0))
+        {
+        // Don't bother to continue.
+        return read;
+        }
+
+    // Store current position,
+    if ((aData->Seek(ESeekCurrent, pos)) != KErrNone)
+        {
+        // Don't bother to continue.
+        return read;
+        }
+
+    // Set data pointer to wanted position.
+    if (aData->Seek(ESeekStart, begin) == KErrNone)
+        {
+        // Resize buffer, if needed, and read data.
+        if (aBuf->Length() < amount)
+            {
+            aBuf->ReAllocL(amount);
+            }
+
+        TPtr8 ptr = aBuf->Des();
+
+        if (aData->Read(ptr, amount) == KErrNone)
+            {
+            read = aBuf->Length();
+            }
+        }
+
+    // Put data pointer back to previous position.
+    aData->Seek(ESeekStart, pos);
+
+    return read;
+    }
+
+EXPORT_C TInt CCrBer::BufferL(
+    HBufC*   aBuf,
+    CCrData* aData,
+    TUint    aBegin  /* = 0 */,
+    TUint8   aAmount /* = 255 */)
+    {
+    TInt      index = 0;
+    TInt      len = 0;
+    TInt      amount = NULL;
+    TBuf<255> buf;
+    HBufC8*   heapBuf = NULL;
+
+    heapBuf = HBufC8::NewLC(255);
+
+    amount = BufferL(heapBuf, aData, aBegin, aAmount);
+
+    len = heapBuf->Length();
+
+    for (index = 0; index < len; index++)
+        {
+        buf.Append((*heapBuf)[index]);
+        }
+
+    *aBuf = buf;
+
+    CleanupStack::PopAndDestroy();      // delete heapBuf;
+    // heapBuf = NULL;
+
+    return amount;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCrBer::Level
+// Return nesting level of this object.
+// -----------------------------------------------------------------------------
+EXPORT_C TUint CCrBer::Level()
+    {
+    return iLevel;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::SetLevel
+// Set nesting level of this object.
+// -----------------------------------------------------------------------------
+EXPORT_C TUint CCrBer::SetLevel(TUint aLevel)
+    {
+    iLevel = aLevel;
+
+    return iLevel;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::AddToContentLen
+// Add given integer to content length of this object.
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBer::AddToContentLen(TInt iLen)
+    {
+    iContentLen += iLen;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::SetObjectLen
+// Calculate object length from tag, length's length, and
+// content's length. Used to 'close' indefinite objects, meaning
+// that their end-of-contents tag is finally found, so their
+// length can be calculated.
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBer::SetObjectLen()
+    {
+    // Objects length is tag len (always 1) + length byte
+    // amount + content length.
+    iObjectLen = 1 + iLenLen + iContentLen;
+
+    // If object was of indefinite length, there are
+    // two additional end-of-contents bytes at the end.
+    if (iIndefinite)
+        {
+        iObjectLen += 2;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::SetObjLenWithOutContent
+// Parameters:     Content length.
+// -----------------------------------------------------------------------------
+TAny CCrBer::SetObjLenWithOutContent(TUint aContentLen)
+    {
+    iObjectLen  = KBerShortLen;             // Tag + len
+    if (aContentLen >= KBerLongLengthBit)
+        {
+        while (aContentLen > 0)                    
+            {
+            aContentLen >>= 8;              // Next byte
+            iObjectLen++;                 
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// Get content functions.
+// -----------------------------------------------------------------------------
+
+// -----------------------------------------------------------------------------
+// CCrBer::GetBooleanL
+// Returns value of Boolean object.
+// -----------------------------------------------------------------------------
+EXPORT_C TBool CCrBer::GetBooleanL()
+    {		
+    TInt err = KErrNone;
+    TASN1DecBoolean dec;                                // ASN1 lib (Symbian)
+    TInt pos    = NULL;
+    TBool ret   = EFalse;
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);            // buffer to object
+
+    TPtr8 ptr   = buf->Des();
+   
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);     // Read object
+
+    if (err == KErrNone)
+        {
+        ret = dec.DecodeDERL(ptr, pos); 	        // decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        User::Leave(err);
+        }
+
+    CleanupStack::PopAndDestroy();                      // delete buf;
+ 
+    return ret;
+    }	
+
+// -----------------------------------------------------------------------------
+// CCrBer::GetIntegerL
+// Returns value of Integer object.
+// -----------------------------------------------------------------------------		
+EXPORT_C TInt CCrBer::GetIntegerL()
+    {
+    TInt err = KErrNone;
+    TASN1DecInteger dec;                                // ASN1 lib (Symbian)
+    TInt pos    = NULL;
+    TInt ret    = NULL;
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);             // buffer to object
+
+    TPtr8 ptr   = buf->Des();
+   
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);     // Read object
+
+    if (err == KErrNone)
+        {
+        ret = dec.DecodeDERShortL(ptr, pos);        	// decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        User::Leave(err);
+        }
+
+    CleanupStack::PopAndDestroy();                      // delete buf;
+
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::GetIntegerL
+// Returns value of Long Integer object.
+// -----------------------------------------------------------------------------		
+EXPORT_C RInteger CCrBer::GetLongIntegerL()
+    {	
+    TInt err    = KErrNone;
+    TInt pos    = NULL;
+    TASN1DecInteger dec;                                // ASN1 lib (Symbian)
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);             // buffer to object
+
+    TPtr8 ptr   = buf->Des();
+    RInteger value;
+
+    // Read object to buf
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);
+
+    if (err == KErrNone)
+        {
+        value = dec.DecodeDERLongL(ptr, pos);           // decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        User::Leave(err);
+        }
+    
+    CleanupStack::PopAndDestroy();                      // delete buf;
+
+    return value;
+    }
+  
+// -----------------------------------------------------------------------------
+// HBufC* CCrBer::GetOidL
+// Returns value of object identifier.
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC* CCrBer::GetOidL()
+    {	
+    TInt err    = KErrNone;
+    TInt pos    = NULL;
+    HBufC* ret  = NULL;
+    TASN1DecObjectIdentifier dec;                       // ASN1 lib (Symbian)
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);            // buffer to object
+
+    TPtr8 ptr   = buf->Des();
+
+    // Read object to buf
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);    
+
+    if (err == KErrNone)
+        {
+        ret = dec.DecodeDERL(ptr, pos);                 // decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        User::Leave(err);
+        }
+
+    CleanupStack::PopAndDestroy();                      // delete buf;
+
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// HBufC8* CCrBer::GetOctetStringL
+// Returns value of octet string.
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC8* CCrBer::GetOctetStringL()
+    {	
+    TInt pos = NULL;
+    HBufC8* ret = NULL;
+    TInt err = KErrNone;
+    TASN1DecOctetString dec;                            // ASN1 lib (Symbian)
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);             // buffer to object
+
+    TPtr8 ptr   = buf->Des();
+
+    // Read object to buf
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);    
+
+    if (err == KErrNone)
+        {
+        ret = dec.DecodeDERL(ptr, pos);                 // decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy(buf);                  // delete buf;
+        User::Leave(err);
+        }
+
+    CleanupStack::PopAndDestroy(buf);                      // delete buf;
+
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// HBufC8* CCrBer::GetOctetStringL
+// Returns value of octet string.
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrBer::GetOctetStringL(CCrData& Trg)
+    {	
+    TUint pos = iContentBegin;
+    TUint end = iContentBegin + iContentLen;
+    TInt err = KErrNone;
+    TInt len = KBufSize;
+    HBufC8* buf = HBufC8::NewL(KBufSize);              // buffer to object
+    CleanupStack::PushL(buf);
+
+    TPtr8 ptr   = buf->Des();
+    // Read object to buf
+    while (pos < end)
+        {
+        len = end - pos;
+
+        if (len > KBufSize)
+            {
+            len = KBufSize;
+            }
+
+        err = iData->Read(pos, ptr, len);    
+        
+        if (err == KErrNone)
+            {
+            Trg.Write(ptr);
+            }
+        if (err < KErrNone)
+            {        
+            CleanupStack::PopAndDestroy();
+            // buf = NULL;
+            User::Leave(err);
+            }
+        pos += KBufSize;
+        }
+    CleanupStack::PopAndDestroy(); // buf
+    }
+
+// -----------------------------------------------------------------------------
+// HBufC8* CCrBer::GetContentStringLC
+// Note buf is left to CleanupStack.
+// Returns value of content string.
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC8* CCrBer::GetContentStringLC()
+    {	       
+    HBufC8* buf = HBufC8::NewL(iContentLen);             // buffer to Content
+    CleanupStack::PushL(buf);
+
+    TPtr8 ptr   = buf->Des();
+
+    // Read object to buf
+    iData->Read(iContentBegin, ptr, iContentLen);    
+
+    return buf;
+    }
+
+// -----------------------------------------------------------------------------
+// HBufC* CCrBer::GetIA5StringL
+// Returns value of IA5 string object.
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC* CCrBer::GetIA5StringL()
+    {		
+    TInt err    = KErrNone;
+    TInt pos    = NULL;
+    HBufC* ret  = NULL;
+    TASN1DecIA5String dec;                              // ASN1 lib (Symbian)
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);             // buffer to object
+    TPtr8 ptr   = buf->Des();
+
+    // Read object to buf
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);    
+
+    if (err == KErrNone)
+        {
+        ret = dec.DecodeDERL(ptr, pos);                 // decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        User::Leave(err);
+        }
+     
+    CleanupStack::PopAndDestroy();                      // delete buf;
+    
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// TTime CCrBer::GetUTCTimeL
+// Returns value of UTC time object.
+// -----------------------------------------------------------------------------
+EXPORT_C TTime CCrBer::GetUTCTimeL()
+    {
+    TInt err = KErrNone;
+    TInt pos = NULL;
+    TTime ret = TTime(0);
+    TASN1DecUTCTime dec;                                // ASN1 lib (Symbian)
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);             // buffer to object
+    TPtr8 ptr   = buf->Des();
+
+    // Read object to buf
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);    
+
+    if (err == KErrNone)
+        {
+        ret = dec.DecodeDERL(ptr, pos);                 // decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        User::Leave(err);
+        }  
+
+    CleanupStack::PopAndDestroy();                      // delete buf;
+
+    return ret;
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// TTime CCrBer::GetGeneralizedTimeL
+// Returns value of generalised time object.
+// -----------------------------------------------------------------------------
+EXPORT_C TTime CCrBer::GetGeneralizedTimeL()
+    {
+    TInt err = KErrNone;
+    TInt pos = NULL;
+    TTime ret = TTime(0);
+    TASN1DecGeneralizedTime dec;                        // ASN1 lib (Symbian)
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);            // buffer to object
+    TPtr8 ptr   = buf->Des();
+
+    // Read object to buf
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);    
+
+    if (err == KErrNone)
+        {
+        ret = dec.DecodeDERL(ptr, pos);                 // decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        User::Leave(err);
+        }  
+
+    CleanupStack::PopAndDestroy();                      // delete buf;
+
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// HBufC* CCrBer::GetPrintStringL
+// Returns value of printable string object.
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC* CCrBer::GetPrintStringL()
+    {		
+    HBufC* ret = NULL;
+    TInt err = KErrNone;
+    TInt pos = NULL;
+    TASN1DecPrintableString dec;                        // ASN1 lib (Symbian)
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);             // buffer to object
+    TPtr8 ptr   = buf->Des();
+
+    // Read object to buf
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);    
+
+    if (err == KErrNone)
+        {
+        ret = dec.DecodeDERL(ptr, pos);                 // decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        User::Leave(err);
+        }
+     
+    CleanupStack::PopAndDestroy();                      // delete buf;
+
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// HBufC* CCrBer::GetTeletextStringL
+// Returns value of teletext string object.
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC* CCrBer::GetTeletextStringL()
+    {																			
+    TInt err = KErrNone;
+    TInt pos = NULL;
+    HBufC* ret = NULL;
+    TASN1DecTeletexString dec;                          // ASN1 lib (Symbian)
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);             // buffer to object
+    TPtr8 ptr   = buf->Des();
+
+    // Read object to buf
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);    
+
+    if (err == KErrNone)
+        {
+        ret = dec.DecodeDERL(ptr, pos);                 // decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        User::Leave(err);
+        }
+    
+    CleanupStack::PopAndDestroy();                      // delete buf;
+    
+    return ret;
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// HBufC8* CCrBer::GetSequence
+// Returns value of segunce object.
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC8* CCrBer::GetSequenceL()
+    {
+    TInt err = KErrNone;
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);             // buffer to object
+    TPtr8 ptr   = buf->Des();
+
+    // Read object to buf
+    err = iData->Read(ContentBegin(),ptr,ContentLen());
+	
+    if (err < KErrNone)
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        // buf = NULL;
+        User::Leave(err);
+        }
+    CleanupStack::PopAndDestroy();                      // delete buf;
+    // buf = NULL;
+
+    return ptr.AllocL();
+    }
+
+// -----------------------------------------------------------------------------
+// HBufC* CCrBer::GetVideoString
+// Returns value of video string object.
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC* CCrBer::GetVideoStringL()
+    {
+    TInt err = KErrNone;
+    HBufC* ret = NULL;
+    TInt pos   = NULL;
+    TASN1DecVideotexString dec;                         // ASN1 lib (Symbian)
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);             // buffer to object
+    TPtr8 ptr   = buf->Des();
+
+    // Read object to buf
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);    
+
+    if (err == KErrNone)
+        {
+        ret = dec.DecodeDERL(ptr, pos);                 // decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        User::Leave(err);
+        }
+    
+    CleanupStack::PopAndDestroy();                      // delete buf;
+
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// HBufC* CCrBer::GetGeneralString
+// Returns value of general string object.
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC* CCrBer::GetGeneralStringL()
+    {
+    TInt err    = KErrNone;
+    TInt pos    = NULL;
+    HBufC* ret  = NULL;
+    TASN1DecGeneralString dec;                          // ASN1 lib (Symbian)
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);             // buffer to object
+    TPtr8 ptr   = buf->Des();
+
+    // Read object to buf
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);    
+
+    if (err == KErrNone)
+        {
+        ret = dec.DecodeDERL(ptr, pos);                 // decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        User::Leave(err);
+        }
+    
+    CleanupStack::PopAndDestroy();                      // delete buf;
+
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// HBufC* CCrBer::GetVisibleStringL
+// Returns value of visible string object.
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC* CCrBer::GetVisibleStringL()
+    {
+    TInt err    = KErrNone;
+    HBufC* ret  = NULL;
+    TInt pos    = NULL;
+    TASN1DecVisibleString dec;                          // ASN1 lib (Symbian)
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);             // buffer to object
+    TPtr8 ptr   = buf->Des();
+
+    // Read object to buf
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);    
+
+    if (err == KErrNone)
+        {
+        ret = dec.DecodeDERL(ptr, pos);                 // decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        User::Leave(err);
+        }
+    
+    CleanupStack::PopAndDestroy();                      // delete buf;
+
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// HBufC* CCrBer::GetGraphicsStringL
+// Returns value of graphical string object.
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC* CCrBer::GetGraphicsStringL()
+    {
+    TInt err    = KErrNone;
+    HBufC* ret  = NULL;
+    TInt pos    = NULL;
+    TASN1DecGraphicString dec;                          // ASN1 lib (Symbian)
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);             // buffer to object
+    TPtr8 ptr   = buf->Des();
+
+    // Read object to buf
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);    
+
+    if (err == KErrNone)
+        {
+        ret = dec.DecodeDERL(ptr, pos);                 // decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        User::Leave(err);
+        }
+   
+    CleanupStack::PopAndDestroy();                      // delete buf;
+    
+    return ret;
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// HBufC* CCrBer::GetNumericStringL
+// Returns value of numeric string object.
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC* CCrBer::GetNumericStringL()
+    {
+    TInt err    = KErrNone;
+    HBufC* ret  = NULL;
+    TInt pos    = NULL;
+    TASN1DecNumericString dec;                          // ASN1 lib (Symbian)
+
+    HBufC8* buf = HBufC8::NewLC(iObjectLen);             // buffer to object
+    TPtr8 ptr   = buf->Des();
+
+    // Read object to buf
+    err = iData->Read(iObjectBegin,ptr,iObjectLen);    
+
+    if (err == KErrNone)
+        {
+        ret = dec.DecodeDERL(ptr, pos);                 // decode object
+        }
+    else
+        {        
+        CleanupStack::PopAndDestroy();                  // delete buf;
+        User::Leave(err);
+        }
+   
+    CleanupStack::PopAndDestroy();                      // delete buf;
+    
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+//  Encoding
+// -----------------------------------------------------------------------------
+
+// -----------------------------------------------------------------------------
+// CCrBer::CreateBool
+// Paremeters:     Value of the boolean object. True or False.
+// -----------------------------------------------------------------------------
+TAny CCrBer::CreateBool(TBool aBool)
+    {
+    iType       = KBerBoolean;
+    iObjectLen  = KBerBooleanLen;           // Boolean object len is always 3
+    iValue      = aBool; 
+    }                                       
+
+// -----------------------------------------------------------------------------
+// CCrBer::CreateInt
+// Paremeters:     Value of the object (positive, null or negative)
+//                 e.g. 234 or 0xFFF or -45676.
+// -----------------------------------------------------------------------------
+TAny CCrBer::CreateInt(TInt aInt)
+    {
+    iType       = KBerInteger;
+    iValue      = aInt; 
+
+    // Find out object len. Tag + len + value.
+    if (aInt == 0 || (aInt > (-0x81) &&  aInt < 0x80 ))
+        iObjectLen  = 0x03;                 
+    
+    else if (aInt > (-0x8001) && aInt < 0x8000)                            
+        iObjectLen  = 0x04;
+
+    else if (aInt > (-0x800001) && aInt < 0x800000)
+        iObjectLen  = 0x05;
+
+    else
+        iObjectLen  = 0x06;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::CreateInt
+// Paremeters:     Value of the object (positive, null or negative)
+//                 e.g. 234 or 0xFFF or -45676.
+// -----------------------------------------------------------------------------
+TAny CCrBer::CreateLongInt(RInteger& aData)
+    {
+    TInt len    = aData.ByteCount();
+    iType       = KBerInteger;
+    iValue      = NULL;
+    iInt        = RInteger::NewL(aData);
+
+    iObjectLen  = KBerShortLen + len;       // Tag + len(lenlen) + string 
+
+    if (len >= KBerLongLengthBit)
+        {         
+        while (len > NULL)                  // add number of lenbytes 
+            {
+            len >>= KOctetWidth;            // Next byte
+            iObjectLen++;   
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::CreateNull
+// -----------------------------------------------------------------------------
+TAny CCrBer::CreateNull()
+    {
+    iType       = KBerNull;                 // Tag
+    iObjectLen  = KBerNullLen;              // 05 00
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::CreateOId
+// Paremeters:     Pointer to string. e.g.(1.2.43.4335.242)
+// -----------------------------------------------------------------------------
+TAny CCrBer::CreateOIdL(TDesC8* aString)
+    {
+    CCrBerSet* set = CCrBerSet::NewLC(1);
+    TInt len    = set->AppendObjectIdL(*aString, ETrue);// ask Oid content len
+    iType       = KBerOid;
+    iValuePtr   = aString;
+        
+    iObjectLen  = (len > NULL) ? KBerShortLen + len : 0; // tag + len + content
+   
+    CleanupStack::PopAndDestroy();  // delete set;
+    // set = NULL;    
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CCrBer::CreateString
+// Paremeters:     Type of object and pointer to string.
+// -----------------------------------------------------------------------------
+TAny CCrBer::CreateString(TBerTag aTag, TDesC8* aString)
+    {
+    TInt len    = aString->Length();
+    iType       = aTag;
+    iValuePtr   = aString;  
+    iObjectLen  = KBerShortLen + len;       // Tag + len(lenlen) + string 
+
+    if (len >= KBerLongLengthBit)
+        {         
+        while (len > NULL)                  // add number of lenbytes 
+            {
+            len >>= KOctetWidth;            // Next byte
+            iObjectLen++;   
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::CreateString
+// -----------------------------------------------------------------------------
+TAny CCrBer::CreateString(TBerTag aTag, CCrData* aData)
+    {
+    TInt len    =  0;
+    aData->Size(len);
+    iType       = aTag;
+    iData   = aData;  
+    iObjectLen  = KBerShortLen + len;       // Tag + len(lenlen) + string 
+
+    if (len >= KBerLongLengthBit)
+        {         
+        while (len > NULL)                  // add number of lenbytes 
+            {
+            len >>= KOctetWidth;            // Next byte
+            iObjectLen++;   
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCrBer::CreateStart
+// Paremeters:     First parameter is tag type (e.g. seq). Second param is
+//                 True if definite length is wanted.
+//                 False if indefinite (xx 80) .
+// -----------------------------------------------------------------------------
+TAny CCrBer::CreateStart(TBerTag aTag, TBool aDefinite)
+    {
+    iType = aTag;
+
+    // Definite object length = 0 (set rigth length later).
+    // Indefinite object length is always 4 (Tag + 80 + 00 + 00)
+    if (!aDefinite)
+        {
+        iObjectLen = KBerIndefiniteLen;
+        }
+    }                                                   
+                                            
+// -----------------------------------------------------------------------------
+// CCrBer::CreateEnd
+// -----------------------------------------------------------------------------
+TAny CCrBer::CreateEnd()
+    {
+    iType   = KBerEndOfContent;                   // =0x00
+    iValue  = KBerEndOfContent;
+    }                                       
+
+// -----------------------------------------------------------------------------
+// CCrBer::CreateBEREncodedObject
+// This fuction can be used to create a BER object
+// from buffer, which already contains a full BER
+// encoded object.
+// Paremeters:     Buffer containing BER encoded object.
+// -----------------------------------------------------------------------------
+TAny CCrBer::CreateBEREncodedObject(TDesC8* aBuffer)
+    {
+    iType      = KBerEncodedObject;
+    iValuePtr  = aBuffer;  
+    iObjectLen = aBuffer->Length();
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+                                                                                
+// ---------------------------------------------------------
+// E32Dll
+// DLL entry point
+// ---------------------------------------------------------
+//
+#ifndef EKA2
+GLDEF_C TInt E32Dll(TDllReason /*aReason*/)
+    {
+    return KErrNone;
+    }
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrBer/Src/crdata.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,668 @@
+/*
+* Copyright (c) 2000, 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This module contains the implementation of CCrTemplate class. 
+*
+*/
+
+
+
+//  INCLUDE FILES
+#include "crdata.h"
+
+
+
+// -----------------------------------------------------------------------------
+// CCrData
+// Constructors
+// These functions construct CCrData object.
+// -----------------------------------------------------------------------------
+CCrData::CCrData()  : iIsFile(ETrue), iPointer(0), iBuffer(NULL)
+    { 
+    }
+
+CCrData::CCrData(TBool aIsFile) : iIsFile(aIsFile), iPointer(0), iBuffer(NULL), iPath(NULL)
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData
+// Destructor
+// This function destructs CCrData object.
+// -----------------------------------------------------------------------------
+CCrData::~CCrData()
+    {
+    if (iBuffer != NULL)
+        {
+        delete iBuffer;
+        }
+    if (iPath != NULL)
+        {
+        delete iPath;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData::ConstructL
+// This function initializes CCrData object's member objects.
+// -----------------------------------------------------------------------------
+TAny CCrData::ConstructL()
+    {
+    if (iIsFile == EFalse)
+        {
+        iBuffer = HBufC8::NewL(0);
+        iPath = HBufC::NewL(0);
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData::NewLC
+// -----------------------------------------------------------------------------
+EXPORT_C CCrData* CCrData::NewLC(TBool aIsFile) // default value ETrue
+    {
+    CCrData* self = new CCrData(aIsFile);
+    CleanupStack::PushL(self);
+
+    self->ConstructL();
+
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData::NewL
+// -----------------------------------------------------------------------------
+EXPORT_C CCrData* CCrData::NewL(TBool aIsFile) // default value ETrue
+    {
+    CCrData* self = NewLC(aIsFile);
+    CleanupStack::Pop();
+
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData::Open
+// Opens an existing file for reading or writing. If the file 
+// does not already exist, an error is returned.
+// Parameters:    aFs The file server session
+//                aName The name of the file. Any path 
+//                      components which are not specified here will be 
+//                      taken from the session path.
+//                aFileMode The mode in which the file is opened. 
+//                          For more information see EFileShareExclusive and 
+//                          other file sharing and access modes.
+// Return Values:  TInt KErrNone if successful, otherwise
+//                 another of the system-wide error codes.
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrData::Open(RFs& aFs,const TDesC& aName,TUint aFileMode)
+    {
+    if (iIsFile) // file
+        {
+        TInt result = iFile.Open(aFs, aName, aFileMode);
+        SetPathL(aName);
+        return result;
+        }
+    else // Buffer
+        {
+        return KErrNotSupported; 
+        }
+    
+    }
+
+EXPORT_C TInt CCrData::Open(RFs& aFs,TUint aFileMode)
+    {
+    TInt result = KErrNone;
+    if (iIsFile) // file
+        {
+        if (iPath != NULL)
+            {
+            result = iFile.Open(aFs, *iPath, aFileMode);
+            }
+        else
+            {
+            result = KErrPathNotFound;
+            }
+        }
+    else // Buffer
+        {
+        result = KErrNotSupported; 
+        }
+    return result;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCrData::Replace
+// Replaces a file. If there is an existing file with the same
+// name, this function will overwrite it. If the file does not 
+// already exist, this function creates it.
+// Parameters:    aFs The file server session
+//                aName The name of the file. 
+//                      Any path components which are not specified 
+//                      here will be taken from the session path.
+//                 aFileMode The mode in which the file  is opened. 
+//                           For more information see EFileShareExclusive and 
+//                           other file sharing and access modes. Note that the 
+//                           access mode is set to 
+//                           EFileWrite whatever the caller specifies.
+// Return Values:  KErrNone if successful, otherwise
+//                 another of the system-wide error codes.
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrData::Replace(RFs& aFs, const TDesC& aName, TUint aFileMode)
+    {
+    if (iIsFile) // File
+        {
+        TInt result = iFile.Replace(aFs, aName, aFileMode);
+        return result;
+        }
+    else // Buffer
+        {
+        return KErrNotSupported; 
+        }  
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData::Close
+// Closes the file. Any open files are closed when the file server 
+// session is closed. Close() is guaranteed to return, and provides 
+// no indication of whether it completed successfully or not. When 
+// closing a file that you have written to, you should ensure that
+// data is committed to the file by invoking RFile::Flush() before 
+// closing. If Flush() completes successfully, Close() is essentially 
+// a no-operation.
+// -----------------------------------------------------------------------------
+EXPORT_C void CCrData::Close()
+    {
+    if (iIsFile) // File
+        {
+        iFile.Close();
+        return; 
+        }
+    else // Buffer
+        {
+        return; 
+        }      
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData::Read
+// Reading transfers data from a file (or a buffer) to a descriptor.
+// If CCrData object is created to be a file function only call 
+// RFile::Read(.), but if CCrData is buffer, function makes same things
+// to buffer as RFile::Read make to file. (See EPOC documentation)
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrData::Read(TDes8& aDes)
+    {
+    TInt err = KErrNone;
+
+    if (!iIsFile)                            // CCrData is buf 
+        {       
+        if (aDes.MaxLength() < iBuffer->Length())
+            {
+            err = KErrOverflow;
+            }
+        else 
+            {
+            aDes.Copy(*iBuffer);            // Copy iBuffer to aDes
+            iPointer = aDes.Length();       // Set pointer to end of buf
+            }           
+        }
+    else                                    // else it is file
+        {  
+        err = iFile.Read(aDes); 
+        }
+    return err;                             // error code
+    }
+
+
+EXPORT_C TInt CCrData::Read(TDes8& aDes,TInt aLength)
+    {
+    TInt err = KErrNone;
+    TInt i;
+
+    if (!iIsFile)                           // CCrData is buffer
+        {       
+        if ((aLength < NULL) || (aLength > aDes.MaxLength())) 
+            {
+            err = KErrGeneral;
+            }
+        else 
+            {
+            aDes.Zero();
+            for (i = iPointer; (i < (aLength + iPointer)) &&
+                (i < iBuffer->Length()); i++)
+                {
+                aDes.Append((*iBuffer)[i]);        // append data to aDes
+                }
+            iPointer = i;                   // set pointer to next byte
+            }
+        }
+    else                                    // else CCrData is file
+        {
+        err = iFile.Read(aDes, aLength);
+        }
+
+    return err;
+    }
+
+
+EXPORT_C TInt CCrData::Read(TInt aPos,TDes8& aDes,TInt aLength)
+    {
+    TInt i;
+    TInt err = KErrNone;
+
+    if (!iIsFile)                           // CCrDAta is buffer 
+        {       
+        if (aLength < NULL)                 // aLength must be positive 
+            {   
+            err = KErrArgument;
+            }
+        else if (aLength > aDes.MaxLength()) // if buffer is too small 
+            {
+            err = KErrOverflow;            
+            }
+        else 
+            {
+            aDes.Delete(0, aDes.Length());  // delete old string
+            TPtr8 ptr = iBuffer->Des();         
+        
+            for (i = aPos; (i < (aLength + aPos)) &&
+                (i < iBuffer->Length()); i++)
+                {
+                aDes.Append(ptr[i]);
+                }
+            iPointer  = i;                  // set pointer to end of read       
+            }
+        }
+    else                                    // CCrData is file
+        { 
+        err = iFile.Read(aPos, aDes, aLength);
+        }
+
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData::Write
+// Writing transfers data from a descriptor to a buffer or file.
+// If CCrData object is created to be a file function only call 
+// RFile::Write(.), but if CCrData is buffer, function makes same things
+// to buffer as RFile::Write make to file. After Write(..) iPointer is moved
+// to end of the buffer. 
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrData::Write(const TDesC8& aDes)
+    { 
+    TInt err = KErrNone;
+    if (!iIsFile)                           // buf
+        {
+        err = Write(aDes, aDes.Length()); 
+        }
+
+     else                                    // file
+        {
+        err = iFile.Write(aDes);
+        }
+
+    return err;
+    }
+
+EXPORT_C TInt CCrData::Write(const TDesC8& aDes, TInt aLength)
+    { 
+    TInt err = KErrNone;
+    if (aLength < NULL)                     // aLen must be positive 
+        {                                   
+        err = KErrArgument;           
+        }
+     
+    if (!iIsFile)                           // buf
+        { 
+        TInt bufferLength = iBuffer->Length();
+        TInt neededBufferLength = iPointer + aLength;
+        if (neededBufferLength > bufferLength) // Reallocation is needed
+            {
+            TRAP(err, iBuffer = iBuffer->ReAllocL(neededBufferLength)); 
+            if (err != KErrNone)
+                    {
+                    return KErrNoMemory;
+                    }
+            }
+            
+        TPtr8 ptr = iBuffer->Des();             
+        // append new data, ONLY the amount of aLength
+        if (aLength == aDes.Length())
+            {
+            ptr.Append(aDes); 
+            }
+        else // aLength < a.Des.Length()
+            {
+            ptr.Append(aDes.Left(aLength));
+            }
+        // iPointer is moved to the end of the buffer.        
+        iPointer = iBuffer->Length();
+        }
+    else                                    // file
+        {
+        err = iFile.Write(aDes);
+        }
+
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData::Zero
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrData::Zero(const TInt aPos, const TInt aLength)
+    {
+	TPtr8 ptr = iBuffer->Des();
+	if (ptr.Length() < aPos + aLength)
+	    {
+		// Out of bounds
+		return KErrArgument;
+	    }
+	for (TInt i = 0; i < aLength; i++)
+	    {
+		ptr[aPos+i] = 0;
+	    }
+	return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData::Seek
+// If CCrData object is created to be a file function only call 
+// RFile::Seek(.), but if CCrData is buffer, function makes same things
+// to buffer as RFile::Seek make to file. (See EPOC documentation)
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrData::Seek(TSeek aMode,TInt& aPos)
+    {
+    TInt err = KErrNone;
+
+    if (aPos < NULL)                        // aPos must be positive
+        {
+        err = KErrArgument;
+        }
+
+    else if (!iIsFile)                      // CCrData is buffer
+        {
+        switch (aMode)
+            {
+            case (ESeekCurrent):            // this place
+                {
+                iPointer += aPos;              
+                break;
+                }
+            case (ESeekStart):              // from start of buf
+                {                
+                iPointer = aPos;   
+                break;
+                }
+            case (ESeekEnd):                // from end of buf 
+                {
+                iPointer = iBuffer->Length() - aPos;
+                break;
+                }
+            default:
+                {
+                break;                      // ESeekAddress
+                }
+            }
+    
+            if (iPointer < NULL)            // iPointer must be positive
+                {
+                iPointer = NULL;            // set pointer to start of buf
+                }
+
+            else if (iPointer > iBuffer->Length())
+                {
+                iPointer = iBuffer->Length();   // set pointer to end of buf
+                }
+          
+            aPos = iPointer;
+            
+        }
+
+    else                                    // CCrData is file
+        {       
+        err = iFile.Seek(aMode, aPos);
+        }
+    
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData::Size
+// Reading the size of data.
+// If CCrData is a buffer, returns length of the buffer. Otherwise 
+// calls RFile::Size( TInt ).
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrData::Size(TInt& aSize)
+    {
+    TInt err = KErrNone;
+
+    if (!iIsFile)                            // CCrData is buf 
+        {       
+        aSize = iBuffer->Length();
+        }
+    else                                    // else it is file
+        {  
+        err = iFile.Size(aSize); 
+        }
+    return err;                             // error code
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCrData::LineL
+// LineL sets data from the current place, where iPointer is, till next new
+// line character to aLine. 
+// iPointer moves to the following item from the found new line character.
+// If no new line character is found, aLine is the rest of the data and 
+// iPointer is moved to the end of the iBuffer or the iFile.
+// Return Values:  KErrNone if everything succeeds
+//                 KErrNoMemory if aLine is not length enough
+//                 KErrEof if iPointer is at the end of file.
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrData::LineL(TDes8& aLine)
+    {
+    TBufC8<2> newLine(KNewLine);  // New line
+
+    // Area to find the new line
+    TInt size = 0;
+    Size(size);
+    TInt currentPlace = iPointer;
+    TInt neededLengthToFind = size - currentPlace;
+
+    if(neededLengthToFind == 0) // If the area is empty
+        {
+        return KErrEof;
+        }
+    TInt newLinePlace = 0;
+
+    if (!iIsFile) // CCrData is a buffer.
+        {
+        TPtrC8 temp = iBuffer->Mid(currentPlace, neededLengthToFind);
+
+        // Find next new line.
+        newLinePlace = temp.Find(newLine);
+        // If not found, return the whole area.
+        if (newLinePlace == KErrNotFound)
+            {
+            newLinePlace = neededLengthToFind;
+            }
+        else
+            {
+            newLinePlace = newLinePlace + newLine.Length();
+            }
+
+        
+        if (aLine.MaxLength() < newLinePlace)
+            {
+            return KErrNoMemory;
+            }
+
+        // Put the line to aLine
+        aLine = temp.Left(newLinePlace);
+        }
+
+    else // CCrData is a file.
+        {
+
+        HBufC8* tempBuf = HBufC8::NewL(neededLengthToFind);
+        TDes8 tempDes = tempBuf->Des();
+
+        // Read data to a buffer from iPointer to end of file
+        Read(currentPlace, tempDes, neededLengthToFind);
+
+        // Find the next new line character
+        newLinePlace = tempDes.Find(newLine);
+        // If not found, return the whole area.
+        if (newLinePlace == KErrNotFound)
+            {
+            newLinePlace = neededLengthToFind;
+            }
+        else
+            {
+            newLinePlace = newLinePlace + newLine.Length();
+            }
+
+        // Is there enough memory
+        if (aLine.MaxLength() < newLinePlace)
+            {
+            delete tempBuf;
+            tempBuf = NULL;
+            return KErrNoMemory;
+            }
+
+        // Put data to aLine
+        aLine = tempBuf->Left(newLinePlace);
+        
+        delete tempBuf;
+        tempBuf = NULL;
+        }
+
+    // Move iPointer to next place from newLine.
+    iPointer = currentPlace + newLinePlace;
+
+    return KErrNone;
+            
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData::Path
+// -----------------------------------------------------------------------------
+EXPORT_C HBufC* CCrData::Path()
+    {
+    return iPath;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData::SetPathL
+// -----------------------------------------------------------------------------
+EXPORT_C TAny CCrData::SetPathL(const TDesC& aPath )
+    {
+    delete iPath;
+    iPath = NULL;
+    iPath = HBufC::NewL( aPath.Length() );
+    TPtr pointer = iPath->Des();
+    pointer.Copy( aPath );
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData::IsFile
+// -----------------------------------------------------------------------------
+EXPORT_C TBool CCrData::IsFile()
+    {
+    return iIsFile;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrData::Delete
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CCrData::Delete( TInt aPos, TInt aLength )
+    {
+    if (!iIsFile)                            // CCrData is buf 
+        {       
+        if(aPos >= 0)
+            {
+            TPtr8 pointer = iBuffer->Des();
+            pointer.Delete(aPos, aLength);
+            }
+        else
+            {
+            return KErrArgument;
+            }
+        }
+    else                                    // else it is file
+        {  
+        return KErrNotSupported;
+        }
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrDataSet
+// -----------------------------------------------------------------------------
+
+
+// -----------------------------------------------------------------------------
+// CCrDataSet
+// Constructor.
+// This function constructs CCrDataSet object.
+// -----------------------------------------------------------------------------
+CCrDataSet::CCrDataSet(TInt aGranularity)
+    : CArrayPtrSeg<CCrData>(aGranularity)
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCrDataSet
+// Destructor.
+// This function destructs CCrDataSet object.
+// -----------------------------------------------------------------------------
+CCrDataSet::~CCrDataSet()
+    {
+    ResetAndDestroy();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrDataSet::ConstructL
+// This function initializes CCrDataSet object's member objects.
+// -----------------------------------------------------------------------------
+TAny CCrDataSet::ConstructL()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CCrDataSet::NewLC
+// -----------------------------------------------------------------------------
+EXPORT_C CCrDataSet* CCrDataSet::NewLC(TInt aGranularity)
+    {
+    CCrDataSet* self = new CCrDataSet(aGranularity);
+    CleanupStack::PushL(self);
+
+    self->ConstructL();
+
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CCrDataSet::NewL
+// -----------------------------------------------------------------------------
+EXPORT_C CCrDataSet* CCrDataSet::NewL(TInt aGranularity)
+    {
+    CCrDataSet* self = NewLC(aGranularity);
+    CleanupStack::Pop();
+
+    return self; 
+    }
+
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrBer/bwinscw/crberU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,108 @@
+EXPORTS
+	??0CCrData@@QAE@H@Z @ 1 NONAME ; CCrData::CCrData(int)
+	??0CCrData@@QAE@XZ @ 2 NONAME ; CCrData::CCrData(void)
+	??1CCrBer@@UAE@XZ @ 3 NONAME ; CCrBer::~CCrBer(void)
+	??1CCrBerSet@@UAE@XZ @ 4 NONAME ; CCrBerSet::~CCrBerSet(void)
+	??1CCrData@@UAE@XZ @ 5 NONAME ; CCrData::~CCrData(void)
+	?AddToContentLen@CCrBer@@QAEXH@Z @ 6 NONAME ; void CCrBer::AddToContentLen(int)
+	?AppendAndUpdateL@CCrBerSet@@QAEXPAVCCrBer@@@Z @ 7 NONAME ; void CCrBerSet::AppendAndUpdateL(class CCrBer *)
+	?BufferL@CCrBer@@SAHPAVHBufC16@@PAVCCrData@@IE@Z @ 8 NONAME ; int CCrBer::BufferL(class HBufC16 *, class CCrData *, unsigned int, unsigned char)
+	?BufferL@CCrBer@@SAHPAVHBufC8@@PAVCCrData@@II@Z @ 9 NONAME ; int CCrBer::BufferL(class HBufC8 *, class CCrData *, unsigned int, unsigned int)
+	?Close@CCrData@@QAEXXZ @ 10 NONAME ; void CCrData::Close(void)
+	?CloseLastSeqOrSet@CCrBerSet@@QAEXI@Z @ 11 NONAME ; void CCrBerSet::CloseLastSeqOrSet(unsigned int)
+	?Content@CCrBer@@QAEHPAVHBufC8@@@Z @ 12 NONAME ; int CCrBer::Content(class HBufC8 *)
+	?ContentBegin@CCrBer@@QAEHXZ @ 13 NONAME ; int CCrBer::ContentBegin(void)
+	?ContentL@CCrBer@@QAEHPAVHBufC16@@@Z @ 14 NONAME ; int CCrBer::ContentL(class HBufC16 *)
+	?ContentLen@CCrBer@@QAEHXZ @ 15 NONAME ; int CCrBer::ContentLen(void)
+	?CreateBEREncodedObjectL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 16 NONAME ; void CCrBerSet::CreateBEREncodedObjectL(class TDesC8 &)
+	?CreateBoolL@CCrBerSet@@QAEXH@Z @ 17 NONAME ; void CCrBerSet::CreateBoolL(int)
+	?CreateConstructedStartL@CCrBerSet@@QAEXEH@Z @ 18 NONAME ; void CCrBerSet::CreateConstructedStartL(unsigned char, int)
+	?CreateEndL@CCrBerSet@@QAEXXZ @ 19 NONAME ; void CCrBerSet::CreateEndL(void)
+	?CreateGenTimeL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 20 NONAME ; void CCrBerSet::CreateGenTimeL(class TDesC8 &)
+	?CreateGeneralL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 21 NONAME ; void CCrBerSet::CreateGeneralL(class TDesC8 &)
+	?CreateGraphicalL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 22 NONAME ; void CCrBerSet::CreateGraphicalL(class TDesC8 &)
+	?CreateIA5L@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 23 NONAME ; void CCrBerSet::CreateIA5L(class TDesC8 &)
+	?CreateIntL@CCrBerSet@@QAEXH@Z @ 24 NONAME ; void CCrBerSet::CreateIntL(int)
+	?CreateLongIntL@CCrBerSet@@QAEXAAVRInteger@@@Z @ 25 NONAME ; void CCrBerSet::CreateLongIntL(class RInteger &)
+	?CreateNullL@CCrBerSet@@QAEXXZ @ 26 NONAME ; void CCrBerSet::CreateNullL(void)
+	?CreateNumericL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 27 NONAME ; void CCrBerSet::CreateNumericL(class TDesC8 &)
+	?CreateOIdL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 28 NONAME ; void CCrBerSet::CreateOIdL(class TDesC8 &)
+	?CreateOctetL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 29 NONAME ; void CCrBerSet::CreateOctetL(class TDesC8 &)
+	?CreateOctetL@CCrBerSet@@QAEXPAVCCrData@@@Z @ 30 NONAME ; void CCrBerSet::CreateOctetL(class CCrData *)
+	?CreatePrintableL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 31 NONAME ; void CCrBerSet::CreatePrintableL(class TDesC8 &)
+	?CreateSeqStartL@CCrBerSet@@QAEXH@Z @ 32 NONAME ; void CCrBerSet::CreateSeqStartL(int)
+	?CreateSetStartL@CCrBerSet@@QAEXH@Z @ 33 NONAME ; void CCrBerSet::CreateSetStartL(int)
+	?CreateT61L@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 34 NONAME ; void CCrBerSet::CreateT61L(class TDesC8 &)
+	?CreateUTCL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 35 NONAME ; void CCrBerSet::CreateUTCL(class TDesC8 &)
+	?CreateVideoTexL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 36 NONAME ; void CCrBerSet::CreateVideoTexL(class TDesC8 &)
+	?CreateVisibleL@CCrBerSet@@QAEXAAVTDesC8@@@Z @ 37 NONAME ; void CCrBerSet::CreateVisibleL(class TDesC8 &)
+	?Data@CCrBer@@QAEPAVCCrData@@XZ @ 38 NONAME ; class CCrData * CCrBer::Data(void)
+	?Delete@CCrData@@QAEHHH@Z @ 39 NONAME ; int CCrData::Delete(int, int)
+	?FindEndOfContent@CCrBer@@QAEIPAVCCrData@@@Z @ 40 NONAME ; unsigned int CCrBer::FindEndOfContent(class CCrData *)
+	?FlushL@CCrBerSet@@QAEHPAVCCrData@@@Z @ 41 NONAME ; int CCrBerSet::FlushL(class CCrData *)
+	?GetBigInt@CCrBer@@QAE?AVRInteger@@XZ @ 42 NONAME ; class RInteger CCrBer::GetBigInt(void)
+	?GetBooleanL@CCrBer@@QAEHXZ @ 43 NONAME ; int CCrBer::GetBooleanL(void)
+	?GetContentStringLC@CCrBer@@QAEPAVHBufC8@@XZ @ 44 NONAME ; class HBufC8 * CCrBer::GetContentStringLC(void)
+	?GetGeneralStringL@CCrBer@@QAEPAVHBufC16@@XZ @ 45 NONAME ; class HBufC16 * CCrBer::GetGeneralStringL(void)
+	?GetGeneralizedTimeL@CCrBer@@QAE?AVTTime@@XZ @ 46 NONAME ; class TTime CCrBer::GetGeneralizedTimeL(void)
+	?GetGraphicsStringL@CCrBer@@QAEPAVHBufC16@@XZ @ 47 NONAME ; class HBufC16 * CCrBer::GetGraphicsStringL(void)
+	?GetIA5StringL@CCrBer@@QAEPAVHBufC16@@XZ @ 48 NONAME ; class HBufC16 * CCrBer::GetIA5StringL(void)
+	?GetIntegerL@CCrBer@@QAEHXZ @ 49 NONAME ; int CCrBer::GetIntegerL(void)
+	?GetLongIntegerL@CCrBer@@QAE?AVRInteger@@XZ @ 50 NONAME ; class RInteger CCrBer::GetLongIntegerL(void)
+	?GetNumericStringL@CCrBer@@QAEPAVHBufC16@@XZ @ 51 NONAME ; class HBufC16 * CCrBer::GetNumericStringL(void)
+	?GetOctetStringL@CCrBer@@QAEPAVHBufC8@@XZ @ 52 NONAME ; class HBufC8 * CCrBer::GetOctetStringL(void)
+	?GetOctetStringL@CCrBer@@QAEXAAVCCrData@@@Z @ 53 NONAME ; void CCrBer::GetOctetStringL(class CCrData &)
+	?GetOidL@CCrBer@@QAEPAVHBufC16@@XZ @ 54 NONAME ; class HBufC16 * CCrBer::GetOidL(void)
+	?GetPrintStringL@CCrBer@@QAEPAVHBufC16@@XZ @ 55 NONAME ; class HBufC16 * CCrBer::GetPrintStringL(void)
+	?GetSequenceL@CCrBer@@QAEPAVHBufC8@@XZ @ 56 NONAME ; class HBufC8 * CCrBer::GetSequenceL(void)
+	?GetTeletextStringL@CCrBer@@QAEPAVHBufC16@@XZ @ 57 NONAME ; class HBufC16 * CCrBer::GetTeletextStringL(void)
+	?GetUTCTimeL@CCrBer@@QAE?AVTTime@@XZ @ 58 NONAME ; class TTime CCrBer::GetUTCTimeL(void)
+	?GetVideoStringL@CCrBer@@QAEPAVHBufC16@@XZ @ 59 NONAME ; class HBufC16 * CCrBer::GetVideoStringL(void)
+	?GetVisibleStringL@CCrBer@@QAEPAVHBufC16@@XZ @ 60 NONAME ; class HBufC16 * CCrBer::GetVisibleStringL(void)
+	?Indefinite@CCrBer@@QAEHXZ @ 61 NONAME ; int CCrBer::Indefinite(void)
+	?IsFile@CCrData@@QAEHXZ @ 62 NONAME ; int CCrData::IsFile(void)
+	?IsKnownType@CCrBer@@SAHE@Z @ 63 NONAME ; int CCrBer::IsKnownType(unsigned char)
+	?IsSeqOrSet@CCrBer@@SAHE@Z @ 64 NONAME ; int CCrBer::IsSeqOrSet(unsigned char)
+	?LenLen@CCrBer@@QAEHXZ @ 65 NONAME ; int CCrBer::LenLen(void)
+	?Level@CCrBer@@QAEIXZ @ 66 NONAME ; unsigned int CCrBer::Level(void)
+	?LineL@CCrData@@QAEHAAVTDes8@@@Z @ 67 NONAME ; int CCrData::LineL(class TDes8 &)
+	?NewL@CCrBer@@SAPAV1@H@Z @ 68 NONAME ; class CCrBer * CCrBer::NewL(int)
+	?NewL@CCrBerSet@@SAPAV1@H@Z @ 69 NONAME ; class CCrBerSet * CCrBerSet::NewL(int)
+	?NewL@CCrData@@SAPAV1@H@Z @ 70 NONAME ; class CCrData * CCrData::NewL(int)
+	?NewL@CCrDataSet@@SAPAV1@H@Z @ 71 NONAME ; class CCrDataSet * CCrDataSet::NewL(int)
+	?NewLC@CCrBer@@SAPAV1@H@Z @ 72 NONAME ; class CCrBer * CCrBer::NewLC(int)
+	?NewLC@CCrBerSet@@SAPAV1@H@Z @ 73 NONAME ; class CCrBerSet * CCrBerSet::NewLC(int)
+	?NewLC@CCrData@@SAPAV1@H@Z @ 74 NONAME ; class CCrData * CCrData::NewLC(int)
+	?NewLC@CCrDataSet@@SAPAV1@H@Z @ 75 NONAME ; class CCrDataSet * CCrDataSet::NewLC(int)
+	?Object@CCrBer@@QAEHPAVHBufC8@@@Z @ 76 NONAME ; int CCrBer::Object(class HBufC8 *)
+	?ObjectBegin@CCrBer@@QAEHXZ @ 77 NONAME ; int CCrBer::ObjectBegin(void)
+	?ObjectL@CCrBer@@QAEHPAVHBufC16@@@Z @ 78 NONAME ; int CCrBer::ObjectL(class HBufC16 *)
+	?ObjectLen@CCrBer@@QAEHXZ @ 79 NONAME ; int CCrBer::ObjectLen(void)
+	?Open@CCrData@@QAEHAAVRFs@@ABVTDesC16@@I@Z @ 80 NONAME ; int CCrData::Open(class RFs &, class TDesC16 const &, unsigned int)
+	?Open@CCrData@@QAEHAAVRFs@@I@Z @ 81 NONAME ; int CCrData::Open(class RFs &, unsigned int)
+	?OpenConstructedEncodingL@CCrBer@@QAEHAAVCCrData@@@Z @ 82 NONAME ; int CCrBer::OpenConstructedEncodingL(class CCrData &)
+	?OpenConstructedEncodingWithTagL@CCrBer@@QAEIPAVCCrData@@AAV1@PAVHBufC8@@@Z @ 83 NONAME ; unsigned int CCrBer::OpenConstructedEncodingWithTagL(class CCrData *, class CCrBer &, class HBufC8 *)
+	?OpenL@CCrBerSet@@QAEIPAVCCrData@@E@Z @ 84 NONAME ; unsigned int CCrBerSet::OpenL(class CCrData *, unsigned char)
+	?Path@CCrData@@QAEPAVHBufC16@@XZ @ 85 NONAME ; class HBufC16 * CCrData::Path(void)
+	?Read@CCrBer@@QAEEPAVCCrData@@@Z @ 86 NONAME ; unsigned char CCrBer::Read(class CCrData *)
+	?Read@CCrData@@QAEHAAVTDes8@@@Z @ 87 NONAME ; int CCrData::Read(class TDes8 &)
+	?Read@CCrData@@QAEHAAVTDes8@@H@Z @ 88 NONAME ; int CCrData::Read(class TDes8 &, int)
+	?Read@CCrData@@QAEHHAAVTDes8@@H@Z @ 89 NONAME ; int CCrData::Read(int, class TDes8 &, int)
+	?ReadLen@CCrBer@@QAEIPAVCCrData@@AAHPAE@Z @ 90 NONAME ; unsigned int CCrBer::ReadLen(class CCrData *, int &, unsigned char *)
+	?ReadType@CCrBer@@SAEPAVCCrData@@@Z @ 91 NONAME ; unsigned char CCrBer::ReadType(class CCrData *)
+	?Replace@CCrData@@QAEHAAVRFs@@ABVTDesC16@@I@Z @ 92 NONAME ; int CCrData::Replace(class RFs &, class TDesC16 const &, unsigned int)
+	?Seek@CCrData@@QAEHW4TSeek@@AAH@Z @ 93 NONAME ; int CCrData::Seek(enum TSeek, int &)
+	?SetLevel@CCrBer@@QAEII@Z @ 94 NONAME ; unsigned int CCrBer::SetLevel(unsigned int)
+	?SetObjLenWithOutContent@CCrBer@@QAEXI@Z @ 95 NONAME ; void CCrBer::SetObjLenWithOutContent(unsigned int)
+	?SetObjectLen@CCrBer@@QAEXXZ @ 96 NONAME ; void CCrBer::SetObjectLen(void)
+	?SetPathL@CCrData@@QAEXABVTDesC16@@@Z @ 97 NONAME ; void CCrData::SetPathL(class TDesC16 const &)
+	?SetValue@CCrBer@@QAEXH@Z @ 98 NONAME ; void CCrBer::SetValue(int)
+	?Size@CCrData@@QAEHAAH@Z @ 99 NONAME ; int CCrData::Size(int &)
+	?Type@CCrBer@@QAEEXZ @ 100 NONAME ; unsigned char CCrBer::Type(void)
+	?Update@CCrBerSet@@QAEXPAVCCrBer@@@Z @ 101 NONAME ; void CCrBerSet::Update(class CCrBer *)
+	?Value@CCrBer@@QAEHXZ @ 102 NONAME ; int CCrBer::Value(void)
+	?ValuePtr@CCrBer@@QAEPAVTDesC8@@XZ @ 103 NONAME ; class TDesC8 * CCrBer::ValuePtr(void)
+	?Write@CCrData@@QAEHABVTDesC8@@@Z @ 104 NONAME ; int CCrData::Write(class TDesC8 const &)
+	?Write@CCrData@@QAEHABVTDesC8@@H@Z @ 105 NONAME ; int CCrData::Write(class TDesC8 const &, int)
+	?Zero@CCrData@@QAEHHH@Z @ 106 NONAME ; int CCrData::Zero(int, int)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrBer/eabi/crberU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,105 @@
+EXPORTS
+	_ZN10CCrDataSet4NewLEi @ 1 NONAME
+	_ZN10CCrDataSet5NewLCEi @ 2 NONAME
+	_ZN6CCrBer10ContentLenEv @ 3 NONAME
+	_ZN6CCrBer10IndefiniteEv @ 4 NONAME
+	_ZN6CCrBer10IsSeqOrSetEh @ 5 NONAME
+	_ZN6CCrBer11GetBooleanLEv @ 6 NONAME
+	_ZN6CCrBer11GetIntegerLEv @ 7 NONAME
+	_ZN6CCrBer11GetUTCTimeLEv @ 8 NONAME
+	_ZN6CCrBer11IsKnownTypeEh @ 9 NONAME
+	_ZN6CCrBer11ObjectBeginEv @ 10 NONAME
+	_ZN6CCrBer12ContentBeginEv @ 11 NONAME
+	_ZN6CCrBer12GetSequenceLEv @ 12 NONAME
+	_ZN6CCrBer12SetObjectLenEv @ 13 NONAME
+	_ZN6CCrBer13GetIA5StringLEv @ 14 NONAME
+	_ZN6CCrBer15AddToContentLenEi @ 15 NONAME
+	_ZN6CCrBer15GetLongIntegerLEv @ 16 NONAME
+	_ZN6CCrBer15GetOctetStringLER7CCrData @ 17 NONAME
+	_ZN6CCrBer15GetOctetStringLEv @ 18 NONAME
+	_ZN6CCrBer15GetPrintStringLEv @ 19 NONAME
+	_ZN6CCrBer15GetVideoStringLEv @ 20 NONAME
+	_ZN6CCrBer16FindEndOfContentEP7CCrData @ 21 NONAME
+	_ZN6CCrBer17GetGeneralStringLEv @ 22 NONAME
+	_ZN6CCrBer17GetNumericStringLEv @ 23 NONAME
+	_ZN6CCrBer17GetVisibleStringLEv @ 24 NONAME
+	_ZN6CCrBer18GetContentStringLCEv @ 25 NONAME
+	_ZN6CCrBer18GetGraphicsStringLEv @ 26 NONAME
+	_ZN6CCrBer18GetTeletextStringLEv @ 27 NONAME
+	_ZN6CCrBer19GetGeneralizedTimeLEv @ 28 NONAME
+	_ZN6CCrBer24OpenConstructedEncodingLER7CCrData @ 29 NONAME
+	_ZN6CCrBer31OpenConstructedEncodingWithTagLEP7CCrDataRS_P6HBufC8 @ 30 NONAME
+	_ZN6CCrBer4DataEv @ 31 NONAME
+	_ZN6CCrBer4NewLEi @ 32 NONAME
+	_ZN6CCrBer4ReadEP7CCrData @ 33 NONAME
+	_ZN6CCrBer4TypeEv @ 34 NONAME
+	_ZN6CCrBer5LevelEv @ 35 NONAME
+	_ZN6CCrBer5NewLCEi @ 36 NONAME
+	_ZN6CCrBer6LenLenEv @ 37 NONAME
+	_ZN6CCrBer6ObjectEP6HBufC8 @ 38 NONAME
+	_ZN6CCrBer7BufferLEP6HBufC8P7CCrDatajj @ 39 NONAME
+	_ZN6CCrBer7BufferLEP7HBufC16P7CCrDatajh @ 40 NONAME
+	_ZN6CCrBer7ContentEP6HBufC8 @ 41 NONAME
+	_ZN6CCrBer7GetOidLEv @ 42 NONAME
+	_ZN6CCrBer7ObjectLEP7HBufC16 @ 43 NONAME
+	_ZN6CCrBer7ReadLenEP7CCrDataRiPh @ 44 NONAME
+	_ZN6CCrBer8ContentLEP7HBufC16 @ 45 NONAME
+	_ZN6CCrBer8ReadTypeEP7CCrData @ 46 NONAME
+	_ZN6CCrBer8SetLevelEj @ 47 NONAME
+	_ZN6CCrBer9ObjectLenEv @ 48 NONAME
+	_ZN6CCrBerD0Ev @ 49 NONAME
+	_ZN6CCrBerD1Ev @ 50 NONAME
+	_ZN6CCrBerD2Ev @ 51 NONAME
+	_ZN7CCrData4NewLEi @ 52 NONAME
+	_ZN7CCrData4OpenER3RFsRK7TDesC16j @ 53 NONAME
+	_ZN7CCrData4OpenER3RFsj @ 54 NONAME
+	_ZN7CCrData4PathEv @ 55 NONAME
+	_ZN7CCrData4ReadER5TDes8 @ 56 NONAME
+	_ZN7CCrData4ReadER5TDes8i @ 57 NONAME
+	_ZN7CCrData4ReadEiR5TDes8i @ 58 NONAME
+	_ZN7CCrData4SeekE5TSeekRi @ 59 NONAME
+	_ZN7CCrData4SizeERi @ 60 NONAME
+	_ZN7CCrData4ZeroEii @ 61 NONAME
+	_ZN7CCrData5CloseEv @ 62 NONAME
+	_ZN7CCrData5LineLER5TDes8 @ 63 NONAME
+	_ZN7CCrData5NewLCEi @ 64 NONAME
+	_ZN7CCrData5WriteERK6TDesC8 @ 65 NONAME
+	_ZN7CCrData5WriteERK6TDesC8i @ 66 NONAME
+	_ZN7CCrData6DeleteEii @ 67 NONAME
+	_ZN7CCrData6IsFileEv @ 68 NONAME
+	_ZN7CCrData7ReplaceER3RFsRK7TDesC16j @ 69 NONAME
+	_ZN7CCrData8SetPathLERK7TDesC16 @ 70 NONAME
+	_ZN9CCrBerSet10CreateEndLEv @ 71 NONAME
+	_ZN9CCrBerSet10CreateIA5LER6TDesC8 @ 72 NONAME
+	_ZN9CCrBerSet10CreateIntLEi @ 73 NONAME
+	_ZN9CCrBerSet10CreateOIdLER6TDesC8 @ 74 NONAME
+	_ZN9CCrBerSet10CreateT61LER6TDesC8 @ 75 NONAME
+	_ZN9CCrBerSet10CreateUTCLER6TDesC8 @ 76 NONAME
+	_ZN9CCrBerSet11CreateBoolLEi @ 77 NONAME
+	_ZN9CCrBerSet11CreateNullLEv @ 78 NONAME
+	_ZN9CCrBerSet12CreateOctetLEP7CCrData @ 79 NONAME
+	_ZN9CCrBerSet12CreateOctetLER6TDesC8 @ 80 NONAME
+	_ZN9CCrBerSet14CreateGenTimeLER6TDesC8 @ 81 NONAME
+	_ZN9CCrBerSet14CreateGeneralLER6TDesC8 @ 82 NONAME
+	_ZN9CCrBerSet14CreateLongIntLER8RInteger @ 83 NONAME
+	_ZN9CCrBerSet14CreateNumericLER6TDesC8 @ 84 NONAME
+	_ZN9CCrBerSet14CreateVisibleLER6TDesC8 @ 85 NONAME
+	_ZN9CCrBerSet15CreateSeqStartLEi @ 86 NONAME
+	_ZN9CCrBerSet15CreateSetStartLEi @ 87 NONAME
+	_ZN9CCrBerSet15CreateVideoTexLER6TDesC8 @ 88 NONAME
+	_ZN9CCrBerSet16AppendAndUpdateLEP6CCrBer @ 89 NONAME
+	_ZN9CCrBerSet16CreateGraphicalLER6TDesC8 @ 90 NONAME
+	_ZN9CCrBerSet16CreatePrintableLER6TDesC8 @ 91 NONAME
+	_ZN9CCrBerSet17CloseLastSeqOrSetEj @ 92 NONAME
+	_ZN9CCrBerSet23CreateBEREncodedObjectLER6TDesC8 @ 93 NONAME
+	_ZN9CCrBerSet23CreateConstructedStartLEhi @ 94 NONAME
+	_ZN9CCrBerSet4NewLEi @ 95 NONAME
+	_ZN9CCrBerSet5NewLCEi @ 96 NONAME
+	_ZN9CCrBerSet5OpenLEP7CCrDatah @ 97 NONAME
+	_ZN9CCrBerSet6FlushLEP7CCrData @ 98 NONAME
+	_ZN9CCrBerSet6UpdateEP6CCrBer @ 99 NONAME
+	_ZTI10CCrDataSet @ 100 NONAME ; #<TI>#
+	_ZTI9CCrBerSet @ 101 NONAME ; #<TI>#
+	_ZTV10CCrDataSet @ 102 NONAME ; #<VT>#
+	_ZTV9CCrBerSet @ 103 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrBer/group/crber.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This is project specification file for the crber.
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+
+TARGET          crber.dll
+TARGETTYPE      dll
+UID             0x1000008d 0x0000908E
+
+SOURCEPATH      ../Src
+
+SOURCE          crber.cpp
+SOURCE          Crberset.cpp
+SOURCE          crdata.cpp
+
+USERINCLUDE     ../Inc
+MW_LAYER_SYSTEMINCLUDE
+SYSTEMINCLUDE   ../../Inc
+
+LIBRARY         euser.lib efsrv.lib asn1.lib cryptography.lib 
+
+CAPABILITY	  CAP_GENERAL_DLL
+VENDORID    	VID_DEFAULT
+
+#if defined(ARMCC)
+deffile ../eabi/ 
+#elif defined( WINSCW )
+deffile ../bwinscw/ 
+#elif defined( WINS )
+deffile ../bwins/ 
+#else
+deffile ../bmarm/ 
+#endif
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrPkcs12/Inc/CX509CertificateSet.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2000, 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This file contains header of the CX509CertificateSet class.
+*
+*/
+
+
+
+#ifndef CERTIFICATESET
+#define CERTIFICATESET
+
+//  INCLUDES
+
+#include <x509cert.h>                   // CX509Certificate
+#include <x509certext.h>                // TKeyUsage
+
+/**
+*  Class CX509CertificateSet
+*  Class CX509CertificateSet contains set of CX509Certificate objects.
+*
+*  @lib crpkcs12.lib
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CX509CertificateSet ): public CArrayPtrFlat<CX509Certificate>
+    {
+   /////////////////////////////////////////////
+   // Constructors and destructors.
+    private:
+        CX509CertificateSet(TInt aGranularity);
+        void ConstructL();
+        
+    public:
+         static CX509CertificateSet* NewLC(TInt aGranularity);
+         static CX509CertificateSet* NewL(TInt aGranularity);
+         ~CX509CertificateSet();
+
+        // Applies CX509Certificates into CX509CertificateSet
+         TUint DecodeCertsL(const TDesC8& aBinaryData);
+    };
+
+#endif CERTIFICATESET
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrPkcs12/Inc/cralginfo.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,200 @@
+/*
+* Copyright (c) 2000, 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This file contains the header of CCrAlgInfo class.
+*
+*/
+
+
+
+#ifndef CR_ALGINFO_H
+#define CR_ALGINFO_H
+
+//  INCLUDES
+#include <e32base.h>    // CBase.
+
+#include "crdefs.h"     // CrDefines.
+
+//  CONSTANTS
+const TUint8 KCrMediumDigestLength = 16;
+const TUint8 KCrLongDigestLength = 20;
+
+const TUint8 KDigestInputSize = 64;
+
+const TUint8 KCrDESKeyLength= 8;
+const TUint8 KCrDESIVLength = 8;
+
+const TUint8 KCrRCLongKeyLength = 16;
+const TUint8 KCrRCMediumKeyLength = 8;
+const TUint8 KCrRCShortKeyLength = 5;
+const TUint8 KCrRCIVLength = 8;
+
+const TUint8 KCrPaddingLength = 8;
+
+//  MACROS
+//  DATA TYPES
+
+// Algorithms.
+enum TCrAlgorithm
+    {
+    // Message digest algorithms.
+    ECrMD2,
+    ECrMD5,
+    ECrRIPEMD,
+    ECrSHA,
+    ECrSHA1,
+    ECrHMAC,          // item is used only with Symbian library
+    ECrHMAC_MD5,      // item is used only with NoCry library
+    ECrHMAC_RIPEMD,   // item is used only with NoCry library
+    ECrHMAC_SHA1,     // item is used only with NoCry library
+    ECrLAST_DIGEST,         
+
+    // Symmetric crypto algorithms.
+    ECrDES,
+    ECrDES2,
+    ECrDES3,
+    ECrDESX,
+    ECrRC2,
+    ECrRC4,
+    ECrRC5,
+    ECrLAST_SYMM_CRYPTO,    
+    };                   
+
+// Mode of the symmetric crypto algorithm.
+enum TCrSymmMode
+    {
+    ECrCBC,
+    ECrCFB,
+    ECrECB,
+    ECrOFB,
+    };
+
+// CLASS DECLARATION
+
+/**
+*  class CCrAlgInfo
+*  CCrAlgInfo contains all information related to symmetric
+*  crypto and digest algorithms.
+*
+*  @lib crpkcs12.lib
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CCrAlgInfo ): public CBase
+    {
+    /////////////////////////////////////////////
+    // Constructors and destructors.
+    private:
+        CCrAlgInfo();
+
+        void ConstructL(
+            const TCrAlgorithm aType,
+            const TInt         aLen,
+            const TInt         aIVLen = 0,
+            const TDesC8*      aKey = NULL,
+            const TDesC8*      aIV = NULL,
+            const TBool        aEncrypt = ETrue,
+            const TBool        aSingleBlock = ETrue,
+            const TCrSymmMode  aMode = ECrCBC);
+        
+    public:
+        ~CCrAlgInfo();
+
+        /**
+        * Constructors
+        * @param aType Type of the algorithm of this object
+        * @param aKey Key of this object. 
+        * @param aIV Initialization vector of this object. 
+        * @param aEncrypt Encrypt if true, otherwise decrypt. 
+        * @param aSingleBlock Single block mode if true. 
+        * @param aMode Algorithm mode.
+        * @return Pointer to the created object.
+        */
+        static CCrAlgInfo* NewLC(
+            const TCrAlgorithm aType,
+            const TDesC8&      aKey,
+            const TDesC8&      aIV,
+            const TBool        aEncrypt = ETrue,
+            const TBool        aSingleBlock = ETrue,
+            const TCrSymmMode  aMode = ECrCBC);
+
+        static CCrAlgInfo* NewLC(
+            const TCrAlgorithm aType);
+
+        static CCrAlgInfo* NewL(
+            const TCrAlgorithm aType,
+            const TDesC8&      aKey,
+            const TDesC8&      aIV,
+            const TBool        aEncrypt = ETrue,
+            const TBool        aSingleBlock = ETrue,
+            const TCrSymmMode  aMode = ECrCBC);
+
+        static CCrAlgInfo* NewL(
+            const TCrAlgorithm aType);
+
+    private: 
+        // Sets parity bits.
+        TCrStatus SetParityBits(TPtr8 aPtrKey);
+    
+    public: // Data
+        // Type of the algorithm.
+        TCrAlgorithm iType;
+
+        // Pointer to initialized algorithm object.
+        TAny* iAlgorithmObject;
+
+        // This buffer contains last portion of the
+        // data to encrypt/decrypt which is encrypted/
+        // decrypted in FinalCryptSymm function. 
+        // Relevant only if symmetric crypto algorithm 
+        // in question.
+        HBufC8* iLastPortion;
+    
+        // This buffer contains digest if calculating
+        // message digest. Relevant only if digest 
+        // algorithm in question.
+        HBufC8* iDigest;
+
+        // This buffer contains key if en/decryption
+        // in process. Relevant only if crypt 
+        // algorithm in question.
+        HBufC8* iKey;
+
+        // This buffer contains initialization
+        // vector if en/decryption in process.
+        // Relevant only if crypt algorithm in question.
+        HBufC8* iIV;
+
+        // Is this object for encrypting or decrypting?
+        // Relevant only if symmetric crypto algorithm
+        // in question.
+        TBool iEncrypt;
+
+        // True if only one block.
+        TBool iSingleBlock;
+    
+        // Block status, first/middle/last. Usage depends on algorithm used.
+        TInt iBlockStatus;
+    
+        // Mode of a symmetric crypto algorithm. Relevant
+        // only if symmetric crypto algorithm in question.
+        TCrSymmMode iMode;
+
+        // Padding. Relevant only if Symbian symmetric
+        // crypto algorithm in question.
+        TAny* iPadding;
+
+    };
+
+#endif // CR_ALGINFO_H
+
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrPkcs12/Inc/crcrypto.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,192 @@
+/*
+* Copyright (c) 2000, 2002, 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This file contains the header of CCrCrypto class.
+*
+*/
+
+
+#ifndef CR_CRYPTO_H
+#define CR_CRYPTO_H
+
+//  INCLUDES
+#include <e32base.h>    // CBase.
+
+#include "cralginfo.h"  // CCrAlgInfo
+#include <crdata.h>
+
+//  CONSTANTS
+const TInt NO_PROCESS = -1;
+const TInt KLenFileBuffer = 1000;
+
+//  DATA TYPES
+// Padding rules. 
+enum TPaddingRule
+    {
+    ECrNone,
+    ECrPKCS1,
+    ECrSSLv3
+    };
+
+// Algorithms.
+enum TCrAsymAlgorithm
+    {
+    ECrRSA,
+    ECrDSA,
+    ECrLAST_ASYMM_CRYPTO
+    };                   
+
+
+// CLASS DECLARATION
+
+/**
+*  class CCrCrypto
+*  CCrCrypto crypto API, which is used in CrPKCS12.
+*
+*  @lib crpkcs12.lib
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CCrCrypto ): public CBase
+    {
+    // Constructors and destructors.
+    private:
+        CCrCrypto();
+
+        void ConstructL();
+        
+    public:
+        ~CCrCrypto();
+        static CCrCrypto* NewLC(); 
+        static CCrCrypto* NewL();
+    
+    public: // Functions.
+
+        /**
+        * Initialize encryption or decryption with Triple DES algorithm
+        * using three different keys.
+        * @param aKey1 1. key.
+        * @param aKey2 2. key.
+        * @param aKey3 3. key.
+        * @param aIV Initialization vector.
+        * @param aEncrypt Encrypt if true.
+        * @param aMode Algorithm mode.
+        * @param aPadRule Padding rule.
+        * @return KCrCrypto | KCrUnknownMode
+        *         KCrCrypto | KCrUnknownLibrary
+        *         KCrOK
+        */
+        TCrStatus InitCrypt3DESL(
+            const TDesC8& aKey1,                
+            const TDesC8& aKey2,                
+            const TDesC8& aKey3,                
+            const TDesC8& aIV,                  
+            TBool         aEncrypt = ETrue,     
+            TCrSymmMode   aMode = ECrCBC,       
+            TPaddingRule  aPadRule = ECrPKCS1); 
+
+        /**
+        * Initialize encryption or decryption with RC2 algorithm.
+        * @param aKey Key.
+        * @param aIV Initialization vector.
+        * @param aEncrypt Encrypt if true.
+        * @param aEffectiveKeyLen Effective key length in bits
+        * @param aMode Algorithm mode.
+        * @param aPadRule Padding rule.
+        * @return KCrCrypto | KCrUnknownMode
+        *         KCrOK
+        */
+        TCrStatus InitCryptRC2L(
+            const TDesC8& aKey,                 
+            const TDesC8& aIV,                  
+            TBool         aEncrypt = ETrue,     
+                                                
+            TInt          aEffectiveKeyLen = 0, 
+                                                
+            TCrSymmMode   aMode = ECrCBC,       
+            TPaddingRule  aPadRule = ECrPKCS1); 
+
+        /**
+        * Initialize HMAC message digest algorithm.
+        * @param aKey Key.
+        * @param aDigestAlg Message digest algorithm that HMAC uses.
+        * @return KCrCrypto | KCrUnknownMode
+        *         KCrOK
+        */
+        TCrStatus InitDigestHMACL(
+            const TDesC8& aKey,             
+            TCrAlgorithm aDigestAlg);       
+                                            
+              
+        /**
+        * Initialize message digest with MD2 algorithm.
+        * @param aAlgorithm      Digest algorithm
+        * @return KCrOK or 
+        *         KCrCrypto | KCrNotSupportedAlg
+        */
+        TCrStatus InitDigestL(TCrAlgorithm aAlgorithm);
+
+        
+
+        /**
+        * Process given source data with initialized crypto operations.
+        * If symmetric crypto is initialized appends to aTrg encrypted
+        * or decrypted data without last portion. If only digest algorithm
+        * is initialized, aTrg is not used.
+        * @param aSrc Source buffer.
+        * @param aTrg  Target buffer.
+        * @return KCrOK
+        *         KCrNotSupportedAlg
+        *         KCrUndefinedLibrary
+        *         KCrUnknownLibrary
+        *         KCrUnknownMode
+        */
+        TCrStatus ProcessL(const TDesC8& aSrc, TDes8& aTrg);
+
+        
+        // Finalize symmetric algorithms. Function appends to aTrg
+        // encrypted or decrypted last portion.
+        TCrStatus FinalCryptL(TDes8& aTrg);
+        
+        // Finalize message digest algorithms. 
+        // aTrg contains message digest of the data.
+        TCrStatus FinalDigest(TDes8& aTrg);        
+
+        // Derive key(s) or IV vector from password, salt and iteration count.
+        TCrStatus DeriveKeyPKCS12L(
+            const TDesC8& aPassword, 
+            const TDesC8& aSalt,
+            const TInt    aIterationCount,
+            TCrAlgorithm  aHashFunc,
+            const TUint8  aID,
+            const TInt    aNumberOfBytes,
+            TDes8&        aTrg);
+
+    private: // Functions
+        // Removes the last portion of the data when encrypting or decrypting.     
+        TInt RemoveLastBlock(
+            TDesC8&           aSrc,
+            const TInt        aBlockSize,
+            CCrAlgInfo*       algInfo);
+
+        TInt MesDigestInputSize(TCrAlgorithm aDigestAlg);
+        TInt MesDigestOutputSize(TCrAlgorithm aDigestAlg);
+        void Reset();
+    
+    private: // Data.
+        // Infos about initialized algorithms are collected in this array.
+        CArrayPtrFlat<CCrAlgInfo>* iAlgorithmInfos;
+    };
+
+#endif // CR_CRYPTO_H
+
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrPkcs12/Inc/crpkcs12.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,326 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This file contains the header of a CCrPKCS12 Class.
+*
+*/
+
+
+
+#ifndef CRPKCS12
+#define CRPKCS12
+
+
+//  INCLUDES
+#include "CX509CertificateSet.h"        // X509CertificateSet
+#include "crcrypto.h"                   // Crypto library
+#include <crber.h>		                // CCrBer
+#include <e32base.h>
+#include <secdlg.h>                    
+
+
+//  EXTERNAL DATA STRUCTURES
+//  FUNCTION PROTOTYPES
+//  FORWARD DECLARATIONS
+//  CLASS DEFINITIONS
+
+// DATA TYPES
+
+// Object Identifiers
+// They are used to identify different objects
+enum TCrPkcs12Algorithm
+    {
+    // Pkcs12 algorithms.
+    ECrpbeWithSHAAnd128BitRC4,
+    ECrpbeWithSHAAnd40BitRC4,
+    ECrpbeWithSHAAnd3_KeyTripleDES_CBC,
+    ECrpbeWithSHAAnd2_KeyTripleDES_CBC,
+    ECrKpbeWithSHAAnd128BitRC2_CBC,
+    ECrKpbeWithSHAAnd40BitRC2_CBC
+    };
+
+// CONSTANTS
+const TInt K40BitRC2KeySize = 5;
+const TInt K128BitRC2KeySize = 16;
+const TInt KDesKeySize = 8;
+
+// Digest algorithm identifiers
+_LIT(KCrSha1,"1.3.14.3.2.26"); // Digest algorithm Sha1.
+_LIT(KCrMD5, "1.2.840.113549.2.5"); // Digest algorithm Sha1.
+
+// Used pkcs12 encryption algorithms
+_LIT(KpbeWithSHAAnd128BitRC4,"1.2.840.113549.1.12.1.1"); // These are algorith
+_LIT(KpbeWithSHAAnd40BitRC4,"1.2.840.113549.1.12.1.2"); // identifiers for deriving
+_LIT(KpbeWithSHAAnd3_KeyTripleDES_CBC,"1.2.840.113549.1.12.1.3"); // keys and IVs.
+_LIT(KpbeWithSHAAnd2_KeyTripleDES_CBC,"1.2.840.113549.1.12.1.4"); // As implied by their
+_LIT(KpbeWithSHAAnd128BitRC2_CBC,"1.2.840.113549.1.12.1.5"); // names, all of the object
+_LIT(KpbeWithSHAAnd40BitRC2_CBC,"1.2.840.113549.1.12.1.6"); // identifiers here use the hash
+                                                         // function SHA-1.
+
+// Pkcs12 SafeBags-types
+_LIT(KkeyBag,"1.2.840.113549.1.12.10.1.1"); // SafeBag types. Each SafeBag holds one piece
+_LIT(Kpkcs8ShroudedKeyBag,"1.2.840.113549.1.12.10.1.2"); // of information -a key,
+_LIT(KcertBag,"1.2.840.113549.1.12.10.1.3"); // a certificate, etc.- which is identified
+_LIT(KcrlBag,"1.2.840.113549.1.12.10.1.4"); // by an object identifier.
+_LIT(KsecretBag,"1.2.840.113549.1.12.10.1.5");
+_LIT(KsafeContentsBag,"1.2.840.113549.1.12.10.1.6");
+
+// Pkcs7 datatypes used in this library
+_LIT(Kpkcs7Data,"1.2.840.113549.1.7.1");  // Pkcs7 Data-type
+_LIT(Kpkcs7EncryptedData,"1.2.840.113549.1.7.6"); // Pkcs7 encryptedData-type
+
+// Pkcs9 object identifiers
+_LIT(Kpkcs9LocalKeyId,"1.2.840.113549.1.9.21");     // LocalKeyId. This is used to identify
+                                                    // what certificate belongs to what
+                                                    // PrivateKey
+
+_LIT(Kx509certificate,"1.2.840.113549.1.9.22.1");   // X509Certificate
+
+// pkcs1 object identifier for rsaEncryption
+_LIT(Kpkcs1rsaEncryption,"1.2.840.113549.1.1.1");   // For PrivateKey
+
+_LIT(KdsaSignatureKey,"1.2.840.10040.4.1");   // DSA signature key
+
+
+const TInt KVersion3 = 0x3; // Version number for PFX
+const TInt KVersion1 = 0x0; // PrivateKey version
+const TInt KFirstObject = 0; // First object
+const TInt KEdVer0 = 0x0;   // PKCS #7 Encrypted-data content type
+                             // version number
+
+const TInt KId1 = 1;        // If ID = 1, then pseudo-random bits being produced are 
+                            // used as key material for performing encryption / decryption
+
+const TInt KId2 = 2;        // If ID = 2, then pseudo-random bits produced are to be used as
+                            // an IV (Initial Value) for encryption / decryption
+
+const TInt KId3 = 3;        // If ID = 3, then pseudo-random bits being produced are to be
+                            // used as an integrity key for MAC-ing.
+
+                     
+/**
+*  Class CCrPKCS12
+*  Class CCrPKCS12 opens pkcs12-file with help of CCrBer-library.
+*
+*  @lib crpkcs12.lib
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CCrPKCS12): public CBase
+    {
+    // Constructors and destructors.
+    private:
+        
+		CCrPKCS12();
+        void ConstructL();
+		
+    public:
+		static CCrPKCS12* NewLC();
+		static CCrPKCS12* NewL();
+		~CCrPKCS12();
+
+    public: // Functions
+
+        // This is the main function of this library. It validates PKCS #12 file,
+        // checks integrity of file, checks password, opens and decrypts ContentInfo,
+        // decrypts certificates and private keys. If this function returns
+        // ValidFile, other exported functions can be called.
+        TCrStatus OpenL(
+            CCrData&       aPkcs12File,
+            const TDesC16& aPassword );
+
+        // Returns set of CX509Certificate objects defined in certman.
+        // These are CACertificates.
+        const CX509CertificateSet& CACertificates() const;
+
+        // Returns set of TDesC8 objects defined in certman.
+        // These are CACertificates.
+        const CArrayPtrFlat<TDesC8>& CACertificateBuffer() const;
+
+        // Returns set of CX509Certificate objects defined in certman.
+        // These are UserCertificates.
+        const CX509CertificateSet& UserCertificates() const;
+
+        // Returns set of TDesC8 objects defined in certman.
+        // These are UserCertificates.
+        const CArrayPtrFlat<TDesC8>& UserCertificateBuffer() const;
+        
+        const CArrayPtrFlat<HBufC8>& PrivateKeys() const;
+		
+        // Returns the number of iterations.
+		TUint Iter();
+
+        // Returns mac.
+		HBufC8* Mac();
+
+        // Returns salt.
+		HBufC8* Salt();
+
+        // Returns number of SafeBags in PKCS #12 file.
+        TUint SafeBagsCount();
+
+    private:
+
+        // Private helper class for asynchronous calls.
+        NONSHARABLE_CLASS( CPKCS12SyncWrapper ): public CActive
+            {
+            public:
+                CPKCS12SyncWrapper();
+                ~CPKCS12SyncWrapper();
+                TInt EnterPasswordL(const TPINParams& aPINParams, TBool aRetry, TPINValue& aPINValue);
+            protected:  // Functions from base classes        
+                /**
+                * From CActive
+                */
+                void DoCancel();
+	            void RunL();
+            private:
+                TInt SetActiveAndWait();
+            private:
+                MSecurityDialog* iSecDlg;
+                CActiveSchedulerWait iWait;
+            };
+        
+    private:
+        // Jumps next object at same level, used in Open-function.
+        TUint JumpNextObjectAtSameLevel();
+        
+        // Returns what's the algorithm (via OID).
+        // Returns 0, if it isn't algorithm at all.
+        TUint GetAlgorithmL( HBufC* aBuf );
+
+        // This function adds given certificate to given set.
+        void PutCertsIntoSetL(CX509CertificateSet* aSet,
+                              CArrayPtrFlat<TDesC8>* aBufSet,
+                              HBufC8* aX509certificate );
+
+        // This function generates double byte pasword from given eight 
+        // byte password and calls VerifyMac.
+        TBool VerifyMacFromEightBytePassword(const TDesC8& aPassWord);
+
+        // Verifies mac (integrity of file and if password is correct).
+        // Used in Open-function.
+        TBool VerifyMacL(const TDesC8& aPassWord);
+        TBool VerifyMacL(const TDesC16& aPassWord);
+
+        // Opens ContentInfo, used in Open-function.
+        TBool ReadContentInfo( CCrData& aContentInfo );
+
+        // Decodes SafeBags. Used in Open function.
+        TInt DecodeSafeBagsL();
+
+        // Decrypts ContentInfo, used in OpenContentInfo-function.
+        TBool UnpackContentInfo( CCrData& aContentData );
+
+        // Decrypts pkcs7Data, used in DecryptContentInfo-function.
+        TBool UnpackPkcs7DataL( CCrData& aPkcs7Data );
+
+        // Unpacks pkcs7EncryptedData, used in DecryptContentInfo-
+        // function.
+        TBool UnpackPkcs7EncryptedDataL( CCrData& aPkcs7EncryptedData );
+
+        // Decrypts pkcs7EncryptesData, used in UnpackPkcs7EncryptedData 
+        // function.
+        TBool DecryptPkcs7EncryptedDataL(HBufC8* aPkcs7EncryptedData,
+                                         HBufC8* aSalt,
+                                         TInt aIter,
+                                         TInt aAlgorithm );
+
+
+        // Extracts contents of keybag, used in DecodeSafeBags function.
+		void CCrPKCS12::ExtractKeybagL( CCrData& aSafeBag );
+
+        // Decrypts pkcs8-shroudedkeybag, used in DecodeSafeBags function.
+        void DecryptShroudedKeybagL( CCrData& aSafeBag );
+
+        // Decodes certificate bag, used in DecodeSafeBags function.
+        void DecodeCertBagL( CCrData& aSafeBags );
+
+        // Decrypts private key, used in DecryptShroudedKeybag.
+        TBool DecryptPrivateKeyL( HBufC8* aEncryptedPrivateKey,
+                                 HBufC8* aSalt,
+                                 TInt aIter,
+                                 TInt aAlgorithm );
+        
+        // Gets SafeBags LocalKeyId. This is used to identidy what certificate
+        // belongs to private key. Used in DecryptPrivateKey function.
+        HBufC8* GetLocalKeyId( CCrData& aBagData );
+        
+        void DecryptDataL( const TDesC8& aEncryptedData,
+                           const TDesC8& aSalt,
+                           TInt aIter,
+                           TInt aAlgorithm,
+                           TDes8& aDecryptedData );
+                                            
+
+	private: // Data.
+
+        // Iterations
+		TUint iIter;
+
+        // CCrBerSet, set of CCrBer-objects, from crber.lib.
+		CCrBerSet* iberSet;
+
+        // CCrBer-object, from crber.lib.
+		CCrBer* iberObject;
+
+        // UserCertificates, contains set of CX509Certificate Objects,
+        // defined in certman. These certificates are user certificates.
+        // Usually there are just one user certificate in PKCS #12 file.
+        CX509CertificateSet* iUserCertificates;
+        
+
+        // CACertificates, contains set of CX509Certificate Objects,
+        // defined in certman. These certificates are CA certificates.
+        CX509CertificateSet* iCACertificates;
+
+        CArrayPtrFlat<TDesC8>* iUserCertificateBuffer;
+        CArrayPtrFlat<TDesC8>* iCACertificateBuffer;
+                
+        // Decrypted PKCS#8 encoded private keys.        
+        CArrayPtrFlat<HBufC8>* iPKCS8PrivateKeyArray;
+        
+        // This is private keys' LocalKeyIds. With these we can identify
+        // a corresponding certificate.        
+        RPointerArray<HBufC8> iPrivateKeyIdArray;
+        
+        // For storing mac.
+		HBufC8* iMac;
+
+        // For storing salt.
+		HBufC8* iSalt;
+        
+        // index number of berObject.
+        TInt iObjectNum;
+
+        // Password given to Open function. Must be available to other
+        // functions also, so it is declared here.
+        HBufC8* iPassWord;
+                        
+        // Number of SafeBags.
+        TInt iSafeBagsCount;
+
+        // Used HMAC-algorithm.
+        TInt iHMACalgorithm;
+
+        // PKCS #7 data.
+        HBufC8* iContentInfo;
+
+        // SafeBags.
+        HBufC8* iBags;
+                                		        
+        HBufC8* iDecryptionKey;
+
+        TFileName iFileName;
+	};
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrPkcs12/Inc/pkcs12.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,119 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Header file of the PKCS#12 parser API
+*
+*/
+
+
+#ifndef __CPKCS12_H__
+#define __CPKCS12_H__
+
+//  INCLUDES
+#include "mpkcs12.h"
+#include <e32std.h>
+#include <e32base.h>
+#include <f32file.h>
+
+// FORWARD DECLARATIONS
+class CCrPKCS12;
+class CX509Certificate;
+class CCrData;
+
+// CLASS DECLARATION
+
+/**
+*  Class CPKCS12
+*  The PKCS12 Library (CrPKCS12) provides opening functionality of a 
+*  PKCS #12 file. PKCS #12 is a format used to store and protect user's
+*  private data, i.e. his/her key pairs, certificates and other personal
+*  information.
+*
+*  @lib crpkcs12.lib
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CPKCS12 ): public MPKCS12, public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CPKCS12* NewL();
+        
+    private:
+        /**
+        * Destructor.
+        */
+        virtual ~CPKCS12();
+
+    public: // Functions from MPKCS12
+    
+        TBool IsPKCS12Data(const TDesC8& aBinaryData);
+
+        /**
+        * Executes actual parsing.
+        * @param aPKCS12 PKCS#12 encoded data
+        * @param aPassword Used to generate encryption key.
+        * @return ?description
+        */        
+        void ParseL(const TDesC8& aPKCS12, const TDesC16& aPassword);
+        
+        /**
+        * ?member_description.
+        * @since Series ?XX ?SeriesXX_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        const CArrayPtr<CX509Certificate>& CACertificates() const;
+        const CArrayPtr<CX509Certificate>& UserCertificates() const;
+        const CArrayPtr<HBufC8>& PrivateKeys() const;
+        
+        // Returns number of SafeBags in PKCS #12 file.
+        TUint SafeBagsCount() const;
+        // Returns the number of iterations.
+		TUint IterCount() const;
+        
+        /**
+	    * Frees resources of the class
+	    */
+        void Release();                
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CPKCS12();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        void Reset();
+                
+        void HandleErrorL( TUint16 aError ) const; 
+        
+        static TBool IsASN1Tag(TInt aTag, const TDesC8& aBinaryData, TInt& aPos);
+        
+        static TBool IsExpectedData(const TDesC8& aBinaryData, TInt& aPos, const TDesC8& aExpectedData);
+
+    private:    // Data
+        CCrPKCS12* iCrPkcs12;        
+        CCrData* iCrData;                 
+    };
+
+#endif      // __CPKCS12_H__   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrPkcs12/Src/cralginfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,503 @@
+/*
+* Copyright (c) 2000, 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This module contains the implementation of CCrAlgInfo class. 
+*
+*/
+
+
+//  INCLUDE FILES
+#include "cralginfo.h"
+
+#include "random.h"  // Random data.
+
+
+// -----------------------------------------------------------------------------
+// CCrAlgInfo
+// Constructor.
+// This function constructs CCrAlgInfo object.
+// -----------------------------------------------------------------------------
+CCrAlgInfo::CCrAlgInfo()
+    {
+    iType = ECrLAST_SYMM_CRYPTO;
+    iAlgorithmObject = NULL;
+    iLastPortion = NULL;
+    iDigest = NULL;
+    iKey = NULL;
+    iIV = NULL;
+    iEncrypt = ETrue;
+    iSingleBlock = ETrue;
+    iMode = ECrCBC;
+    iPadding = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// ~CCrAlgInfo
+// Destructor.
+// This function destructs CCrAlgInfo object.
+// -----------------------------------------------------------------------------
+CCrAlgInfo::~CCrAlgInfo()
+    {    
+    delete iDigest;
+    delete iLastPortion;
+	delete iKey;    
+    delete iIV;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CCrAlgInfo::ConstructL
+// This function initializes this object's members.
+// Parameters: aType                Type of the algorithm
+//             aLen                 Length of the key or digest
+//             aIVLen               Length of the initialization vector
+//                                  of this object.
+//             aKey                 Key of this object.
+//             aIV                  Initialization vector of this object.
+//             aEncrypt = ETrue     Encrypt if true, otherwise decrypt.
+//             aSingleBlock = ETrue Single block mode if true.
+//             aMode = ECrCBC       Algorithm mode.
+// -----------------------------------------------------------------------------
+void CCrAlgInfo::ConstructL(
+    const TCrAlgorithm aType,
+    const TInt         aLen,
+    const TInt         aIVLen       /* = 0 */,
+    const TDesC8*      aKey         /* = NULL */,
+    const TDesC8*      aIV          /* = NULL */,
+    const TBool        aEncrypt     /* = ETrue */,
+    const TBool        aSingleBlock /* = ETrue */,
+    const TCrSymmMode  aMode        /* = ECrCBC */)
+    {
+    iType = aType;
+
+    if (iType < ECrLAST_DIGEST)
+        {
+        iDigest = HBufC8::NewL(aLen);
+        }
+    else
+        {
+        iEncrypt = aEncrypt;
+        iSingleBlock = aSingleBlock;
+        iMode = aMode;
+
+        switch (iType)
+            {
+            case ECrDES3:
+            case ECrDES:
+            case ECrDES2:
+            case ECrDESX:
+            case ECrRC2:
+            case ECrRC5:
+                {
+                iLastPortion = HBufC8::NewL(KCrPaddingLength);
+                iKey = HBufC8::NewL(aLen);
+                iIV = HBufC8::NewL(aIVLen);
+
+                break;
+                }
+            case ECrRC4:
+                {
+                iLastPortion = HBufC8::NewL(KCrPaddingLength);
+                iKey = HBufC8::NewL(aLen);
+
+                break;
+                }
+            default:
+                {
+                break;
+                }
+            }
+
+        // If given key isn't empty,
+        if (aKey && aKey->Length())
+            {
+            // use it,
+            *iKey = *aKey;
+
+            // Check if IV is needed.
+            if (iIV != NULL)
+                {
+                // Use given iv, if any.
+                if (aIV && aIV->Length())
+                    {
+                    *iIV = *aIV;
+                    }
+                else
+                    {
+                    // Otherwise null iv.
+                    TPtr8 ptrIV = iIV->Des();
+
+                    ptrIV.AppendFill(0, aIVLen);
+                    }
+                }
+            }
+        else
+            {
+/*
+            // otherwise create key.
+            TPtr8 ptrKey = iKey->Des();
+            
+            // aLen must have a reasonable value.
+            if (aLen < 1 || aLen > ptrKey.MaxLength())
+                {
+                return; 
+                }
+
+            ptrKey.SetLength(aLen);
+
+            GetRandom(ptrKey);
+						
+			switch (iType)
+				{
+                case ECrDES3:
+                case ECrDES:
+                case ECrDES2:
+                case ECrDESX:
+                    {
+
+                    // Take care that weak keys are not used.
+                    // Set parity bits. Check that the key is not weak.
+                    // Recreate key until it is not weak.
+
+                    // Key is weak, when weakKey is 1. Then it has to 
+					//	be recreated.
+                    // Key is acceptable, when weakKey is 0.
+
+                    if (aLen == 24) // 3des
+                        {
+                        TInt weakKey = 1;
+                        while (weakKey != 0)
+                            {
+                            // Put parity bits to DESkeys.
+                            SetParityBits(ptrKey);
+
+                            TPtrC8 firstKeyPtr = ptrKey.Left(8);
+                            NC_BYTE* tempKey = CONST_CAST(NC_BYTE*, firstKeyPtr.Ptr());                 
+                            weakKey = des_weak_key(tempKey);
+                        
+                            if (weakKey == 0)
+                                {
+                                TPtrC8 secondKeyPtr = ptrKey.Mid(8,8);
+                                tempKey = CONST_CAST(NC_BYTE*, secondKeyPtr.Ptr());
+                                weakKey = des_weak_key(tempKey);
+                            
+                                if (weakKey == 0)
+                                    {
+                                    TPtrC8 thirdKeyPtr  = ptrKey.Right(8);
+                                    tempKey = CONST_CAST(NC_BYTE*, thirdKeyPtr.Ptr());
+                                    weakKey = des_weak_key(tempKey);
+                                    }
+                                }
+
+                            if (weakKey == 1)
+                                {
+                                GetRandom(ptrKey);
+                                }
+                            }
+                        }
+                                       
+                    if (aLen == 8)
+                        {
+                        // Put parity bits to DESkeys.
+                        SetParityBits(ptrKey);
+
+                        NC_BYTE* tempKey = CONST_CAST(NC_BYTE*, iKey->Ptr());
+                        TInt weakKey = des_weak_key(tempKey);
+                        while (weakKey != 0)
+                            {
+                            GetRandom(ptrKey);
+                            SetParityBits(ptrKey);
+                            weakKey = des_weak_key(tempKey );
+                            }
+                        }
+
+                    break;
+                    }
+                default:
+                    break;
+                }
+
+            // Check if IV is needed.
+            if (iIV != NULL)
+                {
+                // create iv.
+                TPtr8 ptrIV = iIV->Des();
+
+                ptrIV.SetLength(aIVLen);
+
+                GetRandom(ptrIV);
+                }*/
+            }
+        }
+		
+    }
+
+// -----------------------------------------------------------------------------
+// CCrAlgInfo::NewLC
+// This function implements the two-phase construction of this class.
+// The function uses standard constructor to reserve memory for
+// CCrAlgInfo object, stores a pointer to the object into clean up
+// stack, and returns the pointer to the object.
+// -----------------------------------------------------------------------------
+CCrAlgInfo* CCrAlgInfo::NewLC(
+    const TCrAlgorithm aType,
+    const TDesC8&      aKey,
+    const TDesC8&      aIV,
+    const TBool        aEncrypt     /* = ETrue */,
+    const TBool        aSingleBlock /* = ETrue */,
+    const TCrSymmMode  aMode        /* = ECrCBC */)
+    {
+    TInt keyLen = aKey.Length();
+    TInt ivLen = aIV.Length();
+
+    CCrAlgInfo* self = new (ELeave) CCrAlgInfo();
+    CleanupStack::PushL(self);
+
+    // If given key is empty, assume that caller wants us to create key.
+    if (keyLen == 0)
+        {
+        switch (aType)
+            {
+            case ECrDES3:
+                {
+                keyLen = 3 * KCrDESKeyLength;
+
+                break;
+                }
+            case ECrDES:
+                {
+                keyLen = KCrDESKeyLength;
+
+                break;
+                }
+            case ECrDES2:
+                {
+                keyLen = 2 * KCrDESKeyLength;
+
+                break;
+                }
+            case ECrDESX:
+                {
+                keyLen = 3 * KCrDESKeyLength;
+
+                break;
+                }
+            case ECrRC2:
+            case ECrRC5:
+                {
+                keyLen = KCrRCLongKeyLength;
+
+                break;
+                }
+            case ECrRC4:
+                {
+                keyLen = KCrRCLongKeyLength;
+
+                break;
+                }
+            default:
+                {
+                break;
+                }
+            }
+        }
+
+    // If given iv is empty, assume that caller wants us to create iv.
+    if (ivLen == 0)
+        {
+        switch (aType)
+            {
+            case ECrDES3:
+                {
+                ivLen = KCrDESIVLength;
+
+                break;
+                }
+            case ECrDES:
+                {
+                ivLen = KCrDESIVLength;
+
+                break;
+                }
+            case ECrDES2:
+                {
+                ivLen = KCrDESIVLength;
+
+                break;
+                }
+            case ECrDESX:
+                {
+                ivLen = KCrDESIVLength;
+
+                break;
+                }
+            case ECrRC2:
+            case ECrRC5:
+                {
+                ivLen = KCrRCIVLength;
+
+                break;
+                }
+            case ECrRC4:
+                {
+                break;
+                }
+            default:
+                {
+                break;
+                }
+            }
+        }
+
+    self->ConstructL(
+        aType,
+        keyLen,
+        ivLen,
+        &aKey,
+        &aIV,
+        aEncrypt,
+        aSingleBlock,
+        aMode);
+
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CCrAlgInfo::NewLC
+// This function implements the two-phase construction of this class.
+// The function uses standard constructor to reserve memory for
+// CCrAlgInfo object, stores a pointer to the object into clean up
+// stack, and returns the pointer to the object.
+// -----------------------------------------------------------------------------
+CCrAlgInfo* CCrAlgInfo::NewLC(const TCrAlgorithm aType)
+    {
+    TInt len = 0;
+
+    CCrAlgInfo* self = new (ELeave) CCrAlgInfo();
+    CleanupStack::PushL(self);
+
+    switch (aType)
+        {
+        case ECrSHA1:
+        case ECrHMAC_SHA1:
+        case ECrHMAC_RIPEMD:
+        case ECrRIPEMD:
+        case ECrSHA:
+            {
+            len = KCrLongDigestLength;
+            break;
+            }
+        case ECrMD5:
+        case ECrMD2:
+        case ECrHMAC_MD5:
+            {
+            len = KCrMediumDigestLength;
+            break;
+            }
+        default:
+            {
+            break;
+            }
+        }
+
+    self->ConstructL(aType, len);
+
+    return self; 
+    }
+
+// --------------------------------------------------------------------------------
+// CCrAlgInfo::NewL
+// This function implements the two-phase construction of this class.
+// The function reserves memory for CCrAlgInfo object and returns
+// pointer to that object. This function uses NewLC to create the object
+// and store it to cleanup stack. Finally the object is popped from clean
+// up stack.
+// --------------------------------------------------------------------------------
+CCrAlgInfo* CCrAlgInfo::NewL(
+    const TCrAlgorithm aType,
+    const TDesC8&      aKey,
+    const TDesC8&      aIV,
+    const TBool        aEncrypt     /* = ETrue */,
+    const TBool        aSingleBlock /* = ETrue */,
+    const TCrSymmMode  aMode        /* = ECrCBC */)
+    {
+    CCrAlgInfo* self = NewLC(
+        aType,
+        aKey,
+        aIV,
+        aEncrypt,
+        aSingleBlock,
+        aMode);
+
+    CleanupStack::Pop();
+
+    return self; 
+    }
+
+// --------------------------------------------------------------------------------
+// CCrAlgInfo::NewL
+// This function implements the two-phase construction of this class.
+// The function reserves memory for CCrAlgInfo object and returns
+// pointer to that object. This function uses NewLC to create the object
+// and store it to cleanup stack. Finally the object is popped from clean
+// up stack.
+// --------------------------------------------------------------------------------
+CCrAlgInfo* CCrAlgInfo::NewL(const TCrAlgorithm aType)
+    {
+    CCrAlgInfo* self = NewLC(aType);
+
+    CleanupStack::Pop();
+
+    return self; 
+    }
+
+// --------------------------------------------------------------------------------
+// CCrAlgInfo::SetParityBits
+// Sets parity bits to des keys.
+// --------------------------------------------------------------------------------
+TCrStatus CCrAlgInfo::SetParityBits(TPtr8 aPtrKey)
+    {
+    TInt len = aPtrKey.Length();
+    if (len < 1 ) // len should be positive
+        {
+        return KCrNotInitialized; 
+        }
+
+    for (TInt i = 0; i < len; i++)
+        {
+        TUint temp = aPtrKey[i];
+        TInt parity = 0; 
+        for (TInt j = 0; j < 7; j++)
+            {
+            temp >>= 1;
+            if (temp & 0x01) 
+                { 
+                parity++; 
+                } 
+            } 
+
+        if ((parity % 2) == 0)
+            { 
+            // even parity, change least significant bit to one.
+              aPtrKey[i] |= 0x01; // or
+            }
+        else
+            {
+            // Change least significant bit to zero.
+            aPtrKey[i] &= 0xfe; // and 
+            }
+        } 
+    return KCrOK;
+    }
+
+// End Of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrPkcs12/Src/crcrypto.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,919 @@
+/*
+* Copyright (c) 2000, 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This file contains the implementation of CCrCrypto class. 
+*
+*/
+
+
+
+//  INCLUDE FILES
+#include "crcrypto.h"
+#include <e32def.h>  // REINTERPRET_CAST
+#include "crdata.h"
+#include <bigint.h>  // Big integer.
+#include <hash.h>
+#include <symmetric.h>
+
+
+// -----------------------------------------------------------------------------
+// CCrCrypto
+// Constructor.
+// -----------------------------------------------------------------------------
+CCrCrypto::CCrCrypto()
+    : iAlgorithmInfos(0)
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// ~CCrCrypto
+// Destructor.
+// -----------------------------------------------------------------------------
+CCrCrypto::~CCrCrypto()
+    {
+    Reset();
+
+    if( iAlgorithmInfos )
+        {
+        iAlgorithmInfos->Reset();
+        delete iAlgorithmInfos;
+        iAlgorithmInfos = NULL;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCrCrypto::ConstructL
+// This function initializes this object's members.
+// -----------------------------------------------------------------------------
+void CCrCrypto::ConstructL()
+    {
+    iAlgorithmInfos = new (ELeave) CArrayPtrFlat<CCrAlgInfo>(1);
+    }
+
+// -----------------------------------------------------------------------------
+// CCrCrypto::NewLC
+// -----------------------------------------------------------------------------
+CCrCrypto* CCrCrypto::NewLC()
+    {
+    CCrCrypto* self = new (ELeave) CCrCrypto();
+    CleanupStack::PushL(self);
+
+    self->ConstructL();
+
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CCrCrypto::NewL
+// -----------------------------------------------------------------------------
+CCrCrypto* CCrCrypto::NewL()
+    {
+    CCrCrypto* self = NewLC();
+    CleanupStack::Pop();
+
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CCrCrypto::Reset
+// Reset all algorithms initialized into this object and free
+// memory associated to them. Note that GetDigest etc. functions are
+// meaningles after this until new ones are initialized and finalized.
+// -----------------------------------------------------------------------------
+void CCrCrypto::Reset()
+    {
+    TInt        i = 0;
+    TInt        size = 0;
+    CCrAlgInfo* algInfo = 0;
+
+    size = iAlgorithmInfos->Count();
+
+    for (i = 0; i < size; i++)
+        {    
+        algInfo = (*iAlgorithmInfos)[i];
+
+		if (algInfo)
+			{
+			switch (algInfo->iType)
+				{
+				case ECrDES2:
+				case ECrDES3:
+					{
+                    if (algInfo->iAlgorithmObject)
+                        {
+						delete algInfo->iAlgorithmObject;
+                        algInfo->iAlgorithmObject = NULL;
+                        }
+                    if (algInfo->iPadding)
+                        {
+                        delete algInfo->iPadding;
+                        algInfo->iPadding = NULL;
+                        }
+
+                    break;
+                    }
+				default:
+					{
+                    if (algInfo->iAlgorithmObject)
+                        {
+                        delete algInfo->iAlgorithmObject;
+                        algInfo->iAlgorithmObject = NULL;
+                        }
+
+                    if (algInfo->iPadding)
+                        {
+                        delete algInfo->iPadding;
+                        algInfo->iPadding = NULL;
+                        }
+
+                    break;
+					}
+                }
+            }
+        }
+
+    iAlgorithmInfos->ResetAndDestroy();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrCrypto::InitCrypt3DESL
+// Initialize encryption or decryption with 3DES algorithm.
+// -----------------------------------------------------------------------------
+TCrStatus CCrCrypto::InitCrypt3DESL(
+    const TDesC8& aKey1,
+    const TDesC8& aKey2,
+    const TDesC8& aKey3,
+    const TDesC8& aIV,              
+    TBool         aEncrypt,   // ETrue  
+    TCrSymmMode   aMode,      // ECrCBC
+    TPaddingRule  /*aPadRule*/)   // ECrPKCS1
+    {
+    // Number of items pushed to CleanupStack
+    TUint pushedToCStack = 0;
+
+    // Combined keys.
+    HBufC8* keys = HBufC8::NewLC(
+        aKey1.Length() + aKey2.Length() + aKey3.Length());
+    ++pushedToCStack;
+
+    TPtr8 ptrKeys = keys->Des();
+
+    // Combine given keys to be able to give them to algorithm info object.
+    ptrKeys = aKey1;
+    ptrKeys.Append(aKey2);
+    ptrKeys.Append(aKey3);
+
+    // Create new algorithm info object.
+    CCrAlgInfo* algInfo = CCrAlgInfo::NewLC(
+        ECrDES3,
+        *keys,
+        aIV,
+        aEncrypt,
+        ETrue,
+        aMode);
+    ++pushedToCStack;
+    
+    switch (aMode)
+        {
+        case ECrCBC:
+            {
+			    if (aEncrypt)
+				    {
+				    C3DESEncryptor* tripleDes = C3DESEncryptor::NewL(*algInfo->iKey);
+				    CleanupStack::PushL(tripleDes);
+
+				    CModeCBCEncryptor* cbcEncryptor = CModeCBCEncryptor::NewL(tripleDes, aIV);
+				    CleanupStack::Pop(tripleDes); // CModeCBCEncryptor takes care of tripleDes now
+				    CleanupStack::PushL(cbcEncryptor);
+
+				    CPaddingPKCS7* padding = CPaddingPKCS7::NewL(tripleDes->BlockSize());							
+				    CleanupStack::PushL(padding);
+
+				    CBufferedEncryptor* encryptor = CBufferedEncryptor::NewL(cbcEncryptor, padding);
+				    CleanupStack::Pop(2); // CBufferedEncryptor takes care of freeing	
+
+				    algInfo->iAlgorithmObject = encryptor;
+				    }
+			    else
+				    {			
+				    C3DESDecryptor* tripleDes = C3DESDecryptor::NewL(*algInfo->iKey);
+				    CleanupStack::PushL(tripleDes);
+
+				    CModeCBCDecryptor* cbcDecryptor = CModeCBCDecryptor::NewL(tripleDes, aIV);
+				    CleanupStack::Pop(tripleDes); // CModeCBCEncryptor takes care of tripleDes now
+				    CleanupStack::PushL(cbcDecryptor);
+
+				    CPaddingPKCS7* padding = CPaddingPKCS7::NewL(tripleDes->BlockSize());
+				    CleanupStack::PushL(padding);
+
+				    CBufferedDecryptor* decryptor = CBufferedDecryptor::NewL(cbcDecryptor, padding);
+				    CleanupStack::Pop(2); // CBufferedDecryptor takes care of freeing	
+
+				    algInfo->iAlgorithmObject = decryptor;							
+				    }	                    
+            break;
+            }
+        case ECrCFB:
+            {
+		    return KCrCrypto | KCrUnknownMode;
+            }
+        case ECrECB:
+            {
+            return KCrCrypto | KCrUnknownMode;
+            }
+        case ECrOFB:
+            {
+		    return KCrCrypto | KCrUnknownMode;
+            }
+        default:
+            {
+            return KCrCrypto | KCrUnknownMode;
+            }
+        }
+
+    CleanupStack::PushL(algInfo->iAlgorithmObject);
+    ++pushedToCStack;
+
+    // Append new algorithm info object into member set.
+    iAlgorithmInfos->AppendL(algInfo);
+ 
+    CleanupStack::Pop(pushedToCStack);
+
+    delete keys;
+    keys = NULL;
+
+    return KCrOK;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrCrypto::InitCryptRC2L
+// Initialize encryption or decryption with RC2 algorithm.
+// -----------------------------------------------------------------------------
+TCrStatus CCrCrypto::InitCryptRC2L(
+    const TDesC8& aKey,             
+    const TDesC8& aIV,
+    TBool         aEncrypt,          // ETrue
+    TInt          aEffectiveKeyLen,  // If 0 given, key len is used.
+    TCrSymmMode   aMode,             // ECrCBC
+    TPaddingRule  /*aPadRule */)          // ECrPKCS1
+    {
+    // Number of items pushed to CleanupStack
+    TUint pushedToCStack = 0;
+
+    // Create new algorithm info object.
+    CCrAlgInfo* algInfo = CCrAlgInfo::NewLC(
+        ECrRC2,
+        aKey,
+        aIV,
+        aEncrypt,
+        ETrue,
+        aMode);
+    ++pushedToCStack;
+
+    // If given effective key length is zero, use key length.
+    if (aEffectiveKeyLen == 0)
+        {
+        aEffectiveKeyLen = algInfo->iKey->Length() * 8;
+        }
+    
+    // Create cipher object.
+    switch (aMode)
+        {
+        case ECrCBC:
+            {
+			if (aEncrypt)
+				{
+				CRC2Encryptor* rc2 = CRC2Encryptor::NewL(*algInfo->iKey, aEffectiveKeyLen);
+				CleanupStack::PushL(rc2);
+
+				CModeCBCEncryptor* cbcEncryptor = CModeCBCEncryptor::NewL(rc2, aIV);
+				CleanupStack::Pop(rc2); // CModeCBCEncryptor takes care of rc2 now
+				CleanupStack::PushL(cbcEncryptor);
+
+				CPaddingPKCS7* padding = CPaddingPKCS7::NewL(rc2->BlockSize());
+				CleanupStack::PushL(padding);
+
+				CBufferedEncryptor* encryptor = CBufferedEncryptor::NewL(cbcEncryptor, padding);
+				CleanupStack::Pop(2); // CBufferedEncryptor takes care of freeing
+
+				algInfo->iAlgorithmObject = encryptor;							
+				}
+			else
+				{			
+				CRC2Decryptor* rc2 = CRC2Decryptor::NewL(*algInfo->iKey, aEffectiveKeyLen);
+				CleanupStack::PushL(rc2);
+
+				CModeCBCDecryptor* cbcDecryptor = CModeCBCDecryptor::NewL(rc2, aIV);
+				CleanupStack::Pop(rc2); // CModeCBCEncryptor takes care of rc2 now
+				CleanupStack::PushL(cbcDecryptor);
+
+				CPaddingPKCS7* padding = CPaddingPKCS7::NewL(rc2->BlockSize());
+				CleanupStack::PushL(padding);
+
+				CBufferedDecryptor* decryptor = CBufferedDecryptor::NewL(cbcDecryptor, padding);
+				CleanupStack::Pop(2); // CBufferedDecryptor takes care of freeing
+
+				algInfo->iAlgorithmObject = decryptor;							
+				}	                    
+            algInfo->iMode = ECrCBC;
+            break;
+            }
+        case ECrCFB:
+            {
+            return KCrCrypto | KCrUnknownMode;
+            }
+        case ECrECB:
+            {          
+            return KCrCrypto | KCrUnknownMode;
+            }
+        case ECrOFB:
+            {
+			return KCrCrypto | KCrUnknownMode;
+            }
+        default:
+            {
+            return KCrCrypto | KCrUnknownMode;
+            }
+        }
+
+    CleanupStack::PushL(algInfo->iAlgorithmObject);
+    ++pushedToCStack;
+
+
+    // Append new algorithm info object into member set.
+    iAlgorithmInfos->AppendL(algInfo);
+
+    CleanupStack::Pop(pushedToCStack);
+ 
+    return KCrOK;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrCrypto::InitDigestL
+// Initialize message digest with MD2 algorithm.
+// -----------------------------------------------------------------------------
+TCrStatus CCrCrypto::InitDigestL(TCrAlgorithm aAlgorithm)    
+    {
+    // Number of items pushed to CleanupStack
+    TUint pushedToCStack = 0;
+
+    // Create new algorithm info object.
+    CCrAlgInfo *algInfo = CCrAlgInfo::NewLC(aAlgorithm);
+    pushedToCStack++;
+
+    switch(aAlgorithm)
+        {
+        case ECrSHA1:
+            {
+            // Create digest object.
+            algInfo->iAlgorithmObject  = CSHA1::NewL();
+            break;
+            }
+        case ECrMD5:
+            {
+            // Create digest object.
+            algInfo->iAlgorithmObject  = CMD5::NewL();
+            break;
+            }
+        case ECrMD2:
+            {
+            // Create digest object.
+            algInfo->iAlgorithmObject = CMD2::NewL();
+            break;
+            }
+        case ECrSHA:
+            {  
+            // Create digest object.
+            algInfo->iAlgorithmObject  = CSHA::NewL();
+            break;
+            }
+        default:
+            {
+            return KCrCrypto | KCrNotSupportedAlg;
+            }
+        }
+
+    CleanupStack::PushL(algInfo->iAlgorithmObject);
+    pushedToCStack++;
+
+    // Append new algorithm info object into member set.
+    iAlgorithmInfos->AppendL(algInfo);
+
+    CleanupStack::Pop(pushedToCStack);
+
+    return KCrOK;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrCrypto::InitDigestHMACL
+// Initialize message digest with HMAC algorithm.
+// -----------------------------------------------------------------------------
+TCrStatus CCrCrypto::InitDigestHMACL(
+    const TDesC8& aKey, 
+    TCrAlgorithm aDigestAlg)     
+    {
+    // Number of items pushed to CleanupStack
+    TUint pushedToCStack = 0;
+
+    TCrAlgorithm hmacDigest;
+
+    switch (aDigestAlg)
+        {
+        case ECrSHA1:
+            {
+            hmacDigest = ECrHMAC_SHA1;
+
+            break;
+            }
+        case ECrMD5:
+            {
+            hmacDigest = ECrHMAC_MD5;
+
+            break;
+            }
+        default:
+            {
+            return KCrCrypto | KCrNotSupportedAlg;
+            }
+        }
+
+    // Create new algorithm info object.
+    CCrAlgInfo *algInfo = CCrAlgInfo::NewLC(hmacDigest);
+    pushedToCStack++;
+
+    CMessageDigest* digest = 0;
+
+    switch(aDigestAlg)
+        {
+        case ECrSHA1:
+            {
+            // Create digest object.
+            digest = CSHA1::NewL();
+            break;
+            }
+        case ECrMD5:
+            {
+            // Create digest object.
+            digest = CMD5::NewL();
+            break;
+            }
+        case ECrMD2:
+            {
+            // Create digest object.
+            digest = CMD2::NewL();
+            break;
+            }
+        case ECrSHA:
+            {   
+            // Create digest object.
+            digest = CSHA::NewL();
+            break;  
+            }   
+        default:
+            {
+            return KCrCrypto | KCrNotSupportedAlg;
+            }
+        }
+    CleanupStack::PushL(digest);
+    ++pushedToCStack;
+    // Create digest object.
+    algInfo->iAlgorithmObject  = CHMAC::NewL(aKey, digest);
+    CleanupStack::PushL(algInfo->iAlgorithmObject);
+    ++pushedToCStack;
+    
+    // Append new algorithm info object into member set.
+    iAlgorithmInfos->AppendL(algInfo);
+
+    CleanupStack::Pop(pushedToCStack);
+
+    return KCrOK;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CCrCrypto::ProcessL
+// Process given source data with initialized crypto operations.
+// If symmetric crypto is initialized sets to aTrg encrypted
+// or decrypted data without last portion. If aProcessFinalBlock
+// is ETrue, appends also last portion. If only digest algorithm
+// is initialized, aTrg is not used.
+// -----------------------------------------------------------------------------
+TCrStatus CCrCrypto::ProcessL(const TDesC8& aSrc, TDes8& aTrg) 
+    {
+    TInt              i, size;
+    TUint             pushedToCStack = 0;
+    CCrAlgInfo* algInfo = 0;
+
+    size = iAlgorithmInfos->Count();
+
+    for (i = 0; i < size; i++)
+        {
+        algInfo = (*iAlgorithmInfos)[i];
+
+        // Message digest algorithm
+        if (algInfo->iType < ECrLAST_DIGEST)
+            {
+            // Casting to right type
+            CMessageDigest* digest = STATIC_CAST(
+                CMessageDigest*, algInfo->iAlgorithmObject);
+
+            // Store the digest to buf
+            //algInfo->iDigest = HBufC8::NewL(digest->HashSize());
+			TPtr8 ptr = algInfo->iDigest->Des();
+			ptr.Copy(digest->Hash(aSrc));
+            }   
+        // Symmetric crypto algorithm
+        else if (algInfo->iType > ECrLAST_DIGEST && algInfo->iType < ECrLAST_SYMM_CRYPTO)
+            {
+            // Casting to right type
+            CSymmetricCipher* cipherSymm =
+                STATIC_CAST(CSymmetricCipher*, algInfo->iAlgorithmObject);
+
+
+			// This is not incremental
+			cipherSymm->ProcessFinalL(aSrc, aTrg);			
+			
+            CleanupStack::Pop(pushedToCStack);
+            }
+        else 
+            {
+            return KCrCrypto | KCrNotSupportedAlg;
+            }
+        }
+    return KCrOK;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrCrypto::FinalCryptL
+// Finalize symmetric algorithms objects.
+// -----------------------------------------------------------------------------
+TCrStatus CCrCrypto::FinalCryptL(TDes8& aTrg)
+    {
+    TInt        i, size;
+    CCrAlgInfo *algInfo = 0;
+    TCrStatus   status = KCrOK;
+    size = iAlgorithmInfos->Count();
+
+    for (i = 0; i < size; i++)
+        {
+        algInfo = (*iAlgorithmInfos)[i];
+
+        if (algInfo->iType > ECrLAST_DIGEST && 
+            algInfo->iType < ECrLAST_SYMM_CRYPTO) 
+            { 
+            TUint8 pushedToCStack = 0;
+
+            CSymmetricCipher* cipherSymm = 
+                STATIC_CAST(CSymmetricCipher*, algInfo->iAlgorithmObject);
+            
+            HBufC8 *lastBlock =
+                HBufC8::NewLC(algInfo->iLastPortion->Size());
+            pushedToCStack++;
+
+            TPtr8 ptrLastBlock = lastBlock->Des();
+
+		    if (cipherSymm->MaxFinalOutputLength(ptrLastBlock.Size()) > 0)
+		    {
+			    cipherSymm->ProcessFinalL(ptrLastBlock, aTrg);                    
+		    }
+
+            CleanupStack::Pop(pushedToCStack);
+
+            delete lastBlock;
+            lastBlock = 0;
+
+            delete cipherSymm;
+            cipherSymm = 0;
+            algInfo->iAlgorithmObject = 0;
+        
+            }                 
+        }
+    return status;
+    }
+
+
+TCrStatus CCrCrypto::FinalDigest(TDes8& aTrg)
+    {
+    TInt              i, size;
+    CCrAlgInfo *algInfo = 0;
+    TCrStatus         status = KCrOK;
+
+    size = iAlgorithmInfos->Count();
+
+    for (i = 0; i < size; i++)
+        {
+        algInfo = (*iAlgorithmInfos)[i];
+
+        if ((algInfo->iType < ECrLAST_DIGEST) && (status == KCrOK))
+            {
+    
+            aTrg.Copy(*algInfo->iDigest);
+
+            CMessageDigest* digest = STATIC_CAST(
+                CMessageDigest*, algInfo->iAlgorithmObject);
+
+            delete digest;
+            digest = 0;
+            algInfo->iAlgorithmObject = 0;
+            }
+        }
+    return status;
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CCrCrypto::RemoveLastBlock
+// Checks that aOriginSrc length is multiple of the block size, If not, 
+// removes data from the end so that it is multiple of the block size.
+// Parameters:     aSrc            Original data to remove the last block 
+//                 aBlockSize      Size of the block
+//                 alginfo         Pointer to object where last portion is 
+//                                 stored.
+// Return Values:  true if size of aOriginSrc is bigger than blockSize
+//                 otherwise false. If false the whole aOriginSrc is stored 
+//                 to alginfo.
+// -----------------------------------------------------------------------------
+TInt CCrCrypto::RemoveLastBlock(
+    TDesC8&           aSrc,
+    const TInt        aBlockSize,
+    CCrAlgInfo*       algInfo)    
+    { 
+    TUint number_of_blocks = aSrc.Size() / aBlockSize;
+    TUint size_of_last_block = aSrc.Size() % aBlockSize;     
+
+    TUint size_of_checked; 
+    
+    // If aOriginSrc's size is smaller or equal than aBlocksize
+    if (number_of_blocks == 0 || (number_of_blocks == 1 && size_of_last_block == 0))
+        {
+        *algInfo->iLastPortion = aSrc;
+        
+        return false;
+        }
+    else if (size_of_last_block == 0 && number_of_blocks > 0)
+        {
+        // 3des fix begins:
+        // Don't do anything if size of data already is multiple of
+        // blocksize. Otherwise padding will be ruined. Return true anyway.
+        if(!algInfo->iEncrypt)
+            {
+            size_of_checked = aSrc.Size() - aBlockSize;
+        
+            *algInfo->iLastPortion = aSrc.Right(aBlockSize);
+
+            aSrc = aSrc.Left(size_of_checked);
+            }
+        
+        // 3des fix ends.
+
+        return true;
+        }
+    else
+        {
+        size_of_checked = aSrc.Size() - size_of_last_block;
+        
+        *algInfo->iLastPortion = aSrc.Right(size_of_last_block);
+
+        aSrc = aSrc.Left(size_of_checked);
+
+        return true;
+        }     
+    }
+
+// -----------------------------------------------------------------------------
+// CCrCrypto::DeriveKeyPKCS12L
+// Derives key(s) or IV vector from password, salt and iterarion count.
+// Return Values:  KCrOK
+//                 KCrNotSupportedAlg
+//                 KCrUndefinedLibrary
+//                 KCrUnknownLibrary
+//                 KCrUnknownMode
+//                 KCrErrorGeneral
+// -----------------------------------------------------------------------------
+TCrStatus CCrCrypto::DeriveKeyPKCS12L(
+    const TDesC8&   aPassword, 
+    const TDesC8&   aSalt,
+    const TInt      aIterationCount,
+    TCrAlgorithm    aHashFunc,
+    const TUint8    aID,
+    const TInt      aNumberOfBytes,
+    TDes8&          aTrg)               // Output data, possible keys and IV
+    {
+    TInt remainder = 0;
+    TInt rounds = 0;
+    TInt pushedToCStack = 0;
+    TInt inputSize = MesDigestInputSize(aHashFunc);
+    TInt outputSize = MesDigestOutputSize(aHashFunc);
+
+    // Step 1: Construct D by concatenating copies of ID.
+    // Construct a string D
+    HBufC8* D_buf = HBufC8::NewLC(inputSize);
+    ++pushedToCStack;
+
+    TPtr8 D_ptr = D_buf->Des();
+	TInt i(0);
+    for (i = 0; i < inputSize; ++i)
+        {
+        D_ptr.Append(aID);
+        }
+
+    // Step 2, 3, 4:
+    TInt s_length = 0;
+    TInt p_length = 0;
+
+    s_length = inputSize * ((aSalt.Size() + inputSize - 1) / inputSize);
+    p_length = inputSize * ((aPassword.Size() + inputSize - 1) / inputSize);
+    
+    HBufC8* I_buf = HBufC8::NewLC(s_length + p_length);
+    ++pushedToCStack;
+    TPtr8 I_ptr = I_buf->Des();
+
+    if (aSalt.Size() != 0)
+        {
+        rounds = s_length / aSalt.Size();
+        for (i = 0; i < rounds; ++i)
+            {
+            I_ptr.Append(aSalt);
+            }
+        remainder = s_length % aSalt.Size();
+        if (remainder != 0)
+            {
+            I_ptr.Append(aSalt.Ptr(), remainder);
+            }
+        }
+             
+    
+    if (aPassword.Size() != 0)
+        {
+        rounds = p_length / aPassword.Size();
+        for (i = 0; i < rounds; ++i)
+            {
+            I_ptr.Append(aPassword);
+            }
+        remainder = p_length % aPassword.Size();
+        if (remainder != 0)
+            {
+            I_ptr.Append(aPassword.Ptr(), remainder);
+            }
+        }
+
+    // Step 5: Set c.
+    TInt c = 0;
+    c = (aNumberOfBytes + outputSize - 1) / outputSize; 
+    
+    // Step 6: Loop
+    TCrStatus status = KCrCrypto | KCrErrorGeneral;
+    
+    CCrCrypto* hash = 0;
+
+    HBufC8* B_buf = HBufC8::NewLC(inputSize);
+    ++pushedToCStack;
+    TPtr8 B_ptr = B_buf->Des();
+
+    HBufC8* A_buf = HBufC8::NewLC(D_ptr.Size() + I_ptr.Size());    
+    ++pushedToCStack;
+    TPtr8 A_ptr = A_buf->Des();
+    
+    TInt j = 0;
+    RInteger B_int;
+    RInteger Ij_int;
+    TInt N = aNumberOfBytes;
+
+    rounds = inputSize / outputSize;
+    remainder = inputSize % outputSize;
+
+    for (i = 0; i < c; ++i)
+        {
+        A_ptr.Zero();
+        A_ptr.Append(D_ptr);
+        A_ptr.Append(I_ptr);
+        
+        hash = CCrCrypto::NewLC();
+
+        for (TInt ii = 0; ii < aIterationCount; ++ii)
+            {
+            status = hash->InitDigestL(aHashFunc);
+            status = hash->ProcessL(A_ptr, A_ptr); 
+            A_ptr.Zero();
+            status = hash->FinalDigest(A_ptr);
+            hash->Reset();
+            }
+        
+        CleanupStack::PopAndDestroy(); // hash
+
+        if (outputSize < N)
+            {
+            aTrg.Append(A_ptr);
+            }
+        else
+            {
+            aTrg.Append(A_ptr.Ptr(), N);
+            }
+
+        if (outputSize >= N)
+            {
+            status = KCrOK;
+            break;
+            }
+
+        N -= outputSize;
+
+        rounds = inputSize / A_ptr.Size();
+        remainder = inputSize % A_ptr.Size();
+        for (j = 0; j < rounds; ++j)
+            {
+            B_ptr.Append(A_ptr);
+            }
+        if (remainder != 0)
+            {
+            B_ptr.Append(A_ptr.Ptr(), remainder);
+            }
+        
+        B_int = RInteger::NewL(B_ptr);  
+		CleanupStack::PushL(B_int);
+        
+        B_int += 1;
+
+        for (j = 0; j < I_ptr.Size(); j += inputSize)
+            {
+            Ij_int = RInteger::NewL(I_ptr.Mid(j, inputSize));
+			CleanupStack::PushL(Ij_int);
+            Ij_int += B_int;
+            
+            I_ptr.Replace(j, inputSize, Ij_int.BufferLC()->Right(inputSize));
+
+            CleanupStack::PopAndDestroy(2); // Ij_int, BufferLC            
+            }
+
+        CleanupStack::PopAndDestroy(); // B_int
+        }
+
+    CleanupStack::PopAndDestroy(pushedToCStack); 
+
+    return status;          
+}
+
+// -----------------------------------------------------------------------------
+// CCrCrypto::MesDigestInputSize
+// Returns input size of the message digest algorithm. 
+// Return Values:      Input size of the message digest algorithm in bytes.
+//                     If unknown algorithm returns -1.      
+// -----------------------------------------------------------------------------
+TInt CCrCrypto::MesDigestInputSize(TCrAlgorithm aDigestAlg)
+    {
+    switch(aDigestAlg)
+        {
+        case ECrSHA1:
+        case ECrMD5:
+        case ECrMD2:
+            {
+            return KDigestInputSize;
+            }
+        default:
+            {
+            return -1;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CCrCrypto::MesDigestOutputSize
+// Returns output size of the message digest algorithm. 
+// Parameters:         aDigestAlg           message digest algortihm
+// Return Values:      Output size of the message digest algorithm in bytes.
+//                     If unknown algorithm returns -1.      
+// -----------------------------------------------------------------------------
+TInt CCrCrypto::MesDigestOutputSize(TCrAlgorithm aDigestAlg)
+    {
+    switch(aDigestAlg)
+        {
+        case ECrSHA1:
+            {
+            return KCrLongDigestLength;
+            }
+        case ECrMD5:
+        case ECrMD2:
+            {
+            return KCrMediumDigestLength;
+            }
+        default:
+            {
+            return -1;
+            }
+        }
+    }
+
+// End Of Line
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrPkcs12/Src/crpkcs12.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,2243 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This file contains the implementation of CCrPKCS12 class. 
+*
+*/
+
+
+
+//  INCLUDE FILES
+#include "crpkcs12.h"
+#include <crdefs.h>      // CCrDefines
+#include <e32std.h>
+#include <x509certext.h>
+
+const TInt KX509Version3 = 3;
+
+// -----------------------------------------------------------------------------
+// CPKCS12SyncWrapper
+// Constructor
+// -----------------------------------------------------------------------------
+//
+CCrPKCS12::CPKCS12SyncWrapper::CPKCS12SyncWrapper(): CActive( EPriorityStandard )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12SyncWrapper
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CCrPKCS12::CPKCS12SyncWrapper::~CPKCS12SyncWrapper()
+    {
+    if (iSecDlg)
+        {
+		iSecDlg->Release();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12SyncWrapper
+// EnterPassword wrapper function.
+// -----------------------------------------------------------------------------
+//
+TInt CCrPKCS12::CPKCS12SyncWrapper::EnterPasswordL(const TPINParams& aPINParams, TBool aRetry, TPINValue& aPINValue)
+    {
+    iSecDlg = SecurityDialogFactory::CreateL();
+    iSecDlg->EnterPIN(aPINParams, aRetry, aPINValue, iStatus);
+    return SetActiveAndWait();
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12SyncWrapper::SetActiveAndWait
+// 
+// -----------------------------------------------------------------------------
+//
+TInt CCrPKCS12::CPKCS12SyncWrapper::SetActiveAndWait()
+    {
+    SetActive();
+    iWait.Start();
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12SyncWrapper::DoCancel
+// 
+// -----------------------------------------------------------------------------
+//
+void CCrPKCS12::CPKCS12SyncWrapper::DoCancel()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12SyncWrapper::RunL
+// 
+// -----------------------------------------------------------------------------
+//
+void CCrPKCS12::CPKCS12SyncWrapper::RunL()
+    {
+    iWait.AsyncStop();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12
+// Constructor
+// This function constructs CCrPKCS12 object
+// Return Values:  None
+// -----------------------------------------------------------------------------
+CCrPKCS12::CCrPKCS12():iIter(1), iPrivateKeyIdArray(1), iSafeBagsCount(0)
+    {
+    // Default iteration count is 1.
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::ConstructL
+// This function initializes CCrPKCS12 object's member objects.
+// Parameters:     None
+// Return Values:  None
+// -----------------------------------------------------------------------------
+void CCrPKCS12::ConstructL()
+    {
+  	iberSet = CCrBerSet::NewL( 1 );
+    iUserCertificates = CX509CertificateSet::NewL( 1 );
+    iCACertificates = CX509CertificateSet::NewL( 1 );
+    iUserCertificateBuffer = new (ELeave) CArrayPtrFlat<TDesC8>(1);
+    iCACertificateBuffer = new (ELeave) CArrayPtrFlat<TDesC8>(1);
+    iPKCS8PrivateKeyArray = new (ELeave) CArrayPtrFlat<HBufC8>(1);
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12
+// Destructor
+// This function destructs CCrPKCS12 object
+// Return Values:  None
+// -----------------------------------------------------------------------------
+CCrPKCS12::~CCrPKCS12()
+    {    
+    delete iberSet;
+    delete iUserCertificates;
+    delete iCACertificates;
+    
+    if (iUserCertificateBuffer)
+        {
+        iUserCertificateBuffer->ResetAndDestroy();
+        delete iUserCertificateBuffer;
+        }
+    if (iCACertificateBuffer)
+        {
+        iCACertificateBuffer->ResetAndDestroy();
+        delete iCACertificateBuffer;
+        }
+    delete iMac;
+    delete iSalt;
+    delete iPassWord;    
+    delete iContentInfo;
+    delete iBags;    
+    delete iDecryptionKey;
+        
+    if (iPKCS8PrivateKeyArray)
+        {        
+        iPKCS8PrivateKeyArray->ResetAndDestroy();    
+        delete iPKCS8PrivateKeyArray;
+        }
+    iPrivateKeyIdArray.ResetAndDestroy();
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::NewLC
+// This function implements the two-phase construction of CCrPKCS12
+// class. The function uses standard constructor to reserve memory
+// for pkcs12-object, stores a pointer to the object into clean up
+// stack, and returns the pointer to the object.
+// Parameters:     None.
+// Return Values:  CCrPKCS12*     Pointer to the CCrPKCS12 object.
+// -----------------------------------------------------------------------------
+CCrPKCS12* CCrPKCS12::NewLC()
+    {
+    CCrPKCS12* self = new ( ELeave ) CCrPKCS12();
+    CleanupStack::PushL( self );
+
+    self->ConstructL();
+
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::NewL
+// This function implements the two-phase construction of CCrPKCS12
+// class. The function reserves memory for pkcs12-object and
+// returns pointer to that object. This function uses NewLC to create
+// the object and store it to cleanup stack. Finally the object is popped
+// from clean up stack.
+// Parameters:     None.
+// Return Values:  CCrPKCS12*    Pointer to the CCrPKCS12 object.
+// -----------------------------------------------------------------------------
+CCrPKCS12* CCrPKCS12::NewL()
+    {
+    CCrPKCS12* self = NewLC();
+    CleanupStack::Pop();
+
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::Open
+// Opens pkcs12-file from location given in parameter afilePath,
+// then it makes a CCrBer::berSet from it. Then it starts testing
+// berObjects from berSet. When it comes long enough, needed
+// information can be get and stored to CCrPKCS12-Class' members.
+// Parameters: CCrData& aPkcs12File    PKCS #12 file.
+//             TBuf<48> aPassWord      password.
+// Returns:    TCrStatus               Value of error.
+// -----------------------------------------------------------------------------
+TCrStatus CCrPKCS12::OpenL(CCrData&       aPkcs12File, 
+                          const TDesC16& aPassword)
+    {
+    TCrStatus status = KCrOK;
+    TInt errData = KErrNone;
+   
+    if (!iberSet)
+        {
+        User::Leave(KErrGeneral);
+        }
+
+    // Number of extracted BER objects.
+    TInt numberOfBerObjects = 0;
+    // make berSet, set of berObjects
+    TRAP( errData,numberOfBerObjects = iberSet->OpenL( &aPkcs12File,KOpenAllLevels ));        
+    if ( errData < KErrNone )
+        {
+        return KCrPkcs12 | KCrBerLibraryError;
+        }
+    // number of ber objects must be > 0.
+    if (numberOfBerObjects < 1)
+        {
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+ 
+    iObjectNum = KFirstObject;
+
+    // Now we have the first object
+    iberObject = iberSet->At( iObjectNum );
+           
+    // File opened successfully, let's start testing berObjects.
+
+    // 1. Test, is berObject Sequence?
+	if ( !iberObject->IsSeqOrSet( iberObject->Type() ) )			
+	    {
+		return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+
+    iObjectNum++;
+    if (numberOfBerObjects < iObjectNum)
+        {
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+    iberObject = iberSet->At(iObjectNum );
+                
+    // 2. Test, is an integer?
+    if ( iberObject->Type() != KBerInteger )					
+        {
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+    
+    TInt version = 0;
+    TRAP( errData,version = iberObject->GetIntegerL() );       
+    if ( errData < KErrNone )
+        {
+        return KCrPkcs12 | KCrBerLibraryError;
+        }
+
+    // 3. Test, is version 3?
+    if ( version != KVersion3 )				
+        {
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+
+    // Is there still ber objects?
+    iObjectNum++;
+    if (numberOfBerObjects < iObjectNum)
+        {
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+    iberObject = iberSet->At(iObjectNum );
+    
+    // 4. Test, is Seq?
+    if ( !iberObject->IsSeqOrSet( iberObject->Type() ) )			
+        {
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+
+    // Remember where we are.
+    TInt place = iObjectNum;
+
+    // Is there still ber objects?
+    iObjectNum++;
+    if (numberOfBerObjects < iObjectNum)
+        {
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+
+    iberObject = iberSet->At(iObjectNum );
+    
+    CCrData* contentInfo = NULL;
+    TRAP (errData, contentInfo = CCrData::NewL(EFalse));
+    if (errData < KErrNone)
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrNoMemory; 
+        }
+        
+    if ( !ReadContentInfo(*contentInfo ) )
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrNotPasswordBasedEncryption;
+        }
+
+    iberObject = iberSet->At( place );
+
+    iObjectNum += JumpNextObjectAtSameLevel();
+
+    iObjectNum++;
+    if (numberOfBerObjects < iObjectNum)
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+    iberObject = iberSet->At( iObjectNum );
+    
+    // 5. Test, is Seq?
+    if ( !iberObject->IsSeqOrSet( iberObject->Type() ) )			
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+    
+    iObjectNum++;
+    if (numberOfBerObjects < iObjectNum)
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+    iberObject = iberSet->At(iObjectNum );
+             
+    // 6. Test, is Seq?
+    if ( !iberObject->IsSeqOrSet( iberObject->Type() ) )			
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+
+    iObjectNum++;
+    if (numberOfBerObjects < iObjectNum)
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+    iberObject = iberSet->At(iObjectNum ); 
+
+     // 6. Test, is Seq?
+    if ( iberObject->IsSeqOrSet( iberObject->Type() ) )
+        {
+        iObjectNum++;
+        if (numberOfBerObjects < iObjectNum)
+            {
+            delete contentInfo;
+            contentInfo = NULL;
+            return KCrPkcs12 | KCrNotValidPkcs12Object;
+            }
+         iberObject = iberSet->At(iObjectNum );
+        }
+
+    // 7. Test, is OID?
+    if ( iberObject->Type() != KBerOid)			
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+ 
+    HBufC* oid = NULL;
+
+    TRAP(errData, oid = iberObject->GetOidL() );
+        
+    if ( errData < KErrNone )
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrBerLibraryError;
+        }
+
+    // 8. What is used HMAC-algorithm??
+    if ( *oid == KCrSha1 )										
+        {  
+        iHMACalgorithm = ECrSHA1; 
+        }
+    else if ( *oid == KCrMD5 )
+        {
+        iHMACalgorithm = ECrMD5;
+        }   
+    else
+        {
+        delete oid;
+        oid = NULL;
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrNotSupportedHMACalgorithm;
+        }
+
+    delete oid;
+    oid = NULL;
+
+    iObjectNum++;
+    if (numberOfBerObjects < iObjectNum)
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+ 
+    iberObject = iberSet->At(iObjectNum);
+    
+    // If Octet String, read mac // Case in Outlook
+    if (iberObject->Type() == KBerOctetString)
+        {
+        }
+    else
+        {
+        // 9. Test, is Null Tag?
+        if ( iberObject->Type() != KBerNull )
+            {
+            delete contentInfo;
+            contentInfo = NULL;
+            return KCrPkcs12 | KCrNotValidPkcs12Object;
+            }
+        
+        iObjectNum++;
+        if (numberOfBerObjects < iObjectNum)
+            {
+            delete contentInfo;
+            contentInfo = NULL;
+            return KCrPkcs12 | KCrNotValidPkcs12Object;
+            }
+        iberObject = iberSet->At(iObjectNum);
+
+        // If Octet String, read mac
+        if ( iberObject->Type() != KBerOctetString )
+            {
+            delete contentInfo;
+            contentInfo = NULL;
+            return EFalse;
+            }
+        } 
+        
+    // This is where needed data can be get
+    TRAP( errData,iMac = iberObject->GetOctetStringL() );
+        
+    if ( errData < KErrNone )
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrBerLibraryError;
+        }
+    
+    iObjectNum++;
+    if (numberOfBerObjects < iObjectNum)
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+    iberObject = iberSet->At(iObjectNum );
+
+    // If Octet String, read salt, if OctetString can be found,
+    // validate of this file is OK.
+    if ( iberObject->Type() != KBerOctetString )
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrNotValidPkcs12Object;
+        }
+
+    TRAP( errData,iSalt = iberObject->GetOctetStringL() );        
+    if ( errData < KErrNone )
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrBerLibraryError;
+        }
+
+    // Here's optional integer value
+    if ( iberSet->Count() > ++iObjectNum )
+        {
+        iberObject = iberSet->At( iObjectNum );
+
+        // If here is an integer, then read the number of iterations,
+        // otherwise leave DEFAULT value ( = 1, given in constructor).
+        if ( iberObject->Type() == KBerInteger )	
+            {
+            TRAP( errData,iIter = iberObject->GetIntegerL() );
+            
+            if ( errData < KErrNone )
+                {
+                delete contentInfo;
+                contentInfo = NULL;
+                return KCrPkcs12 | KCrBerLibraryError;
+                }
+            }
+        }
+    
+    
+    // Verify Mac.
+    TBool result = EFalse;
+    TRAP(errData, result = VerifyMacL(aPassword));
+    if ( errData < KErrNone )
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrWrongPassWordOrCorruptedFile;
+        }
+    if ( result)
+        {
+       // If password was OK, open ContentInfo
+        if ( !UnpackContentInfo(*contentInfo))
+            {
+            delete contentInfo;
+            contentInfo = NULL;
+            return KCrPkcs12 | KCrNotPasswordBasedEncryption;
+            } 
+        
+        delete contentInfo;
+        contentInfo = NULL;
+
+        iSafeBagsCount = DecodeSafeBagsL();
+
+        if ( !iSafeBagsCount )
+            {
+            return KCrPkcs12 | KCrNotPasswordBasedEncryption;
+            } 
+        }
+    // If macs weren't the same, password was wrong
+    else
+        {
+        delete contentInfo;
+        contentInfo = NULL;
+        return KCrPkcs12 | KCrWrongPassWordOrCorruptedFile;
+        }
+
+    return status;    
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::ReadContentInfo
+// Reads ContentInfo.
+// Parameters:     
+// Return Values:  
+// -----------------------------------------------------------------------------
+TBool CCrPKCS12::ReadContentInfo( CCrData& aContentInfo )
+    {
+    // If this object isn't OID, or if it isn't type pkcs7Data, return EFalse
+    if ( iberObject->Type() != KBerOid )
+        {
+        return EFalse;
+        }
+
+    HBufC* oid = NULL;
+    TInt errData = KErrNone;
+    
+    TRAP( errData,oid = iberObject->GetOidL());
+    if ( errData < KErrNone )
+        {
+        delete oid;
+        oid = NULL;
+        return EFalse;
+        }
+
+    if ( *oid != Kpkcs7Data )
+        {
+        delete oid;
+        oid = NULL;
+        return EFalse;
+        }
+
+    delete oid;
+    oid = NULL;
+
+    iberObject = iberSet->At( ++iObjectNum );
+
+    if ( iberObject->Type() != KBerImplicitConstructed )
+        {
+        return EFalse;
+        }
+
+    // Now, let's open Constructed data.
+    iberObject = iberSet->At( ++iObjectNum );
+
+    // Outlook or Netscape
+    if (iberObject->Type() == KBerConstructedBit + KBerOctetString ||
+        iberObject->Type() == KBerOctetString)
+        { 
+        // Outlook
+        if (iberObject->Type() == KBerOctetString )
+            {
+            TRAP (errData, iberObject->GetOctetStringL(aContentInfo));
+            if (errData < KErrNone)
+                {
+                return EFalse;
+                }
+            }
+        // Netscape
+        else  // iberObject->Type() == KBerConstructedBit + KBerOctetString
+            {
+            TRAP(errData,iberObject->OpenConstructedEncodingL(aContentInfo));
+            if ( errData < KErrNone )
+                {
+                return EFalse;
+                }
+            }
+
+        // Size of contentData
+        TInt size = 0;
+        aContentInfo.Seek( ESeekCurrent,size );
+
+        // ContentInfo's size -> Buffer's allocated size
+        TRAP( errData,iContentInfo = HBufC8::NewL( size ) );
+        if ( errData < KErrNone )
+            {
+            return EFalse;
+            }
+
+        // Make pointer to iContentInfo
+        TPtr8 pContentInfo = iContentInfo->Des();
+
+        // Copy readed ContentInfo to aContentInfo (parameter)
+        aContentInfo.Read( pContentInfo );
+       
+        // Go back to start
+        size = 0;
+        aContentInfo.Seek( ESeekStart,size );
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;
+        }    
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::UnpackContentInfo
+// This function unpacks ContentInfo. First, it tests from what level
+// SafeContents begin and after that it goes through ContentData.
+// All sequences, that begin at that level, are tested (via OID) and
+// Unpacked.
+// Parameters: CCrData& aContentData. CCrData containing ContentInfo.             
+// Return Values:  TBool   If OK, returns ETrue and if not, EFalse
+// -----------------------------------------------------------------------------
+TBool CCrPKCS12::UnpackContentInfo( CCrData& aContentData )
+    {
+    TInt objectNum = KFirstObject;
+    TInt count     = 0;
+    TInt errData   = KErrNone;
+    HBufC* oid = NULL;
+
+    CCrBerSet* set = NULL;
+
+    TRAP( errData,set = CCrBerSet::NewL( 1 ) );
+
+    if ( errData < KErrNone )
+        {
+        delete set;
+        set = NULL;
+        return EFalse;
+        }
+
+    // make berSet, set of berObjects
+    TRAP( errData,set->OpenL( &aContentData,KOpenAllLevels ) );
+
+    if ( errData < KErrNone )
+        {
+        delete set;
+        set = NULL;
+        return EFalse;
+        }
+
+    count = set->Count();
+    
+    CCrBer* object = set->At( objectNum );
+        
+    // 1. Test, is seq?
+    if ( !object->IsSeqOrSet( object->Type() ) )
+	    {
+        delete set;
+        set = NULL;
+		return EFalse;
+        }
+
+    object = set->At( ++objectNum );
+    
+	TInt i(0);
+    for (i = objectNum ; i < count ; i++)
+        {
+        // If there exists object, then check
+        //this object
+        if ( i < count )
+            {
+            object = set->At( i );
+            }
+
+        // Next check type of SafeContent
+        if ( object->Type() == KBerOid )
+            {
+            // Get object identifier
+            TRAP( errData, oid = object->GetOidL() );
+
+            if( errData < KErrNone )
+                {
+                delete set;
+                set = NULL;
+                return EFalse;
+                }
+
+            if ( *oid == Kpkcs7Data )
+                {
+                // Unpack PKCS #7 data
+                object = set->At( ++i );
+                
+                // Case it's just an octetstring
+                // NOT TESTED!
+                if ( object->Type() != KBerImplicitConstructed &&
+                     object->Type() == KBerOctetString )
+                    {
+                    HBufC8* pkcs7Data = NULL;
+
+                    TRAP( errData, pkcs7Data = object->GetOctetStringL() );
+                    if ( errData < KErrNone )
+                        {
+                        delete oid;
+                        oid = NULL;
+                        delete set;
+                        set = NULL;
+                        return EFalse;
+                        }
+                    // Riddance from warnings
+                    if ( pkcs7Data == NULL ) { delete pkcs7Data; }
+                    
+                    }
+                else
+                    {
+                    object = set->At( ++i );
+                    
+                    if ( (object->Type() ==
+                            (KBerConstructedBit + KBerOctetString)) ||  
+                         (object->Type() == KBerOctetString))
+                        {
+                        CCrData* pkcs7Data = NULL;
+                        TRAP (errData, pkcs7Data = CCrData::NewL(EFalse));
+                        if (errData < KErrNone)
+                            {
+                            delete pkcs7Data;
+                            pkcs7Data = NULL;
+                            delete oid;
+                            oid = NULL;
+                            delete set;
+                            set = NULL;
+                            return EFalse; 
+                            }
+
+                        // Netscape
+                        if (object->Type() ==
+                                (KBerConstructedBit + KBerOctetString))
+                            {
+
+                            TRAP( errData,
+                                 object->OpenConstructedEncodingL(*pkcs7Data));                            
+                            if ( errData < KErrNone )
+                                {
+                                delete pkcs7Data;
+                                pkcs7Data = NULL;
+                                delete oid;
+                                oid = NULL;
+                                delete set;
+                                set = NULL;
+                                return EFalse;
+                                }
+                            }
+                        // Outlook
+                        else if (object->Type() == KBerOctetString)
+                            {
+                            TRAP (errData, object->GetOctetStringL(*pkcs7Data));
+                            if ( errData < KErrNone )
+                                {
+                                delete pkcs7Data;
+                                pkcs7Data = NULL;
+                                delete oid;
+                                oid = NULL;
+                                delete set;
+                                set = NULL;
+                                return EFalse;
+                                }
+                            }
+             
+                        else
+                            {
+                            delete pkcs7Data;
+                            pkcs7Data = NULL;
+                            delete oid;
+                            oid = NULL;
+                            delete set;
+                            set = NULL;
+                            return EFalse;
+                            }
+
+                        TBool result = EFalse;
+                        TRAP (errData, result = UnpackPkcs7DataL(*pkcs7Data));
+                        if ( !result || errData < KErrNone )
+                            {
+                            delete pkcs7Data;
+                            pkcs7Data = NULL;
+                            delete oid;
+                            oid = NULL;
+                            delete set;
+                            set = NULL;
+                            return EFalse;
+                            }
+                        delete pkcs7Data;
+                        pkcs7Data = NULL;
+                        }
+                    }
+                }
+            else if ( *oid == Kpkcs7EncryptedData )
+                {
+                TInt currentPlace = 0;
+                // Mark, where we are now
+                aContentData.Seek( ESeekCurrent,currentPlace );
+
+                // Unpack PKCS #7 encrypted Data
+                TBool result = EFalse;
+                TRAP(errData, result = UnpackPkcs7EncryptedDataL( aContentData ) );
+                if (!result || errData < KErrNone)
+                    {
+                    delete oid;
+                    oid = NULL;
+                    delete set;
+                    set = NULL;
+                    return EFalse;
+                    }
+                                  
+                // Go back where we were and continue
+                aContentData.Seek( ESeekStart,currentPlace );
+                }
+            delete oid;
+            oid = NULL;
+            }
+        }
+    if( i < count )
+        {
+        object = set->At( i );
+        }
+
+    delete set;
+    set = NULL;
+    // Now iBags contains all SafeBags.
+    return ETrue;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::UnpackPkcs7DataL
+// Unpacks Pkcs7Data.
+// Parameters: CCrData& aPkcs7Data     
+// Return Values:  TBool   If OK, returns ETrue and if not, EFalse
+// -----------------------------------------------------------------------------
+TBool CCrPKCS12::UnpackPkcs7DataL( CCrData& aPkcs7Data )
+    {
+    TInt size = 0;
+
+    // Size fo aPkcs7Data
+    aPkcs7Data.Seek( ESeekCurrent,size );
+    // Add this bag to iBags
+
+    // Allocate needed amount of memory for iBags
+    // If iBags-buffer is NULL
+    if ( iBags == NULL)
+        {
+        iBags = HBufC8::NewL( size );
+        }
+    // If iBags isn't NULL
+    else
+        {
+        // Re-allocated space for iBags is
+        // size of the current iBags buffer + size of aPkcs7Dat
+        iBags = iBags->ReAllocL(iBags->Size() + size);
+        }
+    // Append aPkcs7Data to iBags
+    TPtr8 pBags = iBags->Des();
+    HBufC8* tempBuf = HBufC8::NewLC(size);
+    TPtr8 tempPtr = tempBuf->Des();
+    aPkcs7Data.Read(tempPtr);
+    pBags.Append(tempPtr);
+    CleanupStack::PopAndDestroy(); // tempBuf
+
+    return ETrue;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::UnpackPkcs7EncryptedDataL
+// Unpacks Pkcs7EncryptedData.
+// Parameters: CCrData& aPkcs7EncryptedData     
+// Return Values:  TBool   If OK, returns ETrue and if not, EFalse
+// -----------------------------------------------------------------------------  
+TBool CCrPKCS12::UnpackPkcs7EncryptedDataL( CCrData& aPkcs7EncryptedData )
+    {
+    TInt objectNum = KFirstObject;
+    //TInt count     = 0;
+    HBufC* oid = NULL;
+    HBufC8* pkcs7EncryptedDataBuf = NULL;
+    CCrBerSet* set = NULL;
+    CCrBer* object;
+
+    TInt numberOfItemsInCStack = 0;
+
+    set = CCrBerSet::NewL(1);
+    CleanupStack::PushL(set);
+    numberOfItemsInCStack++;
+
+    // make berSet, set of berObjects
+    set->OpenL( &aPkcs7EncryptedData,KOpenAllLevels );
+
+    //count = set->Count();    
+
+    // Now we should have a sequence here
+    object = set->At( ++objectNum );
+        
+    // 1. Test, is seq?
+    if ( !object->IsSeqOrSet( object->Type() ) )			
+	    {
+        CleanupStack::PopAndDestroy(numberOfItemsInCStack); // set
+        numberOfItemsInCStack = 0;
+        return EFalse;
+        }
+    
+    object = set->At( ++objectNum );
+    
+    // 2. Test, is integer?
+    if ( object->Type() != KBerInteger )
+        {
+        CleanupStack::PopAndDestroy(numberOfItemsInCStack); // set
+        numberOfItemsInCStack = 0;
+        return EFalse;
+        }
+
+    // 3. Test, is version 1?
+    if ( object->GetIntegerL() != KEdVer0 )
+        {
+        CleanupStack::PopAndDestroy(numberOfItemsInCStack); // set
+        numberOfItemsInCStack = 0;
+        return EFalse;
+        }
+
+    object = set->At( ++objectNum );
+        
+    // 4. Test, is seq?
+    if ( !object->IsSeqOrSet( object->Type() ) )			
+	    {
+        CleanupStack::PopAndDestroy(numberOfItemsInCStack); // set
+        numberOfItemsInCStack = 0;
+		return EFalse;
+        }
+
+    object = set->At( ++objectNum );
+        
+    // 5. Test, is OID?
+    if ( object->Type() != KBerOid )
+        {
+        CleanupStack::PopAndDestroy(numberOfItemsInCStack); // set
+        numberOfItemsInCStack = 0;
+        return EFalse;
+        }
+
+    // Get OID.
+    oid = object->GetOidL();
+    CleanupStack::PushL(oid);
+    numberOfItemsInCStack++; // 2 set + oid
+    // Is it pkcs7Data?
+    if ( *oid != Kpkcs7Data )
+        {
+        CleanupStack::PopAndDestroy(numberOfItemsInCStack); // set + oid
+        numberOfItemsInCStack = 0;
+        return EFalse;
+        }
+
+    CleanupStack::PopAndDestroy(); // oid
+    numberOfItemsInCStack--; // 1
+
+    object = set->At( ++objectNum );
+        
+    // 6. Test, is seq?
+    if ( !object->IsSeqOrSet( object->Type() ) )
+	    {
+        CleanupStack::PopAndDestroy(numberOfItemsInCStack); // set
+        numberOfItemsInCStack = 0;
+		return EFalse;
+        }
+
+    object = set->At( ++objectNum );
+
+    // Here should be encryption algorithm
+    if ( object->Type() != KBerOid )
+        {
+        CleanupStack::PopAndDestroy(numberOfItemsInCStack); // set
+        numberOfItemsInCStack = 0;
+        return EFalse;
+        }
+
+    // Get used encryption algorithm
+    TInt algorithm = 0;
+
+    oid = object->GetOidL();
+    CleanupStack::PushL(oid);
+    numberOfItemsInCStack++; // 2 set + oid
+
+    algorithm = GetAlgorithmL( oid );
+    CleanupStack::PopAndDestroy(); // oid
+    numberOfItemsInCStack--; // 1
+
+    object = set->At( ++objectNum );
+        
+    // 7. Test, is seq?
+    if ( !object->IsSeqOrSet(object->Type()))			
+	    {
+        CleanupStack::PopAndDestroy(numberOfItemsInCStack); // set
+        numberOfItemsInCStack = 0;
+		return EFalse;
+        }
+    
+    object = set->At( ++objectNum );
+
+    // Here should be salt
+    if ( object->Type() != KBerOctetString )
+        {
+        CleanupStack::PopAndDestroy(numberOfItemsInCStack); // set
+        numberOfItemsInCStack = 0;
+        return EFalse;
+        }
+
+    HBufC8* salt = NULL;    
+    salt = object->GetOctetStringL();
+    CleanupStack::PushL(salt);
+    numberOfItemsInCStack++; // 2 set + salt
+
+    object = set->At( ++objectNum );
+    
+    // Here should be an iteration count
+    if ( object->Type() != KBerInteger)
+        {
+        CleanupStack::PopAndDestroy(numberOfItemsInCStack); // set + salt
+        numberOfItemsInCStack = 0;
+        return EFalse;
+        }
+
+    // By default, iteration count is set to 1
+    TInt iter = 1;
+    iter = object->GetIntegerL();
+
+    // Next we have encrypted data
+
+    object = set->At( ++objectNum );
+    
+    // If it's an octet string, read it.
+    if (object->Type() == KBerOctetString)
+        {
+        pkcs7EncryptedDataBuf = object->GetOctetStringL();
+        }
+
+    // If it's an Outlook's KBerImplicit, read it.
+    if (object->Type() == KBerImplicit)
+        {
+        pkcs7EncryptedDataBuf = object->GetContentStringLC();
+        numberOfItemsInCStack++;
+        }
+
+    TBool stop = EFalse;
+
+    if (object->Type() == KBerImplicitConstructed )
+        {
+        object = set->At( ++objectNum );
+        
+        for (TInt i = objectNum ; i < set->Count() && !stop ; i++)
+            {
+            if ( object->Type() == KBerOctetString )
+                {
+                // First octet string into buffer...
+                if ( i == objectNum )
+                    {
+                    pkcs7EncryptedDataBuf = object->GetOctetStringL();
+                    CleanupStack::PushL(pkcs7EncryptedDataBuf);
+                    numberOfItemsInCStack++;
+                    }
+                // ...and rest of octet strings. 
+                // New object's content is added to the
+                // pkcs7EncryptedDataBuf 
+                else
+                    {
+                    object = set->At( i );                    
+                    
+                    // Re-allocate buffer
+                    __ASSERT_DEBUG(pkcs7EncryptedDataBuf, User::Invariant());
+                    TInt currentSize = pkcs7EncryptedDataBuf->Size();
+                    CleanupStack::Pop(); // pkcs7EncryptedDataBuf
+                    numberOfItemsInCStack--;
+                  
+                    pkcs7EncryptedDataBuf = pkcs7EncryptedDataBuf->ReAllocL(currentSize + object->ContentLen());
+                    CleanupStack::PushL(pkcs7EncryptedDataBuf);
+                    numberOfItemsInCStack++;
+                
+                    // Get new OctetString
+                    HBufC8* octetString = NULL;
+                    octetString = object->GetOctetStringL();
+                    TPtr8 pOctetString = octetString->Des();
+
+                    // Copy it into buffer
+                    TPtr8 pPkcs7EncryptedData = pkcs7EncryptedDataBuf->Des();
+                    pPkcs7EncryptedData.Append( pOctetString );
+
+                    // Delete OctetString
+                     delete octetString;
+                     octetString = NULL;                    
+                    }
+                }
+            else if ( object->Type() == KBerEndOfContent )
+                {
+                stop = ETrue;
+                }
+            }
+        }
+    // OK, now we have buffer to be decrypted, used algorithm, salt and
+    // an iteration count. Next we decrypt buffer and append it to iBags.
+	
+	DecryptPkcs7EncryptedDataL( pkcs7EncryptedDataBuf,salt,iter,algorithm );
+
+    CleanupStack::PopAndDestroy(numberOfItemsInCStack);
+    numberOfItemsInCStack = 0;
+
+    return ETrue;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::DecryptPkcs7EncryptedDataL
+// Decrypts Pkcs7EncryptedData and adds it to iBags.
+// Parameters:     
+// Return Values:  TBool   If OK, returns ETrue and if not, EFalse
+// -----------------------------------------------------------------------------
+TBool CCrPKCS12::DecryptPkcs7EncryptedDataL( HBufC8* aPkcs7EncryptedData,
+                                             HBufC8* aSalt,
+                                             TInt aIter,
+                                             TInt aAlgorithm)
+    {
+    HBufC8* certificates = HBufC8::NewLC(aPkcs7EncryptedData->Length());    
+    TPtr8 ptrCertificates = certificates->Des();    
+    DecryptDataL(*aPkcs7EncryptedData, *aSalt, aIter, aAlgorithm, ptrCertificates);
+  
+    if (iBags)
+        {
+        iBags = iBags->ReAllocL(iBags->Size() + ptrCertificates.Size());
+        }
+    else
+        {
+        iBags = HBufC8::NewL(ptrCertificates.Size());
+        }
+
+    TPtr8 pIBag = iBags->Des();
+    pIBag.Append(ptrCertificates);
+         
+    CleanupStack::PopAndDestroy(certificates);    
+    return ETrue;
+    }
+// -----------------------------------------------------------------------------
+// CCrPKCS12::DecodeSafeBagsL
+// Decodes SafeBags and if needed, also decrypts them.
+// Parameters:
+// Return Values:  TBool       If OK, returns ETrue and if not, EFalse
+// -----------------------------------------------------------------------------
+TInt CCrPKCS12::DecodeSafeBagsL()
+    {
+    TInt numberOfItemsInCStack = 0;
+    TInt bagCount = 0;
+
+    CCrData* safeBags = CCrData::NewLC(EFalse);
+    ++numberOfItemsInCStack;
+    
+    TPtr8 piBags = iBags->Des();
+    safeBags->Write( piBags );
+
+    // Go back to start
+    TInt start = 0;
+    safeBags->Seek( ESeekStart,start );
+
+    CCrBerSet* set = NULL;
+    CCrBer* object = NULL;
+    
+    set = CCrBerSet::NewLC( 1 );
+    ++numberOfItemsInCStack;
+    
+    set->OpenL( safeBags,KOpenAllLevels );    
+
+    TInt count = set->Count();
+
+    // We have to check first only for a private key, because we need
+    // it's LocalKeyId, so we can identify a corresponding certificate.
+	TInt i(0); 
+    for (i = 0 ; i < count ; i++)
+        {
+        object = set->At( i );
+
+        if ( object->Type() == KBerOid )
+            {
+            
+            HBufC* oid = object->GetOidL();
+            CleanupStack::PushL(oid);
+
+            if ( *oid == Kpkcs8ShroudedKeyBag )
+                {
+                bagCount++;
+                DecryptShroudedKeybagL( * safeBags );                    
+                }
+                
+            if ( *oid == KkeyBag )
+                {
+                bagCount++;
+                
+                ExtractKeybagL( * safeBags );
+                } 
+            
+            CleanupStack::PopAndDestroy(oid);            
+            oid = NULL;
+            }
+        }
+
+    // And now for certificates.
+    for (i = 0 ; i < count ; i++)
+        {
+        object = set->At( i );
+
+        if ( object->Type() == KBerOid )
+            {            
+            HBufC* oid = object->GetOidL();
+            CleanupStack::PushL(oid);
+                        
+            if ( *oid == KcertBag )
+                {
+                bagCount++;
+                DecodeCertBagL( * safeBags );
+                }
+
+            CleanupStack::PopAndDestroy(oid);            
+            oid = NULL;
+            }
+        }
+
+    CleanupStack::PopAndDestroy(numberOfItemsInCStack, safeBags);
+
+    // Return amount fo safebags
+    return bagCount;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::ExtractKeybagL
+// Extract Keybag.
+// Parameters:     
+// Return Values:
+// -----------------------------------------------------------------------------
+void CCrPKCS12::ExtractKeybagL( CCrData& aSafeBag )
+    {
+    TInt numberOfItemsinCStack = 0;
+    CCrBerSet* set = NULL;
+
+    set = CCrBerSet::NewLC( 1 );
+    ++numberOfItemsinCStack;
+    
+    CCrBer* object = NULL;
+    TInt objectNum = KFirstObject;
+
+    set->OpenL( &aSafeBag,KOpenAllLevels );
+    
+    object = set->At( objectNum );
+
+   if ( object->Type() != KBerImplicitConstructed )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    HBufC8* PKCS8PrivateKey = object->GetOctetStringL();
+    iPKCS8PrivateKeyArray->AppendL( PKCS8PrivateKey );
+
+    if ( ++objectNum < set->Count() )
+        {
+        object = set->At( objectNum );        
+        iPrivateKeyIdArray.Append( GetLocalKeyId( aSafeBag ) );
+        }
+
+    CleanupStack::PopAndDestroy( numberOfItemsinCStack, set );
+    
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::DecryptShroudedKeybagL
+// DecryptShroudedKeybag.
+// Parameters:     
+// Return Values:
+// -----------------------------------------------------------------------------
+void CCrPKCS12::DecryptShroudedKeybagL( CCrData& aSafeBag )
+    {
+    TInt numberOfItemsinCStack = 0;
+    CCrBerSet* set = NULL;
+    TInt errData = KErrNone;
+
+    set = CCrBerSet::NewLC( 1 );
+    ++numberOfItemsinCStack;
+    
+    CCrBer* object = NULL;
+    TInt objectNum = KFirstObject;
+
+    set->OpenL( &aSafeBag,KOpenAllLevels );
+    
+    object = set->At( objectNum );
+
+    // This one needs first to be decrypted, first we open SafeBag and
+    // then we decrypt encyrpted PrivateKey
+
+    // Decryption Starts
+    // -----------------
+    if ( object->Type() != KBerImplicitConstructed )
+        {
+        User::Leave(KErrArgument);
+        }
+
+    object = set->At( ++objectNum );
+
+    if ( !object->IsSeqOrSet( object->Type() ) )
+        {
+        User::Leave(KErrArgument);
+        }
+
+    object = set->At( ++objectNum );
+
+    if ( !object->IsSeqOrSet( object->Type() ) )
+        {
+        User::Leave(KErrArgument);
+        }
+
+    object = set->At( ++objectNum );
+
+    if ( object->Type() != KBerOid)
+        {
+        User::Leave(KErrArgument);
+        }
+
+    // Algorithm
+    HBufC* oid = object->GetOidL();   
+    CleanupStack::PushL(oid);
+
+    TInt algorithm = GetAlgorithmL( oid );
+    
+    CleanupStack::PopAndDestroy(oid);
+    oid = NULL;
+
+    object = set->At( ++objectNum );
+
+    if (!object->IsSeqOrSet(object->Type()))
+        {
+        User::Leave(KErrArgument);
+        }
+
+    object = set->At( ++objectNum );
+
+    if ( object->Type() != KBerOctetString )
+        {
+        User::Leave(KErrArgument);
+        }
+
+    // Salt
+    HBufC8* salt = object->GetOctetStringL();
+    CleanupStack::PushL(salt);
+    ++numberOfItemsinCStack;
+    
+    object = set->At( ++objectNum );
+
+    if ( object->Type() != KBerInteger)
+        {
+        User::Leave(KErrArgument);
+        }
+
+    // Iterations
+    TInt iter = 1;
+    iter = object->GetIntegerL();
+
+    object = set->At( ++objectNum );
+
+    if ( object->Type() != KBerOctetString )
+        {
+        User::Leave(KErrArgument);
+        }
+
+    // EncryptedData
+    HBufC8* encryptedPrivateKeyInfo = object->GetOctetStringL();
+    CleanupStack::PushL(encryptedPrivateKeyInfo);
+    ++numberOfItemsinCStack;
+    
+    if ( errData < KErrNone )
+        {
+        User::Leave(KErrArgument);
+        }
+
+    // Decrypt
+    if ( !DecryptPrivateKeyL( encryptedPrivateKeyInfo,
+                                                 salt,
+                                                 iter,
+                                                 algorithm ) )
+        {
+        User::Leave(KErrArgument);
+        }
+
+    // Decryption Ends
+    // ---------------
+    
+    if ( ++objectNum < set->Count() )
+        {
+        object = set->At( objectNum );        
+        iPrivateKeyIdArray.Append(GetLocalKeyId( aSafeBag ));
+        }
+
+    CleanupStack::PopAndDestroy(numberOfItemsinCStack, set);
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::GetLocalKeyId
+// Gets pkcs12-SafeBag-attribute LocalKeyId
+// Parameters:     CCrData& aBagData       SafeBag
+// Return Values:  TBool
+// -----------------------------------------------------------------------------    
+HBufC8* CCrPKCS12::GetLocalKeyId( CCrData& aBagData )
+    {
+    CCrBerSet* set = NULL;
+    CCrBer* object;
+    TInt errData = KErrNone;
+
+    TRAP( errData,set = CCrBerSet::NewL( 1 ) );
+
+    if ( errData < KErrNone )
+        {
+        return NULL;
+        }
+
+    TInt objectNum = KFirstObject;
+
+    TRAP( errData,set->OpenL( &aBagData,KOpenAllLevels ) );
+
+    if ( errData < KErrNone )
+        {
+        delete set;
+        set = NULL;
+        return NULL;
+        }
+
+    TInt count = set->Count();
+
+    // If there are attributes,
+    if( count > 0 )
+        {
+        // continue,
+        object = set->At( KFirstObject );
+        }
+    else
+        {
+        // otherwise go away.
+        delete set;
+        set = NULL;
+        return NULL;
+        }
+
+    // Attributes begin
+    if ( !object->IsSeqOrSet( object->Type() ) )
+        {
+        delete set;
+        set = NULL;
+        return NULL;
+        }
+
+    // Some applications seem to put an empty set in the
+    // place of LocalKeyId. If so, give up.
+    if (object->ContentLen() == 0)
+        {
+        delete set;
+        set = NULL;
+        return NULL;
+        }
+
+    // If there are more ber-objects left,
+    if ( count > ++objectNum )
+        {
+        // get next,
+        object = set->At( objectNum );
+        }
+    else
+        {
+        // otherwise give up.
+        delete set;
+        set = NULL;
+        return NULL;
+        }
+
+    // First attribute
+    if ( !object->IsSeqOrSet( object->Type() ) )
+        {
+        delete set;
+        set = NULL;
+        return NULL;
+        }
+
+    // Remember, at what level we are
+    TUint level = object->Level();
+    TBool stop = EFalse;
+
+    object = set->At( ++objectNum );
+
+    for( TInt i = objectNum ; i < count && !stop; i++ )
+        {
+        object = set->At( i );
+
+        if ( object->Level() < level )
+            {
+            stop = ETrue;
+            }
+               
+        // What is it?
+        if ( object->Type() == KBerOid )
+            {
+            HBufC* oid = NULL;
+
+            TRAP( errData,oid = object->GetOidL() );
+
+            if ( errData < KErrNone )
+                {
+                delete set;
+                set = NULL;
+                return NULL;
+                }
+
+            if ( *oid == Kpkcs9LocalKeyId )
+                {
+				/// BEGIN OF WORKAROUND ///
+				/* There is a major error in this library which causes that in certain 
+				situations the localKeyId attribute is found for certificate even though
+				it is not specified in the file. This happens when for example private key buffer
+				is right after CA certificate buffer in bag data. After the CA certificate is parsed then
+				the module starts searching for localKeyId and it founds it from the private key buffer. 
+				This buffer contains localKeyId and thus CA certificate is wrongly identified to be 
+				user certificate. A proper solution would be somehow limit the searching to correct ASN.1 sets
+				but there's no time for that now. This is a ugly quick fix for this problem:
+				Zero the localKeyId oid so that it is used only once. */	
+								
+				CCrData* data = object->Data();
+				TInt start = object->ContentBegin();
+				TInt len = object->ContentLen();
+				data->Zero(start, len);
+				
+				// END OF WORKAROUND ///
+                i += 2;
+
+                if ( count > i )
+                    {
+                    object = set->At( i );
+                    HBufC8* buf = NULL;
+
+                    // Now we can read LocalKeyId
+                    TRAP( errData,buf = object->GetOctetStringL() );
+
+                    if ( errData < KErrNone )
+                        {
+                        delete set;
+                        set = NULL;
+                        return NULL;
+                    }
+
+                    stop = ETrue;
+                    delete set;
+                    set = NULL;
+                    delete oid;
+                    oid = NULL;
+                    return buf;
+                    }
+                }
+            delete oid;
+            oid = NULL;
+            }
+        }
+
+    delete set;
+    set = NULL;
+    return NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::DecodeCertBagL
+// DecodeCertBag.
+// Parameters:     
+// Return Values: TBool
+// -----------------------------------------------------------------------------    
+void CCrPKCS12::DecodeCertBagL( CCrData& aSafeBags )
+    {
+    TInt numberOfItemsinCStack = 0;
+    CCrBerSet* set = NULL;
+    
+    set = CCrBerSet::NewLC( 1 );
+    ++numberOfItemsinCStack;
+    
+
+    CCrBer* object;
+    TInt objectNum = KFirstObject;
+
+    set->OpenL( &aSafeBags,KOpenAllLevels );   
+
+    object = set->At( objectNum );
+
+    // CertificateBags are decrypted at this phase and they just need
+    // to be decoded from a certificate bag and added to certificate set.
+    // LocalKeyId is used to check if certificate is user's.
+
+    // Decoding starts
+    // -----------------
+    if ( object->Type() != KBerImplicitConstructed )
+        {
+        User::Leave(KErrArgument);
+        }
+
+    object = set->At( ++objectNum );
+
+    if ( !object->IsSeqOrSet( object->Type() ) )
+        {
+        User::Leave(KErrArgument);
+        }
+
+    object = set->At( ++objectNum );
+
+    if ( object->Type() != KBerOid )
+        {
+        User::Leave(KErrArgument);
+        }
+
+    // Algorithm
+    HBufC* oid = NULL;
+
+    oid = object->GetOidL();
+    CleanupStack::PushL(oid);
+        
+    if ( *oid != Kx509certificate )
+        {
+        User::Leave(KErrNotSupported);
+        }
+    
+    CleanupStack::PopAndDestroy(oid);
+    oid = NULL;
+
+    object = set->At( ++objectNum );
+
+    if ( object->Type() != KBerImplicitConstructed )
+        {
+        User::Leave(KErrArgument);
+        }
+
+    object = set->At( ++objectNum );
+
+    if ( object->Type() != KBerOctetString )
+        {
+        User::Leave(KErrArgument);
+        }
+
+    HBufC8* x509certificate = object->GetOctetStringL();   
+    CleanupStack::PushL(x509certificate);
+    ++numberOfItemsinCStack;
+
+    // For identifying certificate's type.
+    HBufC8* localKeyId = NULL;
+    
+    if ( ++objectNum < set->Count() )
+        {
+        object = set->At( objectNum );
+        localKeyId = GetLocalKeyId( aSafeBags );
+        }
+    TBool isCA = EFalse;
+    CX509Certificate* cert  =  CX509Certificate::NewLC( *x509certificate );
+   
+
+    // Check certificate version
+    if ( cert->Version() != KX509Version3 )
+          {
+          isCA = cert->IsSelfSignedL();
+          }
+      else
+          {
+          // X509 v3 certificate. Check basicConstrains
+          const CX509CertExtension* certExt = cert->Extension( KBasicConstraints );
+          if ( certExt )
+              {
+              CX509BasicConstraintsExt* basic = CX509BasicConstraintsExt::NewLC( certExt->Data() );
+              isCA = basic->IsCA();
+              CleanupStack::PopAndDestroy( basic ); //basic
+              }
+          else
+              {
+              isCA = cert->IsSelfSignedL();
+              }
+          }
+     
+     
+    CleanupStack::PopAndDestroy( cert );
+    
+    if( localKeyId == NULL || isCA )
+        {
+        if ( localKeyId )
+        	{
+            delete localKeyId;
+            localKeyId = NULL;
+        	}
+        // Add to CAcertificates;
+        PutCertsIntoSetL( iCACertificates, iCACertificateBuffer, x509certificate );
+        // Do not delete x509certificate in this case 
+        CleanupStack::Pop(x509certificate);
+        --numberOfItemsinCStack;
+        }    
+    else
+        {        
+        CleanupStack::PushL(localKeyId);
+        ++numberOfItemsinCStack;
+        for (TInt i = 0; i < iPrivateKeyIdArray.Count(); ++i)
+            {
+            if (*localKeyId == *(iPrivateKeyIdArray[i]))
+                {
+                PutCertsIntoSetL( iUserCertificates,iUserCertificateBuffer, x509certificate );
+                CleanupStack::PopAndDestroy(localKeyId);
+                --numberOfItemsinCStack;
+                // Do not delete x509certificate in this case 
+                CleanupStack::Pop(x509certificate);
+                --numberOfItemsinCStack;
+                break;
+                }                
+            }                       
+        }
+    /*else
+        {
+        delete x509certificate;
+        x509certificate = NULL; 
+        }
+*/
+    
+    CleanupStack::PopAndDestroy(numberOfItemsinCStack, set);
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::DecryptDataL
+// -----------------------------------------------------------------------------        
+void CCrPKCS12::DecryptDataL( const TDesC8& aEncryptedData,
+                              const TDesC8& aSalt,
+                              TInt aIter,
+                              TInt aAlgorithm,
+                              TDes8& aDecryptedData )
+    {
+    HBufC8* keyBuf = NULL; 
+    TBuf8<8>   iv;
+    TInt keySize = 0;
+    TInt numberOfItemsinCStack = 0;
+            
+    CCrCrypto* crypto = CCrCrypto::NewLC();
+    ++numberOfItemsinCStack;
+        
+    switch(aAlgorithm)
+        {
+        case ECrKpbeWithSHAAnd128BitRC2_CBC:
+            {
+            keySize = K128BitRC2KeySize;
+            break;
+            }
+        case ECrKpbeWithSHAAnd40BitRC2_CBC:
+            {                      
+            keySize = K40BitRC2KeySize;
+            break;
+            }
+        case ECrpbeWithSHAAnd3_KeyTripleDES_CBC:
+            {
+            // We need 3 keys for triple DES.
+            keySize = 3 * KDesKeySize; 
+            break;
+            }
+        case ECrpbeWithSHAAnd2_KeyTripleDES_CBC:
+            {
+            keySize = 2 * KDesKeySize;             
+            break;
+            }
+        default:
+            {
+            User::Leave(KErrNotSupported);
+            }
+        }
+    keyBuf = HBufC8::NewLC(keySize);
+    ++numberOfItemsinCStack;
+    TPtr8 keyPtr = keyBuf->Des();
+    // Get key.
+    crypto->DeriveKeyPKCS12L(*iPassWord,
+                             aSalt,
+                             aIter,
+                             ECrSHA1,
+                             KId1,
+                             keySize,
+                             keyPtr);
+    
+    // Get IV
+    crypto->DeriveKeyPKCS12L(*iPassWord,
+                             aSalt,
+                             aIter,
+                             ECrSHA1,
+                             KId2,
+                             iv.MaxSize(),
+                             iv);
+
+           
+    switch(aAlgorithm)
+        {
+        case ECrKpbeWithSHAAnd128BitRC2_CBC:            
+            {
+            crypto->InitCryptRC2L(*keyBuf, iv, EFalse, 8*K128BitRC2KeySize);    
+            break;
+            }
+        case ECrKpbeWithSHAAnd40BitRC2_CBC:
+            {            
+            crypto->InitCryptRC2L(*keyBuf, iv, EFalse, 40);    
+            break;
+            }
+        case ECrpbeWithSHAAnd3_KeyTripleDES_CBC:
+            {
+            crypto->InitCrypt3DESL(
+                keyPtr.Left(KDesKeySize), keyPtr.Mid(KDesKeySize, KDesKeySize), 
+                keyPtr.Right(KDesKeySize), iv, EFalse); 
+            break;
+            }
+        case ECrpbeWithSHAAnd2_KeyTripleDES_CBC:
+            {
+            crypto->InitCrypt3DESL(
+                keyPtr.Left(KDesKeySize), keyPtr.Right(KDesKeySize), 
+                keyPtr.Left(KDesKeySize), iv, EFalse); 
+            break;
+            }
+        default:
+            {
+            User::Leave(KErrNotSupported);
+            }
+        }
+    crypto->ProcessL(aEncryptedData, aDecryptedData);        
+    crypto->FinalCryptL(aDecryptedData);                       
+    CleanupStack::PopAndDestroy(numberOfItemsinCStack, crypto);
+    }
+    
+// -----------------------------------------------------------------------------
+// CCrPKCS12::DecryptPrivateKey
+// DecryptPrivateKey.
+// Parameters:     
+// Return Values:
+// -----------------------------------------------------------------------------
+
+TBool CCrPKCS12::DecryptPrivateKeyL( HBufC8* aEncryptedPrivateKey,
+                                    HBufC8* aSalt,
+                                    TInt aIter,
+                                    TInt aAlgorithm )
+    {    
+    TBool   returnValue = ETrue;    
+    HBufC8* privateKey = HBufC8::NewLC(aEncryptedPrivateKey->Length());    
+    TPtr8 privateKeyPtr = privateKey->Des();
+    TPtr8   paEncryptedPrivateKey = aEncryptedPrivateKey->Des();
+    TPtr8   paSalt = aSalt->Des();
+
+    DecryptDataL(*aEncryptedPrivateKey, *aSalt, aIter, aAlgorithm, privateKeyPtr);
+   
+    HBufC8* PKCS8PrivateKey = HBufC8::NewL(privateKey->Length());
+    PKCS8PrivateKey->Des().Copy(*privateKey);
+    iPKCS8PrivateKeyArray->AppendL(PKCS8PrivateKey);
+                    
+    CleanupStack::PopAndDestroy(privateKey);
+    return returnValue;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::VerifyMacFromEightBytePassword
+// This function generates double byte pasword from given eight byte
+// password and calls VerifyMac.
+// Parameters:     aPassWord   password given to open function
+// Return Values:  TBool       If OK, returns ETrue and if not, EFalse
+// -----------------------------------------------------------------------------
+TBool CCrPKCS12::VerifyMacFromEightBytePassword(const TDesC8& aPassWord)
+    {
+    TInt errData = KErrNone;
+
+    // Alloc Space for password in pkcs12-format. Needed space is
+    // 2 * aPassWord + 2
+    if (iPassWord == NULL)
+        {
+        TRAP( errData,iPassWord = HBufC8::NewL( (2 * aPassWord.Length()) + 2) );
+        
+        if ( errData < KErrNone )
+            {
+            return EFalse;
+            }
+        }
+
+    // Pointer to allocated pkcs12PassWord
+    TPtr8 aPkcs12PassWord = iPassWord->Des();
+
+    // Make sure password is empty.
+    aPkcs12PassWord = _L8("");
+
+    // Append 0x00 between characters
+    for( TInt i = 0 ; i < aPassWord.Length() ; i++ )
+        {
+        aPkcs12PassWord.Append(0x00);
+        aPkcs12PassWord.Append(aPassWord[i]);
+        }
+
+    // Append last 0x00 0x00
+    aPkcs12PassWord.Append(0x00);
+    aPkcs12PassWord.Append(0x00);
+    
+    TBool result = EFalse;
+    TRAP(errData, result = VerifyMacL(aPkcs12PassWord));
+    if ( errData < KErrNone )
+        {
+        return EFalse;
+        }
+    return result;
+    }
+// -----------------------------------------------------------------------------
+// CCrPKCS12::VerifyMacL
+// Verifies Mac. This function generates mac with password given to
+// open function above, salt and iteration count, It uses crypto-
+// library to do that. Generated mac is compared with iMac (mac within
+// pkcs12 file) and if they are the same, password was OK and if they
+// weren't the same, password was wrong, or file is corrupted.
+// Parameters:     aPassWord   password given to open function
+// Return Values:  TBool       If OK, returns ETrue and if not, EFalse
+// -----------------------------------------------------------------------------  
+TBool CCrPKCS12::VerifyMacL(const TDesC8& aPassWord)
+    { 
+    TPtr8 pContentInfo = iContentInfo->Des();
+    
+    // Key to be derivated
+    iDecryptionKey = HBufC8::NewL( iMac->Length() );
+    TPtr8 pDecryptionKey = iDecryptionKey->Des();
+
+    TInt numberOfItemsInCStack = 0;
+    // Mac to be calculated
+    HBufC8* mac = HBufC8::NewLC( iMac->Length() );
+    numberOfItemsInCStack++;        
+    TPtr8 pMac = mac->Des();
+
+    CCrCrypto* crypto = CCrCrypto::NewLC();
+    numberOfItemsInCStack++;
+
+    if ( iHMACalgorithm == ECrSHA1 )
+        {
+        crypto->DeriveKeyPKCS12L(aPassWord,
+                                 *iSalt,
+                                 iIter,
+                                 ECrSHA1,
+                                 KId3,
+                                 iMac->Length(),
+                                 pDecryptionKey);
+        
+        // Initialize HMAC SHA-1 algorithm
+        crypto->InitDigestHMACL( pDecryptionKey,ECrSHA1 );        
+        }
+    else
+        {
+        CleanupStack::PopAndDestroy(numberOfItemsInCStack);
+        return EFalse;
+        }
+
+    // Process data (filedata)
+    crypto->ProcessL( pContentInfo, pMac);
+    
+    // Final digest algorithm
+    crypto->FinalDigest( pMac );
+
+    if ( pMac == *iMac )
+        {
+        CleanupStack::PopAndDestroy(numberOfItemsInCStack); 
+        return ETrue;
+        }
+    else
+        {
+        CleanupStack::PopAndDestroy(numberOfItemsInCStack);
+        return EFalse;
+        }
+    }
+
+TBool CCrPKCS12::VerifyMacL(const TDesC16& aPassWord)
+    {
+    TUint8  halfCharacter;
+    TUint16 character;
+
+    // Alloc Space for password in pkcs12-format. Needed space is
+    // 2 * aPassWord + 2
+    if (iPassWord == NULL)
+        {
+        iPassWord = HBufC8::NewL( (2 * aPassWord.Length()) + 2);
+        }
+
+    // Pointer to allocated pkcs12PassWord
+    TPtr8 pPkcs12PassWord = iPassWord->Des();
+
+    // Make sure password is empty.
+    pPkcs12PassWord = _L8("");
+
+    // Divide characters into bytes and append them.
+    for (TInt i = 0; i < aPassWord.Length(); i++)
+        {
+        character = aPassWord[i];
+
+        halfCharacter = (TUint8) (character >> 8);
+        pPkcs12PassWord.Append(halfCharacter);
+
+        halfCharacter = (TUint8) (character & 0xFF);
+        pPkcs12PassWord.Append(halfCharacter);
+        }
+
+    // Append last 0x00 0x00
+    pPkcs12PassWord.Append(0x00);
+    pPkcs12PassWord.Append(0x00);
+
+    return VerifyMacL(pPkcs12PassWord);
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::JumpNextObjectAtSameLevel
+// Returns integer value of how many objects shoud be jumped to get
+// next object at same level. Works, when CCrBer-library works with
+// definite values correctly.
+// Parameters:     None.
+// Return Values:  TUint   Next object's index-number at same level
+// -----------------------------------------------------------------------------
+TUint CCrPKCS12::JumpNextObjectAtSameLevel()
+    {
+    TUint levelAt = iberObject->Level();
+    TUint jumps = 1;
+    
+    TUint index_to = iObjectNum + 1;
+
+    iberObject = iberSet->At( index_to );
+    
+    while( iberObject->Level() != levelAt )
+        {
+        jumps++;
+        index_to++;
+        iberObject = iberSet->At( index_to );
+        }   
+
+    return jumps;
+    }
+// -----------------------------------------------------------------------------
+// CCrPKCS12::GetAlgorithm
+// This function identifies algorithm and returns integer about what
+// algorithm was. Algorithm is identified via ObjectIdentifier.
+// For example, in case if aBuf = "1.2.840.113549.1.12.1.2",
+// (pbeWithSHAAnd40BitRC4) function returns 2.
+// Parameters:     aBuf    buffer containing ObjectIdentifier
+// Return Values:  TUint   Last number of an algorithm
+// -----------------------------------------------------------------------------
+TUint CCrPKCS12::GetAlgorithmL( HBufC* aBuf )
+    {
+    // What is the algorithm?
+    TUint algorithm = 0;
+
+    if ( *aBuf == KpbeWithSHAAnd128BitRC4 )
+        {
+        algorithm = ECrpbeWithSHAAnd128BitRC4;
+        }
+    else if ( *aBuf == KpbeWithSHAAnd40BitRC4 )
+        {
+        algorithm = ECrpbeWithSHAAnd40BitRC4;
+        }
+    else if ( *aBuf == KpbeWithSHAAnd3_KeyTripleDES_CBC )
+        {
+        algorithm = ECrpbeWithSHAAnd3_KeyTripleDES_CBC;
+        }
+    else if ( *aBuf == KpbeWithSHAAnd2_KeyTripleDES_CBC )
+        {
+        algorithm = ECrpbeWithSHAAnd2_KeyTripleDES_CBC;
+        }
+    else if ( *aBuf == KpbeWithSHAAnd128BitRC2_CBC )
+        {
+        algorithm = ECrKpbeWithSHAAnd128BitRC2_CBC;
+        }
+    else if ( *aBuf == KpbeWithSHAAnd40BitRC2_CBC )
+        {
+        algorithm = ECrKpbeWithSHAAnd40BitRC2_CBC;
+        }
+    else
+        {
+        User::Leave(KErrNotSupported);
+        }
+
+    return algorithm;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::PutCertsIntoSet
+// This function puts all certificates into set given at parameter.
+// DecodeCertsL calls this functiuon.
+// Parameters:     *set    Set, where certificates will be put into
+// Return Values:  TInt    Value of error
+// -----------------------------------------------------------------------------
+void CCrPKCS12::PutCertsIntoSetL( CX509CertificateSet* aSet,
+                                  CArrayPtrFlat<TDesC8>* aBufSet,
+                                  HBufC8* aX509certificate )
+    {
+    // Pointer to certificate given at third parameter
+    TPtr8 paX509certificate = aX509certificate->Des();
+
+    // Add certificate to CertificateSet given at first parameter
+    aSet->DecodeCertsL( paX509certificate );
+    
+    // Add certificate to CertificateSet given at second parameter 
+    aBufSet->AppendL(aX509certificate);        
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::GetPrivateKeys
+// -----------------------------------------------------------------------------
+const CArrayPtrFlat<HBufC8>& CCrPKCS12::PrivateKeys() const
+    {
+    return *iPKCS8PrivateKeyArray;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::GetUserCertificates
+// This function returns CX509CertificateSet, set of CX509Certificates,
+// that are defined in certman. These certificates are user certificates.
+// All certificates from X509Certificates are tested and if certificate
+// isn't CA Certificate and if KeyUsage don't mach to one given at
+// parameter, it is removed from set. After that, UserCertificates
+// (type CX509CertificateSet *) are returned to caller.
+// Parameters:     TKeyUsage aKeyUsage.
+// Return Values:  CX509CertificateSet*  Pointer to the CX509CertificateSet.
+// -----------------------------------------------------------------------------
+const CX509CertificateSet& CCrPKCS12::UserCertificates() const
+    {
+	return *iUserCertificates;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::GetUserCertificateBuffer
+// This function returns CX509CertificateSet, set of CX509Certificates,
+// that are defined in certman. These certificates are user certificates.
+// All certificates from X509Certificates are tested and if certificate
+// isn't CA Certificate and if KeyUsage don't mach to one given at
+// parameter, it is removed from set. After that, UserCertificateBuffer
+// (type CArrayPtrFlat<TDes>* ) are returned to caller.
+// Parameters:     TKeyUsage aKeyUsage.
+// Return Values:  CArrayPtrFlat<TDesC8>*  Pointer to a buffer.
+// -----------------------------------------------------------------------------
+const CArrayPtrFlat<TDesC8>& CCrPKCS12::UserCertificateBuffer() const
+                                        
+    {
+    return *iUserCertificateBuffer;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::GetCACertificates
+// This function returns CX509CertificateSet, set of CX509Certificates,
+// that are defined in certman. These certificates are CA certificates.
+// All certificates from X509Certificates are tested and if certificate
+// isn't CA Certificate, it is removed from set. After that,
+// CACertificates (type CX509CertificateSet *) are returned to caller.
+// Parameters:     none.
+// Return Values:  CX509CertificateSet*  Pointer to the CX509CertificateSet.
+// -----------------------------------------------------------------------------
+const CX509CertificateSet& CCrPKCS12::CACertificates() const
+    {
+    return *iCACertificates;
+    }
+// -----------------------------------------------------------------------------
+// CCrPKCS12::GetCACertificateBuffer
+// This function returns CX509CertificateSet, set of CX509Certificates,
+// that are defined in certman. These certificates are CA certificates.
+// All certificates from X509Certificates are tested and if certificate
+// isn't CA Certificate, it is removed from set. After that,
+// CACertificates (type CArrayPtrFlat<TDesC8>*) are returned to caller.
+// Parameters:     none.
+// Return Values:  CArrayPtrFlat<TDesC8>*  Pointer to the CX509CertificateSet.
+// -----------------------------------------------------------------------------
+const CArrayPtrFlat<TDesC8>& CCrPKCS12::CACertificateBuffer() const
+    {
+    return *iCACertificateBuffer;
+    } 
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::GetIter
+// This function returns the number of iterations
+// Parameters: none 
+// Returns:    TUint    Number of iterations.
+// -----------------------------------------------------------------------------
+
+TUint CCrPKCS12::Iter()
+	{
+	return iIter;
+	}
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::GetMac
+// This function returns the mac
+// Parameters: none 
+// Returns:    HBufC8*     Pointer to mac.
+// -----------------------------------------------------------------------------
+HBufC8* CCrPKCS12::Mac()
+	{
+	return iMac;
+	}
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::GetSalt
+// This function returns the salt
+// Parameters: none 
+// Returns:    HBufC8*     Pointer to salt.
+// -----------------------------------------------------------------------------
+HBufC8* CCrPKCS12::Salt()
+    {
+	return iSalt;
+    }
+
+// -----------------------------------------------------------------------------
+// CCrPKCS12::GetSafeBagsCount
+// This function returns number of SafeBags
+// Parameters: none
+// Returns:    TInt      Number of SafeBags
+// -----------------------------------------------------------------------------
+TUint CCrPKCS12::SafeBagsCount()
+    {
+	return iSafeBagsCount;
+    }
+// EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrPkcs12/Src/cx509certificateset.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,105 @@
+/*
+* Copyright (c) 2000, 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This file contains the implementation of 
+*                CX509CertificateSet class. 
+*
+*/
+
+
+
+//  INCLUDE FILES
+
+#include "CX509CertificateSet.h"
+
+
+
+// -----------------------------------------------------------------------------
+// CX509CertificateSet
+// Constructor
+// -----------------------------------------------------------------------------
+CX509CertificateSet::CX509CertificateSet( TInt aGranularity )
+                     :CArrayPtrFlat<CX509Certificate>( aGranularity )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CX509CertificateSet::ConstructL
+// -----------------------------------------------------------------------------
+
+void CX509CertificateSet::ConstructL()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CX509CertificateSet::NewLC
+// -----------------------------------------------------------------------------
+CX509CertificateSet* CX509CertificateSet::NewLC( TInt aGranularity )
+    {
+    CX509CertificateSet* self = new (ELeave) CX509CertificateSet(aGranularity);
+    CleanupStack::PushL(self);
+
+    self->ConstructL();
+
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CX509CertificateSet
+// Destructor
+// -----------------------------------------------------------------------------
+CX509CertificateSet::~CX509CertificateSet()
+	{
+    ResetAndDestroy();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CX509CertificateSet::NewL
+// -----------------------------------------------------------------------------
+CX509CertificateSet* CX509CertificateSet::NewL( TInt aGranularity )
+    {
+    CX509CertificateSet* self = NewLC( aGranularity );
+    CleanupStack::Pop();
+
+    return self; 
+    }
+
+// -----------------------------------------------------------------------------
+// CX509CertificateSet::DecodeCertsL
+// This function reads binarydata given as parameter and decodes
+// all certificates from it and puts them into CX509CertificateSet,
+// what is obviously a set of X509Certificates.
+// Parameters: const TDesC8& aBinaryData   Binarydata containing 
+//                                         CX509Certificates.
+// Returns:    Amount of certificates decoded.                                 
+// -----------------------------------------------------------------------------
+TUint CX509CertificateSet::DecodeCertsL(const TDesC8& aBinaryData)
+	{
+	TInt pos = NULL;//start at the start
+    TUint amount = NULL;
+
+    while ( pos < aBinaryData.Length() )
+		{
+        CX509Certificate *aTempCertificate = CX509Certificate::NewLC( aBinaryData, pos );
+ 
+        AppendL( aTempCertificate );
+		CleanupStack::Pop();
+        amount++;
+        }
+
+    return amount; // amount of certificates in CertificateSet
+	}
+
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrPkcs12/Src/pkcs12.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,412 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the PKCS#12 parser API
+*
+*/
+
+
+// INCLUDE FILES
+#include <securityerr.h>
+#include    "pkcs12.h"
+#include    "crpkcs12.h"
+//#include    <?include_file>
+
+// EXTERNAL DATA STRUCTURES
+//extern  ?external_data;
+
+// EXTERNAL FUNCTION PROTOTYPES  
+//extern ?external_function( ?arg_type,?arg_type );
+
+// CONSTANTS
+
+// ASN.1 tag values
+const TInt KASN1SequenceTagValue = 0x30;
+const TInt KASN1ImplicitConstructedTagValue = 0xA0;   // Implicit constructed tag
+const TInt KASN1OctetStringTagValue   = 0x04;     // Octet string tag
+const TInt KASN1BerConstructedBit = 0x20;
+
+_LIT8(KPKCS12Version3, "\x02\x01\x03");
+_LIT8(KPKCS7DataOID, "\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x07\x01");
+_LIT8(KPKC7EncryptedDataOID, "\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x07\x06");
+_LIT8(KSequenceTagInOctet,"\x04\x01\x30\x04\x01\x80");
+_LIT8(KMozillaPKCS7EncryptedDataOID, 
+    "\x04\x01\x06\x04\x01\x09\x04\x09\x2a\x86\x48\x86\xf7\x0d\x01\x07\x06");
+_LIT8(KMozillaPKCS7DataOID, 
+    "\x04\x01\x06\x04\x01\x09\x04\x09\x2a\x86\x48\x86\xf7\x0d\x01\x07\x01");
+
+// MACROS
+//#define ?macro ?macro_def
+
+// LOCAL CONSTANTS AND MACROS
+//const ?type ?constant_var = ?constant;
+//#define ?macro_name ?macro_def
+
+// MODULE DATA STRUCTURES
+//enum ?declaration
+//typedef ?declaration
+
+// LOCAL FUNCTION PROTOTYPES
+//?type ?function_name( ?arg_type, ?arg_type );
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// ---------------------------------------------------------
+// PKCS12Factory::CreateL
+// ---------------------------------------------------------
+//
+EXPORT_C MPKCS12* PKCS12Factory::CreateL()
+    {
+    return CPKCS12::NewL();
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12::CPKCS12
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CPKCS12::CPKCS12()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CPKCS12::ConstructL()
+    {        
+    
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CPKCS12* CPKCS12::NewL()
+    {
+    CPKCS12* self = new( ELeave ) CPKCS12();
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+void CPKCS12::Release()
+    {
+    delete this;
+    }
+
+// ---------------------------------------------------------
+// CPKCS12::IsPKCS12Data
+// ---------------------------------------------------------
+//    
+TBool CPKCS12::IsPKCS12Data(const TDesC8& aBinaryData)
+     {     
+    // We don't decode the data because we may only have the first few bytes -
+	// instead we check the ASN1 by hand.
+	ASSERT(aBinaryData.Length() >= KPKCS12DataMinLength);
+	TInt pos = 0;
+	
+	if (!IsASN1Tag(KASN1SequenceTagValue,aBinaryData, pos))
+	    {
+	    return EFalse;
+	    }
+	if (!IsExpectedData(aBinaryData, pos, KPKCS12Version3))
+	    {
+	    return EFalse;
+	    }
+    if (!IsASN1Tag(KASN1SequenceTagValue, aBinaryData, pos))
+	    {
+	    return EFalse;
+	    } 
+	if (!IsExpectedData(aBinaryData, pos, KPKCS7DataOID))
+	    {
+	    return EFalse;
+	    } 
+    if (!IsASN1Tag(KASN1ImplicitConstructedTagValue, aBinaryData, pos))
+	    {
+	    return EFalse;
+	    } 
+	// OpenSSL, IE and Opera type of PKCS#12 file    
+    if (IsASN1Tag(KASN1OctetStringTagValue, aBinaryData, pos))
+        {
+        if (!IsASN1Tag(KASN1SequenceTagValue, aBinaryData, pos))
+            {
+            return EFalse;
+            }
+        if (!IsASN1Tag(KASN1SequenceTagValue, aBinaryData, pos))
+            {
+            return EFalse;
+            }    
+    	if  (IsExpectedData(aBinaryData, pos, KPKC7EncryptedDataOID) || 
+    	     IsExpectedData(aBinaryData, pos, KPKCS7DataOID))    		
+    	    {    	    
+    	    return ETrue;
+    	    }
+    	else
+    	    {
+    	    return EFalse;
+    	    }
+        }
+    // Netscape and Mozilla type of PKCS#12 file    
+	else if (IsASN1Tag(KASN1OctetStringTagValue + KASN1BerConstructedBit, aBinaryData, pos))
+	    {
+	    if (IsExpectedData(aBinaryData, pos, KSequenceTagInOctet))
+            {
+            if (!IsExpectedData(aBinaryData, pos, KSequenceTagInOctet))
+                {
+                return EFalse;
+                }    
+        	if  (IsExpectedData(aBinaryData, pos, KMozillaPKCS7DataOID) ||
+        		IsExpectedData(aBinaryData, pos, KMozillaPKCS7EncryptedDataOID))
+        	    {    	    
+        	    return ETrue;
+        	    }
+            }
+        // Firefox version 1.5 type of PKCS#12 data    
+        else if (IsASN1Tag(KASN1OctetStringTagValue, aBinaryData, pos))
+            {
+            if (!IsASN1Tag(KASN1SequenceTagValue, aBinaryData, pos))
+                {
+                return EFalse;
+                }
+            if (!IsASN1Tag(KASN1SequenceTagValue, aBinaryData, pos))
+                {
+                return EFalse;
+                }    
+    	    if (IsExpectedData(aBinaryData, pos, KPKC7EncryptedDataOID) || 
+    	     IsExpectedData(aBinaryData, pos, KPKCS7DataOID))    		
+    	        {    	    
+    	        return ETrue;
+    	        }
+    	    else
+    	        {
+    	        return EFalse;
+    	        }
+            }
+        else
+            {
+            return EFalse;
+            }            
+	    }
+    else
+        {            
+        return EFalse;
+        }
+    return EFalse;    
+    }
+    
+// ---------------------------------------------------------
+// CPKCS12Recognizer::IsASN1Tag
+// ---------------------------------------------------------
+//  
+TBool CPKCS12::IsASN1Tag(
+    TInt aTag, 
+    const TDesC8& aBinaryData, 
+    TInt& aPos)
+	{	
+	// Check we have enough data
+	if ((aPos + 2) >= aBinaryData.Length())
+		{
+		return EFalse;
+		}
+	// Check the outermost sequence is valid
+	if (aBinaryData[aPos] != aTag)
+		{
+		return EFalse;
+		}
+	// Skip sequence length
+	aPos++;
+	TInt length0 = aBinaryData[aPos++];
+	if (length0 & 0x80)
+		{
+		aPos += length0 & 0x7f;
+		}
+	return ETrue;
+	}
+
+// ---------------------------------------------------------
+// CPKCS12Recognizer::IsExpectedData
+// ---------------------------------------------------------
+//  
+TBool CPKCS12::IsExpectedData(
+    const TDesC8& aBinaryData, 
+    TInt& aPos, 
+    const TDesC8& aExpectedData)
+	{	
+	TInt length = aExpectedData.Length();
+	// Check we have enough data
+	if (aPos + length >= aBinaryData.Length())
+		{
+		return EFalse;
+		}
+	// Check data matches	
+	if (aBinaryData.Mid(aPos, length) != aExpectedData)
+		{
+		return EFalse;
+		}
+	aPos += length;
+	return ETrue;
+	}    
+
+// -----------------------------------------------------------------------------
+// CPKCS12::ParseL
+// 
+// -----------------------------------------------------------------------------
+//
+void CPKCS12::ParseL(const TDesC8& aPKCS12, const TDesC16& aPassword)
+    {
+    Reset();
+    iCrPkcs12 = CCrPKCS12::NewL();
+    iCrData = CCrData::NewL(EFalse);
+    User::LeaveIfError(iCrData->Write(aPKCS12));
+    TInt start = 0;
+    iCrData->Seek( ESeekStart, start );
+    HandleErrorL( iCrPkcs12->OpenL( *iCrData, aPassword ));
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12::HandleErrorL
+// 
+// -----------------------------------------------------------------------------
+//
+void CPKCS12::HandleErrorL( TUint16 aError ) const
+    {
+
+    switch ( aError & 0x00ff )
+        {
+        case KCrOK:
+            return;
+        case KCrNotValidPkcs12Object:
+            User::Leave(KErrArgument);
+        case KCrBerLibraryError:
+            User::Leave(KErrGeneral);
+        case KCrNotSupportedHMACalgorithm:
+            User::Leave(KErrNotSupported);
+        case KCrCancelled:
+            User::Leave(KErrCancel);
+        case KCrGeneralError:
+            User::Leave(KErrGeneral);
+        case KCrWrongPassWordOrCorruptedFile:
+            User::Leave(KErrBadPassphrase);
+        case KCrNotPasswordBasedEncryption:
+            User::Leave(KErrNotSupported);
+        case KCrNoMemory:
+            User::Leave(KErrNoMemory);
+        default:
+            User::Leave(KErrGeneral);
+        }
+    }
+    
+// Destructor
+CPKCS12::~CPKCS12()
+    {
+    Reset();
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12::Reset
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+void CPKCS12::Reset()
+    {
+    if (iCrData)
+        {        
+        iCrData->Close();
+        delete iCrData;
+        iCrData = NULL;
+        }    
+    delete iCrPkcs12;
+    iCrPkcs12 = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12::CACertificates
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+const CArrayPtr<CX509Certificate>& CPKCS12::CACertificates() const
+    {
+    return iCrPkcs12->CACertificates();
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12::UserCertificates
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+const CArrayPtr<CX509Certificate>& CPKCS12::UserCertificates() const
+    {    
+    return iCrPkcs12->UserCertificates();
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12::PrivateKeys
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+const CArrayPtr<HBufC8>& CPKCS12::PrivateKeys() const
+    {    
+    return iCrPkcs12->PrivateKeys();
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12::SafeBagsCount
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+TUint CPKCS12::SafeBagsCount() const
+    {
+    return iCrPkcs12->SafeBagsCount();
+    }
+
+// -----------------------------------------------------------------------------
+// CPKCS12::IterCount
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//     
+TUint CPKCS12::IterCount() const
+    {
+    return iCrPkcs12->Iter();
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+                                                                                
+// ---------------------------------------------------------
+// E32Dll
+// DLL entry point
+// ---------------------------------------------------------
+//
+#ifndef EKA2
+GLDEF_C TInt E32Dll(TDllReason /*aReason*/)
+    {
+    return KErrNone;
+    }
+#endif
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrPkcs12/bwinscw/CRPKCS12U.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?CreateL@PKCS12Factory@@SAPAVMPKCS12@@XZ @ 1 NONAME ; class MPKCS12 * PKCS12Factory::CreateL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrPkcs12/eabi/crpkcs12U.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	_ZN13PKCS12Factory7CreateLEv @ 1 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/CrPkcs12/group/crpkcs12.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This is project specification file for the CrPkcs12.				 
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          crpkcs12.dll
+TARGETTYPE      DLL
+UID	        0x1000008d 0x10207456
+
+SOURCEPATH      ../Src
+
+SOURCE          pkcs12.cpp
+SOURCE          crpkcs12.cpp
+SOURCE          cx509certificateset.cpp
+SOURCE          crcrypto.cpp
+SOURCE          cralginfo.cpp
+
+USERINCLUDE     ../Inc
+MW_LAYER_SYSTEMINCLUDE
+SYSTEMINCLUDE	../../Inc
+SYSTEMINCLUDE	../../CrBer/Inc
+
+LIBRARY     euser.lib crber.lib x509.lib efsrv.lib
+LIBRARY     cryptography.lib hash.lib
+LIBRARY	    CTFramework.lib	
+
+CAPABILITY  CAP_GENERAL_DLL
+VENDORID    VID_DEFAULT
+
+#if defined(ARMCC)
+deffile ../eabi/ 
+#else
+deffile ../bwinscw/ 
+#endif
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/Inc/crdefs.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,267 @@
+/*
+* Copyright (c) 2000 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This file contains common defines for all Cradle projects.
+*
+*/
+
+
+
+#ifndef CR_DEFS
+#define CR_DEFS
+
+
+//  INCLUDES
+
+#include <e32std.h>
+
+//  CONSTANTS
+
+typedef TUint8  TCrKeyType;
+typedef TUint16 TCrStatus;
+typedef TUint8	TCrApduStatus;
+typedef TUint8  TCrCryptoStatus;
+typedef TUint8  TCrWimStatus;
+typedef TInt    TCrLeaveCode;
+
+// Buffer size
+const TInt KBufSize     = 1024;
+
+// LDAP Server Address size
+const TInt KLDAPBuffer = 128;
+
+// Message digest size
+const TInt KDigestSize  = 20;
+
+// RSA signature length
+const TInt KRSASignatureSize  = 1024;
+
+// Key length
+const TInt KDESKeyLength    = 8;
+
+// Key types.
+const TCrKeyType KCrDigitalSignature = 0x80;
+const TCrKeyType KCrNonRepudiation   = 0x40;
+
+// Upmost byte is used to define context of error.
+const TCrStatus KCrWim          = 0x0100;
+const TCrStatus KCrWimLib       = 0x0200;
+const TCrStatus KCrWimApdu      = 0x0300;
+const TCrStatus KCrKey          = 0x0400;
+const TCrStatus KCrCrypto       = 0x0500;
+const TCrStatus KCrPkcs7        = 0x0600;
+const TCrStatus KCrPkcs12       = 0x0700;
+const TCrStatus KCrCertEng      = 0x0800;
+const TCrStatus KCrSegMsg       = 0x0900;
+
+// Lowest byte defines actual error.
+
+// Common errors.
+const TCrStatus KCrOK           = 0x0000;
+const TCrStatus KCrNotSupported = 0x00a0;
+const TCrStatus KCrNoMemory     = 0x00b0;
+
+// WIM errors are listed in "wim_const.h"
+
+// CrWim errors
+const TCrWimStatus KCrInvalidContext    = 0x01;
+const TCrWimStatus KCrInvalidParameters = 0x02;
+
+// CrKeyApi errors
+
+
+// CrCrypto errors
+const TCrCryptoStatus KCrNoError              = 0x00;
+const TCrCryptoStatus KCrNotSupportedAlg      = 0x01;
+const TCrCryptoStatus KCrUnknownLibrary       = 0x02;
+const TCrCryptoStatus KCrErrorGeneral         = 0x03;
+const TCrCryptoStatus KCrDataValid            = 0x04;
+const TCrCryptoStatus KCrDataInvalid          = 0x05; 
+const TCrCryptoStatus KCrUnknownMode          = 0x06;
+const TCrCryptoStatus KCrUndefinedLibrary     = 0x07; 
+const TCrCryptoStatus KCrWrongAlgType         = 0x08;
+const TCrCryptoStatus KCrNotInitialized       = 0x09;           
+
+
+// CrWimApdu errors
+
+//These errors are defined in WIM library desing spec.
+const TCrApduStatus KCrApduOk                 =	0x00; //APDU_OK
+const TCrApduStatus KCrApduTransmiossionError =	0x01; //APDU_TRANSMISSION_ERROR
+const TCrApduStatus KCrApduCardMute           = 0x02; //APDU_CARD_MUTE		
+const TCrApduStatus KCrApduCardDisconnected   = 0x03; //APDU_CARD_DISCONNECTED
+const TCrApduStatus KCrApduNoCause            =	0x04; //APDU_NO_CAUSE	
+const TCrApduStatus KCrApduReaderNotValid     =	0x05; //APDU_READER_NOT_VALID	
+const TCrApduStatus KCrApduFormatError        =	0x06; //APDU_FORMAT_ERROR	
+const TCrApduStatus KCrApduTypeNotValid       =	0x07; //APDU_TYPE_NOT_VALID	
+const TCrApduStatus KCrApduReaderRemoved      =	0x08; //APDU_CARD_READER_REMOVED
+const TCrApduStatus KCrApduCardRemoved        =	0x09; //APDU_CARD_REMOVED
+const TCrApduStatus KCrApduCardReaderBusy     =	0x0a; //APDU_CARD_READER_BUSY	
+const TCrApduStatus KCrApduCardPoweredOff     =	0x0b; //APDU_CARD_POWERED_OFF
+//CrWimApdu own errors, used only in RequestList
+const TCrApduStatus KCrApduNoMemory           =	0xa0;
+const TCrApduStatus KCrApduScardDatabaseError = 0xa1;
+
+//const TCrStatus KCrNotSupported = 0x00800000;
+
+// Pkcs7 errors
+const TCrStatus KCrNotValidObject       = 0x0001;
+const TCrStatus KCrUnsupportedFormat    = 0x0002;
+const TCrStatus KCrUnsupportedVersion   = 0x0003;
+const TCrStatus KCrDigestInvalid        = 0x0004;
+const TCrStatus KCrEncContentInvalid    = 0x0005;
+const TCrStatus KCrContentInvalid		= 0x0006;
+const TCrStatus KCrSigningFailed        = 0x0007;
+const TCrStatus KCrInvalidAlgorithm     = 0x0008;
+const TCrStatus KCrInvalidCertificate   = 0x0009;
+
+// Pkcs12 errors
+const TCrStatus KCrValidFile = 0x0000;
+const TCrStatus KCrNotValidFile = 0x0001;
+const TCrStatus KCrBerLibraryError = 0x002;
+const TCrStatus KCrNotPasswordBasedEncryption = 0x003;
+const TCrStatus KCrNotSupportedHMACalgorithm = 0x004;
+const TCrStatus KCrWrongPassWordOrCorruptedFile = 0x005;
+const TCrStatus KCrNotValidPkcs12Object = 0x006;
+const TCrStatus KCrCancelled = 0x007;
+const TCrStatus KCrGeneralError = 0x008;
+
+//CrCert own Leave codes
+const TCrLeaveCode KCrLocationNotCertMan  = 0x0001;
+const TCrLeaveCode KCrLocationInvalid     = 0x0002;
+const TCrLeaveCode KCrCertFormatInvalid   = 0x0003;
+const TCrLeaveCode KCrCertNotDeletable    = 0x0004;
+
+// certificate engine errors
+const TCrStatus KCrCertificateCorrupted             = 0x0001;
+const TCrStatus KCrCertificateSaveError             = 0x0003;
+const TCrStatus KCrCertificateLoadError             = 0x0004;
+const TCrStatus KCrLDAPCertificateServerFoundError  = 0x0005;
+const TCrStatus KCrLDAPLoginFailed                  = 0x0006;
+const TCrStatus KCrConnectionFailed                 = 0x0007;
+const TCrStatus KCrLDAPserverIsDownOrNotFound       = 0x0008;
+const TCrStatus KCrInvalidUsernameOrPassword        = 0x0009;
+
+// certificate engine and secure email errors
+const TCrStatus KCrNotEnougtMemory                  = 0x0002;
+
+// secure email errors
+const TCrStatus KCrCanNotOpenMessage                = 0x0001;
+const TCrStatus KCrDeCryptionFailed                 = 0x0003;
+
+// secure email warning code
+//const TCrStatus KCrSignatureIsNotValid              = 0x0001;
+//const TCrStatus KCrSignatureIsExpired               = 0x0003;
+//const TCrStatus KCrSignatureIsNotTrusted            = 0x0004;
+//const TCrStatus KCrSignatureIsInvalid               = 0x0005;
+
+
+// certificate engine's return values
+const TInt KCrCancel       = 0x0001;
+const TInt KCrZero         = 0x0001;
+const TInt KCrTooLong      = 0x0002;
+const TInt KCrSearch       = 0x0003;
+const TInt KCrSend         = 0x0004;
+
+//  MACROS
+//  DATA TYPES
+
+enum TCrEncodeMode
+    {
+    ECrSendMode,
+    ECrDraftMode
+    };
+
+enum TCrDecodeMode
+    {
+    ECrSendingMode,
+    ECrReceivingMode
+    };
+
+// Certificate types
+
+enum TCrCertValidationType
+	{
+    ECrValid,
+    ECrInvalid,
+    ECrRevoked,
+    ECrExpired,
+    ECrNotTrusted,
+	ECrSelfSigned,
+    ECrNotFound,
+	ECrRemoveUser,
+    ECrSignatureInvalid,
+	ECrUnknown,
+    ECrAddressConflict,
+    ECrMultiple,
+    ECrSave,
+	ECrNotSupported,
+    ECrAdded
+	};
+
+//Data types CrCert
+enum TCrCertLocation
+    {
+    ECrCertLocationCertMan,
+    ECrCertLocationPhoneMemory,
+    ECrCertLocationPhoneMemoryURL,
+    ECrCertLocationWIMCard,
+    ECrCertLocationWIMURL
+    };
+
+enum TCrCertType
+    {
+    ECrCertTypeCA,
+    ECrCertTypePersonal
+    };
+
+enum TCrCertFormat
+    {
+    ECrWTLSCertificate,
+    ECrX509Certificate,
+    ECrX968Certificate,
+    ECrCertificateURL
+    };
+
+enum TCrEntryType
+    {
+    ECrEntryTypeAll,
+    ECrEntryTypeCA,
+    ECrEntryTypePersonal
+    };
+
+enum TCrKeyLocation
+    {
+    ECrKeyLocationWIMCard,
+    ECrKeyLocationPhoneMemory,
+    ECrKeyLocationNoKey
+    };
+
+enum TCrCertStoringStatus
+    {
+    ECrCertNotStored
+    };
+
+enum TCrBer
+	{
+	ECrNoBer,
+	ECrSetBer
+	};
+
+//  EXTERNAL DATA STRUCTURES
+//  FUNCTION PROTOTYPES
+//  FORWARD DECLARATIONS
+//  CLASS DEFINITIONS
+
+#endif CR_DEFS
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/PKCS12Recognizer/data/101F8714.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,44 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+//
+
+#include <ecom/registryinfo.rh>
+
+RESOURCE REGISTRY_INFO r_registry
+	{
+	dll_uid = 0x101F8714; //should match name of this file
+	interfaces =
+		{
+		INTERFACE_INFO
+			{
+			interface_uid = 0x101F7D87;
+			implementations =
+			 {
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x101F8803;
+					version_no = 1;
+					display_name = "PKCS12Recognizer";
+					default_data = "";        
+					opaque_data = "";
+					}
+				};
+			}
+		};
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/PKCS12Recognizer/group/PKCS12Recognizer.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,48 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*     This is project specification file for the PKCS12Recognizer
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+target          PKCS12Recognizer.dll
+targettype      plugin
+uid		        0x10009d8d 0x101F8714
+
+START RESOURCE  ../data/101F8714.rss
+TARGET PKCS12Recognizer.rsc
+END
+
+CAPABILITY CAP_RECOGNISER
+VENDORID    VID_DEFAULT
+
+SOURCEPATH     ../src
+USERINCLUDE    ../inc
+MW_LAYER_SYSTEMINCLUDE
+SYSTEMINCLUDE  ../../CrPkcs12/Inc
+
+SOURCE         PKCS12Recognizer.cpp
+
+LIBRARY euser.lib
+LIBRARY apmime.lib
+//LIBRARY x509.lib
+//LIBRARY CTSecDlgs.lib
+LIBRARY crpkcs12.lib
+//LIBRARY CTFramework.lib
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/PKCS12Recognizer/inc/PKCS12Recognizer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Header of recognizer capable of recognizing mime type
+*                application/x-pkcs12
+*
+*/
+
+
+
+#ifndef PKCS12RECOGNIZER_H
+#define PKCS12RECOGNIZER_H
+
+//  INCLUDES
+#include <apmrec.h>
+
+// FORWARD DECLARATION
+class MPKCS12;
+
+// CLASS DECLARATION
+
+/**
+*  CPKCS12Recognizer class.
+*  Recognizes mime-types
+*  application/x-pkcs12
+*/
+class CPKCS12Recognizer : public CApaDataRecognizerType
+    {
+    public: 
+        CPKCS12Recognizer();
+        ~CPKCS12Recognizer();
+    public: // from CApaDataRecognizerType        
+        TUint PreferredBufSize();
+        TDataType SupportedDataTypeL(TInt aIndex) const;
+        
+        //for ECOM
+        static CApaDataRecognizerType* CreateRecognizerL();
+    
+    private: // from CApaDataRecognizerType
+        void DoRecognizeL(const TDesC& aName, const TDesC8& aBuffer);
+        
+    private:
+        MPKCS12* iPKCS12;   
+    };
+
+#endif // PKCS12RECOGNIZER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/PKCS12Recognizer/src/PKCS12Recognizer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,133 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Recogniser of application/x-pkcs12 mime type
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "PKCS12Recognizer.h"
+#include <apmrec.h>
+#include <apmstd.h>
+#include <e32svr.h>
+#include <ecom/implementationproxy.h>
+#include <mpkcs12.h>
+
+_LIT8(KPKCS12MimeType, "application/x-pkcs12");
+const TInt KMimeTypesSupported(1);
+const TUid KUidMimePKCS12Recognizer = { 0x101F8714 };
+
+// ---------------------------------------------------------
+// CPKCS12Recognizer::CPKCS12Recognizer
+// ---------------------------------------------------------
+//
+CPKCS12Recognizer::CPKCS12Recognizer()
+    :CApaDataRecognizerType(
+    KUidMimePKCS12Recognizer, 
+        CApaDataRecognizerType::ELow )
+    {
+    iCountDataTypes = KMimeTypesSupported;
+    #ifdef _DEBUG
+    RDebug::Print(_L("CPKCS12Recognizer constructed"));
+    #endif
+    }
+
+// ---------------------------------------------------------
+// CPKCS12Recognizer::~CPKCS12Recognizer()
+// ---------------------------------------------------------
+//
+CPKCS12Recognizer::~CPKCS12Recognizer()
+    {
+    if (iPKCS12)
+        {
+        iPKCS12->Release();
+        }
+    }
+
+// ---------------------------------------------------------
+// CPKCS12Recognizer::PreferredBufSize
+// ---------------------------------------------------------
+//
+TUint CPKCS12Recognizer::PreferredBufSize()
+    {
+    return KPKCS12DataMinLength; // we don't need bigger
+    }
+
+// ---------------------------------------------------------
+// CPKCS12Recognizer::SupportedDataTypeL
+// ---------------------------------------------------------
+//
+TDataType CPKCS12Recognizer::SupportedDataTypeL(TInt /*aIndex*/) const
+    {
+    return TDataType(KPKCS12MimeType);
+    }
+
+// ---------------------------------------------------------
+// CPKCS12Recognizer::DoRecognizeL
+// Checks if aBuffer contains a PKCS#12.
+// ---------------------------------------------------------
+//
+void CPKCS12Recognizer::DoRecognizeL(
+    const TDesC& /*aName*/, 
+    const TDesC8& aBuffer)
+    {   
+      
+    if (aBuffer.Size() >= KPKCS12DataMinLength)
+		{	
+		if (iPKCS12 == NULL)
+		    {
+		    iPKCS12 = PKCS12Factory::CreateL();
+		    }
+		if (iPKCS12->IsPKCS12Data(aBuffer))
+			{
+			iDataType = TDataType(KPKCS12MimeType);
+			iConfidence = EProbable;			
+			}		
+		}
+   }
+    
+// ---------------------------------------------------------
+// CPKCS12Recognizer::CreateRecognizerL
+// ---------------------------------------------------------
+//
+CApaDataRecognizerType* CPKCS12Recognizer::CreateRecognizerL()
+	{
+	return new (ELeave) CPKCS12Recognizer();
+	}
+
+// ---------------------------------------------------------
+// ImplementationTable
+// ---------------------------------------------------------
+//
+const TImplementationProxy ImplementationTable[] = 
+    {    
+	IMPLEMENTATION_PROXY_ENTRY(0x101F8803,CPKCS12Recognizer::CreateRecognizerL)
+	};
+	
+// ---------------------------------------------------------
+// ImplementationGroupProxy
+// ---------------------------------------------------------
+//
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+    {
+    #ifdef _DEBUG    	
+    RDebug::Print(_L("CPKCS12Recognizer ImplementationGroupProxy"));
+    #endif        
+    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
+    return ImplementationTable;
+    }
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/PKCS12/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Build information of the PKCS12 component
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT -ARMI
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+../CrBer/group/crber.mmp
+../CrPkcs12/group/crpkcs12.mmp
+../PKCS12Recognizer/group/PKCS12Recognizer.mmp
+
+PRJ_TESTMMPFILES
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/BWINSCW/SecModUI_EKA2U.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?CreateL@MSecModUI@@SAPAV1@XZ @ 1 NONAME ; class MSecModUI * MSecModUI::CreateL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/EABI/SecModUI_EKA2U.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,27 @@
+EXPORTS
+	_ZN9MSecModUI7CreateLEv @ 1 NONAME
+	_ZTI14CSecModUIModel @ 2 NONAME ; #<TI>#
+	_ZTI17CSecModUIViewBase @ 3 NONAME ; #<TI>#
+	_ZTI17CSecModUIViewCode @ 4 NONAME ; #<TI>#
+	_ZTI17CSecModUIViewMain @ 5 NONAME ; #<TI>#
+	_ZTI19CSecModUIViewAccess @ 6 NONAME ; #<TI>#
+	_ZTI20CSecModUISyncWrapper @ 7 NONAME ; #<TI>#
+	_ZTI22CSecModUIContainerBase @ 8 NONAME ; #<TI>#
+	_ZTI22CSecModUIContainerCode @ 9 NONAME ; #<TI>#
+	_ZTI22CSecModUIContainerMain @ 10 NONAME ; #<TI>#
+	_ZTI22CSecModUIViewSignature @ 11 NONAME ; #<TI>#
+	_ZTI24CSecModUIContainerAccess @ 12 NONAME ; #<TI>#
+	_ZTI27CSecModUIContainerSignature @ 13 NONAME ; #<TI>#
+	_ZTV14CSecModUIModel @ 14 NONAME ; #<VT>#
+	_ZTV17CSecModUIViewBase @ 15 NONAME ; #<VT>#
+	_ZTV17CSecModUIViewCode @ 16 NONAME ; #<VT>#
+	_ZTV17CSecModUIViewMain @ 17 NONAME ; #<VT>#
+	_ZTV19CSecModUIViewAccess @ 18 NONAME ; #<VT>#
+	_ZTV20CSecModUISyncWrapper @ 19 NONAME ; #<VT>#
+	_ZTV22CSecModUIContainerBase @ 20 NONAME ; #<VT>#
+	_ZTV22CSecModUIContainerCode @ 21 NONAME ; #<VT>#
+	_ZTV22CSecModUIContainerMain @ 22 NONAME ; #<VT>#
+	_ZTV22CSecModUIViewSignature @ 23 NONAME ; #<VT>#
+	_ZTV24CSecModUIContainerAccess @ 24 NONAME ; #<VT>#
+	_ZTV27CSecModUIContainerSignature @ 25 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/data/101F8668.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   ECOM plugin resource file for SecModUI plugin.
+*
+*/
+
+
+// INCLUDES
+#include <ecom/registryinfo.rh>
+
+
+RESOURCE REGISTRY_INFO theInfo
+	{
+	dll_uid     = 0x101F8668;
+	interfaces  = 
+		{
+		INTERFACE_INFO
+			{
+			interface_uid   = 0x10207236;
+			implementations = 
+				{
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid  = 0x101F8668;
+					version_no          = 1;
+					display_name        = "SecModUI Plugin";
+					default_data        = "0x1020743A";
+					opaque_data         = "3";//Order number
+					}
+				};
+			}
+		};
+	}
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/data/SecModUI.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,894 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This file contains all the resources for the SecModUI.
+*
+*/
+
+
+//  RESOURCE IDENTIFIER
+NAME    SMUI // 4 letter ID
+
+//  INCLUDES
+
+#include <eikon.rh>
+#include <secmodui.loc>
+#include <avkon.rsg>
+#include <avkon.rh>
+#include <avkon.mbg>
+#include <avkon.loc>
+#include "secmodui.hrh"
+
+//  RESOURCE DEFINITIONS
+
+RESOURCE RSS_SIGNATURE { }
+
+RESOURCE TBUF { buf = "SecModUI"; }
+    
+// RESOURCE TBUF
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_name
+//     Security module details item
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_name 
+    {
+    buf =    qtn_wim_name;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_keystore_list_text_phone_keystore
+//     Security module details item value
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_keystore_list_text_phone_keystore
+    {
+    buf =    qtn_keystore_list_text_phone_keystore;
+    }
+    
+//----------------------------------------------------
+//    
+//     r_qtn_wim_card_version
+//     Security module details item
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_card_version
+    {
+    buf =    qtn_wim_card_version;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_security_module_location
+//     Security module details item
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_security_module_location
+    {
+    buf =    qtn_wim_security_module_location;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_sett_pin_g
+//     Security module details item
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_sett_pin_g
+    {
+    buf =    qtn_wim_sett_pin_g;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_pin_g_no_label_details
+//     Security module details item value
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_pin_g_no_label_details
+    {
+    buf =    qtn_wim_pin_g_no_label_details;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_pin_nr_no_label_details
+//     Security module details item value
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_pin_nr_no_label_details
+    {
+    buf =    qtn_wim_pin_nr_no_label_details;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_key_pin
+//     Security module details item
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_key_pin
+    {
+    buf =    qtn_wim_key_pin;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_serial_nro
+//     Security module details item
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_serial_nro
+    {
+    buf =    qtn_wim_serial_nro;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_serial_nro
+//     Security module details item
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_manuf
+    {
+    buf =    qtn_wim_manuf;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_settings
+//     General Setting list
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_settings
+    {
+    buf =    qtn_wim_settings;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_title
+//     Main view title pane text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_title
+    {
+    buf =    qtn_wim_title;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_cm_confirm_delete_keys
+//     Confirmation query text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_cm_confirm_delete_keys
+    {
+    buf =    qtn_cm_confirm_delete_keys;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_status_blocked
+//     Code status setting item value
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_status_blocked
+    {
+    buf =    qtn_wim_code_status_blocked;
+    }
+
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_status_closed
+//     Code status setting item value
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_status_closed
+    {
+    buf =    qtn_wim_status_closed;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_opt_open
+//     Code status setting item value
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_opt_open
+    {
+    buf =    qtn_wim_opt_open;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_sett_status
+//     Code status setting item title
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_sett_status
+    {
+    buf =    qtn_wim_sett_status;
+    }
+
+//----------------------------------------------------
+//    
+//     qtn_wim_request_off
+//     Code request setting item value
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_request_off
+    {
+    buf =    qtn_wim_request_off;
+    }
+
+//----------------------------------------------------
+//    
+//     qtn_wim_request_on
+//     Code request setting item value
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_request_on
+    {
+    buf =    qtn_wim_request_on;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_pin_request
+//     Code request setting item title
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_wim_pin_request
+    {
+    buf =    qtn_wim_pin_request;
+    }
+
+//----------------------------------------------------
+//    
+//     r_text_resource_view_empty_wim_list
+//     Empty WIM view list text
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_text_resource_view_empty_wim_list
+    {
+    buf =    qtn_wim_no_wims;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_wim_info_pin_changed
+//     Code changed confirmation note text 
+//
+//----------------------------------------------------
+//    
+RESOURCE TBUF r_qtn_wim_info_pin_changed 
+    { 
+    buf=qtn_wim_info_pin_changed; 
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_keystore_info_unable_to_delete
+//     Key in use note text
+//
+//----------------------------------------------------
+//    
+RESOURCE TBUF r_qtn_keystore_info_unable_to_delete
+    { 
+    buf=qtn_keystore_info_unable_to_delete; 
+    }
+
+
+// RESOURCE HOTKEYS
+
+//----------------------------------------------------
+//   
+//    r_secmodui_hotkeys
+//
+//----------------------------------------------------
+//
+RESOURCE HOTKEYS r_secmodui_hotkeys
+    {
+    control =
+        {
+        HOTKEY { command = EAknCmdExit; key = 'e'; }
+        };
+    }
+
+// RESOURCE LISTBOX
+
+//----------------------------------------------------
+//   
+//    r_secmodui_dynamic_listbox
+//
+//----------------------------------------------------
+//
+RESOURCE LISTBOX r_secmodui_dynamic_listbox
+	{
+	flags = EAknListBoxSelectionList;
+	}
+
+//----------------------------------------------------
+//   
+//    r_secmodui_codes_listbox
+//
+//----------------------------------------------------
+//
+RESOURCE LISTBOX r_secmodui_codes_listbox
+	{
+	array_id = r_code_items;
+	flags = EAknListBoxSelectionList;
+	}
+
+// RESOURCE ARRAY
+
+//----------------------------------------------------
+//   
+//    r_code_items
+//
+//----------------------------------------------------
+//
+RESOURCE ARRAY r_code_items
+    {
+    items = {
+        LBUF { txt="\t"qtn_wim_list_text_access_code""; },
+        LBUF { txt="\t"qtn_wim_list_text_signature_codes""; }
+        };
+    }
+
+// RESOURCE AVKON_VIEW
+
+//----------------------------------------------------
+//   
+//    r_secmodui_view_main
+//
+//----------------------------------------------------
+//
+RESOURCE AVKON_VIEW r_secmodui_view_main
+    {
+    hotkeys = r_secmodui_hotkeys;
+    menubar = r_secmodui_menubar_view_main;  
+    cba     = r_secmodui_softkeys_options_back_open;    
+    }
+
+// ---------------------------------------------------------
+//
+//    r_secmodui_softkeys_options_back_open
+//    Define cba 
+//
+// ---------------------------------------------------------
+//
+RESOURCE CBA r_secmodui_softkeys_options_back_open
+    {
+    buttons =
+        {
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyOptions;
+            txt=text_softkey_option;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyBack;
+            txt=text_softkey_back;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyOpen;
+            txt=qtn_msk_open;
+            }
+       };
+    } 
+
+//----------------------------------------------------
+//   
+//    r_secmodui_view_code
+//
+//----------------------------------------------------
+//
+RESOURCE AVKON_VIEW r_secmodui_view_code
+    {
+    hotkeys = r_secmodui_hotkeys;
+    menubar = r_secmodui_menubar_view_code;  
+    cba     = r_secmodui_softkeys_options_back_open;    
+    }
+
+// ---------------------------------------------------------
+//
+//    r_secmodui_softkeys_options_back_change
+//    Define cba 
+//
+// ---------------------------------------------------------
+//
+RESOURCE CBA r_secmodui_softkeys_options_back_change
+    {
+    buttons =
+        {
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyOptions;
+            txt=text_softkey_option;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyBack;
+            txt=text_softkey_back;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyChange;
+            txt=qtn_msk_change;
+            }
+       };
+    } 
+
+RESOURCE CBA r_secmodui_softkeys_options_back_unblock
+    {
+    buttons =
+        {
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyOptions;
+            txt=text_softkey_option;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyBack;
+            txt=text_softkey_back;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyUnlock;
+            txt=qtn_msk_unblock;
+            }
+       };
+    } 
+
+RESOURCE CBA r_secmodui_softkeys_options_back_close
+    {
+    buttons =
+        {
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyOptions;
+            txt=text_softkey_option;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyBack;
+            txt=text_softkey_back;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyClose;
+            txt=text_softkey_close;
+            }
+       };
+    } 
+
+
+RESOURCE CBA r_secmodui_softkeys_options_back
+    {
+    buttons =
+        {
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyOptions;
+            txt=text_softkey_option;
+            },
+        CBA_BUTTON
+            {
+            id=EAknSoftkeyBack;
+            txt=text_softkey_back;
+            },
+        CBA_BUTTON
+            {
+            txt = text_softkey_empty;
+            }
+       };
+    }
+    
+//----------------------------------------------------
+//   
+//    r_secmodui_view_signature
+//
+//----------------------------------------------------
+//
+RESOURCE AVKON_VIEW r_secmodui_view_signature
+    {
+    hotkeys = r_secmodui_hotkeys;
+    menubar = r_secmodui_menubar_view_signature;  
+    cba     = r_secmodui_softkeys_options_back_change;    
+    }
+    
+//----------------------------------------------------
+//   
+//    r_secmodui_view_access
+//
+//----------------------------------------------------
+//
+RESOURCE AVKON_VIEW r_secmodui_view_access
+    {
+    hotkeys = r_secmodui_hotkeys;
+    menubar = r_secmodui_menubar_view_access;  
+    cba     = r_secmodui_softkeys_options_back_change;    
+    }    
+    
+// RESOURCE MENU_BAR
+
+//----------------------------------------------------
+//   
+//    r_secmodui_menubar_view_main
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_BAR r_secmodui_menubar_view_main
+    {
+    titles =
+        {
+        MENU_TITLE { menu_pane = r_secmodui_view_main_menu; txt = ""; }
+        };
+    }
+    
+//----------------------------------------------------
+//   
+//    r_secmodui_menubar_view_code
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_BAR r_secmodui_menubar_view_code
+    {
+    titles =
+        {
+        MENU_TITLE { menu_pane = r_secmodui_view_code_menu; txt = ""; }
+        };
+    }
+    
+//----------------------------------------------------
+//   
+//    r_secmodui_menubar_view_signature
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_BAR r_secmodui_menubar_view_signature
+    {
+    titles =
+        {
+        MENU_TITLE { menu_pane = r_secmodui_view_signature_menu; txt = ""; }
+        };
+    }
+    
+//----------------------------------------------------
+//   
+//    r_secmodui_menubar_view_access
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_BAR r_secmodui_menubar_view_access
+    {
+    titles =
+        {
+        MENU_TITLE { menu_pane = r_secmodui_view_access_menu; txt = ""; }
+        };
+    }
+    
+// RESOURCE MENU_PANE    
+            
+//----------------------------------------------------
+//   
+//    r_secmodui_view_main_menu
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_PANE r_secmodui_view_main_menu
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            command = ESecModUICmdOpen;
+            txt = qtn_wim_options_open;
+            flags = EEikMenuItemAction;
+            },
+        MENU_ITEM
+            {
+            command = ESecModUICmdModuleInfo;
+            txt = qtn_wim_opt_details;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = ESecModUICmdDelKeyStore;
+            txt = qtn_cm_options_delete_keystore;
+            flags = EEikMenuItemSpecific;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdHelp;
+            txt = qtn_options_help;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdExit;
+            txt = qtn_options_exit;
+            }
+        };
+    }  
+    
+//----------------------------------------------------
+//   
+//    r_secmodui_view_code_menu
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_PANE r_secmodui_view_code_menu
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            command = ESecModUICmdOpen;
+            txt = qtn_wim_options_open;
+            flags = EEikMenuItemAction;
+            },
+        MENU_ITEM
+            {
+            command = ESecModUICmdModuleInfo;
+            txt = qtn_wim_opt_details;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdHelp;
+            txt = qtn_options_help;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdExit;
+            txt = qtn_options_exit;
+            }
+        };
+    }
+
+//----------------------------------------------------
+//   
+//    r_secmodui_view_signature_menu
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_PANE r_secmodui_view_signature_menu
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            command = ESecModUICmdChange;
+            txt = qtn_options_change;
+            flags = EEikMenuItemAction;
+            },
+        MENU_ITEM
+            {
+            command = ESecModUICmdUnblock;
+            txt = qtn_wim_sett_opt_unblock;
+            },
+        MENU_ITEM
+            {
+            command = ESecModUICmdModuleInfo;
+            txt = qtn_wim_opt_details;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdHelp;
+            txt = qtn_options_help;
+            },
+        MENU_ITEM
+            {
+            command=EAknCmdExit;
+            txt = qtn_options_exit;
+            }
+        };
+    }    
+    
+//----------------------------------------------------
+//   
+//    r_secmodui_view_access_menu
+//
+//----------------------------------------------------
+//
+RESOURCE MENU_PANE r_secmodui_view_access_menu
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            command = ESecModUICmdChange;
+            txt = qtn_options_change;
+            flags = EEikMenuItemAction;
+            },
+        MENU_ITEM
+            {
+            command = ESecModUICmdUnblock;
+            txt = qtn_wim_sett_opt_unblock;
+            },
+        MENU_ITEM
+            {
+            command = ESecModUICmdClose;
+            txt = qtn_wim_options_close_code;
+            },
+        MENU_ITEM
+            {
+            command = ESecModUICmdModuleInfo;
+            txt = qtn_wim_opt_details;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdHelp;
+            txt = qtn_options_help;
+            },
+        MENU_ITEM
+            {
+            command = EAknCmdExit;
+            txt = qtn_options_exit;
+            }
+        };
+    }  
+
+// RESOURCE DIALOGS
+
+//----------------------------------------------------
+//    
+//     r_message_query_details_view
+//     Certificate Management Details view query
+//
+//----------------------------------------------------
+//
+RESOURCE DIALOG r_secmod_details_view
+    {
+    flags = EGeneralQueryFlags | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow;
+    buttons = R_AVKON_SOFTKEYS_OK_EMPTY__OK;
+    items=
+        {
+        DLG_LINE 
+            {
+            type = EAknCtPopupHeadingPane;
+            id = EAknMessageQueryHeaderId;
+            control = AVKON_HEADING
+                {
+                label= qtn_wim_info_header;
+                };
+            },
+         DLG_LINE
+            {
+            type = EAknCtMessageQuery;
+            id = EAknMessageQueryContentId;
+            control = AVKON_MESSAGE_QUERY
+                {
+                };
+            }
+        };
+    }
+
+// ---------------------------------------------------------
+//    
+//     r_certmanui_confirmation_query_yes_no
+//     Delete certificate confirmation query 
+//
+// ---------------------------------------------------------
+//
+RESOURCE DIALOG r_secmod_confirmation_query_yes_no
+    {
+    flags=EGeneralQueryFlags;
+    buttons=R_AVKON_SOFTKEYS_YES_NO;
+         items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_CONFIRMATION_QUERY 
+                { 
+                layout = EConfirmationLayout;
+                label = "dummy";
+                };
+            }
+        };
+    }
+
+// RESOURCE NAVI_LABELS
+
+// ---------------------------------------------------------
+//    
+//     r_navipane_access_text
+//     Access code view navipane text
+//
+// ---------------------------------------------------------
+//
+RESOURCE NAVI_LABEL r_navipane_access_text
+    {
+    txt = qtn_wim_navi_text_access_codes;
+    }
+
+// ---------------------------------------------------------
+//    
+//     r_navipane_signature_text
+//     Signature codes view navipane text
+//
+// ---------------------------------------------------------
+//
+RESOURCE NAVI_LABEL r_navipane_signature_text
+    {
+    txt = qtn_wim_navi_text_signature_codes;
+    }
+           
+           
+//----------------------------------------------------
+//    
+//     r_qtn_secmod_status_value_blocked
+//     Code status setting item value
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_qtn_secmod_status_value_blocked
+    {
+    buf = qtn_secmod_status_value_blocked;
+    }
+
+//----------------------------------------------------
+//    
+//     r_qtn_secmod_status_value_blocked
+//     Security module details item value
+//
+//----------------------------------------------------
+//    
+RESOURCE TBUF r_qtn_secmod_title_phone_keystore_code
+    {
+    buf = qtn_secmod_title_phone_keystore_code;    
+    }
+    
+//----------------------------------------------------
+//    
+//     r_qtn_keystore_title_phone_keystore
+//
+//----------------------------------------------------
+//    
+RESOURCE TBUF r_qtn_keystore_title_phone_keystore
+    {
+    buf = qtn_keystore_title_phone_keystore;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/group/SecModUIPlugin.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,110 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Project specification file.
+*
+*/
+
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET            SecModUI.dll
+TARGETTYPE        PLUGIN
+UID  0x10009D8D   0x101F8668
+
+CAPABILITY        CAP_ECOM_PLUGIN
+VENDORID          VID_DEFAULT
+
+// Resource file location
+SOURCEPATH        ../data
+
+
+START RESOURCE    101F8668.rss
+TARGET            SecModUI.rsc
+END
+
+
+// Resource file
+START RESOURCE    SecModUI.rss
+HEADER
+TARGETPATH        RESOURCE_FILES_DIR
+LANGUAGE_IDS
+END
+
+SOURCEPATH        ../src
+SOURCE            SecModUIContainerBase.cpp
+SOURCE            SecModUIContainerMain.cpp
+SOURCE            SecModUIViewBase.cpp
+SOURCE            SecModUIViewMain.cpp
+SOURCE            SecModUIViewCode.cpp
+SOURCE            SecModUIContainerCode.cpp
+SOURCE            SecModUIViewAccess.cpp
+SOURCE            SecModUIContainerAccess.cpp
+SOURCE            SecModUIViewSignature.cpp
+SOURCE            SecModUIContainerSignature.cpp
+SOURCE            SecModUIModel.cpp
+SOURCE            SecModUISyncWrapper.cpp
+SOURCE            SecModUIPlugin.cpp
+SOURCE            SecModUIPluginContainer.cpp
+SOURCE            SecModUIPluginImplementationTable.cpp
+
+
+USERINCLUDE       .
+USERINCLUDE       ../inc
+
+APP_LAYER_SYSTEMINCLUDE
+
+
+LIBRARY           euser.lib
+LIBRARY           cone.lib
+LIBRARY           eikcore.lib
+LIBRARY           eikcoctl.lib
+LIBRARY           avkon.lib
+LIBRARY           aknskins.lib
+LIBRARY           bafl.lib
+
+// Dependencies
+LIBRARY           crypto.lib
+LIBRARY           certstore.lib       // TCertManClientInfo::Id
+LIBRARY           commonengine.lib    // StringLoader.h
+LIBRARY           eikctl.lib          // markable icons
+LIBRARY           efsrv.lib           // needed by CertManUI debug logger
+LIBRARY           SysUtil.lib         // For FFS Space checking
+LIBRARY           commonui.lib        // for CErrorUI
+LIBRARY           CTFramework.lib     // CCertAttributeFilter
+LIBRARY           X509.lib
+LIBRARY           pkixcert.lib        // Validation
+LIBRARY           x509certnameparser.lib    // parsing of label
+LIBRARY           hash.lib
+LIBRARY           Featmgr.lib         // feature manager support
+LIBRARY           aknnotify.lib
+LIBRARY           ecom.lib
+LIBRARY           GSFramework.lib
+LIBRARY           GSEcomPlugin.lib
+LIBRARY           hlplch.lib          // for "Help" options menu
+
+
+// Turn logging on/off
+// #define _SECMODUI_LOGGING_ON
+
+#ifdef _SECMODUI_LOGGING_ON
+MACRO _SECMODUI_LOG_
+LIBRARY         flogger.lib
+#else
+DEBUGLIBRARY    flogger.lib
+#endif
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Interface of the Security Module UI DLL
+*
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+//help
+#include "../help/group/bld.inf"
+
+PRJ_EXPORTS
+../loc/secmodui.loc   MW_LAYER_LOC_EXPORT_PATH(secmodui.loc)
+
+PRJ_MMPFILES
+SecModUIPlugin.mmp
+
+
+
Binary file pkiutilities/SecModUI/help/data/xhtml.zip has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/help/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - Initial contribution
+* 
+* Contributors:
+* 
+* 
+* Description:
+* Export help related files.
+*
+*/
+
+#include <platform_paths.hrh>				
+PRJ_EXPORTS
+:zip ../data/xhtml.zip   /epoc32/data/z/resource/ overwrite
+:zip ../data/xhtml.zip   /epoc32/winscw/c/resource/ overwrite
+
+../inc/wim.hlp.hrh	MW_LAYER_PLATFORM_EXPORT_PATH(csxhelp/wim.hlp.hrh)
+../rom/secmoduihelps_variant.iby		CUSTOMER_APP_LAYER_IBY_EXPORT_PATH(secmoduihelps_variant.iby)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/help/inc/wim.hlp.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*/
+	
+//
+// wim.hlp.hrh generated by CSXHelp Utilities.
+//           
+
+#ifndef __WIM_HLP_HRH__
+#define __WIM_HLP_HRH__
+
+_LIT(KSECMOD_HLP_ACCESSCODE_VIEW, "SECMOD_HLP_ACCESSCODE_VIEW"); // 
+_LIT(KSECMOD_HLP_CODE_VIEW, "SECMOD_HLP_CODE_VIEW"); // 
+_LIT(KSECMOD_HLP_MAIN_VIEW, "SECMOD_HLP_MAIN_VIEW"); // 
+_LIT(KSEMOD_HLP_SIGNINGCODE_VIEW, "SEMOD_HLP_SIGNINGCODE_VIEW"); // 
+
+#endif 
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/help/rom/secmoduihelps_variant.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,28 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Image description file for SecModUI helps
+*
+*/
+
+#ifndef __SECMODUIHELPS_VARIANT_IBY__
+#define __SECMODUIHELPS_VARIANT_IBY__
+
+#if defined(FF_S60_HELPS_IN_USE)
+    data=LOCALISE(DATAZ_\resource\xhtml\%02d\0x101F8668\contents.zip, RESOURCE_FILES_DIR\xhtml\%02d\0x101F8668\contents.zip)
+    data=LOCALISE(DATAZ_\resource\xhtml\%02d\0x101F8668\index.xml, RESOURCE_FILES_DIR\xhtml\%02d\0x101F8668\index.xml)
+    data=LOCALISE(DATAZ_\resource\xhtml\%02d\0x101F8668\keywords.xml, RESOURCE_FILES_DIR\xhtml\%02d\0x101F8668\keywords.xml)
+    data=LOCALISE(DATAZ_\resource\xhtml\%02d\0x101F8668\meta.xml, RESOURCE_FILES_DIR\xhtml\%02d\0x101F8668\meta.xml)
+#endif
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUI.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,61 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Interface of the Security Module UI DLL
+*
+*/
+
+
+#ifndef SECMODUI_H
+#define SECMODUI_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+const TUid KSecModUIViewMainId = {22};
+const TUid KSecModUIViewCodeId = {23};
+const TUid KSecModUIViewAccessId = {45};
+const TUid KSecModUIViewSignatureId = {46};
+
+
+// CLASS DECLARATION
+
+/**
+*  Interface of the Security Module UI.
+*  Creates and deletes instance of the Security Module UI.
+*
+*  @lib SecModUI.lib
+*  @since Series 60 3.0
+*/
+class MSecModUI
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Creates an instance of a subclass of MSecModUI.
+        *
+        * @return	An object that implements MSecModUI destructor.
+        */
+        IMPORT_C static MSecModUI* CreateL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~MSecModUI() {};
+
+    };
+    
+#endif      // SECMODUI_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUIContainerAccess.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CSecModUIContainerAccess class
+*
+*/
+
+
+#ifndef SECMODUICONTAINERACCESS_H
+#define SECMODUICONTAINERACCESS_H
+
+// INCLUDES
+#include "SecModUIContainerBase.h"
+#include "SecModUIViewAccess.h" 
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+/**
+*  CSecModUIContainerAccess  container control class.
+*  
+*/
+class CSecModUIContainerAccess : public CSecModUIContainerBase, public MCoeControlObserver
+    {
+    public: // Constructors and destructor
+    
+        /**
+        * Overrided Default constructor
+        */
+        CSecModUIContainerAccess(CSecModUIModel& aModel, CSecModUIViewAccess* aView );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSecModUIContainerAccess();
+         
+       
+        //from MCoeControlObserver
+        void HandleControlEventL(CCoeControl* aControl,TCoeEvent aEventType); 
+
+    
+    private: // Functions from base classes
+        void SetupListItemsL();
+        void ConstructListL();
+    private: 
+        CSecModUIViewAccess* iView;     
+   };
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUIContainerBase.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,117 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CSecModUIContainerBase class
+*
+*/
+
+
+#ifndef SECMODUICONTAINERBASE_H
+#define SECMODUICONTAINERBASE_H
+
+// INCLUDES
+#include <coecntrl.h>
+#include "SecModUISyncWrapper.h"   
+// FORWARD DECLARATIONS
+class CEikLabel;        // for example labels
+//class CAknColumnListBox;
+class CEikTextListBox;
+class CSecModUIModel;
+
+// CLASS DECLARATION
+
+/**
+*  CSecModUIContainerBase  container control class.
+*  
+*/
+class CSecModUIContainerBase : public CCoeControl
+    {
+    public: // Constructors and destructor
+    
+        /**
+        * Overrided Default constructor
+        */
+        CSecModUIContainerBase(CSecModUIModel& aModel, const TDesC& aContextName);
+        
+        /**
+        * EPOC default constructor.
+        * @param aRect Frame rectangle for container.
+        */
+        virtual void ConstructL(const TRect& aRect);
+
+ 
+        /**
+        * Destructor.
+        */
+        virtual ~CSecModUIContainerBase();
+
+    public: // New functions
+            
+        CEikTextListBox& ListBox();
+        virtual void SetupListItemsL();
+        
+        //CCoeControl
+        void FocusChanged( TDrawNow aDrawNow );
+
+    protected: // New functions
+    	
+    	virtual void CreateListL();
+    	virtual void CreateResourceReaderLC(TResourceReader& aReader);	
+    	virtual void ConstructListL();
+    
+
+    protected: // Functions from base classes
+
+        /**
+        * From CoeControl,SizeChanged.
+        */
+        virtual void SizeChanged();
+
+        /**
+        * From CoeControl,CountComponentControls.
+        */
+        virtual TInt CountComponentControls() const;
+
+        /**
+        * From CCoeControl,ComponentControl.
+        */
+        virtual CCoeControl* ComponentControl(TInt aIndex) const;
+        
+        /**
+        * From CCoeControl, OfferKeyEventL.
+        */
+        virtual TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType);
+ 
+        /**
+        * From CCoeControl, GetHelpContext.
+        */
+        void GetHelpContext(TCoeHelpContext& aContext) const;
+        
+        /**
+        * Handles resource change
+        */
+		void HandleResourceChange(TInt aType);
+                
+    protected:        
+        CEikTextListBox*    iListBox;
+    	CSecModUIModel& iModel;       
+    private: //data
+        TCoeContextName iContextName;
+    
+    	
+        
+    };
+
+#endif  // SECMODUICONTAINERMAIN_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUIContainerCode.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CSecModUIContainerCode class
+*
+*/
+
+
+#ifndef SECMODUICONTAINERCODE_H
+#define SECMODUICONTAINERCODE_H
+
+// INCLUDES
+#include "SecModUIContainerBase.h"
+ 
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+/**
+*  CSecModUIContainerCode  container control class.
+*  
+*/
+class CSecModUIContainerCode : public CSecModUIContainerBase
+    {
+    public: // Constructors and destructor
+    
+        /**
+        * Overrided Default constructor
+        */
+        CSecModUIContainerCode(CSecModUIModel& aModel);
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSecModUIContainerCode();
+
+    public: // New functions
+
+    private: // Functions from base classes
+        
+        void SetupListItemsL();
+        void CreateResourceReaderLC(TResourceReader& aReader);	
+                   
+    private: // New functions
+    	 
+    private: //data
+ 
+   };
+
+#endif // SECMODUICONTAINERCODE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUIContainerMain.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,67 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CSecModUIContainerMain class
+*
+*/
+
+
+#ifndef SECMODUICONTAINERMAIN_H
+#define SECMODUICONTAINERMAIN_H
+
+// INCLUDES
+#include "SecModUIContainerBase.h"
+#include <coecntrl.h>
+#include <eiklbo.h>
+   
+// FORWARD DECLARATIONS
+class CEikLabel;        // for example labels
+class CAknColumnListBox;
+class CSecModUIModel;
+
+// CLASS DECLARATION
+
+/**
+*  CSecModUIContainerMain  container control class.
+*  
+*/
+class CSecModUIContainerMain : public CSecModUIContainerBase
+    {
+    public: // Constructors and destructor
+    
+        /**
+        * Overrided Default constructor
+        */
+        CSecModUIContainerMain(CSecModUIModel& aModel);
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CSecModUIContainerMain();
+
+    public: // New functions
+       
+    private: // Functions from base classes
+           
+        void SetupListItemsL();
+        void ConstructListL();
+        
+    private: // New functions
+    	 
+    private: //data
+      
+    };
+
+#endif  // SECMODUICONTAINERMAIN_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUIContainerSignature.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,64 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CSecModUIContainerSignature class
+*
+*/
+
+
+#ifndef SECMODUICONTAINERSIGNATURE_H
+#define SECMODUICONTAINERSIGNATURE_H
+
+// INCLUDES
+#include "SecModUIContainerBase.h"
+#include "SecModUIViewSignature.h"
+   
+// FORWARD DECLARATIONS
+
+
+// CLASS DECLARATION
+
+/**
+*  CSecModUIContainerSignature  container control class.
+*  
+*/
+class CSecModUIContainerSignature : public CSecModUIContainerBase, public MCoeControlObserver
+    {
+    public: // Constructors and destructor
+        
+        /**
+        * Overrided Default constructor
+        */
+        CSecModUIContainerSignature(CSecModUIModel& aModel, CSecModUIViewSignature* aView );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSecModUIContainerSignature();
+    
+    public: // Function from CSecModUIContainerBase    
+        void SetupListItemsL();
+        
+        // from MCoeControlObserver
+        void HandleControlEventL(CCoeControl* aControl,TCoeEvent aEventType); 
+
+    private: // Functions from base classes        
+        void ConstructListL();             
+           
+    private: //data
+        CSecModUIViewSignature* iView; //Not owned
+    };
+
+#endif // SECMODUICONTAINERSIGNATURE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUILogger.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,143 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implements logger functionality of the module
+*
+*/
+
+
+
+#ifndef SECMODUI_LOGGER_H
+#define SECMODUI_LOGGER_H
+
+
+#if defined ( _DEBUG ) || defined ( _SECMODUI_LOG_ )
+
+// INCLUDES
+#include <flogger.h>
+#include <e32debug.h>
+
+enum TLoggingSelectors
+	{ 
+	EEnterFunction = 1,
+    ELeaveFunction,
+    EWriteLog
+	};
+
+// CONSTANTS
+
+// Macros to be substituted
+_LIT( KLogMessageAppBanner,   "SecModUI: module (%d.%d.%d) started" );
+_LIT( KLogExit,               "SecModUI: module exit" );
+_LIT( KLogTimeFormatString,   "%H:%T:%S:%*C3" );
+_LIT8( KLogEnterFn,           "ENTRY " );
+_LIT8( KLogLeaveFn,           "EXIT " );
+
+// ATTENTION!!! We're depending on FLogger DLL, because it presumes the
+// existance of C:\LOGS directory.
+_LIT( KFLoggerDependency,		"c:\\logs\\" );
+_LIT( KDoubleBackSlash,		    "\\" );
+_LIT( KLogDir,					"SecModUI" );
+_LIT( KLogFile,				    "SecModUI.log" );
+
+/**
+* Use this macro in order to initialize logger :
+* - create log directory,
+* - write version information into the log file
+*/
+#define LOG_CREATE  { TFileName path( KFLoggerDependency );  \
+    path.Append( KLogDir ); path.Append( KDoubleBackSlash ); \
+    RFs& fs = CEikonEnv::Static()->FsSession(); fs.MkDirAll( path ); \
+    RFileLogger::WriteFormat( \
+        KLogDir, KLogFile, EFileLoggingModeOverwrite, KLogMessageAppBanner ); }
+
+/**
+* Use this macro for writing information about exiting.
+*/
+#define LOG_DELETE { \
+    RFileLogger::Write( KLogDir, KLogFile, EFileLoggingModeAppend, KLogExit ); }
+
+/**
+* Use this function at the entry point of any functions.
+* @param a Entry information of the method.
+*/
+#define LOG_ENTERFN( a ) write_log (EEnterFunction, a)
+/**
+* Use this function right before you leave the method.
+* @param a Leaving information of the method.
+*/
+#define LOG_LEAVEFN( a ) write_log (ELeaveFunction, a)
+
+/**
+* Use this function at any points of a function for logging the current state.
+* @param a String to be written into logfile about the current state
+*/
+#define LOG_WRITE( a ) write_log (EWriteLog, a)
+/**
+* Use this function at any points of a function for logging the current state.
+* You can use printf-like formats, but with only one parameter to be substituted..
+* @param a Format string,
+* @param b Parameter to be substituted.
+*/
+#define LOG_WRITE_FORMAT( a, b ) write_log (EWriteLog, a, b)
+
+inline void write_log (TInt aSelector, const char* aFmt,...) //lint !e960
+    {
+    TBuf8<256> buf;
+        {
+	    VA_LIST ap;//lint !e960
+        TPtrC8 fmt((unsigned char *)aFmt);
+	    VA_START(ap, aFmt);  //lint !e960
+	    buf.FormatList(fmt, ap);
+	    VA_END(ap);  //lint !e960
+        }
+    switch(aSelector)
+        {
+        case EEnterFunction:
+            buf.Insert(0, KLogEnterFn);
+            break;
+        case ELeaveFunction:
+            buf.Insert(0, KLogLeaveFn);
+            break;
+        default:
+            break;
+        }
+
+    RFileLogger::Write( KLogDir, KLogFile, EFileLoggingModeAppend, buf);
+
+    TBuf<256> tempBuf;
+    tempBuf.Copy( buf );
+    RDebug::Print( tempBuf );
+    }
+
+#define LOG_HEXDUMP(aBuf) { \
+    RFileLogger::HexDump(KLogDir, KLogFile, EFileLoggingModeAppend, \
+    ((const TText *)" "), ((const TText *)" "), aBuf.Ptr(), aBuf.Size());}
+
+
+#else // _DEBUG || _SECMODUI_LOG_
+
+// Empty macros
+#define LOG_CREATE 
+#define LOG_DELETE
+#define LOG_ENTERFN( a )
+#define LOG_LEAVEFN( a )
+#define LOG_WRITE( a )
+#define LOG_WRITE_FORMAT( a, b )
+#define LOG_HEXDUMP( a)
+
+#endif // _DEBUG || _SECMODUI_LOG_
+
+#endif	// SECMODUI_LOGGER_H
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUIModel.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,396 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CSecModUIModel class 
+*
+*/
+
+
+#ifndef CSECMODUIMODEL_H
+#define CSECMODUIMODEL_H
+
+//  INCLUDES
+#include "SecModUI.h"
+#include <e32base.h>
+#include <bamdesca.h>
+#include <ct/rmpointerarray.h>
+
+// CONSTANTS
+const TInt KPinGIndex = 0; // PIN-G should be always first AO in the AO list.
+const TInt KMaxSettItemSize = 200;
+
+const TInt KPinGSettIndex = 0;
+const TInt KPinNrSettIndex = 1;
+
+const TUid KUidSecMod = { 0x101F8668 };
+
+// Panic strings
+_LIT(KPanicNullPointer, "SecModUI: invalid pointer");
+_LIT(KPanicIndexOutOfRange, "SecModUI: array indexed out of range");
+
+// FORWARD DECLARATIONS
+class CUnifiedKeyStore;
+class MCTAuthenticationObject;
+class MCTAuthenticationObjectList;
+class CSecModUISyncWrapper;
+class CEikTextListBox;
+class MCTKeyStore;
+class MCTToken;
+class CEikonEnv;
+
+
+// DATA TYPES
+enum TSecModPanicCode
+    {
+    EPanicNullPointer,
+    EPanicIndexOutOfRange
+    };
+
+// FUNCTION PROTOTYPES
+GLREF_C void Panic( TInt aPanic );
+
+// CLASS DECLARATION
+
+/**
+*  class CSecModUIModel
+*  Model of the application
+*
+*  @lib SecModUI.lib
+*  @since Series 60 3.0
+*/
+class CSecModUIModel : public CBase, public MSecModUI
+    {
+    public:  // Constructors and destructLoadTokenLabelsLor
+        
+        /**
+        * Two-phased constructor.
+        */        
+        static CSecModUIModel* NewL();
+                
+        /**
+        * Destructor.
+        */
+        virtual ~CSecModUIModel();
+
+    public: // New functions
+        
+        /**
+        * Activates title to the title pane        
+        * @param aTitle Title to be activated
+        * @return void
+        */
+        void ActivateTitleL(const TDesC& aTitle) const;
+        
+        /**
+        * Activates current tokens label to the title pane                
+        * @return void
+        */
+        void ActivateTokenLabelToTitleL() const;
+    
+        /**
+        * Initializes unified keystore        
+        * @return Error value
+        */
+        TInt InitializeKeyStoreL();
+        
+        /**
+        * Load labels of the tokens to the listbox        
+        * @param aListBox Listbox
+        * @return void
+        */        
+        void LoadTokenLabelsL(CEikTextListBox& aListBox);
+        
+        /**
+        * Checks that does active token have also signing code(s)
+        * @param aItemArray contains localised stings 
+        * @return void
+        */
+        void CheckCodeViewStringsL(MDesCArray& aItemArray);
+        
+        /**
+        * Opens and activates token        
+        * @param aTokenIndex Index of the token to be opened.
+        * @return void
+        */
+        void OpenTokenL(TInt aTokenIndex);
+        
+        /**
+        * Opens authentication object view        
+        * @param aIndex 0 is access code view
+        *               1 is signing code view
+        * @return void
+        */
+        void OpenAuthObjViewL(TInt aIndex);
+        
+        /**
+        * Closes authentication object       
+        * @param aIndex Index of the AO to be closed.
+        * @return void
+        */
+        void CloseAuthObjL(TInt aIndex);
+        
+        /**
+        * Loads PIN-NR labels to the listbox        
+        * @param aListBox 
+        * @param aShowBlockedNote If ETrue, shows code blocked if code is blocked.
+        * @return void 
+        */
+        void LoadPinNRLabelsL(CEikTextListBox& aListBox, TBool aShowBlockedNote);
+        
+        /**
+        * Loads items of the access code view list         
+        * @param aListBox where items are appended.
+        * @return void
+        */
+        void LoadPinGItemsL(CEikTextListBox& aListBox);
+        
+        /**
+        * Writes AO status item to the descriptor        
+        * @param aIndex Index of the authentication object
+        * @param aItem Descriptor where status is written.
+        * @param aShowBlockedNote If ETrue, shows code blocked if code is blocked.
+        * @return void
+        */
+        void PINStatusItemL(
+            TInt aIndex, TDes& aItem, TBool aShowBlockedNote) const;
+        
+        /**
+        * Writes AO request status to the descriptor
+        * @param aIndex Index of the authentication object
+        * @param aItem Descriptor where status is written.
+        * @return void
+        */
+        void PINRequestItemL(TInt aIndex, TDes& aItem) const;
+        
+        /**
+        * Displays security module details dialog.        
+        * @param aTokenIndex Index of the token, which details are shown.
+        * @return void
+        */
+        void ViewSecModDetailsL(TInt aTokenIndex);
+        
+        /**
+        * Displays details dialog of the active security module .                        
+        * @return void
+        */
+        void ViewOpenedSecModDetailsL();
+        
+        /**
+        * Deletes keystore        
+        * @param aTokenIndex Index of the token to be deleted.
+        * @return ETrue if keystore was deleted.
+        */
+        TBool DeleteKeyStoreL(TInt aTokenIndex);
+        
+        /**
+        * Returns ETrue if token is deletable.
+        * @param aTokenIndex Index of the token to be deleted.
+        * @return ETrue / EFalse
+        */
+        TBool IsTokenDeletable(TInt aTokenIndex);
+        
+        /**
+        * Launches change or unblock operation depending
+        * of the status of the PIN-NR        
+        * @param aIndex Index of the AO
+        * @return ?description
+        */
+        void ChangeOrUnblockPinNrL(TInt aIndex);
+        
+        /**
+        * Launches change or unblock operation depending
+        * of the status of the PIN        
+        * @param aIndex Index of the AO
+        * @return ?description
+        */
+        void ChangeOrUnblockPinL(TInt aIndex);
+        
+        /**
+        * Changes PIN-NR
+        * @param aIndex Index of the AO
+        * @return void
+        */
+        void ChangePinNrL(TInt aIndex);
+        
+        /**
+        * Changes PIN
+        * @param aIndex Index of the AO
+        * @return void
+        */
+        void ChangePinL(TInt aIndex);
+        
+        /**
+        * Unblocks PIN-NR
+        * @param aIndex Index of the AO
+        * @return void
+        */
+        void UnblockPinNrL(TInt aIndex);
+        
+        /**
+        * Unblocks PIN
+        * @param aIndex Index of the AO
+        * @return void
+        */
+        void UnblockPinL(TInt aIndex);
+        
+        /**
+        * Returns ETrue if PIN-NR is changeable.        
+        * @param aIndex Index of the AO
+        * @return ETrue / EFalse
+        */
+        TBool PinNrChangeable(TInt aIndex) const;
+        
+        /**
+        * Returns ETrue if PIN is changeable.        
+        * @param aIndex Index of the AO
+        * @return ETrue / EFalse
+        */
+        TBool PinChangeable(TInt aIndex) const;
+        
+        /**
+        * Returns ETrue if PIN-NR is unblockable.        
+        * @param aIndex Index of the AO
+        * @return ETrue / EFalse
+        */
+        TBool PinNrUnblockable(TInt aIndex) const;
+        
+        /**
+        * Returns ETrue if PIN is unblockable.        
+        * @param aIndex Index of the AO
+        * @return ETrue / EFalse
+        */
+        TBool PinUnblockable(TInt aIndex) const;
+        
+        /**
+        * Returns ETrue if PIN request can be disabled / enabled.        
+        * @param aIndex Index of the AO
+        * @return ETrue / EFalse
+        */
+        TBool PinRequestChangeable(TInt aIndex) const;
+        
+        /**
+        * Returs ETrue if PIN is open.
+        * @param aIndex Index of the AO
+        * @return ?description
+        */
+        TBool PinOpen(TInt aIndex) const;
+        
+        /**
+        * Disables / enables PIN depending on the status of the PIN.        
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        TInt ChangeCodeRequestL(TInt aIndex);
+        
+        /**
+        * Shows confirmation query.        
+        * @param aResourceId Id of the resource
+        * @return Response of the user.
+        */
+        TInt ShowConfirmationQueryL(TInt aResourceId) const;
+       
+        /**
+        * Shows confirmation note dialog.        
+        * @param aResourceId Id of the resource
+        * @return void
+        */
+        void ShowConfirmationNoteL(TInt aResourceId) const;
+        
+        /**
+        * Shows information note dialog.        
+        * @param aResourceId Id of the resource
+        * @return void
+        */
+        void ShowInformationNoteL(TInt aResourceId, const TDesC& aString = KNullDesC) const;
+        
+        /**
+        * Shows error note if needed.        
+        * @param aError 
+        * @return void
+        */
+        void ShowErrorNoteL(TInt aError) const;
+        
+        CSecModUISyncWrapper& Wrapper();            
+        
+        /**
+         * Returns the number of security modules.
+         */
+        TInt SecurityModuleCount() const;
+        
+    private:
+
+        /**
+        * C++ default constructor.
+        */        
+        CSecModUIModel();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();        
+        
+        void ResetAndDestroyCTObjects();
+        
+        void ResetAndDestroyAOs();
+        
+        void AddResourceFileL();
+        
+        void InitAuthObjectsL();
+        
+        void ListAuthObjectsL();
+        
+        void CreateSettingItem(const TDesC& aTitle, 
+                               const TDesC& aValue,  
+                               TDes& aItem) const;
+        
+        void AppendItemL(TDes& aMessage,
+                         TInt aResItem, 
+                         const TDesC& aValue, 
+                         TInt aResNotDefined) const; 
+         
+        void AppendResourceL(TDes& aMessage, TInt aResource) const;
+        
+        void AppendResourceAndEnterL(TDes& aMessage, TInt aResource) const;
+                        
+        void AppendValueL(TDes& aMessage, 
+                          const TDesC& aValue, 
+                          TInt aResNotDefined) const;
+        
+        void AppendLocationL(TDes& aMessage, TUid aUid, TInt aItemRes=0) const;         
+        
+        void AppendPinNRsL( TDes& aMessage ) const;   
+
+    private:    // Data
+        // Resource file offsets		
+		TInt		iResourceFileOffset;
+		TInt        iResourceFileOffset2;
+		TInt        iResourceFileOffset3;
+		
+		CSecModUISyncWrapper* iWrapper; // owned             
+		
+		CEikonEnv* iEikEnv;
+		
+		/**
+        * Crypto Token objects
+        */
+        CUnifiedKeyStore* iUnifiedKeyStore; // owned
+        MCTKeyStore* iKeyStore; // not owned
+        MCTAuthenticationObjectList*  iAOList; // owned, items not owned
+        RMPointerArray<MCTAuthenticationObject> iAOArray; // items not owned		
+		                                         
+        RMPointerArray<MCTKeyStore> iAOKeyStores; // items not owned       		                                         
+    };
+
+#endif      // CSecModUIModel_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUIPlugin.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,137 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CSecModUIPlugin class
+*
+*/
+
+
+
+#ifndef CSECMODUIPLUGIN_H
+#define CSECMODUIPLUGIN_H
+
+// Includes
+#include <aknview.h>
+#include <eikclb.h>
+#include <ConeResLoader.h>
+
+#include <gsplugininterface.h>
+
+// Forward declarations
+class CSecModUIModel;
+class CSecModUIPluginContainer;
+class CAknViewAppUi;
+
+// Constants
+
+/**
+* Used for both the view UID and the ECOM plugin implementation UID.
+*/
+const TUid KSecModUIPluginUid = { 0x101F8668 };
+
+// CLASS DECLARATION
+
+/**
+* @since Series60_3.1
+*/
+class CSecModUIPlugin : public CGSPluginInterface
+    {
+
+    public: // Constructors and destructor
+
+        /**
+        * Symbian OS two-phased constructor
+        * @return
+        */
+        static CSecModUIPlugin* NewL( TAny* aInitParams );
+
+        /**
+        * Destructor.
+        */
+        ~CSecModUIPlugin();
+
+    public: // From CAknView
+
+        /**
+        * See base class.
+        *
+        * This function is used also for identifying the plugin so be sure to
+        * return correct UID.
+        */
+        TUid Id() const;
+
+        /**
+        * See base class.
+        */
+        void HandleClientRectChange();
+
+        /**
+        * See base class.
+        */
+        void DoActivateL( const TVwsViewId& aPrevViewId,
+                          TUid aCustomMessageId,
+                          const TDesC8& aCustomMessage );
+
+        /**
+        * See base class.
+        */
+        void DoDeactivate();
+
+        /**
+        * See base class.
+        */
+        void GetCaptionL( TDes& aCaption ) const;
+        
+        /**
+         * See base class.
+         */
+        TBool Visible() const;
+
+    private: // New
+
+        /**
+        * C++ default constructor.
+        */
+        CSecModUIPlugin();
+
+        /**
+        * Symbian OS default constructor.
+        */
+        void ConstructL();
+        
+        /**
+         * Leaving part of Visible() member.
+         */
+        TBool DoIsVisibleL() const;
+
+     private: // Data
+
+        // Pointer to application UI
+        CAknViewAppUi* iAppUi;
+
+        // Resouce loader.
+        RConeResourceLoader iResourceLoader;
+
+        CSecModUIModel* iSecUiModel;
+
+        // Pointer to the container
+        CSecModUIPluginContainer* iContainer;
+
+        //Previous view (Security view)
+        TVwsViewId iPrevViewId;
+
+        CEikonEnv* iEikEnv;
+    };
+
+#endif // CSECMODUIPLUGIN_H
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUIPluginContainer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,71 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CSecModUIPluginContainer class
+*
+*/
+
+
+
+#ifndef CSECMODUIPLUGINCONTAINER_H
+#define CSECMODUIPLUGINCONTAINER_H
+
+// INCLUDES
+#include    <coeccntx.h>
+#include    <eikclb.h>
+
+// CLASS DECLARATION
+
+/**
+*  CSecModUIPluginContainer container class
+*
+*  container class for Security UI Module view
+*/
+class CSecModUIPluginContainer : public CCoeControl
+    {
+    public: // Constructors and destructor
+
+        CSecModUIPluginContainer();
+
+        /**
+        * Symbian OS constructor.
+        *
+        * @param aRect Listbox's rect.
+        */
+        void ConstructL( const TRect& aRect );
+
+        /**
+        * Destructor.
+        */
+        ~CSecModUIPluginContainer();
+
+    public: // From CCoeControl
+
+        /**
+        * From CoeControl returns the amount of controls
+        */
+        TInt CountComponentControls() const;
+
+        /**
+        * From CCoeControl returns controls for CONE actions
+        */
+        CCoeControl* ComponentControl( TInt aIndex ) const;
+
+        /**
+        * From CCoeControl changes the size of the list box
+        */
+        void SizeChanged();
+
+    };
+
+#endif //CSECMODUIPLUGINCONTAINER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUISyncWrapper.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,152 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Wrapper class for Symbian's Security Framework's calls.
+*
+*/
+
+
+#ifndef SECMODUISYNCWRAPPER_H
+#define SECMODUISYNCWRAPPER_H
+
+
+// INCLUDES
+#include <e32base.h>
+#include <f32file.h>
+#include <ct/rcpointerarray.h>
+#include <ct/rmpointerarray.h>
+
+// FORWARD DECLERATIONS
+class MCTToken;
+class MCTAuthenticationObject;
+class MCTAuthenticationObjectList;
+class CUnifiedKeyStore;
+class MCTTokenInterface;
+class CCTKeyInfo;
+class TCTKeyAttributeFilter;
+class MCTKeyStore;
+class TCTTokenObjectHandle;
+// CLASS DECLARATION
+
+/**
+*  class CSecModUISyncWrapper
+*  Wrapper class for Symbian's Security Framework's calls.
+*
+*  @lib wimmanui.dll
+*  @since Series 60 2.0
+*/
+class CSecModUISyncWrapper : public CActive
+    {
+    public:
+
+        /**
+        * Two-phased constructor.
+        */
+        static CSecModUISyncWrapper* NewLC();
+
+        /**
+        * Two-phased constructor.
+        */
+        static CSecModUISyncWrapper* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSecModUISyncWrapper();
+
+    public: // New functions
+
+        /**
+        * TInt ListL
+        * @since S60 2.0
+        * @param aStore reference to store where operation is done.
+        * @param aArray certificates are stored here.
+        * @param aFilter Information on what kind certificates are looked.
+        * @return TInt Status Symbian's API's call.
+        */
+        
+
+        TInt Initialize(CUnifiedKeyStore& aKeyStore );
+
+        TInt OpenWIM();
+
+        TInt GetAuthObjectInterface(
+            MCTToken& aToken, 
+            MCTTokenInterface*& aTokenInterface);
+
+        TInt ListAuthObjects( 
+            MCTAuthenticationObjectList& aAuthObjList, 
+            RMPointerArray<MCTAuthenticationObject>& aAuthObjects );
+                             
+        TInt ListKeys(
+            MCTKeyStore& aKeyStore, 
+            RMPointerArray<CCTKeyInfo>& aKeysInfos, 
+		    const TCTKeyAttributeFilter& aFilter);
+					  
+	    TInt DeleteKey(
+	        CUnifiedKeyStore& aKeyStore, 
+	        TCTTokenObjectHandle aHandle);				                       
+    
+        TInt ChangeReferenceData( MCTAuthenticationObject& aAuthObject );
+
+        TInt UnblockAuthObject( MCTAuthenticationObject& aAuthObject );
+        
+        TInt EnableAuthObject( MCTAuthenticationObject& aAuthObject );
+        
+        TInt DisableAuthObject( MCTAuthenticationObject& aAuthObject );
+        
+        TInt CloseAuthObject( MCTAuthenticationObject& aAuthObject );
+        
+        TInt TimeRemaining( MCTAuthenticationObject& aAuthObject, TInt& aStime );
+
+    protected:
+        
+        void DoCancel();
+	    void RunL();
+
+    private:
+
+        CSecModUISyncWrapper();
+        void HandleErrorL();
+
+    private:    //Data
+
+        // Internal operation states.
+        enum TOperation
+            {
+            EOperationInit,            
+            EOperationGetAOInterface,
+            EOperationListAOs,
+            EOperationListKeys,
+            EOperationDelKey,                                  
+            EOperationChangeReferenceData,
+            EOperationUnblockAO,
+            EOperationEnableAO,
+            EOperationDisableAO,
+            EOperationCloseAO,
+            EOperationTimeRemAO,
+            EOperationNone
+            };
+
+        // For wrapping asynchronous calls.
+        CActiveSchedulerWait    iWait;
+        // Internal state of operation.
+        TOperation              iOperation;
+        
+        // CT objects
+        TAny* iObject;
+    };
+
+#endif // SECMODUISYNCWRAPPER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUIViewAccess.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,130 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CSecModUIViewAccess class
+*
+*/
+
+
+#ifndef SECMODUIVIEWACCESS_H
+#define SECMODUIVIEWACCESS_H
+
+// INCLUDES
+#include "SecModUIViewBase.h"
+
+enum
+    {
+    EIndexCodeLabel = 0,
+    EIndexCodeRequest,
+    EIndexCodeStatus 
+    };
+                
+// FORWARD DECLARATIONS
+class CSecModUIContainerAccess;
+class CSecModUIModel;
+
+// CLASS DECLARATION
+
+/**
+*  CSecModUIViewAccess view class.
+* 
+*/
+class CSecModUIViewAccess : public CSecModUIViewBase
+    {
+    public: // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CSecModUIViewAccess* NewLC(CSecModUIModel& aModel);
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSecModUIViewAccess();
+
+     public: // Functions from base classes
+     
+        /**
+        * From MEikMenuObserver delegate commands from the menu
+        * @param aCommand a command emitted by the menu 
+        * @return void
+        */
+        virtual void HandleCommandL(TInt aCommand);
+        
+        /**
+        * From CAknView returns Uid of View
+        * @return TUid uid of the view
+        */
+        TUid Id() const;
+        
+        void HandleListBoxEventL(CEikListBox* aListBox, TListBoxEvent aEventType);
+        
+        void UpdateCbaL();
+        
+        void SetCbaL( TInt aCbaResourceId );
+        
+        virtual void HandleForegroundEventL(TBool aForeground);
+        
+   protected: // Functions from base classes
+   
+        /**
+        * From CAknView activate the view
+        * @param aPrevViewId 
+        * @param aCustomMessageId 
+        * @param aCustomMessage 
+        * @return void
+        */
+        virtual void DoActivateL(const TVwsViewId& aPrevViewId, TUid aCustomMessageId,
+            const TDesC8& aCustomMessage);
+            
+        /**
+        * From CAknView deactivate the view (free resources)
+        * @return void
+        */
+        virtual void DoDeactivate();  
+           
+    private: // Functions from base classes
+    
+        
+        void CreateContainerL();
+        
+        void DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane);
+        
+        void AddNaviPaneLabelL();
+        
+    private: // New functions
+    
+        void HandleChangeL();
+        
+        void UpdateListBoxItemL(TInt aIndex);
+        
+        void HandleEnterKeyL(TInt aIndex);
+        
+        /**
+        * Constructor
+        */
+        CSecModUIViewAccess(CSecModUIModel& aModel);
+
+        /**
+        * EPOC default constructor.
+        */
+        void ConstructL();
+
+    private: // Data   
+       
+    };
+
+#endif // SECMODUIVIEWACCESS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUIViewBase.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,129 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CSecModUIViewBase class
+*
+*/
+
+
+#ifndef SECMODUIVIEWBASE_H
+#define SECMODUIVIEWBASE_H
+
+// INCLUDES
+#include <aknview.h>
+#include <eiklbo.h>
+
+// CONSTANTS
+enum TCurrentMSK
+     {
+     EEmpty,
+     EChange,
+     EUnblock,
+     EClose
+     };
+     
+// FORWARD DECLARATIONS
+class CSecModUIContainerBase;
+class CSecModUIModel;
+class CAknNavigationDecorator;
+
+// CLASS DECLARATION
+
+/**
+*  CSecModUIViewBase view class.
+* 
+*/
+class CSecModUIViewBase : public CAknView, public MEikListBoxObserver
+    {
+    public: // Constructors and destructor
+                
+        /**
+        * Constructor
+        */
+        CSecModUIViewBase(CSecModUIModel& aModel);
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CSecModUIViewBase();
+
+    public: // Functions from CAknView 
+
+        /**
+        * From MEikMenuObserver delegate commands from the menu
+        * @param aCommand a command emitted by the menu 
+        * @return void
+        */
+        virtual void HandleCommandL(TInt aCommand);
+
+        /**
+        * From CAknView reaction if size change
+        * @return void
+        */
+        virtual void HandleClientRectChange();
+      
+    public: // Function from MEikListBoxObserver
+    
+        void HandleListBoxEventL(CEikListBox* aListBox, TListBoxEvent aEventType);
+        
+    protected:
+    
+        virtual void CreateContainerL()=0;
+        
+        virtual void SetTitlePaneL();
+        
+        virtual void AddNaviPaneLabelL();        
+        
+        virtual void DoAddNaviPaneL(TInt aResource = 0);
+        
+        /**
+        * From CAknView activate the view
+        * @param aPrevViewId 
+        * @param aCustomMessageId 
+        * @param aCustomMessage 
+        * @return void
+        */
+        virtual void DoActivateL(const TVwsViewId& aPrevViewId, TUid aCustomMessageId,
+            const TDesC8& aCustomMessage);
+            
+        /**
+        * From CAknView deactivate the view (free resources)
+        * @return void
+        */
+        virtual void DoDeactivate();         
+
+    protected:
+        CSecModUIContainerBase* iContainer;
+        CSecModUIModel& iModel;    
+        TVwsViewId  iPrevViewId;
+    
+    private: // Data
+        /**
+        * For Navipane
+        */
+        CAknNavigationDecorator*		iNaviDecorator;        
+ 
+        /**
+        * To store the position of the focus in the Authority view
+        */
+        TInt    iCurrentPosition;
+
+        /**
+        * Stores top item in the listbox
+        */
+        TInt  iTopItem;     
+    };
+
+#endif // SECMODUIVIEWBASE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUIViewCode.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,108 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CSecModUIViewCode class
+*
+*/
+
+
+#ifndef SECMODUIVIEWCODE_H
+#define SECMODUIVIEWCODE_H
+
+// INCLUDES
+#include "SecModUIViewBase.h"
+
+
+// CONSTANTS
+
+// FORWARD DECLARATIONS
+class CSecModUIContainerCode;
+class CSecModUIModel;
+
+// CLASS DECLARATION
+
+/**
+*  CSecModUIViewCode view class.
+* 
+*/
+class CSecModUIViewCode : public CSecModUIViewBase
+    {
+    public: // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CSecModUIViewCode* NewLC(CSecModUIModel& aModel);
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSecModUIViewCode();
+
+    public: // Functions from base classes
+        
+        /**
+        * From MEikMenuObserver delegate commands from the menu
+        * @param aCommand a command emitted by the menu 
+        * @return void
+        */
+        virtual void HandleCommandL(TInt aCommand);
+        
+        /**
+        * From CAknView returns Uid of View
+        * @return TUid uid of the view
+        */
+        TUid Id() const;
+        
+        void HandleListBoxEventL(
+            CEikListBox* aListBox, 
+            TListBoxEvent aEventType);
+        
+   //protected: // Functions from base classes
+   
+        /**
+        * From CAknView activate the view
+        * @param aPrevViewId 
+        * @param aCustomMessageId 
+        * @param aCustomMessage 
+        * @return void
+        */
+        //virtual void DoActivateL(const TVwsViewId& aPrevViewId, TUid aCustomMessageId,
+        //    const TDesC8& aCustomMessage);
+            
+        /**
+        * From CAknView deactivate the view (free resources)
+        * @return void
+        */
+        //virtual void DoDeactivate();                 
+
+    private: // Functions from base classes
+    
+        void CreateContainerL();
+        
+        /**
+        * Constructor
+        */
+        CSecModUIViewCode(CSecModUIModel& aModel);
+
+        /**
+        * EPOC default constructor.
+        */
+        void ConstructL();
+
+    private: // Data
+    };
+
+#endif // SECMODUIVIEWCODE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUIViewMain.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,129 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CSecModUIViewMain class
+*
+*/
+
+
+#ifndef SECMODUIVIEWMAIN_H
+#define SECMODUIVIEWMAIN_H
+
+// INCLUDES
+#include "SecModUIViewBase.h"
+#include <aknview.h>
+
+
+// CONSTANTS
+
+
+// FORWARD DECLARATIONS
+class CSecModUIContainerMain;
+class CSecModUIModel;
+
+// CLASS DECLARATION
+
+/**
+*  CSecModUIViewMain view class.
+* 
+*/
+class CSecModUIViewMain : public CSecModUIViewBase
+    {
+    public: // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CSecModUIViewMain* NewLC(CSecModUIModel& aModel);
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSecModUIViewMain();
+
+    public: // Functions from base classes
+    
+        /**
+        * From MEikMenuObserver delegate commands from the menu
+        * @param aCommand a command emitted by the menu 
+        * @return void
+        */
+        virtual void HandleCommandL(TInt aCommand);
+        
+        /**
+        * From CAknView returns Uid of View
+        * @return TUid uid of the view
+        */
+        TUid Id() const;
+    
+        void HandleListBoxEventL(
+            CEikListBox* aListBox, 
+            TListBoxEvent aEventType);
+    
+    private: // Functions from base classes
+    
+        
+        /**
+        * From CAknView activate the view
+        * @param aPrevViewId 
+        * @param aCustomMessageId 
+        * @param aCustomMessage 
+        * @return void
+        */
+        void DoActivateL(
+            const TVwsViewId& aPrevViewId,
+            TUid aCustomMessageId,
+            const TDesC8& aCustomMessage);
+        
+        /**
+        * From CSecModUIViewBase create container
+        * @return void
+        */    
+        void CreateContainerL();
+        
+        /**
+        * From CSecModUIViewBase set title pane
+        * @return void
+        */    
+        void SetTitlePaneL();
+        
+        /**
+        * Constructor
+        */
+        CSecModUIViewMain(CSecModUIModel& aModel);
+
+        /**
+        * EPOC default constructor.
+        */
+        void ConstructL();
+        
+        /**
+        * From MEikMenuObserver
+		* Updates Options list with correct items depending on 
+		* whether the listbox is empty or if it has any marked items
+        */
+		void DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane);
+		
+		void UpdateCbaL();
+
+        void SetCbaL( TInt aCbaResourceId );
+        
+        void HandleForegroundEventL(TBool aForeground);
+        
+    private: // Data
+        
+    };
+
+#endif // SECMODUIVIEWMAIN_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/SecModUIViewSignature.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,106 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Declaration of the CSecModUIViewSignature class
+*
+*/
+
+
+#ifndef SECMODUIVIEWSIGNATURE_H
+#define SECMODUIVIEWSIGNATURE_H
+
+// INCLUDES
+#include "SecModUIViewBase.h"
+
+// CONSTANTS
+
+// FORWARD DECLARATIONS
+class CSecModUIContainerSignature;
+class CSecModUIModel;
+
+// CLASS DECLARATION
+
+/**
+*  CSecModUIViewSignature view class.
+* 
+*/
+class CSecModUIViewSignature : public CSecModUIViewBase
+    {
+    public: // Constructors and destructor
+
+         /**
+        * Two-phased constructor.
+        */
+        static CSecModUIViewSignature* NewLC(CSecModUIModel& aModel);
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSecModUIViewSignature();
+
+    public: // Functions from base classes
+     
+        /**
+        * From MEikMenuObserver delegate commands from the menu
+        * @param aCommand a command emitted by the menu 
+        * @return void
+        */
+        virtual void HandleCommandL(TInt aCommand);
+        
+        /**
+        * From CAknView returns Uid of View
+        * @return TUid uid of the view
+        */
+        TUid Id() const;
+        
+        void HandleListBoxEventL(CEikListBox* aListBox, TListBoxEvent aEventType);
+        
+        void UpdateCbaL(TInt aIndex);
+        
+        void SetCbaL( TInt aCbaResourceId );
+        
+   protected: // Functions from base classes
+   
+     
+        virtual void DoActivateL(const TVwsViewId& aPrevViewId, TUid aCustomMessageId,
+            const TDesC8& aCustomMessage);
+            
+        virtual void DoDeactivate();  
+        
+    private: // Functions from base classes
+    
+        void CreateContainerL();
+        
+        void DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane);
+        
+        void AddNaviPaneLabelL();
+        
+    private: // New funtions
+        
+        /**
+        * Constructor
+        */
+        CSecModUIViewSignature(CSecModUIModel& aModel);
+
+        /**
+        * EPOC default constructor.
+        */
+        void ConstructL();
+
+    private: // Data  
+    
+    };
+
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/secmodui.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,42 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Interface of the Security Module UI DLL
+*
+*/
+
+#ifndef SECMODUI_HRH
+#define SECMODUI_HRH
+
+enum TSecModUICommandIds
+    {
+    ESecModUICmdOpen = 1,
+    ESecModUICmdModuleInfo,
+    ESecModUICmdDelKeyStore,
+    ESecModUICmdChange,
+    ESecModUICmdUnblock,
+    ESecModUICmdClose,    
+    ESecModUICmdAppTest    
+    };
+
+enum TSecModUITabViewId
+    {
+    ESecModUIView1Tab= 1,
+    ESecModUIView2Tab
+    };
+ 
+
+
+
+
+#endif      // SECMODUI_HRH
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/inc/wim.hlp.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+//
+// wim.hlp.hrh
+//
+
+//
+// File generated by cshlpcmp Version 011
+//
+
+#ifndef __WIM_HLP_HRH__
+#define __WIM_HLP_HRH__
+
+
+_LIT(KSECMOD_HLP_MAIN_VIEW,"SECMOD_HLP_MAIN_VIEW"); //Security module view
+_LIT(KSECMOD_HLP_CODE_VIEW,"SECMOD_HLP_CODE_VIEW"); //Code selection view
+_LIT(KSECMOD_HLP_ACCESSCODE_VIEW,"SECMOD_HLP_ACCESSCODE_VIEW");
+_LIT(KSEMOD_HLP_SIGNINGCODE_VIEW,"SEMOD_HLP_SIGNINGCODE_VIEW"); //Signing code view
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/loc/secmodui.loc	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,269 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Localisation strings of Security Module UI
+*
+*/
+
+
+
+// LOCALISATION STRINGS
+
+
+//d: Command in general settings security folder, opens Security Module view
+//l: title_pane_t2/opt9
+//w:
+//r:3.0
+#define qtn_wim_settings "Security module"
+
+//d:Title of main view
+//l:title_pane_t2/opt9
+//w:
+//r:3.2
+#define qtn_wim_title "Security module"
+
+//d:Command in options menu.
+//d:Opens highlighted item
+//l:list_single_pane_t1_cp2
+//w:
+//r:3.0
+#define qtn_wim_options_open "Open"
+
+//d:Command in options menu.
+//d:Views details of the highlighted token
+//l:list_single_pane_t1_cp2
+//w:
+//r:3.0
+#define qtn_wim_opt_details "Module info"
+
+//d:Command in options menu.
+//l:list_single_pane_t1_cp2
+//w:
+//r:3.0
+#define qtn_cm_options_delete_keystore "Delete keystore"
+
+//d:Command in options menu.
+//l:list_single_pane_t1_cp2
+//w:
+//r:3.0
+#define qtn_wim_sett_opt_unblock "Unblock"
+
+//d:Command in options menu.
+//l:list_single_pane_t1_cp2
+//w:
+//r:3.0
+#define qtn_wim_options_close_code "Close access code"
+
+//d:WIM Main view empty list placeholder text
+//l:main_list_empty_pane
+//w:
+//r:3.0
+#define qtn_wim_no_wims "(no security modules)"
+
+//d:Selection list item
+//d:
+//l:list_single_pane_t1_cp2
+//w:
+//r:3.0
+#define qtn_wim_list_text_access_code "Access code"
+
+//d:Selection list item
+//d:
+//l:list_single_pane_t1_cp2
+//w:
+//r:3.0
+#define qtn_wim_list_text_signature_codes "Signing codes"
+
+//d:Setting item title
+//d:
+//l:list_setting_pane_t1
+//w:
+//r:3.0
+#define qtn_wim_pin_request "Access code request"
+
+//d:Setting value text
+//d:
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define qtn_wim_request_on "On"
+
+//d:Setting value text
+//d:
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define qtn_wim_request_off "Off"
+
+//d:Setting item title
+//d:
+//l:list_setting_pane_t1
+//w:
+//r:3.0
+#define qtn_wim_sett_status "Status"
+
+//d:Setting value text
+//d:
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define qtn_wim_opt_open "Open"
+
+//d:Setting value text
+//d:
+//l:popup_info_list_pane_t1
+//w:
+//r:3.0
+#define qtn_wim_status_closed "Closed"
+
+//d:Setting value text
+//d:
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define qtn_wim_code_status_blocked "Blocked"
+
+//d:Wait note text shown when retrieving data from Security Module
+//l:popup_note_wait_window
+//w:
+//r:3.0
+#define qtn_wim_retrieving_data "Retrieving data from the Security Module."
+
+//d:Setting item title
+//d:Shown if Security Module has no label
+//l:list_double_pane_t1
+//w:
+//r:3.0
+#define qtn_wim_no_label_list "(no label)"
+
+//d:Security Module details heading
+//l:heading_pane_t1
+//w:
+//r:3.0
+#define qtn_wim_info_header "Module Info"
+
+//d:Details view field names.
+//l:main_list_empty_pane
+//w:
+//r:3.0
+#define qtn_wim_name "Name:"
+
+//d:Details view field names.
+//l:main_list_empty_pane
+//w:
+//r:3.0
+#define qtn_wim_card_version "Version:"
+
+//d:Details view field names.
+//l:main_list_empty_pane
+//w:
+//r:3.0
+#define qtn_wim_security_module_location "Security module location:"
+
+//d:Details view field names.
+//l:main_list_empty_pane
+#define qtn_wim_sett_pin_g "Access code:"
+
+//d:Details view field names.
+//l:main_list_empty_pane
+#define qtn_wim_key_pin	"Signing code:"
+
+//d:Details view field names.
+//l:main_list_empty_pane
+//w:
+//r:3.0
+#define qtn_wim_serial_nro "Serial number:"
+
+//d:Details view field names.
+//l:main_list_empty_pane
+//w:
+//r:3.0
+#define qtn_wim_manuf "Manufacturer:"
+
+//d:Details view field value.
+//d:Used in module info message popup,
+//l:popup_info_list_pane_t1
+//w:
+//r:3.0
+#define qtn_wim_pin_g_no_label_details "Access code"
+
+//d:Details view field value.
+//d:Used in module info message popup,
+//l:popup_info_list_pane_t1
+//w:
+//r:3.0
+#define qtn_wim_pin_nr_no_label_details "Signing code %N"
+
+//d:Confirmation query text when deleting keys
+//l:popup_note_window
+//w:
+//r:2.8
+#define qtn_cm_confirm_delete_keys "All private keys will be deleted. Continue?"
+
+//d:Phone keystore title pane text
+//l:title_pane_t2/opt9
+//w:
+//r:3.0
+#define qtn_keystore_title_phone_keystore "Phone keystore"
+
+//d:Details view changeable item value
+//l:list_double_pane_t1
+//w:
+//r:3.0
+#define qtn_keystore_list_text_phone_keystore "Phone keystore"
+
+//d:Access code view navi pane text
+//l:navi_text_pane_t1
+//w:
+//r:3.0
+#define qtn_wim_navi_text_access_codes "Access code"
+
+//d:Signature code view navi pane text
+//l:navi_text_pane_t1
+//w:
+//r:3.0
+#define qtn_wim_navi_text_signature_codes "Signing codes"
+
+//d:Confirmation note shown after code change
+//d:
+//l:popup_note_window
+//w:
+//r:3.0
+#define qtn_wim_info_pin_changed "Code changed"
+
+//d:Information note shown if key is in use when trying to delete keystore.
+//l:popup_note_window
+//w:
+//r:3.0
+#define qtn_keystore_info_unable_to_delete "Key is currently in use. Unable to delete. Close applications and try again."
+
+//d:Setting value text
+//d:
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define qtn_secmod_status_value_blocked "Blocked"
+
+//d:Setting item title
+//l:list_setting_pane_t1
+//w:
+//r:3.0
+#define qtn_secmod_title_phone_keystore_code "Phone keystore code"
+
+//d: Middle soft key label for unblock
+//l:  control_pane_t3/opt7
+//w:
+//r:3.2
+#define qtn_msk_unblock "Unblock"
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUIContainerAccess.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,81 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecModUIContainerAccess class
+*
+*/
+
+
+// INCLUDE FILES
+#include "SecModUIContainerAccess.h"
+#include "SecModUIModel.h"
+#include "wim.hlp.hrh"
+#include <SecModUI.rsg>
+#include <aknlists.h>
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CSecModUIContainerAccess::CSecModUIContainerAccess(
+//     CSecModUIModel& aModel)
+// Constructor
+// ---------------------------------------------------------
+//
+CSecModUIContainerAccess::CSecModUIContainerAccess(CSecModUIModel& aModel, CSecModUIViewAccess* aView)
+    :CSecModUIContainerBase(aModel, KSECMOD_HLP_ACCESSCODE_VIEW)
+    {  
+    iView = aView;  
+	}
+
+// Destructor
+CSecModUIContainerAccess::~CSecModUIContainerAccess()
+    {
+    }
+
+// ---------------------------------------------------------
+// CSecModUIContainerSignature::ConstructListL()
+// Constructs listbox
+// ---------------------------------------------------------
+//
+void CSecModUIContainerAccess::ConstructListL()	
+    {
+    iListBox = new (ELeave) CAknSettingStyleListBox();
+    iListBox->SetObserver(this);
+    }
+
+
+// ---------------------------------------------------------
+// CSecModUIContainerAccess::SetupListItemsL()
+// Setups list items to listbox.
+// ---------------------------------------------------------
+//	
+void CSecModUIContainerAccess::SetupListItemsL()
+    {
+    iModel.LoadPinGItemsL(*iListBox);
+    }   
+
+// ---------------------------------------------------------
+// CSecModUIContainerAccess::HandleControlEventL()
+// Notify the highlight move event
+// ---------------------------------------------------------
+//    
+void CSecModUIContainerAccess::HandleControlEventL(CCoeControl* /*aControl*/,
+                                               TCoeEvent aEventType)
+    {
+	if( aEventType == EEventStateChanged )
+	    {
+	    iView->UpdateCbaL();	
+	    }
+    }     
+
+// End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUIContainerBase.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,233 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecModUIContainerBase class
+*
+*/
+
+
+// INCLUDE FILES
+#include "SecModUIContainerBase.h"
+#include "SecModUIModel.h"
+#include "SecModUILogger.h"
+#include <SecModUI.rsg>
+#include <aknlists.h>
+#include <barsread.h>
+#include <StringLoader.h>
+
+// ================= MEMBER FUNCTIONS =======================
+CSecModUIContainerBase::CSecModUIContainerBase(
+    CSecModUIModel& aModel,
+    const TDesC& aContextName)
+    :iModel(aModel), iContextName(aContextName)
+    {
+    LOG_WRITE( "CSecModUIContainerBase::CSecModUIContainerBase" );
+	}
+
+// ---------------------------------------------------------
+// CSecModUIContainerBase::ConstructL(const TRect& aRect)
+// EPOC two phased constructor
+// ---------------------------------------------------------
+//
+void CSecModUIContainerBase::ConstructL(const TRect& aRect)
+    {
+    CreateWindowL();
+    CreateListL();
+    SetupListItemsL();
+    SetRect(aRect);
+    }
+
+// Destructor
+CSecModUIContainerBase::~CSecModUIContainerBase()
+    {
+    LOG_ENTERFN("CSecModUIContainerBase::~CSecModUIContainerBase()");              
+    delete iListBox;
+    LOG_LEAVEFN("CSecModUIContainerBase::~CSecModUIContainerBase()");
+	}
+
+// ---------------------------------------------------------
+// CSecModUIContainerBase::ConstructListL()
+// Constructs listbox
+// ---------------------------------------------------------
+//
+void CSecModUIContainerBase::ConstructListL()	
+    {
+    LOG_ENTERFN("CSecModUIContainerBase::ConstructListL()");   
+    iListBox = new (ELeave) CAknSingleStyleListBox();
+    LOG_LEAVEFN("CSecModUIContainerBase::ConstructListL()");    
+    }
+
+// ---------------------------------------------------------
+// CSecModUIContainerBase::ListBox()
+// 
+// ---------------------------------------------------------
+//
+CEikTextListBox& CSecModUIContainerBase::ListBox()
+    {
+    return *iListBox;
+    }
+
+// ---------------------------------------------------------
+// CSecModUIContainerBase::CreateResourceReaderLC(
+//  TResourceReader& aReader)
+// 
+// ---------------------------------------------------------
+//
+void CSecModUIContainerBase::CreateResourceReaderLC(TResourceReader& aReader)	
+    {
+    LOG_ENTERFN("CSecModUIContainerBase::CreateResourceReaderLC()");   
+    iEikonEnv->CreateResourceReaderLC(aReader, R_SECMODUI_DYNAMIC_LISTBOX);
+    LOG_LEAVEFN("CSecModUIContainerBase::CreateResourceReaderLC()");    
+    }
+
+// ---------------------------------------------------------
+// CSecModUIContainerBase::CreateListL()
+// Constructs listbox from resource
+// ---------------------------------------------------------
+//	
+void CSecModUIContainerBase::CreateListL()
+    {
+    LOG_ENTERFN("CSecModUIContainerBase::CreateListL()");   
+    ConstructListL();
+    __ASSERT_ALWAYS(iListBox, Panic(EPanicNullPointer));
+    iListBox->SetContainerWindowL(*this);
+    
+    iListBox->CreateScrollBarFrameL(ETrue);
+	iListBox->ScrollBarFrame()->SetScrollBarVisibilityL(
+	    CEikScrollBarFrame::EOff,CEikScrollBarFrame::EAuto);
+    
+    TResourceReader reader;
+    
+    CreateResourceReaderLC(reader);
+    iListBox->ConstructFromResourceL(reader);
+    CleanupStack::PopAndDestroy(); // reader
+    
+    HBufC* stringHolder = StringLoader::LoadLC(R_TEXT_RESOURCE_VIEW_EMPTY_WIM_LIST);
+	iListBox->View()->SetListEmptyTextL(*stringHolder);
+	CleanupStack::PopAndDestroy(stringHolder);
+	LOG_LEAVEFN("CSecModUIContainerBase::CreateListL()");    
+    }
+    
+// ---------------------------------------------------------
+// CSecModUIContainerBase::SetupListItemsL()
+// Setups list items to listbox.
+// ---------------------------------------------------------
+//	
+void CSecModUIContainerBase::SetupListItemsL()
+    {
+    LOG_ENTERFN("CSecModUIContainerBase::SetupListItemsL()");   
+    LOG_LEAVEFN("CSecModUIContainerBase::SetupListItemsL()");    
+    }
+
+// ---------------------------------------------------------
+// CSecModUIContainerBase::SizeChanged()
+// Called by framework when the view size is changed
+// ---------------------------------------------------------
+//
+void CSecModUIContainerBase::SizeChanged()
+    {
+    LOG_ENTERFN("CSecModUIContainerBase::SizeChanged()");   
+    __ASSERT_ALWAYS(iListBox, Panic(EPanicNullPointer));
+    iListBox->SetRect(Rect());
+    LOG_LEAVEFN("CSecModUIContainerBase::SizeChanged()");    
+    }
+
+// ---------------------------------------------------------
+// CSecModUIContainerBase::CountComponentControls() const
+// ---------------------------------------------------------
+//
+TInt CSecModUIContainerBase::CountComponentControls() const
+    {
+    LOG_ENTERFN("CSecModUIContainerBase::CountComponentControls()");   
+    LOG_LEAVEFN("CSecModUIContainerBase::CountComponentControls()");    
+    return 1;
+    }
+
+// ---------------------------------------------------------
+// CSecModUIContainerBase::ComponentControl(TInt aIndex) const
+// ---------------------------------------------------------
+//
+CCoeControl* CSecModUIContainerBase::ComponentControl(TInt aIndex) const
+    {
+    LOG_ENTERFN("CSecModUIContainerBase::ComponentControl()");   
+    LOG_LEAVEFN("CSecModUIContainerBase::ComponentControl()");    
+    switch ( aIndex )
+        {
+        case 0:
+            return iListBox;           
+        default:
+            return NULL;
+        }
+    }
+    
+// ---------------------------------------------------------
+// CSecModUIContainerBase::OfferKeyEventL(
+//     const TKeyEvent& aKeyEvent,TEventCode aType)
+// ---------------------------------------------------------
+//
+TKeyResponse CSecModUIContainerBase::OfferKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType)
+    {
+    if (iModel.Wrapper().IsActive())
+        {
+        // Do not start new operation, if previous is still ongoing.
+        return EKeyWasConsumed;
+        }
+    LOG_ENTERFN("CSecModUIContainerBase::OfferKeyEventL()");   
+    LOG_LEAVEFN("CSecModUIContainerBase::OfferKeyEventL()");    
+    return iListBox->OfferKeyEventL(aKeyEvent, aType);
+    }
+    
+// ---------------------------------------------------------
+// CCertManUIContainerAuthority::HandleResourceChange
+// 
+// ---------------------------------------------------------
+//
+void CSecModUIContainerBase::HandleResourceChange(TInt aType)
+    {        
+    CCoeControl::HandleResourceChange(aType);        
+    if (aType == KEikDynamicLayoutVariantSwitch)
+        {		
+        TRect mainPaneRect;
+        AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EMainPane, mainPaneRect);
+        SetRect(mainPaneRect);
+		DrawDeferred();
+        }  
+    }
+
+
+// ---------------------------------------------------------
+// CSecModUIContainerBase::GetHelpContext
+// This function is called when Help application is launched.  
+// (other items were commented in a header).
+// ---------------------------------------------------------
+//
+void CSecModUIContainerBase::GetHelpContext( 
+    TCoeHelpContext& aContext ) const
+    {
+	aContext.iMajor = KUidSecMod;
+    aContext.iContext = iContextName;
+    }
+
+
+// ---------------------------------------------------------
+// CSecModUIContainerBase::FocusChanged(TDrawNow aDrawNow)
+// ---------------------------------------------------------
+//
+void CSecModUIContainerBase::FocusChanged( TDrawNow aDrawNow )
+    {
+    if ( iListBox )
+        {
+        iListBox->SetFocus( IsFocused(), aDrawNow );
+        }
+    }
+// End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUIContainerCode.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,75 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecModUIContainerCode class
+*
+*/
+
+
+// INCLUDE FILES
+#include "SecModUIContainerCode.h"
+#include "SecModUIModel.h"
+#include "SecModUILogger.h"
+#include "wim.hlp.hrh"
+#include <SecModUI.rsg>
+#include <aknlists.h>
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CSecModUIContainerCode::CSecModUIContainerCode(
+//     CSecModUIModel& aModel)
+// Constructor
+// ---------------------------------------------------------
+//
+CSecModUIContainerCode::CSecModUIContainerCode(CSecModUIModel& aModel)
+    :CSecModUIContainerBase(aModel, KSECMOD_HLP_CODE_VIEW)
+    {    
+	}
+
+// Destructor
+CSecModUIContainerCode::~CSecModUIContainerCode()
+    {
+    LOG_ENTERFN( "CSecModUIContainerCode::~CSecModUIContainerCode" );
+    LOG_LEAVEFN( "CSecModUIContainerCode::~CSecModUIContainerCode" );
+    }
+    
+// ---------------------------------------------------------
+// CSecModUIContainerBase::CreateResourceReaderLC(
+//  TResourceReader& aReader)
+// 
+// ---------------------------------------------------------
+//
+void CSecModUIContainerCode::CreateResourceReaderLC(TResourceReader& aReader)	
+    {
+    LOG_ENTERFN( "CSecModUIContainerCode::CreateResourceReaderLC" );
+    iEikonEnv->CreateResourceReaderLC(aReader, R_SECMODUI_CODES_LISTBOX);
+    LOG_LEAVEFN( "CSecModUIContainerCode::CreateResourceReaderLC" );
+    }
+
+// ---------------------------------------------------------
+// CSecModUIContainerCode::SetupListItemsL()
+// Setups list items to listbox.
+// ---------------------------------------------------------
+//	
+void CSecModUIContainerCode::SetupListItemsL()
+    {
+    LOG_ENTERFN( "CSecModUIContainerCode::SetupListItemsL" );
+    CTextListBoxModel* model = iListBox->Model();
+    //model->SetOwnershipType(
+    CDesCArray* itemArray = STATIC_CAST(CDesCArray*, model->ItemTextArray());
+    iModel.CheckCodeViewStringsL(*itemArray);
+    LOG_LEAVEFN( "CSecModUIContainerCode::SetupListItemsL" );
+    }    
+ 
+// End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUIContainerMain.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,65 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecModUIContainerMain class
+*
+*/
+
+
+// INCLUDE FILES
+#include "SecModUIContainerMain.h"
+#include "SecModUIModel.h"
+#include "SecModUILogger.h"
+#include "wim.hlp.hrh"
+#include <SecModUI.rsg>
+#include <aknlists.h>
+#include <barsread.h>
+#include <StringLoader.h>
+
+
+// ================= MEMBER FUNCTIONS =======================
+CSecModUIContainerMain::CSecModUIContainerMain(CSecModUIModel& aModel)
+    :CSecModUIContainerBase(aModel, KSECMOD_HLP_MAIN_VIEW)
+    {    
+	}
+
+// Destructor
+CSecModUIContainerMain::~CSecModUIContainerMain()
+    { 
+    LOG_ENTERFN("CSecModUIContainerMain::~CSecModUIContainerMain()");   
+    LOG_LEAVEFN("CSecModUIContainerMain::~CSecModUIContainerMain()");       
+	}
+
+// ---------------------------------------------------------
+// CSecModUIContainerSignature::ConstructListL()
+// Constructs listbox
+// ---------------------------------------------------------
+//
+void CSecModUIContainerMain::ConstructListL()	
+    {
+    iListBox = new (ELeave) CAknDoubleStyleListBox();
+    }
+	
+// ---------------------------------------------------------
+// CSecModUIContainerMain::SetupListItemsL()
+// Setups list items to listbox.
+// ---------------------------------------------------------
+//	
+void CSecModUIContainerMain::SetupListItemsL()
+    {
+    LOG_ENTERFN("CSecModUIContainerMain::SetupListItemsL()");   
+    iModel.LoadTokenLabelsL(*iListBox);
+    LOG_LEAVEFN("CSecModUIContainerMain::SetupListItemsL()");   
+    }
+       
+// End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUIContainerSignature.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,81 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecModUIContainerSignature class
+*
+*/
+
+
+// INCLUDE FILES
+#include "SecModUIContainerSignature.h"
+#include "SecModUIModel.h"
+#include "wim.hlp.hrh"
+#include <SecModUI.rsg>
+#include <aknlists.h>
+
+// ================= MEMBER FUNCTIONS =======================
+// ---------------------------------------------------------
+// CSecModUIContainerSignature::CSecModUIContainerSignature(
+//     CSecModUIModel& aModel)
+// Constructor
+// ---------------------------------------------------------
+//
+CSecModUIContainerSignature::CSecModUIContainerSignature(CSecModUIModel& aModel, CSecModUIViewSignature* aView )
+    :CSecModUIContainerBase(aModel, KSEMOD_HLP_SIGNINGCODE_VIEW)
+    {    
+    iView = aView;
+	}
+
+// Destructor
+CSecModUIContainerSignature::~CSecModUIContainerSignature()
+    {
+    
+    }
+
+// ---------------------------------------------------------
+// CSecModUIContainerSignature::ConstructListL()
+// Constructs listbox
+// ---------------------------------------------------------
+//
+void CSecModUIContainerSignature::ConstructListL()	
+    {
+    iListBox = new (ELeave) CAknSettingStyleListBox();
+    iListBox->SetObserver( this );
+    }
+
+// ---------------------------------------------------------
+// CSecModUIContainerSignature::SetupListItemsL()
+// Setups list items to listbox.
+// ---------------------------------------------------------
+//	
+void CSecModUIContainerSignature::SetupListItemsL()
+    {
+    iModel.LoadPinNRLabelsL(*iListBox, ETrue);
+    }    
+
+// ---------------------------------------------------------
+// CSecModUIContainerSignature::HandleControlEventL()
+// 
+// ---------------------------------------------------------
+// 
+void CSecModUIContainerSignature::HandleControlEventL(CCoeControl* /*aControl*/,
+                                               TCoeEvent aEventType)
+    {
+	if( aEventType == EEventStateChanged )
+	    {
+	    iView->UpdateCbaL(iListBox->CurrentItemIndex());	
+	    }
+    }     
+       
+
+// End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUIModel.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1384 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecModUIModel class
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "SecModUI.h"
+#include    "SecModUIModel.h"
+#include    "SecModUIViewAccess.h"
+#include    "SecModUIViewCode.h"
+#include    "SecModUIViewMain.h"
+#include    "SecModUIViewSignature.h"
+#include    "SecModUISyncWrapper.h"
+#include    "SecModUILogger.h"
+#include    <SecModUI.rsg>
+#include    <certmanui.rsg>
+#include    <CTSecDlgs.rsg>
+#include    <aknViewAppUi.h>
+#include    <AknUtils.h>
+#include    <data_caging_path_literals.hrh>
+#include    <bautils.h>
+#include    <unifiedkeystore.h>
+#include    <aknlists.h>
+#include    <mctauthobject.h>
+#include    <aknnotewrappers.h>
+#include    <StringLoader.h>
+#include    <mctkeystore.h>
+#include    <akntitle.h>
+#include    <aknmessagequerydialog.h>
+#include    <eikenv.h>
+#include    <securityerr.h>
+#include    <AknGlobalNote.h>
+
+// CONSTANTS
+_LIT(KResourceFile, "z:SecModUI.rsc");
+_LIT(KResourceFile2, "z:CertManUI.rsc");
+_LIT(KResourceFile3, "z:CTsecdlgs.rsc");
+_LIT(KTab, " \t");
+_LIT(KDoubleTab, "\t\t");
+_LIT(KFourAsterisks,"****");
+_LIT(KEnter, "\n");
+_LIT(KDoubleEnter, "\n\n");
+
+_LIT(KSecModUIPanic, "Security Module UI panic");
+
+const TInt KMaxLengthTextDetailsBody = 750;
+const TInt KMaxLengthItemValue = 100;
+const TInt KWIMStoreUid ( 0x101F79D9 );
+const TInt KItemLength (200);
+
+// ============================= LOCAL FUNCTIONS ===============================
+GLDEF_C void Panic(TInt aPanic)
+  {
+  User::Panic(KSecModUIPanic, aPanic);
+  }
+
+// ============================ MEMBER FUNCTIONS ===============================
+#ifndef RD_GS_RENOVATION
+EXPORT_C MSecModUI* MSecModUI::CreateL()
+    {
+    LOG_CREATE;
+    LOG_ENTERFN("MSecModUI::CreateL()");
+    LOG_LEAVEFN("MSecModUI::CreateL()");
+    return CSecModUIModel::NewL();
+    }
+#endif
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::CSecModUIModel
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CSecModUIModel::CSecModUIModel()
+    {
+  LOG_WRITE( "CSecModUIModel::CSecModUIModel" );
+    }
+
+// Destructor
+CSecModUIModel::~CSecModUIModel()
+    {
+    LOG_ENTERFN("CSecModUIModel::~CSecModUIModel");    
+    delete iWrapper;
+    if ( iResourceFileOffset )
+        {
+    iEikEnv->DeleteResourceFile( iResourceFileOffset );
+        }
+    if ( iResourceFileOffset2 )
+        {
+    iEikEnv->DeleteResourceFile( iResourceFileOffset2 );
+        }
+    if ( iResourceFileOffset3 )
+        {
+    iEikEnv->DeleteResourceFile( iResourceFileOffset3 );
+        }    
+    ResetAndDestroyCTObjects();
+    LOG_LEAVEFN("CSecModUIModel::~CSecModUIModel");
+    LOG_DELETE;
+    }
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ResetAndDestroyCTObjects()
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ResetAndDestroyCTObjects()
+    {
+    LOG_ENTERFN("CSecModUIModel::ResetAndDestroyCTObjects()");
+
+    ResetAndDestroyAOs();
+    
+    iAOKeyStores.Reset();
+
+    delete iUnifiedKeyStore;
+    iUnifiedKeyStore = NULL;
+    iKeyStore = NULL;
+    LOG_LEAVEFN("CSecModUIModel::ResetAndDestroyCTObjects()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ResetAndDestroyAOs()
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ResetAndDestroyAOs()
+    {
+    LOG_ENTERFN("CSecModUIModel::ResetAndDestroyAOs()");
+    if (iAOList)
+        {
+        iAOList->Release();
+        iAOList = NULL;
+        }
+    if (iAOArray.Count() > 0 &&
+        iAOArray[0]->Token().TokenType().Type().iUid == KTokenTypeFileKeystore)
+        {
+        iAOArray.Reset();
+        }
+    else
+        {
+        iAOArray.Close();
+        }
+    LOG_LEAVEFN("CSecModUIModel::ResetAndDestroyAOs()");
+    }
+    
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ConstructL()
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ConstructL()
+    {
+    LOG_ENTERFN("CSecModUIModel::ConstructL()");
+    iEikEnv = CEikonEnv::Static();
+    AddResourceFileL();
+
+#ifndef RD_GS_RENOVATION
+
+    CSecModUIViewMain* viewMain = CSecModUIViewMain::NewLC(*this);
+    ((CAknViewAppUi*)iEikEnv->EikAppUi())->AddViewL(viewMain);
+    CleanupStack::Pop(viewMain);
+
+    CSecModUIViewCode* viewCode = CSecModUIViewCode::NewLC(*this);
+    ((CAknViewAppUi*)iEikEnv->EikAppUi())->AddViewL(viewCode);
+    CleanupStack::Pop(viewCode);
+
+    CSecModUIViewAccess* viewAccess = CSecModUIViewAccess::NewLC(*this);
+    ((CAknViewAppUi*)iEikEnv->EikAppUi())->AddViewL(viewAccess);
+    CleanupStack::Pop(viewAccess);
+
+    CSecModUIViewSignature* viewSignature = 
+        CSecModUIViewSignature::NewLC(*this);
+    ((CAknViewAppUi*)iEikEnv->EikAppUi())->AddViewL(viewSignature);
+    CleanupStack::Pop(viewSignature);
+#endif
+    InitializeKeyStoreL();
+    LOG_LEAVEFN("CSecModUIModel::ConstructL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::NewL()
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CSecModUIModel* CSecModUIModel::NewL()
+    {
+    LOG_ENTERFN("CSecModUIModel::NewL()");
+    CSecModUIModel* self = new( ELeave ) CSecModUIModel();
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    LOG_LEAVEFN("CSecModUIModel::NewL()");
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::InitializeKeyStoreL()
+// -----------------------------------------------------------------------------
+//
+TInt CSecModUIModel::InitializeKeyStoreL()
+    {
+    LOG_ENTERFN("CSecModUIModel::InitializeKeyStoreL()");
+    ResetAndDestroyCTObjects();
+    iUnifiedKeyStore = CUnifiedKeyStore::NewL(iEikEnv->FsSession());
+
+    if (iWrapper == NULL)
+        {
+        iWrapper = CSecModUISyncWrapper::NewL();
+        }
+
+    TInt err = iWrapper->Initialize(*iUnifiedKeyStore);
+
+    ShowErrorNoteL(err);
+    if (KErrNone != err && KErrHardwareNotAvailable != err)
+        {
+        LOG_LEAVEFN("CSecModUIModel::InitializeKeyStoreL()");
+        return err;
+        }
+    TInt keyStoreCount = iUnifiedKeyStore->KeyStoreCount();
+    if (0 >= keyStoreCount)
+        {
+        LOG_LEAVEFN("CSecModUIModel::InitializeKeyStoreL()");
+        return KErrNone;
+        }
+
+    RMPointerArray<CCTKeyInfo> keyInfos;
+    CleanupClosePushL(keyInfos);
+    TCTKeyAttributeFilter filter;
+    TInt keyInfoCount = 0;
+    filter.iPolicyFilter = TCTKeyAttributeFilter::EAllKeys;
+
+    for (TInt i = 0; i < keyStoreCount; i++)
+        {
+        err = iWrapper->ListKeys(iUnifiedKeyStore->KeyStore(i), keyInfos, filter);
+        LOG_WRITE_FORMAT( "CSecModUIModel::InitializeKeyStoreL() list err = %d ", err );
+        
+        //If list ok, append the AO, otherwise go next
+        if ( err == KErrNone )
+            {
+             keyInfoCount = keyInfos.Count();
+            for (TInt j = 0; j < keyInfoCount; j++)
+                {
+                // Check that keystore has at least one AO.
+                if (NULL != keyInfos[j]->Protector())
+                    {
+                    // If keystore has AO, add it to the array.
+                    User::LeaveIfError(
+                        iAOKeyStores.Append(&(iUnifiedKeyStore->KeyStore(i))));
+                    break;
+                    }
+                } 
+            }
+        keyInfos.Close();
+        }
+    CleanupStack::PopAndDestroy(&keyInfos);  //keyInfos
+
+    LOG_LEAVEFN("CSecModUIModel::InitializeKeyStoreL()");
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::AddResourceFileL()
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::AddResourceFileL()
+  {
+  LOG_ENTERFN("CSecModUIModel::AddResourceFileL()");
+    // Resource file loading
+  RFs& fs = iEikEnv->FsSession();
+
+  TFileName fileName;
+
+  TParse parse;
+  // secmodui.rsc
+    parse.Set(KResourceFile, &KDC_RESOURCE_FILES_DIR, NULL);
+
+  fileName = parse.FullName();
+
+  BaflUtils::NearestLanguageFile( fs, fileName );
+  iResourceFileOffset = iEikEnv->AddResourceFileL( fileName );
+
+  // CertManUI.rsc
+  parse.Set(KResourceFile2, &KDC_RESOURCE_FILES_DIR, NULL);
+    fileName = parse.FullName();
+    BaflUtils::NearestLanguageFile( fs, fileName );
+    iResourceFileOffset2 = iEikEnv->AddResourceFileL( fileName );
+
+  // CTSecDlg.rsc
+  parse.Set(KResourceFile3, &KDC_RESOURCE_FILES_DIR, NULL);
+    fileName = parse.FullName();
+    BaflUtils::NearestLanguageFile( fs, fileName );
+    iResourceFileOffset3 = iEikEnv->AddResourceFileL( fileName );
+
+  LOG_LEAVEFN("CSecModUIModel::AddResourceFileL()");
+  }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::LoadTokenLabelsL(CEikTextListBox& aListBox)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::LoadTokenLabelsL(CEikTextListBox& aListBox)
+    {
+    LOG_ENTERFN("CSecModUIModel::LoadTokenLabelsL()");
+
+    TInt keyStoreCount = iAOKeyStores.Count();
+
+    if (0 == keyStoreCount)
+        {
+        LOG_WRITE_FORMAT("keyStoreCount == %i",keyStoreCount);
+        LOG_LEAVEFN("CSecModUIModel::LoadTokenLabelsL()");
+        //disable the scrollbar if no keystore
+        aListBox.ScrollBarFrame()->SetScrollBarVisibilityL(
+	    CEikScrollBarFrame::EOff,CEikScrollBarFrame::EOff);
+        return;
+        }
+    TBuf<KItemLength> item;
+    TBuf<KItemLength> label;
+
+    CDesCArray* itemArray =
+        STATIC_CAST(CDesCArray*, aListBox.Model()->ItemTextArray());
+    for (TInt i = 0; i < keyStoreCount; i++)
+        {
+        if (iAOKeyStores[i]->Token().TokenType().Type().iUid 
+            == KTokenTypeFileKeystore)
+            {
+            AppendResourceL(label, R_QTN_KEYSTORE_LIST_TEXT_PHONE_KEYSTORE);
+            }
+        else 
+            {                
+            label = iAOKeyStores[i]->Token().Label();
+            }
+        item += KTab;
+        item += label;
+        item += KTab;
+        AppendLocationL(item, iAOKeyStores[i]->Token().TokenType().Type());
+        item.SetLength(item.Length() - 1); // Remove \n from the end
+        itemArray->AppendL(item);
+        label.Zero();
+        item.Zero();
+        }
+
+    LOG_LEAVEFN("CSecModUIModel::LoadTokenLabelsL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::CheckCodeViewStringsL(MDesCArray& aItemArray)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::CheckCodeViewStringsL(MDesCArray& aItemArray)
+    {
+    LOG_ENTERFN("CSecModUIModel::CheckCodeViewStringsL()");       
+    InitAuthObjectsL();
+    ListAuthObjectsL();
+        
+    if (0 >= iAOArray.Count())
+        {
+        // Handle error
+        }
+    else if (1 == iAOArray.Count())
+        {
+        // Only PIN-G exists, let's remove "signing codes" from the list
+        CDesCArray* itemArray = STATIC_CAST(CDesCArray*, &aItemArray);
+        itemArray->Delete(1); // signing code is in the second position
+        }
+    else
+        {
+        // Do nothing
+        }
+    LOG_LEAVEFN("CSecModUIModel::CheckCodeViewStringsL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::InitAuthObjectsL()
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::InitAuthObjectsL()
+    {
+    LOG_ENTERFN("CSecModUIModel::InitAuthObjectsL()");
+    TInt err = KErrNone;
+    // Symbian's file key store does not support
+    // MCTAuthenticationObjectList interface, so we need to use
+    // other way to get AO.
+    if (iKeyStore->Token().TokenType().Type().iUid == KTokenTypeFileKeystore)
+        {
+        if (iAOArray.Count()==0)
+            {
+            RMPointerArray<CCTKeyInfo> keyInfos;
+            CleanupClosePushL(keyInfos);
+            TCTKeyAttributeFilter filter;
+            TInt keyInfoCount = 0;
+            filter.iPolicyFilter = TCTKeyAttributeFilter::EAllKeys;
+            err = iWrapper->ListKeys(*iKeyStore, keyInfos, filter);
+            ShowErrorNoteL(err);
+            User::LeaveIfError(err);
+            keyInfoCount = keyInfos.Count();
+            for (TInt j = 0; j < keyInfoCount; j++)
+                {
+                // Check that keystore has at least one AO.
+                if (NULL != keyInfos[j]->Protector())
+                    {
+                    // If keystore has AO, add it to the array.
+                    User::LeaveIfError(iAOArray.Append(keyInfos[j]->Protector()));
+                    break;
+                    }
+                }
+            CleanupStack::PopAndDestroy(&keyInfos);  //keyInfos
+            }
+        }
+    else
+        {
+        if (NULL == iAOList)
+            {
+            MCTTokenInterface* tokenInterface = NULL;
+            err = iWrapper->GetAuthObjectInterface(
+                iKeyStore->Token(), tokenInterface);
+            if ( KErrNone != err || NULL == tokenInterface )
+                {
+                ShowErrorNoteL(err);
+                LOG_LEAVEFN("CSecModUIModel::InitAuthObjectsL()");
+                User::Leave(err);
+                }
+            iAOList = (MCTAuthenticationObjectList*)tokenInterface;
+            }
+        }
+    LOG_LEAVEFN("CSecModUIModel::InitAuthObjectsL()");
+    }
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ListAuthObjectsL()
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ListAuthObjectsL()
+    {
+    LOG_ENTERFN("CSecModUIModel::ListAuthObjectsL()");
+    if (0 >= iAOArray.Count())
+        {
+        __ASSERT_ALWAYS(iAOList, Panic(EPanicNullPointer));
+        TInt err = iWrapper->ListAuthObjects(*iAOList, iAOArray);
+        if (err)
+            {
+            ShowErrorNoteL(err);
+            User::Leave(err);
+            }
+        }
+    LOG_LEAVEFN("CSecModUIModel::ListAuthObjectsL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::OpenTokenL(TInt aTokenIndex)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::OpenTokenL(TInt aTokenIndex)
+    {
+    LOG_ENTERFN("CSecModUIModel::OpenTokenL()");
+    ResetAndDestroyAOs();
+    iKeyStore = iAOKeyStores[aTokenIndex];
+    ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL(KSecModUIViewCodeId);
+    LOG_LEAVEFN("CSecModUIModel::OpenTokenL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::OpenAuthObjViewL(TInt aIndex)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::OpenAuthObjViewL(TInt aIndex)
+    {
+    LOG_ENTERFN("CSecModUIModel::OpenAuthObjViewL()");
+    if (KPinGSettIndex==aIndex)
+        {
+        ((CAknViewAppUi*)iAvkonAppUi)->ActivateLocalViewL(KSecModUIViewAccessId);
+        }
+    else if (KPinNrSettIndex==aIndex)
+        {
+        ((CAknViewAppUi*)iAvkonAppUi)->
+            ActivateLocalViewL(KSecModUIViewSignatureId);
+        }
+    else
+        {
+
+        }
+    LOG_LEAVEFN("CSecModUIModel::OpenAuthObjViewL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::CloseAuthObjL(TInt aIndex)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::CloseAuthObjL(TInt aIndex)
+    {
+    LOG_ENTERFN("CSecModUIModel::CloseAuthObjL()");
+    if (PinOpen(aIndex))
+        {
+        __ASSERT_ALWAYS(aIndex < iAOArray.Count(), Panic(EPanicIndexOutOfRange));
+        TInt err = iWrapper->CloseAuthObject(*(iAOArray[aIndex]));
+        if (err)
+            {
+            ShowErrorNoteL(err);
+            User::Leave(err);
+            }
+        }
+    LOG_LEAVEFN("CSecModUIModel::CloseAuthObjL()");
+    }
+
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ViewSecModDetailsL(TInt aTokenIndex)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ViewSecModDetailsL(TInt aTokenIndex)
+    {
+    LOG_ENTERFN("CSecModUIModel::ViewSecModDetailsL(TInt aTokenIndex)");
+    iKeyStore = iAOKeyStores[aTokenIndex];
+    InitAuthObjectsL();
+    ListAuthObjectsL();
+    ViewOpenedSecModDetailsL();
+    iKeyStore = NULL; // not owned
+    if (iAOList)
+        {
+        iAOList->Release();
+        iAOList = NULL;
+        }
+    iAOArray.Reset();
+
+    LOG_LEAVEFN("CSecModUIModel::ViewSecModDetailsL(TInt aTokenIndex)");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ViewOpenedSecModDetailsL()
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ViewOpenedSecModDetailsL()
+    {
+    LOG_ENTERFN("CSecModUIModel::ViewSecModDetailsL()");
+    // Create message buffer
+    HBufC* message = HBufC::NewLC(KMaxLengthTextDetailsBody);
+    TPtr messagePtr = message->Des();
+    MCTToken& token = iKeyStore->Token();
+    
+    if (token.TokenType().Type().iUid == KTokenTypeFileKeystore)
+        { 
+        AppendItemL(messagePtr, R_QTN_WIM_NAME,
+            KNullDesC, R_QTN_KEYSTORE_LIST_TEXT_PHONE_KEYSTORE);        
+        }
+    else 
+        {            
+        AppendItemL(messagePtr, R_QTN_WIM_NAME,
+            token.Label(), R_TEXT_RESOURCE_VIEW_NO_LABEL_DETAILS);
+        }
+
+    AppendItemL(messagePtr, R_QTN_WIM_CARD_VERSION,
+        token.Information( MCTToken::EVersion ),
+        R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED );
+
+    AppendLocationL(messagePtr, token.TokenType().Type(), R_QTN_WIM_SECURITY_MODULE_LOCATION);
+    messagePtr.Append(KEnter); // AppendLocationL does not add enter as others
+    
+    if (token.TokenType().Type().iUid == KTokenTypeFileKeystore)
+        { 
+        AppendItemL(messagePtr, R_QTN_WIM_SETT_PIN_G,
+            KNullDesC, R_QTN_SECMOD_TITLE_PHONE_KEYSTORE_CODE);        
+        }
+    else 
+        {            
+        AppendItemL(messagePtr, R_QTN_WIM_SETT_PIN_G,
+            iAOArray[0]->Label(), R_QTN_WIM_PIN_G_NO_LABEL_DETAILS);
+        }
+
+    AppendPinNRsL(messagePtr);
+
+    AppendItemL(messagePtr, R_QTN_WIM_SERIAL_NRO,
+        token.Information( MCTToken::ESerialNo),
+        R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED);
+
+    AppendItemL(messagePtr, R_QTN_WIM_MANUF,
+        token.Information( MCTToken::EManufacturer),
+        R_TEXT_RESOURCE_DETAILS_VIEW_NOT_DEFINED);
+
+    CAknMessageQueryDialog* dlg = CAknMessageQueryDialog::NewL(*message);
+    dlg->PrepareLC(R_SECMOD_DETAILS_VIEW);
+    dlg->RunLD();
+    CleanupStack::PopAndDestroy(message);
+    LOG_LEAVEFN("CSecModUIModel::ViewSecModDetailsL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::AppendPinNRsL(TDes& aMessage) const
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::AppendPinNRsL(TDes& aMessage) const
+    {
+    TInt pinCount = iAOArray.Count();
+    HBufC* value = NULL;
+    TInt j = 1;
+
+    for (TInt i=1; i<pinCount; i++)
+      {
+      AppendResourceAndEnterL(aMessage, R_QTN_WIM_KEY_PIN);
+      if (iAOArray[i]->Label().Length() > 0)
+          {
+          aMessage.Append(iAOArray[i]->Label());
+          }
+      else
+          {
+          value = StringLoader::LoadLC(R_QTN_WIM_PIN_NR_NO_LABEL_DETAILS, j);
+          aMessage.Append(*value);
+          j++;
+          }
+      aMessage.Append(KDoubleEnter);
+      }
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::AppendLocationL(...)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::AppendLocationL(
+    TDes& aMessage,
+    TUid aUid,
+    TInt aItemRes) const
+    {
+    TInt location = 0;
+
+
+    switch ( aUid.iUid )
+        {
+        case KTokenTypeFileKeystore:
+            {
+            location = R_TEXT_RESOURCE_DETAILS_VIEW_LOCATION_PHONE_MEMORY;
+            break;
+            }
+        case KWIMStoreUid:
+            {
+            location = R_TEXT_RESOURCE_DETAILS_VIEW_LOCATION_SMART_CARD;
+            break;
+            }
+        default:
+            {
+            break;
+            }
+        }
+    if (0 != aItemRes)
+        {
+        AppendResourceAndEnterL(aMessage, aItemRes);
+        }
+    AppendResourceAndEnterL(aMessage, location);
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::AppendItemL(...)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::AppendItemL(
+    TDes& aMessage,
+    TInt aResItem,
+    const TDesC& aValue,
+    TInt aResNotDefined) const
+    {
+    AppendResourceAndEnterL(aMessage, aResItem);
+    AppendValueL(aMessage, aValue, aResNotDefined);
+    aMessage.Append(KEnter);
+    }
+
+// ---------------------------------------------------------
+// CSecModUIModel::AppendResourceL(TDes& aMessage, TInt aResource)
+// Appends aResource to aMessage
+// ---------------------------------------------------------
+//
+void CSecModUIModel::AppendResourceL(TDes& aMessage, TInt aResource) const
+  {
+  HBufC* stringHolder = StringLoader::LoadLC(aResource);
+  aMessage.Append(*stringHolder);
+  CleanupStack::PopAndDestroy(stringHolder);  
+  }
+  
+// ---------------------------------------------------------
+// CSecModUIModel::AppendResourceL(TDes& aMessage, TInt aResource)
+// Appends aResource to aMessage
+// ---------------------------------------------------------
+//
+void CSecModUIModel::AppendResourceAndEnterL(TDes& aMessage, TInt aResource) const
+  {
+  HBufC* stringHolder = StringLoader::LoadLC(aResource);
+  aMessage.Append(*stringHolder);
+  CleanupStack::PopAndDestroy(stringHolder);
+  aMessage.Append(KEnter);
+  }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::AppendValueL(...)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::AppendValueL(
+    TDes& aMessage,
+    const TDesC& aValue,
+    TInt aResNotDefined) const
+  {
+  HBufC* buf = HBufC::NewLC(KMaxLengthItemValue);
+  buf->Des() = aValue;
+  buf->Des().TrimLeft();
+  TInt length = buf->Des().Length();
+  if (length == 0 )
+    {
+    AppendResourceAndEnterL(aMessage, aResNotDefined);
+    }
+  else
+    {
+    aMessage.Append(*buf);
+    aMessage.Append(KEnter);
+    }
+  CleanupStack::PopAndDestroy(buf);
+  }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::DeleteKeyStoreL(TInt aTokenIndex)
+// -----------------------------------------------------------------------------
+//
+TBool CSecModUIModel::DeleteKeyStoreL(TInt aTokenIndex)
+    {
+    LOG_ENTERFN("CSecModUIModel::DeleteKeyStoreL()");
+    __ASSERT_ALWAYS(aTokenIndex < iAOKeyStores.Count(), Panic(EPanicIndexOutOfRange));
+    // ask confirmation from the user
+    if (ShowConfirmationQueryL(R_QTN_CM_CONFIRM_DELETE_KEYS))
+        {
+        RMPointerArray<CCTKeyInfo> keyInfos;
+        CleanupClosePushL(keyInfos);
+        TCTKeyAttributeFilter filter;
+        filter.iPolicyFilter = TCTKeyAttributeFilter::EAllKeys;
+        TInt err = iWrapper->ListKeys(*iAOKeyStores[aTokenIndex], keyInfos, filter);
+        ShowErrorNoteL(err);
+        User::LeaveIfError(err);
+        for (TInt i = 0; i < keyInfos.Count(); ++i)
+            {
+            err = iWrapper->DeleteKey(*iUnifiedKeyStore, keyInfos[i]->Handle());
+            ShowErrorNoteL(err);
+
+            if (KErrHardwareNotAvailable == err )
+                {
+                break; // Break the loop, if keystore not available
+                }
+            }
+        CleanupStack::PopAndDestroy(&keyInfos);  //keyInfos
+        ResetAndDestroyCTObjects();
+        InitializeKeyStoreL();
+        LOG_LEAVEFN("CSecModUIModel::DeleteKeyStoreL()");
+        return ETrue;
+        }
+    else
+        {
+        LOG_LEAVEFN("CSecModUIModel::DeleteKeyStoreL()");
+        return EFalse;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::IsTokenDeletable(TInt aTokenIndex)
+// -----------------------------------------------------------------------------
+//
+TBool CSecModUIModel::IsTokenDeletable(TInt aTokenIndex)
+    {
+    LOG_ENTERFN("CSecModUIModel::IsTokenDeletable()");
+    __ASSERT_ALWAYS(aTokenIndex < iAOKeyStores.Count(), Panic(EPanicIndexOutOfRange));
+    TBool ret = EFalse;
+    if (iAOKeyStores[aTokenIndex]->Token().TokenType().Type().iUid
+        == KTokenTypeFileKeystore)
+        {
+        ret = ETrue;
+        }
+    else
+        {
+        ret = EFalse;
+        }
+    LOG_LEAVEFN("CSecModUIModel::IsTokenDeletable()");
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::LoadPinNRLabelsL(...)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::LoadPinNRLabelsL(CEikTextListBox& aListBox, TBool aShowBlockedNote)
+    {
+    LOG_ENTERFN("CSecModUIModel::LoadPinNRLabelsL()");
+    TBuf<KMaxSettItemSize> item;
+    TBuf<KMaxSettItemSize> label;
+    CDesCArray* itemArray = STATIC_CAST(CDesCArray*, aListBox.Model()->ItemTextArray());
+    itemArray->Reset();
+
+    LOG_WRITE_FORMAT("CSecModUIModel::LoadPinNRLabelsL, iAOArray.Count() == %i",iAOArray.Count());
+    TUint32 status = 0;
+    // Here is assumed that the first AO is always PIN-G
+    for (TInt i = 1; i < iAOArray.Count(); i++)
+        {
+        label = iAOArray[i]->Label();
+        status = iAOArray[i]->Status();
+        LOG_WRITE_FORMAT("PIN-NR status == %i", status);
+        if (status & EAuthObjectBlocked)
+            {
+            if (aShowBlockedNote)
+                {
+                if (status & EUnblockDisabled)
+                    {
+                    ShowInformationNoteL(R_QTN_WIM_PIN_TOTALBLOCKED, label);
+                    }
+                else
+                    {
+                    ShowInformationNoteL(R_QTN_WIM_ERR_PIN_BLOCKED, label);
+                    }
+                }
+            HBufC* value = StringLoader::LoadLC(R_QTN_WIM_STATUS_BLOCKED);
+            CreateSettingItem(label, *value, item );
+            CleanupStack::PopAndDestroy(value);
+            }
+        else
+            {
+            CreateSettingItem(label, KFourAsterisks, item);
+            }
+        itemArray->AppendL(item);
+        label.Zero();
+        item.Zero();
+        }
+    LOG_LEAVEFN("CSecModUIModel::LoadPinNRLabelsL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::LoadPinGItemsL(CEikTextListBox& aListBox)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::LoadPinGItemsL(CEikTextListBox& aListBox)
+    {
+    LOG_ENTERFN("CSecModUIModel::LoadPinGItemsL()");
+    TBuf<KMaxSettItemSize> item;
+    TBuf<KMaxSettItemSize> label;
+
+    CDesCArray* itemArray = STATIC_CAST(CDesCArray*,
+        aListBox.Model()->ItemTextArray());
+
+    if (iKeyStore->Token().TokenType().Type().iUid 
+        == KTokenTypeFileKeystore)
+        {
+        AppendResourceL(label, R_QTN_SECMOD_TITLE_PHONE_KEYSTORE_CODE);
+        }
+    else
+        {                
+        label = iAOArray[KPinGIndex]->Label();
+        }
+    CreateSettingItem(label, KFourAsterisks, item);
+    itemArray->AppendL(item);
+    item.Zero();
+    PINRequestItemL(KPinGIndex, item);
+    itemArray->AppendL(item);
+    item.Zero();
+    PINStatusItemL(KPinGIndex, item, ETrue);
+    itemArray->AppendL(item);
+    LOG_LEAVEFN("CSecModUIModel::LoadPinGItemsL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::PINRequestItemL(...)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::PINRequestItemL(TInt aIndex, TDes& aItem) const
+    {
+    LOG_ENTERFN("CSecModUIModel::PINRequestItemL()");
+    __ASSERT_ALWAYS(aIndex < iAOArray.Count(), Panic(EPanicIndexOutOfRange));
+    TUint32 status = iAOArray[aIndex]->Status();
+    HBufC* title = NULL;
+    HBufC* value = NULL;
+    title = StringLoader::LoadLC(R_QTN_WIM_PIN_REQUEST);
+
+    if (status & EEnabled)
+        {
+        value = StringLoader::LoadLC(R_QTN_WIM_REQUEST_ON);
+        CreateSettingItem(*title, *value, aItem );
+        }
+    else
+        {
+        value = StringLoader::LoadLC(R_QTN_WIM_REQUEST_OFF);
+        CreateSettingItem(*title, *value, aItem );
+        }
+    CleanupStack::PopAndDestroy(2, title);
+    LOG_LEAVEFN("CSecModUIModel::PINRequestItemL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::PINStatusItemL(...)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::PINStatusItemL(
+    TInt aIndex,
+    TDes& aItem,
+    TBool aShowBlockedNote) const
+    {
+    LOG_ENTERFN("CSecModUIModel::PINStatusItemL()");
+    __ASSERT_ALWAYS(aIndex < iAOArray.Count(), Panic(EPanicIndexOutOfRange));
+    TUint32 status = iAOArray[aIndex]->Status();
+    HBufC* title = NULL;
+    HBufC* value = NULL;
+    title = StringLoader::LoadLC(R_QTN_WIM_SETT_STATUS);
+
+    LOG_WRITE_FORMAT("PIN-G status == %i", status);
+
+    if (status & EAuthObjectBlocked)
+        {
+        if (aShowBlockedNote)
+            {
+            if (status & EUnblockDisabled)
+                {
+                ShowInformationNoteL(
+                    R_QTN_WIM_PIN_TOTALBLOCKED, iAOArray[aIndex]->Label());
+                }
+            else
+                {
+                ShowInformationNoteL(
+                    R_QTN_WIM_ERR_PIN_BLOCKED, iAOArray[aIndex]->Label());
+                }
+            }            
+        value = StringLoader::LoadLC(R_QTN_SECMOD_STATUS_VALUE_BLOCKED);
+        }
+    else if ( PinOpen(aIndex) )
+        {
+        value = StringLoader::LoadLC(R_QTN_WIM_OPT_OPEN);
+        }
+    else
+        {
+        value = StringLoader::LoadLC(R_QTN_WIM_STATUS_CLOSED);
+        }
+    CreateSettingItem(*title, *value, aItem );
+    CleanupStack::PopAndDestroy(2, title);
+    LOG_LEAVEFN("CSecModUIModel::PINStatusItemL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::CreateSettingItem(...)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::CreateSettingItem(
+    const TDesC& aTitle, const TDesC& aValue, TDes& aItem) const
+  {
+    LOG_ENTERFN("CSecModUIModel::CreateSettingItem()");
+    aItem += KTab;
+    aItem += aTitle;
+    aItem += KDoubleTab;
+    aItem += aValue;
+    LOG_LEAVEFN("CSecModUIModel::CreateSettingItem()");
+  }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::eOrUnblockPinNrL(TInt aIndex)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ChangeOrUnblockPinNrL(TInt aIndex)
+    {
+    LOG_ENTERFN("CSecModUIModel::ChangeOrUnblockPinNrL()");
+    // Add PIN-G to the list
+    ChangeOrUnblockPinL(aIndex+1);
+    LOG_LEAVEFN("CSecModUIModel::ChangeOrUnblockPinNrL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ChangeOrUnblockPinL(TInt aIndex)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ChangeOrUnblockPinL(TInt aIndex)
+    {
+    LOG_ENTERFN("CSecModUIModel::ChangeOrUnblockPinL()");
+    __ASSERT_ALWAYS(aIndex < iAOArray.Count(), Panic(EPanicIndexOutOfRange));
+    TUint32 status = iAOArray[aIndex]->Status();
+
+    if ((status & EAuthObjectBlocked) && (status & EUnblockDisabled))
+        {
+        return; // We cannot do anything. PIN is total bolcked.
+        }
+    else if (status & EAuthObjectBlocked)
+        {
+        // Let's unblock the PIN
+        UnblockPinL(aIndex);
+        }
+    else if (status & EChangeDisabled)
+        {
+        // We cannot do anything. Change is disabled.
+        }
+     else if (status & EEnabled)
+        {
+        // PIN is enabled. Let's change the PIN.
+        ChangePinL(aIndex);
+        }
+     else
+        {
+        // PIN is disabled. Not possible to change PIN.
+        }
+    LOG_LEAVEFN("CSecModUIModel::ChangeOrUnblockPinL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ChangePinNrL(TInt aIndex)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ChangePinNrL(TInt aIndex)
+    {
+    LOG_ENTERFN("CSecModUIModel::ChangePinNrL()");
+    ChangePinL(aIndex+1);
+    LOG_LEAVEFN("CSecModUIModel::ChangePinNrL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ChangePinL(TInt aIndex)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ChangePinL(TInt aIndex)
+    {
+    LOG_ENTERFN("CSecModUIModel::ChangePinL()");
+    __ASSERT_ALWAYS(aIndex < iAOArray.Count(), Panic(EPanicIndexOutOfRange));
+    TInt err = KErrNone;
+  
+    err = iWrapper->ChangeReferenceData(*(iAOArray[aIndex]));
+    if (err)
+        {
+        ShowErrorNoteL(err);
+        }
+    else
+        {
+        ShowConfirmationNoteL(R_QTN_WIM_INFO_PIN_CHANGED);
+        }
+    
+    LOG_LEAVEFN("CSecModUIModel::ChangePinL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::UnblockPinNrL(TInt aIndex)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::UnblockPinNrL(TInt aIndex)
+    {
+    LOG_ENTERFN("CSecModUIModel::UnblockPinNrL()");
+    UnblockPinL(aIndex+1);
+    LOG_LEAVEFN("CSecModUIModel::UnblockPinNrL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::UnblockPinL(TInt aIndex)
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::UnblockPinL(TInt aIndex)
+    {
+    LOG_ENTERFN("CSecModUIModel::UnblockPinL()");
+    __ASSERT_ALWAYS(aIndex < iAOArray.Count(), Panic(EPanicIndexOutOfRange));
+    TInt err = iWrapper->UnblockAuthObject(*(iAOArray[aIndex]));
+    if (KErrNone == err)
+        {
+        ShowConfirmationNoteL(R_QTN_WIM_INFO_PIN_UNBLOCKED);
+        }
+    else
+        {
+        ShowErrorNoteL(err);
+        }
+    LOG_LEAVEFN("CSecModUIModel::UnblockPinL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::PinNrChangeable(TInt aIndex) const
+// -----------------------------------------------------------------------------
+//
+TBool CSecModUIModel::PinNrChangeable(TInt aIndex) const
+    {
+    // Add PIN-G to the list
+    return PinChangeable(aIndex+1);
+    }
+// -----------------------------------------------------------------------------
+// CSecModUIModel::PinChangeable(TInt aIndex) const
+// -----------------------------------------------------------------------------
+//
+TBool CSecModUIModel::PinChangeable(TInt aIndex) const
+    {
+    LOG_ENTERFN("CSecModUIModel::PinChangeable()");
+    __ASSERT_ALWAYS(aIndex < iAOArray.Count(), Panic(EPanicIndexOutOfRange));
+    TUint32 status = iAOArray[aIndex]->Status();
+    TBool ret = ETrue;
+    if ( (status & EAuthObjectBlocked) || (status & EChangeDisabled) )
+    //if ( status & (EAuthObjectBlocked | EChangeDisabled))
+        {
+        ret = EFalse;
+        }
+    else if ( status & EEnabled )
+        {
+        ret = ETrue;
+        }
+    else // PIN is disabled;
+        {
+        ret = EFalse;
+        }
+    LOG_LEAVEFN("CSecModUIModel::PinChangeable()");
+    return ret;
+    }
+// -----------------------------------------------------------------------------
+// CSecModUIModel::PinNrUnblockable(TInt aIndex) const
+// -----------------------------------------------------------------------------
+//
+TBool CSecModUIModel::PinNrUnblockable(TInt aIndex) const
+    {
+    // Add PIN-G to the list
+    return PinUnblockable(aIndex+1);
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::PinUnblockable(TInt aIndex) const
+// -----------------------------------------------------------------------------
+//
+TBool CSecModUIModel::PinUnblockable(TInt aIndex) const
+    {
+    LOG_ENTERFN("CSecModUIModel::PinUnblockable()");
+    TUint32 status = iAOArray[aIndex]->Status();
+    TBool ret = ETrue;
+    if ( status & EUnblockDisabled )
+        {
+        ret = EFalse;
+        }
+    else if ( status & EAuthObjectBlocked )
+        {
+        ret = ETrue;
+        }
+    else // PIN is not blocked;
+        {
+        ret = EFalse;
+        }
+    LOG_LEAVEFN("CSecModUIModel::PinUnblockable()");
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::PinOpen(TInt aIndex) const
+// -----------------------------------------------------------------------------
+//
+TBool CSecModUIModel::PinOpen(TInt aIndex) const
+    {
+    LOG_ENTERFN("CSecModUIModel::PinOpen()");
+    __ASSERT_ALWAYS(aIndex < iAOArray.Count(), Panic(EPanicIndexOutOfRange));
+    TInt timeRemaining = 0;
+    TInt err = iWrapper->TimeRemaining(*(iAOArray[aIndex]), timeRemaining);
+    TBool ret = ETrue;
+    if ( 0 < timeRemaining )
+        {
+        ret = ETrue;
+        }
+    else if( timeRemaining == -1 )
+        {
+        ret = ETrue;
+        }
+    else
+        {
+        ret = EFalse;
+        }
+    LOG_LEAVEFN("CSecModUIModel::PinOpen()");
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ChangeCodeRequestL(TInt aIndex)
+// -----------------------------------------------------------------------------
+//
+TInt CSecModUIModel::ChangeCodeRequestL(TInt aIndex)
+    {
+    LOG_ENTERFN("CSecModUIModel::ChangeCodeRequestL()");
+    __ASSERT_ALWAYS(aIndex < iAOArray.Count(), Panic(EPanicIndexOutOfRange));
+    TUint32 status = iAOArray[aIndex]->Status();
+    TInt err = KErrNone;
+    if (status & EDisableAllowed &&  !(status & EAuthObjectBlocked))
+        {
+        if ( status & EEnabled )
+            {
+            err = iWrapper->DisableAuthObject(*(iAOArray[aIndex]));
+            }
+        else
+            {
+            err = iWrapper->EnableAuthObject(*(iAOArray[aIndex]));
+            }
+        ShowErrorNoteL(err);
+        }
+    LOG_LEAVEFN("CSecModUIModel::ChangeCodeRequestL()");
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::PinRequestChangeable(TInt aIndex) const
+// -----------------------------------------------------------------------------
+//
+TBool CSecModUIModel::PinRequestChangeable(TInt aIndex) const
+    {
+    LOG_ENTERFN("CSecModUIModel::PinRequestChangeable()");
+    __ASSERT_ALWAYS(aIndex < iAOArray.Count(), Panic(EPanicIndexOutOfRange));
+    TUint32 status = iAOArray[aIndex]->Status();
+    TBool ret = EFalse;
+    if ( status & EAuthObjectBlocked )
+        {
+        ret = EFalse;
+        }
+    else if ( status & EDisableAllowed )
+        {
+        ret = ETrue;
+        }
+    else // Disable not allowed;
+        {
+        ret = EFalse;
+        }
+    LOG_LEAVEFN("CSecModUIModel::PinRequestChangeable()");
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ShowErrorNoteL(TInt aError) const
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ShowErrorNoteL(TInt aError) const
+    {
+    LOG_ENTERFN("CSecModUIModel::ShowErrorNoteL()");
+    HBufC* text = NULL;
+
+    switch (aError)
+        {
+        case KErrCancel:
+        case KErrLocked:
+        case KErrNone:
+            {
+            LOG_WRITE_FORMAT("aError == %i",aError);
+            LOG_LEAVEFN("CSecModUIModel::ShowErrorNoteL()");
+            break;
+            }
+        case KErrInUse:
+            {
+            text = StringLoader::LoadLC(R_QTN_KEYSTORE_INFO_UNABLE_TO_DELETE);
+            break;
+            }
+        case KErrBadPassphrase:
+            {
+            text = StringLoader::LoadLC(R_QTN_WIM_ERR_WRONG_PIN);
+            break;
+            }
+        case KErrHardwareNotAvailable: // flow thru
+        default:
+            {
+            LOG_WRITE_FORMAT("ERROR: aError == %i",aError);
+            text = StringLoader::LoadLC(R_QTN_WIM_ERR_IO_ERROR);
+            break;
+            }
+        }
+
+    if (text)
+        {
+        CAknErrorNote* note = new (ELeave) CAknErrorNote;
+        note->ExecuteLD(*text);
+        CleanupStack::PopAndDestroy(text);
+        }
+    LOG_LEAVEFN("CSecModUIModel::ShowErrorNoteL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ShowConfirmationQueryL(TInt aResourceId) const
+// -----------------------------------------------------------------------------
+//
+TInt CSecModUIModel::ShowConfirmationQueryL(TInt aResourceId) const
+    {
+    LOG_ENTERFN("CSecModUIModel::ShowConfirmationQueryL ()");
+    HBufC* text = NULL;
+    text = StringLoader::LoadLC(aResourceId);
+    CAknQueryDialog* dlg = CAknQueryDialog::NewL(CAknQueryDialog::ENoTone);
+    TInt selection = dlg->ExecuteLD(R_SECMOD_CONFIRMATION_QUERY_YES_NO, *text);
+    CleanupStack::PopAndDestroy(text);
+    LOG_LEAVEFN("CSecModUIModel::ShowConfirmationNoteL()");
+    return selection;
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ShowConfirmationNoteL(TInt aResourceId) const
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ShowConfirmationNoteL(TInt aResourceId) const
+    {
+    LOG_ENTERFN("CSecModUIModel::ShowConfirmationNoteL()");
+    HBufC* text = NULL;
+    text = StringLoader::LoadLC(aResourceId);
+    CAknConfirmationNote * note = new (ELeave) CAknConfirmationNote;
+    note->ExecuteLD(*text);
+    CleanupStack::PopAndDestroy(text);
+    LOG_LEAVEFN("CSecModUIModel::ShowConfirmationNoteL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ShowInformationNoteL(...)
+// Global note needs to be used here because otherwise view might cancel
+// the query too early when the view is activated.
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ShowInformationNoteL(
+    TInt aResourceId,
+    const TDesC& aString) const
+    {
+    LOG_ENTERFN("CSecModUIModel::ShowInformationNoteL()");
+    HBufC* text = NULL;
+    if (0 == aString.Length())
+        {
+        text = StringLoader::LoadLC(aResourceId);
+        }
+    else
+        {
+        text = StringLoader::LoadLC(aResourceId, aString);
+        }
+    CAknGlobalNote * note = CAknGlobalNote::NewLC();
+    note->ShowNoteL(EAknGlobalInformationNote, *text);
+    CleanupStack::PopAndDestroy(2, text);
+    LOG_LEAVEFN("CSecModUIModel::ShowInformationNoteL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ActivateTitleL(const TDesC& aTitle) const
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ActivateTitleL(const TDesC& aTitle) const
+    {
+    LOG_ENTERFN("CSecModUIModel::ActivateTitleL()");
+    TUid titlePaneUid;
+    titlePaneUid.iUid = EEikStatusPaneUidTitle;
+    CEikStatusPane* sp = iAvkonAppUi->StatusPane();
+
+    CEikStatusPaneBase::TPaneCapabilities subPane =
+      sp->PaneCapabilities(titlePaneUid);
+
+    if (subPane.IsPresent() && subPane.IsAppOwned())
+      {
+      // Fetch pointer to the default title pane control
+      CAknTitlePane* title = STATIC_CAST(
+        CAknTitlePane*, sp->ControlL(titlePaneUid) );
+        title->SetTextL(aTitle);
+      }
+    LOG_LEAVEFN("CSecModUIModel::ActivateTitleL()");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::ActivateTokenLabelToTitleL() const
+// -----------------------------------------------------------------------------
+//
+void CSecModUIModel::ActivateTokenLabelToTitleL() const
+    {
+    if (iKeyStore->Token().TokenType().Type().iUid 
+        == KTokenTypeFileKeystore)
+        {
+        HBufC* stringHolder = 
+            StringLoader::LoadLC(R_QTN_KEYSTORE_TITLE_PHONE_KEYSTORE);
+        ActivateTitleL(*stringHolder);
+        CleanupStack::PopAndDestroy(stringHolder);        
+        }
+    else
+        {            
+        ActivateTitleL(iKeyStore->Token().Label());
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::Wrapper()
+// -----------------------------------------------------------------------------
+//
+CSecModUISyncWrapper& CSecModUIModel::Wrapper()
+    {
+    return *iWrapper;
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::SecurityModuleCount() const
+// -----------------------------------------------------------------------------
+//
+TInt CSecModUIModel::SecurityModuleCount() const
+    {
+    return iAOKeyStores.Count();
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUIPlugin.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,251 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecModUIPlugin class
+*
+*/
+
+
+// Includes
+#include <aknViewAppUi.h>
+#include <bautils.h>
+
+#include <SecModUI.rsg>
+#include "SecModUIModel.h"
+#include "SecModUIPlugin.h"
+#include "SecModUIPluginContainer.h"
+#include "SecModUIViewAccess.h"
+#include "SecModUIViewCode.h"
+#include "SecModUIViewMain.h"
+#include "SecModUIViewSignature.h"
+#include "StringLoader.h"
+
+
+// Constants
+
+// ========================= MEMBER FUNCTIONS ================================
+
+
+// ---------------------------------------------------------------------------
+// CSecModUIPlugin::CSecModUIPlugin()
+// Constructor
+//
+// ---------------------------------------------------------------------------
+//
+CSecModUIPlugin::CSecModUIPlugin():
+    iResourceLoader( *CCoeEnv::Static() ),
+    iPrevViewId()
+    {
+
+    }
+
+
+// ---------------------------------------------------------------------------
+// CSecModUIPlugin::~CSecModUIPlugin()
+// Destructor
+//
+// ---------------------------------------------------------------------------
+//
+CSecModUIPlugin::~CSecModUIPlugin()
+    {
+    delete iContainer;
+    delete iSecUiModel;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CSecModUIPlugin::ConstructL(const TRect& aRect)
+// Symbian OS two-phased constructor
+//
+// ---------------------------------------------------------------------------
+//
+void CSecModUIPlugin::ConstructL()
+    {
+
+    BaseConstructL();
+    
+    iSecUiModel = CSecModUIModel::NewL();
+
+    CSecModUIViewMain* viewMain = CSecModUIViewMain::NewLC(*iSecUiModel);
+    AppUi()->AddViewL(viewMain);
+    CleanupStack::Pop(viewMain);
+
+    CSecModUIViewCode* viewCode = CSecModUIViewCode::NewLC(*iSecUiModel);
+    AppUi()->AddViewL(viewCode);
+    CleanupStack::Pop(viewCode);
+
+    CSecModUIViewAccess* viewAccess = CSecModUIViewAccess::NewLC(*iSecUiModel);
+    AppUi()->AddViewL(viewAccess);
+    CleanupStack::Pop(viewAccess);
+
+    CSecModUIViewSignature* viewSignature = CSecModUIViewSignature::NewLC(*iSecUiModel);
+    AppUi()->AddViewL(viewSignature);
+    CleanupStack::Pop(viewSignature);
+
+    }
+// ---------------------------------------------------------------------------
+// CSecModUIPlugin::NewL()
+// Static constructor
+//
+// ---------------------------------------------------------------------------
+//
+CSecModUIPlugin* CSecModUIPlugin::NewL( TAny* /*aInitParams*/ )
+    {
+    CSecModUIPlugin* self = new( ELeave ) CSecModUIPlugin();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CSecModUIPlugin::Id()
+//
+//
+// ---------------------------------------------------------------------------
+//
+TUid CSecModUIPlugin::Id() const
+    {
+    return KSecModUIPluginUid;
+    }
+
+
+
+// ---------------------------------------------------------
+// CApSettingsPlugin::HandleClientRectChange
+// ---------------------------------------------------------
+void CSecModUIPlugin::HandleClientRectChange()
+    {
+    if ( iContainer )
+        {
+        iContainer->SetRect( ClientRect() );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CSecModUIPlugin::DoActivateL()
+//
+//
+// ---------------------------------------------------------------------------
+//
+void CSecModUIPlugin::DoActivateL( const TVwsViewId& aPrevViewId,
+                                   TUid /*aCustomMessageId*/,
+                                   const TDesC8& /*aCustomMessage*/ )
+    {
+
+  	if (iPrevViewId.iViewUid.iUid == 0)
+    	{
+    	// This is Security View
+    	iPrevViewId = aPrevViewId;
+    	}
+
+    if( iContainer )
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainer );
+        delete iContainer;
+        iContainer=NULL;
+        }
+
+    iContainer = new( ELeave ) CSecModUIPluginContainer;
+    iContainer->SetMopParent( this );
+    iContainer->ConstructL( ClientRect() );
+
+    AppUi()->AddToViewStackL( *this, iContainer );
+
+    iContainer->MakeVisible( ETrue );
+    iContainer->ActivateL();
+    iContainer->DrawNow();
+
+    if ( iPrevViewId != aPrevViewId )
+      {
+      // Activate parent view Security View
+      AppUi()->ActivateLocalViewL( iPrevViewId.iViewUid );
+      }
+    else
+      {
+      // Activate Security Module Main View
+      AppUi()->ActivateLocalViewL( KSecModUIViewMainId );
+      }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CSecModUIPlugin::DoDeactivate()
+//
+//
+// ---------------------------------------------------------------------------
+//
+void CSecModUIPlugin::DoDeactivate()
+    {
+    if( iContainer )
+       {
+       AppUi()->RemoveFromViewStack( *this, iContainer );
+       delete iContainer;
+       iContainer = NULL;
+       }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CSecModUIPlugin::GetCaptionL()
+//
+//
+// ---------------------------------------------------------------------------
+//
+void CSecModUIPlugin::GetCaptionL( TDes& aCaption ) const
+    {
+    StringLoader::Load( aCaption, R_QTN_WIM_SETTINGS  );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CSecModUIPlugin::Visible()
+//
+//
+// ---------------------------------------------------------------------------
+//
+TBool CSecModUIPlugin::Visible() const
+    {
+    TBool visible( EFalse );
+    TRAPD( err, visible = DoIsVisibleL() );
+    if( !err && visible )
+        {
+        return ETrue;
+        }
+    return EFalse;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CSecModUIPlugin::DoIsVisibleL()
+//
+//
+// ---------------------------------------------------------------------------
+//
+TBool CSecModUIPlugin::DoIsVisibleL() const
+    {
+    TBool isVisible( EFalse );
+    const TInt KItemCount = 4;
+    CDesCArray* itemArray = new (ELeave) CDesCArrayFlat( KItemCount );
+    CleanupStack::PushL( itemArray );
+    if( iSecUiModel )
+        {
+        isVisible = ( iSecUiModel->SecurityModuleCount() != 0 );
+        }
+    CleanupStack::PopAndDestroy( itemArray );
+    return isVisible;
+    }
+
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUIPluginContainer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,87 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecModUIPluginContainer class
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "SecModUIPluginContainer.h"
+
+// CONSTANTS
+
+// ========================= MEMBER FUNCTIONS ================================
+
+CSecModUIPluginContainer::CSecModUIPluginContainer()
+    {
+
+    }
+
+// ---------------------------------------------------------------------------
+// CApSettingsPluginContainer::ConstructL(const TRect& aRect)
+// Symbian OS two phased constructor
+//
+// ---------------------------------------------------------------------------
+//
+void CSecModUIPluginContainer::ConstructL( const TRect& aRect )
+    {
+
+    CreateWindowL();
+    SetRect( aRect );
+
+    }
+
+// ---------------------------------------------------------------------------
+// CSecModUIPluginContainer::~CSecModUIPluginContainer()
+// Destructor
+//
+// ---------------------------------------------------------------------------
+//
+CSecModUIPluginContainer::~CSecModUIPluginContainer()
+    {
+
+    }
+
+// ---------------------------------------------------------------------------
+// CSecModUIPluginContainer::SizeChanged
+//  
+// ---------------------------------------------------------------------------
+//
+void CSecModUIPluginContainer::SizeChanged()
+    {
+
+    }
+
+// ---------------------------------------------------------------------------
+// CSecModUIPluginContainer::CountComponentControls
+//  
+// ---------------------------------------------------------------------------
+//
+TInt CSecModUIPluginContainer::CountComponentControls() const
+    {
+    return 0;
+    }
+
+// ---------------------------------------------------------------------------
+// CSecModUIPluginContainer::ComponentControl
+//  
+// ---------------------------------------------------------------------------
+//
+CCoeControl* CSecModUIPluginContainer::ComponentControl( TInt /*aIndex*/ ) const
+    {
+    return NULL;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUIPluginImplementationTable.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,48 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   ECOM proxy table for this plugin
+*
+*/
+
+
+
+// System includes
+#include <e32std.h>
+#include <ecom/implementationproxy.h>
+
+// User includes
+#include "SecModUIPlugin.h"
+
+// Constants
+const TImplementationProxy KSecModUIPluginImplementationTable[] =
+  	{
+  	IMPLEMENTATION_PROXY_ENTRY( 0x101F8668, CSecModUIPlugin::NewL )
+  	};
+
+
+// ---------------------------------------------------------------------------
+// ImplementationGroupProxy
+// Gate/factory function
+//
+// ---------------------------------------------------------------------------
+//
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt& aTableCount )
+  	{
+  	aTableCount = sizeof( KSecModUIPluginImplementationTable )
+        	/ sizeof( TImplementationProxy );
+  	return KSecModUIPluginImplementationTable;
+  	}
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUISyncWrapper.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,399 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecModUISyncWrapper class
+*                Implements a synchronous wrapper for easier use of Symbian's
+*                Security Frameworks's API's.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "SecModUISyncWrapper.h"
+#include <ct/ccttokentypeinfo.h>
+#include <ct/mcttokentype.h>
+#include <ct/ccttokentype.h>
+#include <ct/tcttokenobjecthandle.h>
+#include <mctauthobject.h>
+#include <unifiedkeystore.h>
+#include "SecModUILogger.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CSecModUISyncWrapper::CSecModUISyncWrapper()
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CSecModUISyncWrapper::CSecModUISyncWrapper() : CActive( EPriorityStandard )
+    {
+    CActiveScheduler::Add(this);
+    }
+
+
+// -----------------------------------------------------------------------------
+// CSecModUISyncWrapper::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CSecModUISyncWrapper* CSecModUISyncWrapper::NewLC()
+    {
+    CSecModUISyncWrapper* wrap = new (ELeave) CSecModUISyncWrapper();
+    CleanupStack::PushL(wrap);    
+    return wrap;
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUISyncWrapper::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CSecModUISyncWrapper* CSecModUISyncWrapper::NewL()
+    {
+    LOG_ENTERFN("CSecModUISyncWrapper::NewL");
+    CSecModUISyncWrapper* wrap = CSecModUISyncWrapper::NewLC();
+    CleanupStack::Pop(wrap);
+    LOG_LEAVEFN("CSecModUISyncWrapper::NewL");
+    return wrap;
+    }
+
+// Destructor
+CSecModUISyncWrapper::~CSecModUISyncWrapper()
+    {
+    LOG_ENTERFN("CSecModUISyncWrapper::~CSecModUISyncWrapper");
+    Cancel();
+    iOperation = EOperationNone;
+    LOG_LEAVEFN("CSecModUISyncWrapper::~CSecModUISyncWrapper");
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUISyncWrapper::Initialize(CUnifiedKeyStore& aKeyStore)
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+TInt CSecModUISyncWrapper::Initialize(CUnifiedKeyStore& aKeyStore)
+    {
+    LOG_ENTERFN("CSecModUISyncWrapper::Initialize");
+    iOperation = EOperationInit;    
+    iObject = STATIC_CAST(TAny*, &aKeyStore);
+    aKeyStore.Initialize(iStatus);    
+    SetActive();
+    iWait.Start();
+    iOperation = EOperationNone;
+    LOG_LEAVEFN("CSecModUISyncWrapper::Initialize");    
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::GetAuthObjectInterface(...)
+// -----------------------------------------------------------------------------
+//
+TInt CSecModUISyncWrapper::GetAuthObjectInterface(
+    MCTToken& aToken, MCTTokenInterface*& aTokenInterface)
+    {
+    LOG_ENTERFN("CSecModUISyncWrapper::GetAuthObjectInterface");
+    iOperation = EOperationGetAOInterface;    
+    iObject = STATIC_CAST(TAny*, &aToken);
+    const TUid KUidInterfaceAO = { KCTInterfaceAuthenticationObject };    
+    aToken.GetInterface(KUidInterfaceAO, aTokenInterface, iStatus);
+    iOperation = EOperationGetAOInterface;
+    SetActive();
+	iWait.Start();
+	iOperation = EOperationNone;
+	LOG_LEAVEFN("CSecModUISyncWrapper::GetAuthObjectInterface");	
+    return iStatus.Int();
+    }
+    
+// -----------------------------------------------------------------------------
+// CSecModUISyncWrapper::ListAuthObjects(...)
+// -----------------------------------------------------------------------------
+//
+TInt CSecModUISyncWrapper::ListAuthObjects(
+    MCTAuthenticationObjectList& aAuthObjList,
+    RMPointerArray<MCTAuthenticationObject>& aAuthObjects)
+    {
+    LOG_ENTERFN("CSecModUISyncWrapper::ListAuthObjects");
+    iOperation = EOperationListAOs;
+    iObject = STATIC_CAST(TAny*, &aAuthObjList);    
+    aAuthObjList.List( aAuthObjects, iStatus );    
+    iOperation = EOperationListAOs;
+    SetActive();
+	iWait.Start();
+	iOperation = EOperationNone;
+	LOG_LEAVEFN("CSecModUISyncWrapper::ListAuthObjects");
+    return iStatus.Int();
+    }
+ 
+// -----------------------------------------------------------------------------
+// CSecModUISyncWrapper::ListKeys(...)
+// -----------------------------------------------------------------------------
+// 
+TInt CSecModUISyncWrapper::ListKeys(
+    MCTKeyStore& aKeyStore, 
+    RMPointerArray<CCTKeyInfo>& aKeysInfos, 
+    const TCTKeyAttributeFilter& aFilter)
+    {
+    LOG_ENTERFN("CSecModUISyncWrapper::ListKeys");
+    iOperation = EOperationListKeys;
+    iObject = STATIC_CAST(TAny*, &aKeyStore);    
+    aKeyStore.List(aKeysInfos, aFilter, iStatus);
+    SetActive();
+	iWait.Start();
+	iOperation = EOperationNone;
+	LOG_LEAVEFN("CSecModUISyncWrapper::ListKeys");
+	return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUISyncWrapper::DeleteKey(...)
+// -----------------------------------------------------------------------------
+//    
+TInt CSecModUISyncWrapper::DeleteKey(
+    CUnifiedKeyStore& aKeyStore, 
+    TCTTokenObjectHandle aHandle)
+    {
+    LOG_ENTERFN("CSecModUISyncWrapper::DeleteKey");
+    iOperation = EOperationDelKey;
+    iObject = STATIC_CAST(TAny*, &aKeyStore);    
+    aKeyStore.DeleteKey(aHandle, iStatus);
+    SetActive();
+	iWait.Start();
+	iOperation = EOperationNone;
+	LOG_LEAVEFN("CSecModUISyncWrapper::DeleteKey");
+	return iStatus.Int();
+    }
+    
+// -----------------------------------------------------------------------------
+// CSecModUISyncWrapper::ChangeReferenceData(MCTAuthenticationObject& aAuthObject)
+// -----------------------------------------------------------------------------
+//
+TInt CSecModUISyncWrapper::ChangeReferenceData(
+    MCTAuthenticationObject& aAuthObject)
+    {
+    LOG_ENTERFN("CSecModUISyncWrapper::ChangeReferenceData");
+    iOperation = EOperationChangeReferenceData;    
+    iObject = STATIC_CAST(TAny*, &aAuthObject);
+    aAuthObject.ChangeReferenceData(iStatus);
+    SetActive();
+    iWait.Start();
+    iOperation = EOperationNone;
+    LOG_LEAVEFN("CSecModUISyncWrapper::ChangeReferenceData");
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::UnblockAuthObject(MCTAuthenticationObject& aAuthObject)
+// -----------------------------------------------------------------------------
+//
+TInt CSecModUISyncWrapper::UnblockAuthObject(
+    MCTAuthenticationObject& aAuthObject)
+    {
+    LOG_ENTERFN("CSecModUISyncWrapper::UnblockAuthObject");
+    iOperation = EOperationUnblockAO;
+    iObject = STATIC_CAST(TAny*, &aAuthObject);
+    aAuthObject.Unblock(iStatus);    
+    SetActive();
+    iWait.Start();
+    iOperation = EOperationNone;
+    LOG_LEAVEFN("CSecModUISyncWrapper::UnblockAuthObject");
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::EnableAuthObject(MCTAuthenticationObject& aAuthObject)
+// -----------------------------------------------------------------------------
+//    
+TInt CSecModUISyncWrapper::EnableAuthObject( 
+    MCTAuthenticationObject& aAuthObject)
+    {
+    LOG_ENTERFN("CSecModUISyncWrapper::EnableAuthObject");
+    iOperation = EOperationEnableAO;
+    iObject = STATIC_CAST(TAny*, &aAuthObject);
+    aAuthObject.Enable(iStatus);
+    iOperation = EOperationUnblockAO;
+    SetActive();
+    iWait.Start();
+    iOperation = EOperationNone;
+    LOG_LEAVEFN("CSecModUISyncWrapper::EnableAuthObject");
+    return iStatus.Int();
+    }
+  
+// -----------------------------------------------------------------------------
+// CSecModUIModel::DisableAuthObject(MCTAuthenticationObject& aAuthObject)
+// -----------------------------------------------------------------------------
+//  
+TInt CSecModUISyncWrapper::DisableAuthObject(
+    MCTAuthenticationObject& aAuthObject)
+    {
+    LOG_ENTERFN("CSecModUISyncWrapper::DisableAuthObject");
+    iOperation = EOperationDisableAO;
+    iObject = STATIC_CAST(TAny*, &aAuthObject);
+    aAuthObject.Disable(iStatus);    
+    SetActive();
+    iWait.Start();
+    iOperation = EOperationNone;
+    LOG_LEAVEFN("CSecModUISyncWrapper::DisableAuthObject");
+    return iStatus.Int();
+    }    
+    
+// -----------------------------------------------------------------------------
+// CSecModUISyncWrapper::CloseAuthObject(MCTAuthenticationObject& aAuthObject)
+// -----------------------------------------------------------------------------
+//
+TInt CSecModUISyncWrapper::CloseAuthObject(
+    MCTAuthenticationObject& aAuthObject)
+    {
+    LOG_ENTERFN("CSecModUISyncWrapper::CloseAuthObject");
+    iOperation = EOperationCloseAO;
+    iObject = STATIC_CAST(TAny*, &aAuthObject);
+    aAuthObject.Close(iStatus);    
+    SetActive();
+    iWait.Start();
+    iOperation = EOperationNone;
+    LOG_LEAVEFN("CSecModUISyncWrapper::CloseAuthObject");
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIModel::TimeRemaining(...)
+// -----------------------------------------------------------------------------
+//    
+TInt CSecModUISyncWrapper::TimeRemaining( 
+    MCTAuthenticationObject& aAuthObject, 
+    TInt& aStime )
+    {
+    LOG_ENTERFN("CSecModUISyncWrapper::TimeRemaining");
+    iOperation = EOperationTimeRemAO;
+    iObject = STATIC_CAST(TAny*, &aAuthObject);
+    aAuthObject.TimeRemaining(aStime, iStatus);
+    SetActive();
+    iWait.Start();
+    iOperation = EOperationNone;
+    LOG_LEAVEFN("CSecModUISyncWrapper::TimeRemaining");
+    return iStatus.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUISyncWrapper::DoCancel
+// Cancels the ongoing operation if possible.
+// -----------------------------------------------------------------------------
+//
+void CSecModUISyncWrapper::DoCancel()
+    {
+    LOG_ENTERFN("CSecModUISyncWrapper::DoCancel");
+    switch ( iOperation )
+        {
+        case EOperationInit:
+            {  
+            LOG_WRITE("CSecModUISyncWrapper::DoCancel: EOperationInit");          
+            STATIC_CAST(CUnifiedKeyStore*, iObject)->CancelInitialize();
+            break;
+            }
+        case EOperationGetAOInterface:
+            {            
+            LOG_WRITE("CSecModUISyncWrapper::DoCancel: EOperationGetAOInterface");          
+            STATIC_CAST(MCTToken*, iObject)->CancelGetInterface();
+            break;
+            }        
+        case EOperationListAOs:
+            {
+            LOG_WRITE("CSecModUISyncWrapper::DoCancel: EOperationListAOs");          
+            STATIC_CAST(MCTAuthenticationObjectList*, iObject)->CancelList();
+            break;
+            }
+        case EOperationListKeys:
+            {
+            LOG_WRITE("CSecModUISyncWrapper::DoCancel: EOperationListKeys");          
+            STATIC_CAST(MCTKeyStore*, iObject)->CancelList();
+            break;
+            }            
+        case EOperationDelKey:
+            {
+            LOG_WRITE("CSecModUISyncWrapper::DoCancel: EOperationDelKey");          
+            STATIC_CAST(CUnifiedKeyStore*, iObject)->CancelDeleteKey();
+            break;
+            }
+        case EOperationChangeReferenceData:
+            {
+            LOG_WRITE("CSecModUISyncWrapper::DoCancel: EOperationChangeReferenceData");          
+            STATIC_CAST(MCTAuthenticationObject*, iObject)->
+                CancelChangeReferenceData();
+            break;
+            }
+        case EOperationUnblockAO:
+            {
+            LOG_WRITE("CSecModUISyncWrapper::DoCancel: EOperationInit");          
+            STATIC_CAST(MCTAuthenticationObject*, iObject)->CancelUnblock();
+            break;
+            }
+        case EOperationEnableAO:
+            {
+            LOG_WRITE("CSecModUISyncWrapper::DoCancel: EOperationEnableAO");          
+            STATIC_CAST(MCTAuthenticationObject*, iObject)->CancelEnable();
+            break;
+            }
+        case EOperationDisableAO:
+            {
+            LOG_WRITE("CSecModUISyncWrapper::DoCancel: EOperationDisableAO");          
+            STATIC_CAST(MCTAuthenticationObject*, iObject)->CancelDisable();
+            break;
+            }
+        case EOperationCloseAO:
+            {
+            LOG_WRITE("CSecModUISyncWrapper::DoCancel: EOperationCloseAO");          
+            STATIC_CAST(MCTAuthenticationObject*, iObject)->CancelClose();
+            break;
+            }
+        case EOperationTimeRemAO:
+            {
+            LOG_WRITE("CSecModUISyncWrapper::DoCancel: EOperationTimeRemAO");          
+            STATIC_CAST(MCTAuthenticationObject*, iObject)->CancelTimeRemaining();
+            break;
+            }        
+        default:
+            {
+            break;
+            }
+        }
+    if (iWait.IsStarted())
+        {
+        iWait.AsyncStop();
+        }
+    LOG_LEAVEFN("CSecModUISyncWrapper::DoCancel");    
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUISyncWrapper::RunL
+// If no errors happened, stop. Show an error note if needed.
+// -----------------------------------------------------------------------------
+//
+void CSecModUISyncWrapper::RunL()
+    {    
+    iWait.AsyncStop();    
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUISyncWrapper::HandleErrorL()
+// Shows an error note according to status of operation,
+// -----------------------------------------------------------------------------
+//
+void CSecModUISyncWrapper::HandleErrorL()
+    {
+        
+    }
+
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUIViewAccess.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,503 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecModUIViewAccess class
+*
+*/
+
+
+// INCLUDE FILES
+#include  "SecModUIContainerAccess.h"
+#include  "SecModUIViewAccess.h" 
+#include  "SecModUIModel.h"
+#include  "SecModUISyncWrapper.h"
+#include  "secmodui.hrh"
+#include  <SecModUI.rsg>
+#include  <aknViewAppUi.h>
+#include  <avkon.hrh>
+#include  <aknlists.h>
+#include  <eikmenup.h>
+#include  <featmgr.h>
+
+// CONSTANTS
+
+// ================= MEMBER FUNCTIONS =======================
+
+// -----------------------------------------------------------------------------
+// CSecModUIViewAccess::CSecModUIViewAccess
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CSecModUIViewAccess::CSecModUIViewAccess(CSecModUIModel& aModel):
+    CSecModUIViewBase(aModel)
+    {
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewAccess::ConstructL(const TRect& aRect)
+// EPOC two-phased constructor
+// ---------------------------------------------------------
+//
+void CSecModUIViewAccess::ConstructL()
+    {
+    BaseConstructL( R_SECMODUI_VIEW_ACCESS );
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewAccess::~CSecModUIViewAccess()
+// destructor
+// ---------------------------------------------------------
+//
+CSecModUIViewAccess::~CSecModUIViewAccess()
+    {
+    
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewCode::NewLC
+// Two-phased constructor.
+// ---------------------------------------------------------
+//
+CSecModUIViewAccess* CSecModUIViewAccess::NewLC(CSecModUIModel& aModel)
+    {
+    CSecModUIViewAccess* self = new (ELeave) CSecModUIViewAccess(aModel);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// TUid CSecModUIViewAccess::Id()
+//
+// ---------------------------------------------------------
+//
+TUid CSecModUIViewAccess::Id() const
+    {
+    return KSecModUIViewAccessId;
+    }
+
+// ---------------------------------------------------------
+// void CSecModUIViewCode::CreateContainerL()
+// Creates container
+// ---------------------------------------------------------
+//
+void CSecModUIViewAccess::CreateContainerL()
+    {
+    iContainer = new (ELeave) CSecModUIContainerAccess(iModel, this);
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewAccess::AddNavipaneLabelL()
+// Default implementation is empty
+// ---------------------------------------------------------
+//
+void CSecModUIViewAccess::AddNaviPaneLabelL()
+    { 
+    DoAddNaviPaneL(R_NAVIPANE_ACCESS_TEXT);   
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewAccess::HandleCommandL(TInt aCommand)
+// takes care of view command handling
+// ---------------------------------------------------------
+//
+void CSecModUIViewAccess::HandleCommandL(TInt aCommand)
+    {
+    if (iModel.Wrapper().IsActive())
+        {
+        return;
+        }   
+    switch ( aCommand )
+        {
+        case ESecModUICmdChange:
+            {
+            HandleChangeL();            
+            break;
+            }
+        case ESecModUICmdUnblock:
+            {
+            iModel.UnblockPinL(KPinGIndex);
+            UpdateListBoxItemL(EIndexCodeStatus);
+            UpdateListBoxItemL(EIndexCodeRequest);
+            UpdateCbaL();
+            break;
+            }
+        case ESecModUICmdClose:
+            {
+            iModel.CloseAuthObjL(KPinGIndex);
+            UpdateListBoxItemL(EIndexCodeStatus);
+            UpdateCbaL();
+            break;
+            }
+        case EAknSoftkeyChange:
+            {
+            HandleChangeL();	
+            break;	
+            }
+        case EAknSoftkeyClose:
+            {
+            iModel.CloseAuthObjL(KPinGIndex);
+            UpdateListBoxItemL(EIndexCodeStatus);
+            UpdateCbaL();
+            break;	
+            }
+            
+        case EAknSoftkeyUnlock:
+            {
+            iModel.UnblockPinL(KPinGIndex);
+            UpdateListBoxItemL(EIndexCodeStatus);
+            UpdateListBoxItemL(EIndexCodeRequest);
+            UpdateCbaL();
+            break;	
+            }
+        default:
+            {
+            CSecModUIViewBase::HandleCommandL( aCommand );
+            break;
+            }
+        }
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewAccess::HandleChangeL()
+// takes care of Change command handling
+// ---------------------------------------------------------
+//
+void CSecModUIViewAccess::HandleChangeL()
+    {
+    TInt currentItem = iContainer->ListBox().CurrentItemIndex();
+    
+    switch (currentItem)
+        {
+        case EIndexCodeLabel:
+            {
+            iModel.ChangeOrUnblockPinL(KPinGIndex);
+            UpdateListBoxItemL(EIndexCodeStatus);
+            UpdateCbaL();
+            break;
+            }
+        case EIndexCodeRequest:
+            {
+            if (KErrCancel != iModel.ChangeCodeRequestL(KPinGIndex))
+                {
+                UpdateListBoxItemL(EIndexCodeRequest);
+                UpdateListBoxItemL(EIndexCodeStatus);
+                UpdateCbaL();
+                }
+            break;
+            }
+        default:
+            {
+            break;
+            }                
+        }
+    }
+// ---------------------------------------------------------
+// CSecModUIViewAccess::HandleForegroundEventL()
+// ---------------------------------------------------------
+//
+void CSecModUIViewAccess::HandleForegroundEventL(TBool aForeground)
+    {
+	if( aForeground && !iModel.Wrapper().IsActive() )
+	    {
+	    UpdateListBoxItemL(EIndexCodeRequest);
+        UpdateListBoxItemL(EIndexCodeStatus);
+        UpdateCbaL();	
+	    }
+    }
+
+
+// ---------------------------------------------------------
+// CSecModUIViewAccess::UpdateListBoxItemL(TInt aIndex)
+// Updates listbox item
+// ---------------------------------------------------------
+//
+void CSecModUIViewAccess::UpdateListBoxItemL(TInt aIndex)
+    {
+    TBuf<KMaxSettItemSize> item; 
+        CDesCArray* itemArray = STATIC_CAST(CDesCArray*, 
+            iContainer->ListBox().Model()->ItemTextArray());
+    switch(aIndex)
+        {
+        case EIndexCodeRequest:
+            {
+            iModel.PINRequestItemL(KPinGIndex, item);
+            break;
+            }
+        case EIndexCodeStatus:
+            {
+            iModel.PINStatusItemL(KPinGIndex, item, EFalse);
+            break;
+            }
+        default: 
+            {
+            return;
+            }
+        }
+    itemArray->Delete(aIndex);    
+    itemArray->InsertL(aIndex, item);
+    iContainer->ListBox().HandleItemAdditionL();
+    iContainer->DrawNow();
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewAccess::UpdateCbaL()
+// Updates Cba area
+// ---------------------------------------------------------
+//    
+void CSecModUIViewAccess::UpdateCbaL()
+    {
+    TInt currentItem = iContainer->ListBox().CurrentItemIndex();
+    switch (currentItem)
+            {
+            case EIndexCodeLabel:
+                {
+                 if( iModel.PinChangeable(KPinGIndex) )
+                     {
+                     SetCbaL(R_SECMODUI_SOFTKEYS_OPTIONS_BACK_CHANGE);
+                     }   
+                 else
+                     {
+                     if( !iModel.PinUnblockable(KPinGIndex) )
+                         {
+                         SetCbaL(R_SECMODUI_SOFTKEYS_OPTIONS_BACK);
+                         } 
+                     else
+                         {
+                         SetCbaL(R_SECMODUI_SOFTKEYS_OPTIONS_BACK_UNBLOCK);	
+                         }     
+                     }    	    
+                break;
+                }
+            case EIndexCodeRequest:
+                {
+                if( iModel.PinRequestChangeable(KPinGIndex) )
+                     {
+                     SetCbaL(R_SECMODUI_SOFTKEYS_OPTIONS_BACK_CHANGE);
+                     }   
+                 else
+                     {
+                     if( !iModel.PinUnblockable(KPinGIndex) )
+                         {
+                         SetCbaL(R_SECMODUI_SOFTKEYS_OPTIONS_BACK);
+                         } 
+                     else
+                         {
+                         SetCbaL(R_SECMODUI_SOFTKEYS_OPTIONS_BACK_UNBLOCK);	
+                         }     
+                     }     
+                break;
+                }
+            case EIndexCodeStatus:
+                {
+                if( !iModel.PinChangeable(KPinGIndex) && iModel.PinUnblockable(KPinGIndex))
+                    {
+                    SetCbaL(R_SECMODUI_SOFTKEYS_OPTIONS_BACK_UNBLOCK);	
+                    }     
+                else if(iModel.PinOpen(KPinGIndex))  
+                    {
+                	SetCbaL(R_SECMODUI_SOFTKEYS_OPTIONS_BACK_CLOSE);
+                    }
+                else
+                    {
+                    SetCbaL(R_SECMODUI_SOFTKEYS_OPTIONS_BACK);	
+                    }    
+                
+                break;
+                }
+            default:
+                {
+                break;
+                }
+            }    	
+    }
+
+
+// ---------------------------------------------------------
+// CSecModUIViewAccess::SetCbaL( TInt aCbaResourceId )
+// Sets Cba area
+// ---------------------------------------------------------
+//  
+void CSecModUIViewAccess::SetCbaL( TInt aCbaResourceId )
+    {
+	CEikButtonGroupContainer*  cba = Cba();
+    cba->SetCommandSetL(aCbaResourceId);
+    cba->DrawNow();
+    }
+    
+    
+// ---------------------------------------------------------
+// TUid CSecModUIViewAccess::DynInitMenuPaneL(
+//      TInt aResourceId, CEikMenuPane* aMenuPane)
+//
+// ---------------------------------------------------------
+//
+void CSecModUIViewAccess::DynInitMenuPaneL(
+    TInt aResourceId, 
+    CEikMenuPane* aMenuPane)
+    {
+    if( R_SECMODUI_VIEW_ACCESS_MENU == aResourceId )
+        {        
+        if( aResourceId == !FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+            {
+            aMenuPane->DeleteMenuItem( EAknCmdHelp ); //remove help
+            }     
+
+        TInt currentItem = iContainer->ListBox().CurrentItemIndex();
+        if( currentItem == EIndexCodeLabel )
+            {
+            if( !iModel.PinChangeable(KPinGIndex) )
+                {
+                aMenuPane->SetItemDimmed( ESecModUICmdChange, ETrue );
+                }
+            }
+        else if( currentItem == EIndexCodeRequest )
+            {
+            if( !iModel.PinRequestChangeable(KPinGIndex) )
+                {
+                aMenuPane->SetItemDimmed( ESecModUICmdChange, ETrue );
+                }
+            }
+        else // it is EIndexCodeStatus
+            {
+            aMenuPane->SetItemDimmed( ESecModUICmdChange, ETrue );
+            }
+
+        if( !iModel.PinUnblockable(KPinGIndex) )
+            {
+            aMenuPane->SetItemDimmed( ESecModUICmdUnblock, ETrue );
+            }
+        if( !iModel.PinOpen(KPinGIndex) )
+            {
+            aMenuPane->SetItemDimmed( ESecModUICmdClose, ETrue );
+            }
+        }
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewAccess::HandleEnterKeyL(TInt aIndex)
+//     
+// ---------------------------------------------------------
+//   
+void CSecModUIViewAccess::HandleEnterKeyL(TInt aIndex)
+    {
+    switch(aIndex)
+        {        
+        case EIndexCodeLabel:
+            {
+            HandleChangeL();
+            break;
+            }
+        case EIndexCodeRequest:
+            {
+            HandleChangeL();
+            break;
+            }
+        case EIndexCodeStatus:
+            {
+            iModel.CloseAuthObjL(KPinGIndex);
+            UpdateListBoxItemL(EIndexCodeStatus);
+            UpdateCbaL();
+            break;
+            }
+        default:
+            {
+            break;
+            }
+        }
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewAccess::HandleListBoxEventL(
+//     CEikListBox* aListBox, TListBoxEvent aEventType)
+// ---------------------------------------------------------
+//   
+void CSecModUIViewAccess::HandleListBoxEventL(
+    CEikListBox* aListBox, 
+    TListBoxEvent aEventType)
+    {
+    if(iModel.Wrapper().IsActive())
+        {
+        return;	
+        }
+        
+    TInt index = aListBox->CurrentItemIndex();
+
+    switch( aEventType )
+		{
+		case EEventEnterKeyPressed:
+		case EEventItemDoubleClicked:
+		case EEventItemSingleClicked:
+			{
+			HandleEnterKeyL(index);
+            break;
+			}
+        default:
+            {
+			break;
+            }
+		}           
+    }
+
+
+// ---------------------------------------------------------
+// CSecModUIViewAccess::DoDeactivate()
+// 
+// ---------------------------------------------------------
+//
+void CSecModUIViewAccess::DoActivateL(
+   const TVwsViewId& aPrevViewId,TUid /*aCustomMessageId*/,
+   const TDesC8& /*aCustomMessage*/)
+    {
+  
+    if (KNullUid == iPrevViewId.iViewUid)
+        {
+        iPrevViewId = aPrevViewId;
+        }
+    SetTitlePaneL();
+    AddNaviPaneLabelL();
+                    
+    if (!iContainer)
+        {
+        CreateContainerL();
+        iContainer->SetMopParent(this);
+        iContainer->ConstructL(ClientRect());
+        iContainer->ListBox().SetListBoxObserver(this);
+        AppUi()->AddToStackL(*this, iContainer);
+        }         
+   iContainer->MakeVisible(ETrue);
+   iContainer->SetRect(ClientRect());
+   iContainer->ActivateL();
+   
+   UpdateCbaL();  
+   }
+
+// ---------------------------------------------------------
+// CSecModUIViewAccess::DoDeactivate()
+// 
+// ---------------------------------------------------------
+//
+void CSecModUIViewAccess::DoDeactivate()
+    {
+    if ( iContainer )
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainer );
+        }
+    
+    delete iContainer;
+    iContainer = NULL;    
+    }    
+    
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUIViewBase.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,262 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecModUIViewBase class
+*
+*/
+
+
+// INCLUDE FILES
+#include  "SecModUIViewBase.h"
+#include  "SecModUIContainerBase.h" 
+#include  "SecModUIModel.h"
+#include  "SecModUILogger.h"
+#include  "secmodui.hrh"
+#include  <SecModUI.rsg>
+#include  <aknViewAppUi.h>
+#include  <avkon.hrh>
+#include  <eiktxlbx.h>
+#include  <aknnavi.h>
+#include  <aknnavide.h> 
+#include  <barsread.h>
+#include    <hlplch.h>   // For HlpLauncher 
+#include  <featmgr.h>
+
+
+// ================= MEMBER FUNCTIONS =======================
+
+// -----------------------------------------------------------------------------
+// CSecModUIViewBase::CSecModUIViewBase
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CSecModUIViewBase::CSecModUIViewBase(CSecModUIModel& aModel):
+    CAknView(), iModel(aModel)
+    {    
+    LOG_WRITE( "CSecModUIViewBase::CSecModUIViewBase" );
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewBase::~CSecModUIViewBase()
+// destructor
+// ---------------------------------------------------------
+//
+CSecModUIViewBase::~CSecModUIViewBase()
+    {
+    LOG_WRITE( "CSecModUIViewBase::~CSecModUIViewBase" );
+    delete iNaviDecorator;
+    if (iContainer)
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainer );
+        }
+    delete iContainer;
+    }
+    
+// ---------------------------------------------------------
+// CSecModUIViewBase::HandleCommandL(TInt aCommand)
+// takes care of view command handling
+// ---------------------------------------------------------
+//
+void CSecModUIViewBase::HandleCommandL(TInt aCommand)
+    {
+    LOG_ENTERFN("CSecModUIViewBase::HandleCommandL()");   
+    switch ( aCommand )
+        {
+        case EAknSoftkeyBack:
+            {
+            AppUi()->ActivateLocalViewL(iPrevViewId.iViewUid);
+            break;
+            }
+        case ESecModUICmdModuleInfo:
+            {
+            iModel.ViewOpenedSecModDetailsL();
+            break;
+            }
+        case EAknCmdExit:
+            {
+            ((CAknViewAppUi*)iAvkonAppUi)->HandleCommandL(EAknCmdExit);
+            break;
+            }
+        case EAknCmdHelp: 
+            {
+            if( FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+                {
+                HlpLauncher::LaunchHelpApplicationL(
+                    iEikonEnv->WsSession(), AppUi()->AppHelpContextL() );   
+                }    
+            break;
+            }    
+        default:
+            {            
+            break;
+            }
+        }
+    LOG_LEAVEFN("CSecModUIViewBase::HandleCommandL()");    
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewBase::HandleClientRectChange()
+// ---------------------------------------------------------
+//
+void CSecModUIViewBase::HandleClientRectChange()
+    {
+    LOG_ENTERFN("CSecModUIViewBase::HandleClientRectChange()");   
+    if ( iContainer )
+        {
+        iContainer->SetRect( ClientRect() );
+        }
+    LOG_LEAVEFN("CSecModUIViewBase::HandleClientRectChange()");        
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewBase::DoActivateL(...)
+// 
+// ---------------------------------------------------------
+//
+void CSecModUIViewBase::SetTitlePaneL()
+    {
+    iModel.ActivateTokenLabelToTitleL();
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewBase::AddNavipaneLabelL()
+// Default implementation is empty
+// ---------------------------------------------------------
+//
+void CSecModUIViewBase::AddNaviPaneLabelL()
+    {
+    DoAddNaviPaneL();               
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewBase::DoAddNaviPaneL()
+// Creates navi pane text
+// ---------------------------------------------------------
+//
+void CSecModUIViewBase::DoAddNaviPaneL(TInt aResource)
+    {
+    TUid naviPaneUid;
+    naviPaneUid.iUid = EEikStatusPaneUidNavi;
+    CEikStatusPane* statusPane = StatusPane();
+    CAknNavigationControlContainer* naviPane =
+        (CAknNavigationControlContainer*) statusPane->ControlL(naviPaneUid);
+    if(!iNaviDecorator)
+        {
+        // Let's try to create navipane
+        CEikStatusPaneBase::TPaneCapabilities subPane =
+        statusPane->PaneCapabilities(naviPaneUid);
+    
+        if (subPane.IsPresent() && subPane.IsAppOwned())
+            {
+            if (0 != aResource)
+                {
+                TResourceReader reader;
+                iCoeEnv->CreateResourceReaderLC(reader, aResource);
+
+                 // set the navigation pane label
+                iNaviDecorator = naviPane->CreateNavigationLabelL(reader);
+                CleanupStack::PopAndDestroy();
+                }
+             else
+                {
+                iNaviDecorator = naviPane->CreateNavigationLabelL();
+                }
+            }
+        }
+    if (iNaviDecorator)
+        {
+        naviPane->PushL(*iNaviDecorator);
+        }
+    }
+        
+// ---------------------------------------------------------
+// CSecModUIViewBase::DoActivateL(...)
+// 
+// ---------------------------------------------------------
+//
+void CSecModUIViewBase::DoActivateL(
+   const TVwsViewId& aPrevViewId,TUid /*aCustomMessageId*/,
+   const TDesC8& /*aCustomMessage*/)
+    {
+    LOG_ENTERFN("CSecModUIViewBase::DoActivateL()");   
+    if (KNullUid == iPrevViewId.iViewUid)
+        {
+        iPrevViewId = aPrevViewId;
+        }
+    SetTitlePaneL();
+    AddNaviPaneLabelL();
+                    
+    if (!iContainer)
+        {
+        CreateContainerL();
+        iContainer->SetMopParent(this);
+        iContainer->ConstructL(ClientRect());
+        iContainer->ListBox().SetListBoxObserver(this);
+        AppUi()->AddToStackL(*this, iContainer);
+        }         
+   iContainer->ListBox().SetTopItemIndex( iTopItem );
+   //the iCurrentPostion can be -1, if no keystore presents.
+   if ( iCurrentPosition >= 0 )
+       {
+       iContainer->ListBox().SetCurrentItemIndex( iCurrentPosition ); 	
+       } 
+   iContainer->MakeVisible(ETrue);
+   iContainer->SetRect(ClientRect());
+   iContainer->ActivateL();
+   
+   
+   LOG_LEAVEFN("CSecModUIViewBase::DoActivateL()");    
+   }
+
+// ---------------------------------------------------------
+// CSecModUIViewBase::DoDeactivate()
+// 
+// ---------------------------------------------------------
+//
+void CSecModUIViewBase::DoDeactivate()
+    {
+    LOG_ENTERFN("CSecModUIViewBase::DoDeactivate()");   
+    if ( iContainer )
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainer );
+        iCurrentPosition = iContainer->ListBox().CurrentItemIndex();
+        iTopItem = iContainer->ListBox().TopItemIndex();
+        }
+    
+    delete iContainer;
+    iContainer = NULL;
+    LOG_LEAVEFN("CSecModUIViewBase::DoDeactivate()");    
+    }
+
+// ---------------------------------------------------------
+// CSecModUIContainerBase::HandleListBoxEventL(
+//     CEikListBox* aListBox, TListBoxEvent aEventType)
+// ---------------------------------------------------------
+//    
+void CSecModUIViewBase::HandleListBoxEventL(
+    CEikListBox* /*aListBox*/, 
+    TListBoxEvent aEventType)
+    {
+    LOG_ENTERFN("CSecModUIContainerBase::HandleListBoxEventL()");   
+    switch( aEventType )
+		{	
+        default:
+            {
+			break;
+            }
+		} 
+    LOG_LEAVEFN("CSecModUIContainerBase::HandleListBoxEventL()");    		          
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUIViewCode.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,228 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecModUIViewCode class
+*
+*/
+
+
+// INCLUDE FILES
+#include  "secmodui.hrh"
+#include  "SecModUIViewCode.h"
+#include  "SecModUIContainerCode.h" 
+#include  "SecModUIModel.h"
+#include  "SecModUILogger.h"
+#include  "SecModUISyncWrapper.h"
+#include  <aknViewAppUi.h>
+#include  <avkon.hrh>
+#include  <aknlists.h>
+#include  <SecModUI.rsg>
+
+// ================= MEMBER FUNCTIONS =======================
+
+// -----------------------------------------------------------------------------
+// CSecModUIViewCode::CSecModUIViewCode
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CSecModUIViewCode::CSecModUIViewCode(CSecModUIModel& aModel):CSecModUIViewBase(aModel)
+    {
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewCode::ConstructL(const TRect& aRect)
+// EPOC two-phased constructor
+// ---------------------------------------------------------
+//
+void CSecModUIViewCode::ConstructL()
+    {
+    LOG_ENTERFN("CSecModUIViewCode::ConstructL()");     
+    BaseConstructL( R_SECMODUI_VIEW_CODE );
+    LOG_LEAVEFN("CSecModUIViewCode::ConstructL()");        
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewCode::~CSecModUIViewCode()
+// destructor
+// ---------------------------------------------------------
+//
+CSecModUIViewCode::~CSecModUIViewCode()
+    {  
+    LOG_ENTERFN("CSecModUIViewCode::~CSecModUIViewCode()");     
+    LOG_LEAVEFN("CSecModUIViewCode::~CSecModUIViewCode()");        
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIViewCode::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CSecModUIViewCode* CSecModUIViewCode::NewLC(CSecModUIModel& aModel)
+    {
+    LOG_ENTERFN("CSecModUIViewCode::NewLC()");   
+    CSecModUIViewCode* self = new (ELeave) CSecModUIViewCode(aModel);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    LOG_LEAVEFN("CSecModUIViewCode::NewLC()");        
+    return self;
+    }
+
+// ---------------------------------------------------------
+// TUid CSecModUIViewCode::Id()
+// 
+// ---------------------------------------------------------
+//
+TUid CSecModUIViewCode::Id() const
+    {
+    return KSecModUIViewCodeId;
+    }
+
+// ---------------------------------------------------------
+// TUid CSecModUIViewCode::CreateContainerL()
+// Creates container
+// ---------------------------------------------------------
+//
+void CSecModUIViewCode::CreateContainerL()
+    {
+    LOG_ENTERFN("CSecModUIViewCode::CreateContainerL()");   
+    iContainer = new (ELeave) CSecModUIContainerCode(iModel);
+    LOG_LEAVEFN("CSecModUIViewCode::CreateContainerL()");        
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewCode::HandleCommandL(TInt aCommand)
+// takes care of view command handling
+// ---------------------------------------------------------
+//
+void CSecModUIViewCode::HandleCommandL(TInt aCommand)
+    {   
+    LOG_ENTERFN("CSecModUIViewCode::HandleCommandL()");   
+    if (iModel.Wrapper().IsActive())
+        {
+        return;
+        }
+    switch ( aCommand )
+        {
+        case ESecModUICmdOpen:
+            {
+            iModel.OpenAuthObjViewL(iContainer->ListBox().CurrentItemIndex());
+            break;
+            }
+        case ESecModUICmdModuleInfo:
+            {
+            iModel.ViewOpenedSecModDetailsL();
+            break;
+            }
+        case EAknSoftkeyOpen:
+            {
+            iModel.OpenAuthObjViewL(iContainer->ListBox().CurrentItemIndex());
+            break;	
+            }
+        default:
+            {
+            CSecModUIViewBase::HandleCommandL(aCommand);
+            break;
+            }
+        }
+    LOG_LEAVEFN("CSecModUIViewCode::HandleCommandL()");        
+    }
+    
+
+
+// ---------------------------------------------------------
+// CSecModUIViewBase::DoActivateL(...)
+// 
+// ---------------------------------------------------------
+//
+/*void CSecModUIViewCode::DoActivateL(
+   const TVwsViewId& aPrevViewId,TUid aCustomMessageId,
+   const TDesC8& aCustomMessage)
+    {
+    LOG_ENTERFN("CSecModUIViewCode::DoActivateL()");   
+    if (KNullUid == iPrevViewId.iViewUid)
+        {
+        iPrevViewId = aPrevViewId;
+        }
+    SetTitlePaneL();
+    AddNaviPaneLabelL();
+    
+    if (aPrevViewId.iViewUid == KSecModUIViewMainId)
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainer );
+        delete iContainer;
+        iContainer = NULL;
+        }
+                    
+    if (!iContainer)
+        {
+        CreateContainerL();
+        iContainer->SetMopParent(this);
+        iContainer->ConstructL(ClientRect());
+        iContainer->ListBox().SetListBoxObserver(this);        
+        }         
+   AppUi()->AddToStackL(*this, iContainer);            
+   iContainer->MakeVisible(ETrue);
+   iContainer->SetRect(ClientRect());
+   iContainer->ActivateL();
+     
+   LOG_LEAVEFN("CSecModUIViewCode::DoActivateL()");    
+   }*/
+
+// ---------------------------------------------------------
+// CSecModUIViewBase::DoDeactivate()
+// 
+// ---------------------------------------------------------
+//
+/*void CSecModUIViewCode::DoDeactivate()
+    {
+    LOG_ENTERFN("CSecModUIViewCode::DoDeactivate()");   
+    if ( iContainer )
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainer );
+        }
+        
+    LOG_LEAVEFN("CSecModUIViewCode::DoDeactivate()");    
+    }*/
+
+// ---------------------------------------------------------
+// CSecModUIViewCode::HandleListBoxEventL(
+//     CEikListBox* aListBox, TListBoxEvent aEventType)
+// ---------------------------------------------------------
+//    
+void CSecModUIViewCode::HandleListBoxEventL(CEikListBox* aListBox, TListBoxEvent aEventType)
+    {
+    LOG_ENTERFN("CSecModUIViewCode::HandleListBoxEventL()");   
+    if(iModel.Wrapper().IsActive())
+        {
+        return;	
+        }
+         
+    switch( aEventType )
+		{
+		case EEventEnterKeyPressed:
+		case EEventItemDoubleClicked:
+		case EEventItemSingleClicked:
+			{
+			iModel.OpenAuthObjViewL(aListBox->CurrentItemIndex());
+            break;
+			}
+        default:
+            {
+			break;
+            }
+		}           
+    LOG_LEAVEFN("CSecModUIViewCode::HandleListBoxEventL()");        		
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUIViewMain.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,311 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecModUIViewMain class
+*
+*/
+
+
+// INCLUDE FILES
+#include  "secmodui.hrh"
+#include  <SecModUI.rsg>
+#include  "SecModUIViewMain.h"
+#include  "SecModUIContainerMain.h" 
+#include  "SecModUIModel.h"
+#include  "SecModUISyncWrapper.h"
+#include  "SecModUILogger.h"
+#include  <SecModUI.rsg>
+#include  <aknViewAppUi.h>
+#include  <avkon.hrh>
+#include  <aknlists.h>
+#include  <eikmenup.h>
+#include  <StringLoader.h> 
+#include  <badesca.h>
+#include  <featmgr.h>
+// ================= MEMBER FUNCTIONS =======================
+
+// -----------------------------------------------------------------------------
+// CSecModUIViewMain::CSecModUIViewMain
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CSecModUIViewMain::CSecModUIViewMain(CSecModUIModel& aModel):
+    CSecModUIViewBase(aModel)
+    {
+    //LOG_CREATE;
+    LOG_WRITE( "CSecModUIViewMain::CSecModUIViewMain" );
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewMain::ConstructL(const TRect& aRect)
+// EPOC two-phased constructor
+// ---------------------------------------------------------
+//
+void CSecModUIViewMain::ConstructL()
+    {
+    LOG_ENTERFN("CSecModUIViewMain::ConstructL()");
+    BaseConstructL( R_SECMODUI_VIEW_MAIN );
+    LOG_LEAVEFN("CSecModUIViewMain::ConstructL()");
+    }
+
+// ---------------------------------------------------------
+// TUid CSecModUIViewMain::CreateContainerL()
+// Creates container
+// ---------------------------------------------------------
+//
+void CSecModUIViewMain::CreateContainerL()
+    {
+    LOG_ENTERFN("CSecModUIViewMain::CreateContainerL()");
+    iContainer = new (ELeave) CSecModUIContainerMain(iModel);
+    LOG_LEAVEFN("CSecModUIViewMain::CreateContainerL()");
+    }
+// ---------------------------------------------------------
+// CSecModUIViewMain::~CSecModUIViewMain()
+// destructor
+// ---------------------------------------------------------
+//
+CSecModUIViewMain::~CSecModUIViewMain()
+    {
+    LOG_WRITE( "CSecModUIViewMain::~CSecModUIViewMain" );    
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIViewMain::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CSecModUIViewMain* CSecModUIViewMain::NewLC(CSecModUIModel& aModel)
+    {
+    LOG_ENTERFN("CSecModUIViewMain::NewLC()");
+    CSecModUIViewMain* self = new (ELeave) CSecModUIViewMain(aModel);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    LOG_LEAVEFN("CSecModUIViewMain::NewLC()");
+    return self;
+    }
+    
+// ---------------------------------------------------------
+// TUid CSecModUIViewMain::Id()
+//
+// ---------------------------------------------------------
+//
+TUid CSecModUIViewMain::Id() const
+    {
+    return KSecModUIViewMainId;
+    }
+
+// ---------------------------------------------------------
+// TUid CSecModUIViewMain::DynInitMenuPaneL(
+//      TInt aResourceId, CEikMenuPane* aMenuPane)
+//
+// ---------------------------------------------------------
+//
+void CSecModUIViewMain::DynInitMenuPaneL(
+    TInt aResourceId, 
+    CEikMenuPane* aMenuPane)
+    {
+    LOG_ENTERFN("CSecModUIViewMain::DynInitMenuPaneL()");
+        
+    if (aResourceId == R_SECMODUI_VIEW_MAIN_MENU)
+        {
+        if( !FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+            {
+            aMenuPane->DeleteMenuItem( EAknCmdHelp ); //remove help
+            }
+        TInt currentItem = iContainer->ListBox().CurrentItemIndex();
+        // The security module list is empty.  
+        // All except Exit and Help is dimmed.
+        if (currentItem == -1)
+            {
+            aMenuPane->SetItemDimmed( ESecModUICmdOpen, ETrue );
+            aMenuPane->SetItemDimmed( ESecModUICmdModuleInfo, ETrue );
+            aMenuPane->SetItemDimmed( ESecModUICmdDelKeyStore, ETrue );
+            }
+        else if (!iModel.IsTokenDeletable(currentItem))
+            {
+            aMenuPane->SetItemDimmed( ESecModUICmdDelKeyStore, ETrue ); 
+            }
+         else
+            {
+            }
+        }
+    
+    LOG_LEAVEFN("CSecModUIViewMain::DynInitMenuPaneL()");
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewMain::HandleCommandL(TInt aCommand)
+// takes care of view command handling
+// ---------------------------------------------------------
+//
+void CSecModUIViewMain::HandleCommandL(TInt aCommand)
+    {  
+    LOG_ENTERFN("CSecModUIViewMain::HandleCommandL()"); 
+    
+    if(iModel.Wrapper().IsActive())
+        {
+        return;	
+        }
+    
+    switch ( aCommand )
+        {
+        case ESecModUICmdOpen:
+            {
+            iModel.OpenTokenL(iContainer->ListBox().CurrentItemIndex());
+            break;
+            }
+        case ESecModUICmdDelKeyStore:
+            {
+            if (iModel.DeleteKeyStoreL(iContainer->ListBox().CurrentItemIndex()))            
+                {
+                CDesCArray* itemArray = STATIC_CAST(
+                CDesCArray*, iContainer->ListBox().Model()->ItemTextArray());
+                itemArray->Reset();                
+                iModel.LoadTokenLabelsL(iContainer->ListBox());
+                iContainer->DrawNow(); 
+                UpdateCbaL();          
+                }
+            break;
+            }
+        case ESecModUICmdModuleInfo:
+            {
+            iModel.ViewSecModDetailsL(iContainer->ListBox().CurrentItemIndex());
+            break;
+            } 
+        case EAknSoftkeyOpen:
+            {
+            iModel.OpenTokenL(iContainer->ListBox().CurrentItemIndex());
+            break;	
+            }
+        default:
+            {
+            CSecModUIViewBase::HandleCommandL(aCommand);
+            break;
+            }
+        }
+    LOG_LEAVEFN("CSecModUIViewMain::HandleCommandL()");
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewMain::SetTitlePaneL()
+// 
+// ---------------------------------------------------------
+//
+void CSecModUIViewMain::SetTitlePaneL()
+    {
+    LOG_ENTERFN("SecModUIViewMain::SetTitlePaneL()");
+	HBufC* titleText = StringLoader::LoadLC(R_QTN_WIM_TITLE);
+	iModel.ActivateTitleL(*titleText);
+	CleanupStack::PopAndDestroy(titleText);
+ 	LOG_LEAVEFN("SecModUIViewMain::SetTitlePaneL()");
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewMain::DoActivateL(...)
+// 
+// ---------------------------------------------------------
+//
+void CSecModUIViewMain::DoActivateL(
+   const TVwsViewId& aPrevViewId,TUid aCustomMessageId,
+   const TDesC8& aCustomMessage)
+   {
+   LOG_ENTERFN("CSecModUIViewMain::DoActivateL()");   
+   CSecModUIViewBase::DoActivateL(
+       aPrevViewId, aCustomMessageId, aCustomMessage);
+   UpdateCbaL();    
+   LOG_LEAVEFN("CSecModUIViewMain::DoActivateL()");    
+   }
+
+// ---------------------------------------------------------
+// CSecModUIContainerMain::HandleListBoxEventL(
+//     CEikListBox* aListBox, TListBoxEvent aEventType)
+// ---------------------------------------------------------
+//    
+void CSecModUIViewMain::HandleListBoxEventL(
+    CEikListBox* aListBox, 
+    TListBoxEvent aEventType)
+    {
+    LOG_ENTERFN("CSecModUIViewMain::HandleListBoxEventL()");   
+      
+    if(iModel.Wrapper().IsActive())
+        {
+        return;	
+        }
+        
+    switch( aEventType )
+		{
+		case EEventEnterKeyPressed:
+		case EEventItemDoubleClicked:
+		case EEventItemSingleClicked:
+			{
+			iModel.OpenTokenL(aListBox->CurrentItemIndex());
+            break;
+			}
+        default:
+            {
+			break;
+            }
+		} 
+	LOG_LEAVEFN("CSecModUIViewMain::HandleListBoxEventL()");   	          
+    }
+
+
+// ---------------------------------------------------------
+// CSecModUIViewMain::UpdateCbaL()
+// ---------------------------------------------------------
+//
+void CSecModUIViewMain::UpdateCbaL()
+    {
+    CDesCArray* itemArray = STATIC_CAST(
+                CDesCArray*, iContainer->ListBox().Model()->ItemTextArray());
+    if(itemArray->Count() == 0 )
+       {
+       SetCbaL(R_SECMODUI_SOFTKEYS_OPTIONS_BACK);	
+       }
+    else
+       {
+       SetCbaL(R_SECMODUI_SOFTKEYS_OPTIONS_BACK_OPEN);	
+       }           
+    }
+    
+// ---------------------------------------------------------
+// CSecModUIViewMain::SetCbaL( TInt aCbaResourceId )
+// Sets Cba area
+// ---------------------------------------------------------
+//  
+void CSecModUIViewMain::SetCbaL( TInt aCbaResourceId )
+    {
+	CEikButtonGroupContainer*  cba = Cba();
+    cba->SetCommandSetL(aCbaResourceId);
+    cba->DrawDeferred();
+    }
+    
+// ---------------------------------------------------------
+// CSecModUIViewMain::HandleForegroundEventL()
+// ---------------------------------------------------------
+//
+void CSecModUIViewMain::HandleForegroundEventL(TBool aForeground)
+    {
+	if( aForeground && !iModel.Wrapper().IsActive() )
+	    {
+	    iModel.InitializeKeyStoreL();          
+        CDesCArray* itemArray = STATIC_CAST(CDesCArray*, iContainer->ListBox().Model()->ItemTextArray());
+        itemArray->Reset();                
+        iModel.LoadTokenLabelsL(iContainer->ListBox());
+        iContainer->DrawDeferred(); 
+        UpdateCbaL();                	
+	    }
+    }    
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/SecModUI/src/SecModUIViewSignature.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,320 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Implementation of the CSecModUIViewSignature class
+*
+*/
+
+
+// INCLUDE FILES
+#include  "secmodui.hrh"
+#include  "SecModUIViewSignature.h"
+#include  "SecModUIContainerSignature.h" 
+#include  "SecModUIModel.h"
+#include  "SecModUISyncWrapper.h"
+#include  <aknViewAppUi.h>
+#include  <avkon.hrh>
+#include  <SecModUI.rsg>
+#include  <aknlists.h>
+#include  <eikmenup.h>
+#include  <featmgr.h>
+
+// ================= MEMBER FUNCTIONS =======================
+
+// -----------------------------------------------------------------------------
+// CSecModUIViewMain::CSecModUIViewMain
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CSecModUIViewSignature::CSecModUIViewSignature(CSecModUIModel& aModel):CSecModUIViewBase(aModel)
+    {
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewSignature::ConstructL(const TRect& aRect)
+// EPOC two-phased constructor
+// ---------------------------------------------------------
+//
+void CSecModUIViewSignature::ConstructL()
+    {
+    BaseConstructL( R_SECMODUI_VIEW_SIGNATURE );
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewSignature::~CSecModUIViewSignature()
+// destructor
+// ---------------------------------------------------------
+//
+CSecModUIViewSignature::~CSecModUIViewSignature()
+    {
+   
+    }
+
+// -----------------------------------------------------------------------------
+// CSecModUIViewSignature::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CSecModUIViewSignature* CSecModUIViewSignature::NewLC(CSecModUIModel& aModel)
+    {
+    CSecModUIViewSignature* self = new (ELeave) CSecModUIViewSignature(aModel);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    return self;
+    }
+
+// ---------------------------------------------------------
+// void CSecModUIViewSignature::CreateContainerL()
+// Creates container
+// ---------------------------------------------------------
+//
+void CSecModUIViewSignature::CreateContainerL()
+    {
+    iContainer = new (ELeave) CSecModUIContainerSignature(iModel, this);
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewSignature::AddNavipaneLabelL()
+// Default implementation is empty
+// ---------------------------------------------------------
+//
+void CSecModUIViewSignature::AddNaviPaneLabelL()
+    { 
+    DoAddNaviPaneL(R_NAVIPANE_SIGNATURE_TEXT);   
+    }
+
+// ---------------------------------------------------------
+// TUid CSecModUIViewSignature::Id()
+//
+// ---------------------------------------------------------
+//
+TUid CSecModUIViewSignature::Id() const
+    {
+    return KSecModUIViewSignatureId;
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewSignature::HandleCommandL(TInt aCommand)
+// takes care of view command handling
+// ---------------------------------------------------------
+//
+void CSecModUIViewSignature::HandleCommandL(TInt aCommand)
+    {
+    if (iModel.Wrapper().IsActive())
+        {
+        return;
+        }  
+    switch ( aCommand )
+        {
+        case ESecModUICmdChange:
+            {
+            iModel.ChangePinNrL(iContainer->ListBox().CurrentItemIndex());
+            iModel.LoadPinNRLabelsL(iContainer->ListBox(), EFalse);
+            iContainer->DrawNow();
+            UpdateCbaL(iContainer->ListBox().CurrentItemIndex());
+            break;
+            }            
+        case ESecModUICmdUnblock:
+            {
+            iModel.UnblockPinNrL(iContainer->ListBox().CurrentItemIndex());
+            iModel.LoadPinNRLabelsL(iContainer->ListBox(), EFalse);
+            iContainer->DrawNow();
+            UpdateCbaL(iContainer->ListBox().CurrentItemIndex());
+            break;
+            }
+        case EAknSoftkeyChange:
+            {
+            iModel.ChangePinNrL(iContainer->ListBox().CurrentItemIndex());
+            iModel.LoadPinNRLabelsL(iContainer->ListBox(), EFalse);
+            iContainer->DrawNow();
+            UpdateCbaL(iContainer->ListBox().CurrentItemIndex());	
+            break;	
+            }
+        case EAknSoftkeyUnlock:
+            {
+            iModel.UnblockPinNrL(iContainer->ListBox().CurrentItemIndex());
+            iModel.LoadPinNRLabelsL(iContainer->ListBox(), EFalse);
+            iContainer->DrawNow();
+            UpdateCbaL(iContainer->ListBox().CurrentItemIndex());
+            break;	
+            }
+        default:
+            {
+            CSecModUIViewBase::HandleCommandL( aCommand );
+            break;
+            }
+        }
+    
+    }
+
+
+// ---------------------------------------------------------
+// TUid CSecModUIViewSignature::DynInitMenuPaneL(
+//      TInt aResourceId, CEikMenuPane* aMenuPane)
+//
+// ---------------------------------------------------------
+//
+void CSecModUIViewSignature::DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane)
+    {
+    TInt currentItem = iContainer->ListBox().CurrentItemIndex();
+    switch(aResourceId)
+        {
+        case R_SECMODUI_VIEW_SIGNATURE_MENU:
+            {
+            if( aResourceId == !FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+                {
+                aMenuPane->DeleteMenuItem( EAknCmdHelp ); //remove help
+                } 
+            // The security module list is empty.  
+            // All except Exit and Help is dimmed.
+            if (!iModel.PinNrChangeable(currentItem))
+                {
+                aMenuPane->SetItemDimmed( ESecModUICmdChange, ETrue );
+                }
+            if (!iModel.PinNrUnblockable(currentItem))
+                {
+                aMenuPane->SetItemDimmed( ESecModUICmdUnblock, ETrue );
+                }
+            break;
+            }
+        default:
+            {
+            break;
+            }    
+        }  
+    }
+
+// ---------------------------------------------------------
+// CSecModUIViewSignature::HandleListBoxEventL(
+//     CEikListBox* aListBox, TListBoxEvent aEventType)
+// ---------------------------------------------------------
+//     
+void CSecModUIViewSignature::HandleListBoxEventL(CEikListBox* aListBox, TListBoxEvent aEventType)
+    {
+    if(iModel.Wrapper().IsActive())
+        {
+        return;	
+        }
+        
+    switch( aEventType )
+		{
+		case EEventEnterKeyPressed:
+		case EEventItemDoubleClicked:
+		case EEventItemSingleClicked:
+			{			
+			iModel.ChangeOrUnblockPinNrL(aListBox->CurrentItemIndex());
+			iModel.LoadPinNRLabelsL(iContainer->ListBox(), EFalse);
+            iContainer->DrawNow();
+            UpdateCbaL(aListBox->CurrentItemIndex());
+            break;
+			}
+        default:
+            {
+			break;
+            }
+		}           
+    }
+
+
+// ---------------------------------------------------------
+// CSecModUIViewSignature::UpdateCbaL()
+//     
+// ---------------------------------------------------------
+//
+void CSecModUIViewSignature::UpdateCbaL( TInt aIndex )
+    {
+    if( iModel.PinNrChangeable(aIndex) )
+        {
+        SetCbaL(R_SECMODUI_SOFTKEYS_OPTIONS_BACK_CHANGE);
+        }
+    else
+        {
+        if( !iModel.PinNrUnblockable(aIndex) )
+            {
+            SetCbaL(R_SECMODUI_SOFTKEYS_OPTIONS_BACK);
+            } 
+        else
+            {
+            SetCbaL(R_SECMODUI_SOFTKEYS_OPTIONS_BACK_UNBLOCK);	
+            }     
+        }    	
+    }
+
+
+// ---------------------------------------------------------
+// CSecModUIViewSignature::SetCbaL()
+//     
+// ---------------------------------------------------------
+// 
+void CSecModUIViewSignature::SetCbaL( TInt aCbaResourceId )
+    {
+	CEikButtonGroupContainer*  cba = Cba();
+    cba->SetCommandSetL(aCbaResourceId);
+    cba->DrawNow();
+    }
+
+
+// ---------------------------------------------------------
+// CSecModUIViewSignature::DoActivateL()
+//     
+// ---------------------------------------------------------
+//     
+void CSecModUIViewSignature::DoActivateL(
+   const TVwsViewId& aPrevViewId,TUid /*aCustomMessageId*/,
+   const TDesC8& /*aCustomMessage*/)
+    {
+  
+    if (KNullUid == iPrevViewId.iViewUid)
+        {
+        iPrevViewId = aPrevViewId;
+        }
+    SetTitlePaneL();
+    AddNaviPaneLabelL();
+                    
+    if (!iContainer)
+        {
+        CreateContainerL();
+        iContainer->SetMopParent(this);
+        iContainer->ConstructL(ClientRect());
+        iContainer->ListBox().SetListBoxObserver(this);
+        AppUi()->AddToStackL(*this, iContainer);
+        }         
+   iContainer->MakeVisible(ETrue);
+   iContainer->SetRect(ClientRect());
+   iContainer->ActivateL();
+   
+   UpdateCbaL(iContainer->ListBox().CurrentItemIndex());
+       
+   }
+
+// ---------------------------------------------------------
+// CSecModUIViewSignature::DoDeactivate()
+// 
+// ---------------------------------------------------------
+//
+void CSecModUIViewSignature::DoDeactivate()
+    {
+ 
+    if ( iContainer )
+        {
+        AppUi()->RemoveFromViewStack( *this, iContainer );
+        }
+    
+    delete iContainer;
+    iContainer = NULL;
+        
+    }  
+           
+// End of File
+
Binary file pkiutilities/StubSIS/CenRepStub.sis has changed
Binary file pkiutilities/StubSIS/agnmodel.sis has changed
Binary file pkiutilities/StubSIS/c32exe.sis has changed
Binary file pkiutilities/StubSIS/cntmodel.sis has changed
Binary file pkiutilities/StubSIS/esock.sis has changed
Binary file pkiutilities/StubSIS/msgs.sis has changed
Binary file pkiutilities/StubSIS/swicertstore.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/StubSIS/swipolicy.ini	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,20 @@
+AllowUnsigned = false
+MandatePolicies = false
+MandateCodeSigningExtension = false
+Oid = 1.2.3.4.5.6
+Oid = 2.3.4.5.6.7
+DRMEnabled = true
+DRMIntent = 3
+OcspMandatory = false
+OcspEnabled = true
+AllowGrantUserCapabilities = true
+AllowOrphanedOverwrite = true
+UserCapabilities = NetworkServices LocalServices ReadUserData WriteUserData UserEnvironment Location 
+AllowPackagePropagate = true
+SISCompatibleIfNoTargetDevices = false
+RunWaitTimeoutSeconds = 600
+AllowRunOnInstallUninstall = false
+DeletePreinstalledFilesOnUninstall = true
+AlternativeCodeSigningOID = 1.3.6.1.4.1.94.1.49.1.2.2.1 1.3.6.1.4.1.94.1.49.1.2.2.5
+RemoveOnlyWithLastDependent = true
+PhoneTsyName = phonetsy
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/StubSIS/tlsproviderpolicy.ini	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,2 @@
+ClientAuthDlgEnabled = true
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Common build information for the SecurityUIs project
+*
+*/
+
+
+#include "../x509certnameparser/group/bld.inf"
+#include "../PKCS12/group/bld.inf"
+#include "../CertmanUi/GROUP/bld.inf"
+#include "../CTSecurityDialogs/Group/bld.inf"
+#include "../CertSaver/group/bld.inf"
+#include "../SecModUI/group/bld.inf"
+#include "../DeviceToken/Group/bld.inf"
+
+//Stub SIS
+PRJ_EXPORTS
+../StubSIS/CenRepStub.sis   /epoc32/data/z/system/install/CenRepStub.sis
+../StubSIS/c32exe.sis   /epoc32/data/z/system/install/c32exe.sis
+
+//SWI and TLSProvider config files
+../StubSIS/swipolicy.ini    /epoc32/release/winscw/udeb/z/system/data/swipolicy.ini
+../StubSIS/swipolicy.ini    /epoc32/release/winscw/urel/z/system/data/swipolicy.ini
+../StubSIS/swipolicy.ini    /epoc32/data/z/system/data/swipolicy.ini
+                            
+../StubSIS/tlsproviderpolicy.ini  /epoc32/release/winscw/urel/z/resource/tlsproviderpolicy.ini
+../StubSIS/tlsproviderpolicy.ini  /epoc32/release/winscw/udeb/z/resource/tlsproviderpolicy.ini
+
+// export iby files
+../rom/x509certnameparser.iby   CORE_MW_LAYER_IBY_EXPORT_PATH( x509certnameparser.iby )
+../rom/pkcs12.iby               CORE_MW_LAYER_IBY_EXPORT_PATH( pkcs12.iby )
+../rom/certmanui.iby            CORE_MW_LAYER_IBY_EXPORT_PATH( certmanui.iby )
+../rom/certmanui_resources.iby  LANGUAGE_MW_LAYER_IBY_EXPORT_PATH( certmanui_resources.iby )
+../rom/CTSecurityDialogs.iby    CORE_MW_LAYER_IBY_EXPORT_PATH( CTSecurityDialogs.iby )
+../rom/CTSecurityDialogs_resources.iby LANGUAGE_MW_LAYER_IBY_EXPORT_PATH( CTSecurityDialogs_resources.iby )
+../rom/CertSaver.iby            CORE_MW_LAYER_IBY_EXPORT_PATH( CertSaver.iby )
+../rom/CertSaver_resources.iby  LANGUAGE_MW_LAYER_IBY_EXPORT_PATH( CertSaver_resources.iby )
+../rom/SecModUI.iby             CORE_MW_LAYER_IBY_EXPORT_PATH( SecModUI.iby )
+../rom/SecModUI_resources.iby   LANGUAGE_MW_LAYER_IBY_EXPORT_PATH( SecModUI_resources.iby )
+../rom/DevToken.iby             CORE_MW_LAYER_IBY_EXPORT_PATH( DevToken.iby )
+../rom/StubSIS.iby              CORE_MW_LAYER_IBY_EXPORT_PATH( StubSIS.iby )
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/bwins/ocsp_v2U.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,44 @@
+EXPORTS
+	?AddAuthorisationSchemeL@COCSPParameters@@QAEXPAVMOCSPAuthorisationScheme@@@Z @ 1 NONAME ; void COCSPParameters::AddAuthorisationSchemeL(class MOCSPAuthorisationScheme *)
+	?AddCertificateL@COCSPParameters@@QAEXABVCX509Certificate@@0@Z @ 2 NONAME ; void COCSPParameters::AddCertificateL(class CX509Certificate const &, class CX509Certificate const &)
+	?AddCertificatesL@COCSPParameters@@QAEXABVCX509CertChain@@@Z @ 3 NONAME ; void COCSPParameters::AddCertificatesL(class CX509CertChain const &)
+	?ArchiveCutoff@COCSPResponse@@QBEPBVTTime@@XZ @ 4 NONAME ; class TTime const * COCSPResponse::ArchiveCutoff(void) const
+	?CancelCheck@COCSPClient@@QAEXXZ @ 5 NONAME ; void COCSPClient::CancelCheck(void)
+	?CertCount@COCSPRequest@@QBEHXZ @ 6 NONAME ; int COCSPRequest::CertCount(void) const
+	?CertCount@COCSPResponse@@QBEHXZ @ 7 NONAME ; int COCSPResponse::CertCount(void) const
+	?CertInfo@COCSPRequest@@QBEABVCOCSPRequestCertInfo@@I@Z @ 8 NONAME ; class COCSPRequestCertInfo const & COCSPRequest::CertInfo(unsigned int) const
+	?CertInfo@COCSPResponse@@QBEABVCOCSPResponseCertInfo@@I@Z @ 9 NONAME ; class COCSPResponseCertInfo const & COCSPResponse::CertInfo(unsigned int) const
+	?Check@COCSPClient@@QAEXAAVTRequestStatus@@@Z @ 10 NONAME ; void COCSPClient::Check(class TRequestStatus &)
+	?Issuer@COCSPRequestCertInfo@@QBEABVCX509Certificate@@XZ @ 11 NONAME ; class CX509Certificate const & COCSPRequestCertInfo::Issuer(void) const
+	?NewL@COCSPClient@@SAPAV1@PBVCOCSPParameters@@@Z @ 12 NONAME ; class COCSPClient * COCSPClient::NewL(class COCSPParameters const *)
+	?NewL@COCSPParameters@@SAPAV1@XZ @ 13 NONAME ; class COCSPParameters * COCSPParameters::NewL(void)
+	?NewLC@COCSPDirectAuthorisationScheme@@SAPAV1@ABVTUid@@AAVMCertStore@@@Z @ 14 NONAME ; class COCSPDirectAuthorisationScheme * COCSPDirectAuthorisationScheme::NewLC(class TUid const &, class MCertStore &)
+	?NewLC@COCSPParameters@@SAPAV1@XZ @ 15 NONAME ; class COCSPParameters * COCSPParameters::NewLC(void)
+	?NextUpdate@COCSPResponseCertInfo@@QBEPBVTTime@@XZ @ 16 NONAME ; class TTime const * COCSPResponseCertInfo::NextUpdate(void) const
+	?Nonce@COCSPRequest@@QBEPBVTDesC8@@XZ @ 17 NONAME ; class TDesC8 const * COCSPRequest::Nonce(void) const
+	?Outcome@COCSPClient@@QBEABVTOCSPOutcome@@H@Z @ 18 NONAME ; class TOCSPOutcome const & COCSPClient::Outcome(int) const
+	?ProducedAt@COCSPResponse@@QBE?AVTTime@@XZ @ 19 NONAME ; class TTime COCSPResponse::ProducedAt(void) const
+	?Request@COCSPClient@@QBEABVCOCSPRequest@@H@Z @ 20 NONAME ; class COCSPRequest const & COCSPClient::Request(int) const
+	?Response@COCSPClient@@QBEPBVCOCSPResponse@@H@Z @ 21 NONAME ; class COCSPResponse const * COCSPClient::Response(int) const
+	?RevocationTime@COCSPResponseCertInfo@@QBEPBVTTime@@XZ @ 22 NONAME ; class TTime const * COCSPResponseCertInfo::RevocationTime(void) const
+	?SetMaxStatusAgeL@COCSPParameters@@QAEXI@Z @ 23 NONAME ; void COCSPParameters::SetMaxStatusAgeL(unsigned int)
+	?SetTimeLeewayL@COCSPParameters@@QAEXI@Z @ 24 NONAME ; void COCSPParameters::SetTimeLeewayL(unsigned int)
+	?SetTransport@COCSPParameters@@QAEXPAVMOCSPTransport@@@Z @ 25 NONAME ; void COCSPParameters::SetTransport(class MOCSPTransport *)
+	?SetURIL@COCSPParameters@@QAEXABVTDesC8@@H@Z @ 26 NONAME ; void COCSPParameters::SetURIL(class TDesC8 const &, int)
+	?SetUseNonce@COCSPParameters@@QAEXH@Z @ 27 NONAME ; void COCSPParameters::SetUseNonce(int)
+	?SetValidationTimeL@COCSPParameters@@QAEXABVTTime@@@Z @ 28 NONAME ; void COCSPParameters::SetValidationTimeL(class TTime const &)
+	?Status@COCSPResponseCertInfo@@QBE?AW4TResult@OCSP@@XZ @ 29 NONAME ; enum OCSP::TResult COCSPResponseCertInfo::Status(void) const
+	?Subject@COCSPRequestCertInfo@@QBEABVCX509Certificate@@XZ @ 30 NONAME ; class CX509Certificate const & COCSPRequestCertInfo::Subject(void) const
+	?SummaryResult@COCSPClient@@QBE?AW4TResult@OCSP@@XZ @ 31 NONAME ; enum OCSP::TResult COCSPClient::SummaryResult(void) const
+	?ThisUpdate@COCSPResponseCertInfo@@QBE?AVTTime@@XZ @ 32 NONAME ; class TTime COCSPResponseCertInfo::ThisUpdate(void) const
+	?TransactionCount@COCSPClient@@QBEHXZ @ 33 NONAME ; int COCSPClient::TransactionCount(void) const
+	?AddAllAuthorisationSchemesL@COCSPParameters@@QAEXABVTUid@@AAVMCertStore@@@Z @ 34 NONAME ; void COCSPParameters::AddAllAuthorisationSchemesL(class TUid const &, class MCertStore &)
+	?NewLC@COCSPCaDirectAuthorisationScheme@@SAPAV1@XZ @ 35 NONAME ; class COCSPCaDirectAuthorisationScheme * COCSPCaDirectAuthorisationScheme::NewLC(void)
+	?NewLC@COCSPDelegateAuthorisationScheme@@SAPAV1@AAVMCertStore@@@Z @ 36 NONAME ; class COCSPDelegateAuthorisationScheme * COCSPDelegateAuthorisationScheme::NewLC(class MCertStore &)
+	?SetTimeout@COCSPParameters@@QAEXH@Z @ 37 NONAME ; void COCSPParameters::SetTimeout(int)
+	?SetRetryCount@COCSPParameters@@QAEXI@Z @ 38 NONAME ; void COCSPParameters::SetRetryCount(unsigned int)
+	?SetOCSPCheckForResponderCert@COCSPParameters@@QAEXH@Z @ 39 NONAME ; void COCSPParameters::SetOCSPCheckForResponderCert(int)
+	?CertsAvailableForOCSPCheck@COCSPClient@@QAEHXZ @ 40 NONAME ; int COCSPClient::CertsAvailableForOCSPCheck(void)
+	?SetCheckCertsWithAiaOnly@COCSPParameters@@QAEXH@Z @ 41 NONAME ; void COCSPParameters::SetCheckCertsWithAiaOnly(int)
+	?SetUseAIA@COCSPParameters@@QAEXH@Z @ 42 NONAME ; void COCSPParameters::SetUseAIA(int)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/bwins/ocspcommonu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	?NewL@COcspPolicy@@SAPAV1@XZ @ 1 NONAME ; class COcspPolicy * COcspPolicy::NewL(void)
+	?IsHttpGETMethodEnabled@COcspPolicy@@QBEHXZ @ 2 NONAME ; int COcspPolicy::IsHttpGETMethodEnabled(void) const
+	?IsGenerateResponseForMissingUriEnabled@COcspPolicy@@QBEHXZ @ 3 NONAME ; int COcspPolicy::IsGenerateResponseForMissingUriEnabled(void) const
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/bwins/ocsptransport_v2U.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,4 @@
+EXPORTS
+	?NewL@COCSPTransportDefault@@SAPAV1@AAK@Z @ 1 NONAME ; class COCSPTransportDefault * COCSPTransportDefault::NewL(unsigned long &)
+	?NewL@COCSPTransportHttp@@SAPAV1@ABVTDesC8@@AAK@Z @ 2 NONAME ; class COCSPTransportHttp * COCSPTransportHttp::NewL(class TDesC8 const &, unsigned long &)
+
Binary file pkiutilities/ocsp/doxygen_docs/Pkiutilities_OCSP_SoftwareInstall.png has changed
Binary file pkiutilities/ocsp/doxygen_docs/Pkiutilities_OCSP_multiservers1.png has changed
Binary file pkiutilities/ocsp/doxygen_docs/Pkiutilities_OCSP_multiservers2.png has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/doxygen_docs/Pkiutilities_OCSP_overview.dox	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,140 @@
+/**
+
+@page overview_OCSP  OCSP -- Online Certificate Status Protocol 
+\n
+
+@section overview_of_ocsp Overview of OCSP
+
+OCSP is a simple request/response protocol.
+
+To establish whether a given @ref certificate or list of certificates has been revoked, a client forms an OCSP request 
+and sends this to an OCSP server. The server maintains revocation information in the form of, say, 
+@ref CRL "Certificate Revocation Lists" (CRLs). The server replies to the client with a signed OCSP response, stating for each certificate whether the 
+status is \b Good, \b Revoked, or \b Unknown. This response in turn is checked to ensure that it is valid, and that it 
+is from an entity trusted for performing revocation checking.
+
+The Symbian platform provides the ability to validate and manage @ref X509_certificate "X.509 certificates".  This ability is integrated into 
+the software installation process to provide 'Secure Software Install' certificate checking at installation time to 
+verify the identity of the software supplier.
+
+Secure Software Install (see below: @ref SWI) needs to be able to check whether certificates have been revoked. The 
+rationale for this is that if a developer certificate has been revoked because it has been compromised, or used 
+maliciously, we should be able to ensure that packages signed by that certificate are not accepted by the platform.
+
+This requirement is satisfied by:
+@li The implementation of the Online Certificate Status Protocol.  OCSP is an Internet protocol that is defined in
+<A HREF="http://www.ietf.org/rfc/rfc2560.txt">RFC2560</A>.
+The OCSP module forms part of the @ref X509_certificate "X.509 certificate" management code
+@li The integration of revocation checking into the Secure Software Installation process.
+
+<hr>
+
+@section ocsp_protocol The OCSP Protocol
+
+The OCSP protocol comes in two parts: the request and the response, each given in @ref ASN "ASN.1" @ref DER notation. 
+
+In its simplest form, an OCSP request consists of one or more identifiers for the certificates whose status is in question.
+The request is sent to a server identified by a @ref URI. 
+
+In its simplest form, the response consists of a status indication for each certificate identifier in the request. The 
+whole response being signed with a key pair trusted as authoritative by the client.  Alternatively, an unsigned error code
+may be returned.
+
+When a response has been received, it is then validated to see if it can be trusted.
+OCSP is transport-neutral: the @ref URI of the server indicates the scheme required; currently, only HTTP is 
+supported.
+
+@section locating_the_ocsp_server Locating the OCSP Server
+
+When performing revocation checking, it is necessary to know where to send a request.  In addition, the server to which 
+the request is sent may not actually be the server to which is authoritative to answer the request, but may act as a proxy 
+client and the destination server.  In an OCSP request, this behaviour is requested by adding a serviceLocator extension 
+containing the @ref URI.
+
+The situation is complicated by the fact that there may be a serviceLocator extension for each @ref certificate in the request, 
+and so it is syntactically possible for the request to be split into multiple parts, with each part routed to a different 
+OCSP responder. The intermediate server collates the individual responses into one and returns this to the client.  This 
+response is signed only by the intermediate server, so it is this server the client must trust. 
+There are 3 possible scenarios for the arrangement of OCSP responders:
+
+@li Single OCSP responder.  
+One OCSP server contains the revocation information for all certificates that will be checked. 
+One request containing all certificates to be checked is sent to the responder, which replies with a single response: \n\n
+@image html Certman_OCSP_singleserver.png 
+\n\n
+
+@li Multiple OCSP responders using an intermediate OCSP server to route requests to the appropriate one. One request is 
+sent to the intermediate server, which sends multiple individual requests to the destination responders.  The responses 
+are collated, and one response is sent back to the client: \n\n
+@image html Certman_OCSP_multiservers1.png 
+\n\n
+
+@li Multiple OCSP responders without an intermediate server.  The client does the work of sending each request to the 
+appropriate responder.  The client collates the responses received: \n\n
+@image html Certman_OCSP_multiservers2.png 
+\n\n
+ 
+
+Which scenario is appropriate depends on the nature of the @ref PKI, and the availability of OCSP responders that will act
+as intermediates and route requests appropriately.
+
+@section outcome_result Outcome result
+
+If the response passes all validation, the outcome result is determined by applying the following rules to the certificate statuses in the response:
+@li If any certificate was 'revoked', the result is \b 'Revoked'
+@li If all certificates were 'valid', the result is \b 'Good'
+@li Otherwise, the result is \b 'Unknown'.
+
+@note
+A certificate status of 'Good' does not indicate that the @ref certificate may be trusted.  It merely indicates that 
+the certificate has not been revoked.  The normal validation of that @ref certificate (or the chain in which it lies) must 
+still be performed.
+
+
+<hr> 
+
+@section SWI OCSP Integration with Secure Software Install
+
+Software Install may be configured to check revocation status of certificates or not. Software Install supplies the OCSP 
+client with a default URI for the OCSP server. Both of these are controlled by a user preference.  
+Currently, Software Install uses the direct authorisation scheme to validate OCSP responders, with a UID allocated for 
+Software Install OCSP signing. 
+
+Embedded packages are verified using the same logic as is used for the outer package.
+
+@subsection installing_software Installing software
+
+Software Install first validates the @ref certificate in the install file by using the certificate validation module. 
+@li If revocation checking is switched off, a warning is displayed giving options to do revocation checking anyway, 
+continue without revocation checking, or cancel installation 
+@li If revocation checking is switched on, or the user requests it, all certificates in the chain except the root will 
+be checked for revocation, while Software Install displays appropriate feedback to the user about the owner(s) of 
+the certificate(s) being checked.
+ 
+Future implementations may check multiple certificates with a single OCSP request, however at present, one network access 
+is made for every certificate checked; each one has the potential to generate a warning or error. 
+
+@li If the OCSP client indicates that no certificates have been revoked and the operation completed successfully with 
+no errors or warnings, the software can be installed
+@li If OCSP indicates that any of the certificates have been revoked, or if the signature on the OCSP response is invalid, 
+a security error will be issued and the software cannot be installed
+@li If the revocation status of a certificate cannot be determined (e.g. due to lack of network access, or a OCSP responder 
+error), the behaviour will be as if the software is unsigned. (That is, if unsigned software may be installed, issue a 
+warning but allow installation, otherwise issue an error and do not allow installation.)
+
+@section configuration Configuration
+
+The Software Install component is responsible for storing the address of the OCSP server, and a flag indicating whether 
+OCSP checking should be performed.  The address of the OCSP server is a user-modifiable URL set initially from a 
+localisable default.
+The InstCtrl dialog contains a 'Security' tab, as shown below.  The 'Server address' line is greyed out when the 
+'Enabled' checkbox is clear.
+If checking is enabled, the server address is parsed when the dialog is closed, to check that is a valid URL.  A warning 
+dialog is presented if it is not (text = 'Invalid revocation server URL') and focus moved to the server address field, 
+ready for the user to change its contents.\n\n
+ 
+@image html Certman_OCSP_SoftwareInstall.png 
+\n\n
+
+
+*/
\ No newline at end of file
Binary file pkiutilities/ocsp/doxygen_docs/Pkiutilities_OCSP_singleserver.png has changed
Binary file pkiutilities/ocsp/doxygen_docs/Thumbs.db has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/eabi/ocsp_v2U.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,62 @@
+EXPORTS
+	_ZN11COCSPClient11CancelCheckEv @ 1 NONAME
+	_ZN11COCSPClient4NewLEPK15COCSPParameters @ 2 NONAME
+	_ZN11COCSPClient5CheckER14TRequestStatus @ 3 NONAME
+	_ZN15COCSPParameters11SetUseNonceEi @ 4 NONAME
+	_ZN15COCSPParameters12SetTransportEP14MOCSPTransport @ 5 NONAME
+	_ZN15COCSPParameters14SetTimeLeewayLEj @ 6 NONAME
+	_ZN15COCSPParameters15AddCertificateLERK16CX509CertificateS2_ @ 7 NONAME
+	_ZN15COCSPParameters16AddCertificatesLERK14CX509CertChain @ 8 NONAME
+	_ZN15COCSPParameters16SetMaxStatusAgeLEj @ 9 NONAME
+	_ZN15COCSPParameters18SetValidationTimeLERK5TTime @ 10 NONAME
+	_ZN15COCSPParameters23AddAuthorisationSchemeLEP24MOCSPAuthorisationScheme @ 11 NONAME
+	_ZN15COCSPParameters4NewLEv @ 12 NONAME
+	_ZN15COCSPParameters5NewLCEv @ 13 NONAME
+	_ZN15COCSPParameters7SetURILERK6TDesC8i @ 14 NONAME
+	_ZN30COCSPDirectAuthorisationScheme5NewLCERK4TUidR10MCertStore @ 15 NONAME
+	_ZNK11COCSPClient13SummaryResultEv @ 16 NONAME
+	_ZNK11COCSPClient16TransactionCountEv @ 17 NONAME
+	_ZNK11COCSPClient7OutcomeEi @ 18 NONAME
+	_ZNK11COCSPClient7RequestEi @ 19 NONAME
+	_ZNK11COCSPClient8ResponseEi @ 20 NONAME
+	_ZNK12COCSPRequest5NonceEv @ 21 NONAME
+	_ZNK12COCSPRequest8CertInfoEj @ 22 NONAME
+	_ZNK12COCSPRequest9CertCountEv @ 23 NONAME
+	_ZNK13COCSPResponse10ProducedAtEv @ 24 NONAME
+	_ZNK13COCSPResponse13ArchiveCutoffEv @ 25 NONAME
+	_ZNK13COCSPResponse8CertInfoEj @ 26 NONAME
+	_ZNK13COCSPResponse9CertCountEv @ 27 NONAME
+	_ZNK20COCSPRequestCertInfo6IssuerEv @ 28 NONAME
+	_ZNK20COCSPRequestCertInfo7SubjectEv @ 29 NONAME
+	_ZNK21COCSPResponseCertInfo10NextUpdateEv @ 30 NONAME
+	_ZNK21COCSPResponseCertInfo10ThisUpdateEv @ 31 NONAME
+	_ZNK21COCSPResponseCertInfo14RevocationTimeEv @ 32 NONAME
+	_ZNK21COCSPResponseCertInfo6StatusEv @ 33 NONAME
+	_ZTI11COCSPClient @ 34 NONAME ; #<TI>#
+	_ZTI12COCSPRequest @ 35 NONAME ; #<TI>#
+	_ZTI13COCSPResponse @ 36 NONAME ; #<TI>#
+	_ZTI15COCSPParameters @ 37 NONAME ; #<TI>#
+	_ZTI20COCSPRequestCertInfo @ 38 NONAME ; #<TI>#
+	_ZTI21COCSPResponseCertInfo @ 39 NONAME ; #<TI>#
+	_ZTI30COCSPDirectAuthorisationScheme @ 40 NONAME ; #<TI>#
+	_ZTV11COCSPClient @ 41 NONAME ; #<VT>#
+	_ZTV12COCSPRequest @ 42 NONAME ; #<VT>#
+	_ZTV13COCSPResponse @ 43 NONAME ; #<VT>#
+	_ZTV15COCSPParameters @ 44 NONAME ; #<VT>#
+	_ZTV20COCSPRequestCertInfo @ 45 NONAME ; #<VT>#
+	_ZTV21COCSPResponseCertInfo @ 46 NONAME ; #<VT>#
+	_ZTV30COCSPDirectAuthorisationScheme @ 47 NONAME ; #<VT>#
+	_ZN15COCSPParameters27AddAllAuthorisationSchemesLERK4TUidR10MCertStore @ 48 NONAME
+	_ZN32COCSPCaDirectAuthorisationScheme5NewLCEv @ 49 NONAME
+	_ZN32COCSPDelegateAuthorisationScheme5NewLCER10MCertStore @ 50 NONAME
+	_ZTI32COCSPCaDirectAuthorisationScheme @ 51 NONAME ; #<TI>#
+	_ZTI32COCSPDelegateAuthorisationScheme @ 52 NONAME ; #<TI>#
+	_ZTV32COCSPCaDirectAuthorisationScheme @ 53 NONAME ; #<VT>#
+	_ZTV32COCSPDelegateAuthorisationScheme @ 54 NONAME ; #<VT>#
+	_ZN15COCSPParameters10SetTimeoutEi @ 55 NONAME
+	_ZN15COCSPParameters13SetRetryCountEj @ 56 NONAME
+	_ZN15COCSPParameters28SetOCSPCheckForResponderCertEi @ 57 NONAME
+	_ZN11COCSPClient26CertsAvailableForOCSPCheckEv @ 58 NONAME
+	_ZN15COCSPParameters24SetCheckCertsWithAiaOnlyEi @ 59 NONAME
+	_ZN15COCSPParameters9SetUseAIAEi @ 60 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/eabi/ocspcommonu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	_ZN11COcspPolicy4NewLEv @ 1 NONAME
+	_ZNK11COcspPolicy22IsHttpGETMethodEnabledEv @ 2 NONAME
+	_ZNK11COcspPolicy38IsGenerateResponseForMissingUriEnabledEv @ 3 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/eabi/ocsptransport_v2U.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,8 @@
+EXPORTS
+	_ZN18COCSPTransportHttp4NewLERK6TDesC8Rm @ 1 NONAME
+	_ZN21COCSPTransportDefault4NewLERm @ 2 NONAME
+	_ZTI18COCSPTransportHttp @ 3 NONAME ; #<TI>#
+	_ZTI21COCSPTransportDefault @ 4 NONAME ; #<TI>#
+	_ZTV18COCSPTransportHttp @ 5 NONAME ; #<VT>#
+	_ZTV21COCSPTransportDefault @ 6 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,236 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description: Online Certificate Status Protocol ( OCSP )
+// 
+//
+
+/**
+ @file
+*/
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+// specify the source file followed by its destination here
+// copy will be used to copy the source file to its destination
+// If there's no destination then the source file will be copied
+// to the same name in /epoc32/include
+
+../inc/ocsppolicy.h					SYMBIAN_MW_LAYER_PLATFORM_EXPORT_PATH(ocsppolicy.h)
+../inc/ocsp_v2.h					SYMBIAN_MW_LAYER_PLATFORM_EXPORT_PATH(ocsp.h)
+../inc/ocsptransport_v2.h				SYMBIAN_MW_LAYER_PLATFORM_EXPORT_PATH(ocsptransport.h)
+../inc/ocsprequestandresponse.h     			SYMBIAN_MW_LAYER_PLATFORM_EXPORT_PATH(ocsprequestandresponse.h)
+
+// ROMKIT includes
+../inc/ocsp.iby					/epoc32/rom/include/ocsp.iby
+
+PRJ_MMPFILES
+
+#ifndef TOOLS
+#ifndef TOOLS2
+
+
+#ifndef WINC
+ocspcommon.mmp
+ocsp.mmp
+../transport/ocsptransport.mmp
+#endif	//	WINC
+
+#endif	//	TOOLS2
+#endif	//	TOOLS
+
+PRJ_TESTMMPFILES
+// specify the .mmp files required for building any test programs here
+//
+// you can specify "manual" to denote that a test should be listed in a generated
+// batch file for running a group of tests which require user input during testing.
+// you can specify "support" to denote that a file is a test support file and shouldn't
+// be listed in a batch file for running a group of tests
+// By default, each test will be listed in a batch file for running a group of tests
+// which can be left to run without requiring watching over by the person running the tests,
+// i.e. tests where no user input is required.  The default will apply if neither "manual"
+// or "support" is specified.
+
+#ifndef TOOLS
+../test/resign/resign.mmp
+../test/tocsphttpfilter/tocsphttpfilter.mmp
+../test/tocsp.mmp
+#endif	//	TOOLS
+
+
+PRJ_TESTEXPORTS
+
+
+//
+// OCSP tests - Begin
+
+../test/scripts/XCert.txt          	/epoc32/winscw/c/system/tocsp/scripts/xcert.txt
+../test/scripts/XCert-logging.txt		/epoc32/winscw/c/system/tocsp/scripts/xcert-logging.txt
+../test/scripts/OpenSSL-logging.txt    /epoc32/winscw/c/system/tocsp/scripts/openssl-logging.txt
+../test/scripts/Valicert.txt	    	/epoc32/winscw/c/system/tocsp/scripts/valicert.txt
+../test/scripts/CertCo.txt	        	/epoc32/winscw/c/system/tocsp/scripts/certco.txt
+../test/scripts/SmartTrust.txt	    	/epoc32/winscw/c/system/tocsp/scripts/smarttrust.txt
+
+
+// OCSP Central repository - for newpolicy test - only on emulator.
+../test/scripts/2002b28b-new.txt	/epoc32/winscw/c/system/tocsp/scripts/2002b28b-new.txt
+
+../test/scripts/setupOcspPolicy.bat	/epoc32/winscw/c/system/tocsp/scripts/setupocsppolicy.bat
+../test/scripts/setupOcspPolicy_urel.bat	/epoc32/winscw/c/system/tocsp/scripts/setupocsppolicy_urel.bat
+
+../test/scripts/openssl-ocspsupport.txt     	/epoc32/winscw/c/system/tocsp/scripts/openssl-ocspsupport.txt
+../test/scripts/openssl-ocspsupport-oom.txt    /epoc32/winscw/c/system/tocsp/scripts/openssl-ocspsupport-oom.txt
+
+
+../test/scripts/openssl.script        		/epoc32/winscw/c/system/tocsp/scripts/openssl.script
+../test/scripts/openssl.ini        		/epoc32/winscw/c/system/tocsp/scripts/openssl.ini
+
+../test/scripts/XCert-local.script		/epoc32/winscw/c/system/tocsp/scripts/xcert-local.script
+../test/scripts/XCert-local.ini		/epoc32/winscw/c/system/tocsp/scripts/xcert-local.ini
+
+../test/scripts/XCert-oom.script			/epoc32/winscw/c/system/tocsp/scripts/xcert-oom.script
+../test/scripts/XCert-oom.ini			/epoc32/winscw/c/system/tocsp/scripts/xcert-oom.ini
+
+../test/scripts/OpenSSL-local.script 	        /epoc32/winscw/c/system/tocsp/scripts/openssl-local.script
+../test/scripts/OpenSSL-local.ini  	        /epoc32/winscw/c/system/tocsp/scripts/openssl-local.ini
+
+../test/scripts/Error.script    	    	        /epoc32/winscw/c/system/tocsp/scripts/error.script
+../test/scripts/Error.ini    	    	        /epoc32/winscw/c/system/tocsp/scripts/error.ini
+
+../test/scripts/DefaultPolicy.script		/epoc32/winscw/c/system/tocsp/scripts/defaultpolicy.script
+../test/scripts/DefaultPolicy.ini		/epoc32/winscw/c/system/tocsp/scripts/defaultpolicy.ini
+
+../test/scripts/NewPolicy.script			/epoc32/winscw/c/system/tocsp/scripts/newpolicy.script
+../test/scripts/NewPolicyTEF.ini			/epoc32/winscw/c/system/tocsp/scripts/newpolicytef.ini
+
+../test/scripts/httpinterface.script				/epoc32/winscw/c/system/tocsp/scripts/httpinterface.script
+../test/scripts/httpinterface.ini				/epoc32/winscw/c/system/tocsp/scripts/httpinterface.ini
+
+
+../test/responses/response.n1	/epoc32/winscw/c/system/tocsp/responses/response.n1
+../test/responses/response.n2	/epoc32/winscw/c/system/tocsp/responses/response.n2
+../test/responses/response.000	/epoc32/winscw/c/system/tocsp/responses/response.000
+../test/responses/response.001	/epoc32/winscw/c/system/tocsp/responses/response.001
+../test/responses/response.002	/epoc32/winscw/c/system/tocsp/responses/response.002
+../test/responses/response.003	/epoc32/winscw/c/system/tocsp/responses/response.003
+../test/responses/response.004	/epoc32/winscw/c/system/tocsp/responses/response.004
+../test/responses/response.005	/epoc32/winscw/c/system/tocsp/responses/response.005
+../test/responses/response.006	/epoc32/winscw/c/system/tocsp/responses/response.006
+../test/responses/response.007	/epoc32/winscw/c/system/tocsp/responses/response.007
+../test/responses/response.008	/epoc32/winscw/c/system/tocsp/responses/response.008
+../test/responses/response.009	/epoc32/winscw/c/system/tocsp/responses/response.009
+../test/responses/response.010	/epoc32/winscw/c/system/tocsp/responses/response.010
+../test/responses/response.011	/epoc32/winscw/c/system/tocsp/responses/response.011
+../test/responses/response.012	/epoc32/winscw/c/system/tocsp/responses/response.012
+../test/responses/response.013	/epoc32/winscw/c/system/tocsp/responses/response.013
+../test/responses/response.014	/epoc32/winscw/c/system/tocsp/responses/response.014
+../test/responses/response.015	/epoc32/winscw/c/system/tocsp/responses/response.015
+../test/responses/response.016	/epoc32/winscw/c/system/tocsp/responses/response.016
+../test/responses/response.018	/epoc32/winscw/c/system/tocsp/responses/response.018
+../test/responses/vs_explicit_version.dat /epoc32/winscw/c/system/tocsp/responses/vs_explicit_version.dat
+../test/responses/response.019	/epoc32/winscw/c/system/tocsp/responses/response.019
+../test/responses/response.020	/epoc32/winscw/c/system/tocsp/responses/response.020
+../test/responses/response.021	/epoc32/winscw/c/system/tocsp/responses/response.021
+../test/responses/response.022	/epoc32/winscw/c/system/tocsp/responses/response.022
+../test/responses/response.023	/epoc32/winscw/c/system/tocsp/responses/response.023
+../test/responses/response.024	/epoc32/winscw/c/system/tocsp/responses/response.024
+../test/responses/response.025	/epoc32/winscw/c/system/tocsp/responses/response.025
+../test/responses/response.026	/epoc32/winscw/c/system/tocsp/responses/response.026
+../test/responses/response.027	/epoc32/winscw/c/system/tocsp/responses/response.027
+../test/responses/response.028	/epoc32/winscw/c/system/tocsp/responses/response.028
+../test/responses/response.029	/epoc32/winscw/c/system/tocsp/responses/response.029
+../test/responses/response.030	/epoc32/winscw/c/system/tocsp/responses/response.030
+../test/responses/response.031	/epoc32/winscw/c/system/tocsp/responses/response.031
+../test/responses/response.032	/epoc32/winscw/c/system/tocsp/responses/response.032
+../test/responses/response.033	/epoc32/winscw/c/system/tocsp/responses/response.033
+../test/responses/response.034	/epoc32/winscw/c/system/tocsp/responses/response.034
+../test/responses/response.035	/epoc32/winscw/c/system/tocsp/responses/response.035
+
+../test/responses/XCert_00_Good_RSA_XCert.rsp              /epoc32/winscw/c/system/tocsp/responses/xcert_00_good_rsa_xcert.rsp
+../test/responses/XCert_01_Revoked_RSA_XCert.rsp           /epoc32/winscw/c/system/tocsp/responses/xcert_01_revoked_rsa_xcert.rsp
+../test/responses/XCert_02_Suspended_RSA_XCert.rsp         /epoc32/winscw/c/system/tocsp/responses/xcert_02_suspended_rsa_xcert.rsp
+../test/responses/XCert_03_Unknown_RSA_XCert.rsp           /epoc32/winscw/c/system/tocsp/responses/xcert_03_unknown_rsa_xcert.rsp
+../test/responses/XCert_04_Good_DSA_XCert.rsp              /epoc32/winscw/c/system/tocsp/responses/xcert_04_good_dsa_xcert.rsp
+../test/responses/XCert_05_Revoked_DSA_XCert.rsp           /epoc32/winscw/c/system/tocsp/responses/xcert_05_revoked_dsa_xcert.rsp
+../test/responses/XCert_06_Suspended_DSA_XCert.rsp         /epoc32/winscw/c/system/tocsp/responses/xcert_06_suspended_dsa_xcert.rsp
+../test/responses/XCert_07_Unknown_DSA_XCert.rsp           /epoc32/winscw/c/system/tocsp/responses/xcert_07_unknown_dsa_xcert.rsp
+../test/responses/XCert_08_All_RSA_XCert.rsp               /epoc32/winscw/c/system/tocsp/responses/xcert_08_all_rsa_xcert.rsp
+../test/responses/XCert_09_All_DSA_XCert.rsp               /epoc32/winscw/c/system/tocsp/responses/xcert_09_all_dsa_xcert.rsp
+../test/responses/XCert_10_Expired_Subject_and_Issuer.rsp  /epoc32/winscw/c/system/tocsp/responses/xcert_10_expired_subject_and_issuer.rsp
+../test/responses/XCert_11_Expired_Signing.rsp             /epoc32/winscw/c/system/tocsp/responses/xcert_11_expired_signing.rsp
+../test/responses/XCert_12_Expired_Subject.rsp             /epoc32/winscw/c/system/tocsp/responses/xcert_12_expired_subject.rsp
+../test/responses/XCert_14_Expired_subject_valid_time.rsp  /epoc32/winscw/c/system/tocsp/responses/xcert_14_expired_subject_valid_time.rsp
+../test/responses/XCert_15_Expired_unspecified.rsp         /epoc32/winscw/c/system/tocsp/responses/xcert_15_expired_unspecified.rsp
+../test/responses/XCert_16_ThisUpdateTooEarly.rsp          /epoc32/winscw/c/system/tocsp/responses/xcert_16_thisupdatetooearly.rsp
+../test/responses/XCert_20_Nonce_Off.rsp                   /epoc32/winscw/c/system/tocsp/responses/xcert_20_nonce_off.rsp
+../test/responses/XCert_22_BadSig_DSA_XCert.rsp            /epoc32/winscw/c/system/tocsp/responses/xcert_22_badsig_dsa_xcert.rsp
+../test/responses/XCert_23_ResultCombination1.rsp          /epoc32/winscw/c/system/tocsp/responses/xcert_23_resultcombination1.rsp
+../test/responses/XCert_24_ResultCombination2.rsp          /epoc32/winscw/c/system/tocsp/responses/xcert_24_resultcombination2.rsp
+../test/responses/XCert_25_ResultCombination3.rsp          /epoc32/winscw/c/system/tocsp/responses/xcert_25_resultcombination3.rsp
+../test/responses/XCert_26_ResultCombination4.rsp          /epoc32/winscw/c/system/tocsp/responses/xcert_26_resultcombination4.rsp
+../test/responses/Error_00_Single_R5.rsp            		/epoc32/winscw/c/system/tocsp/responses/error_00_single_r5.rsp
+../test/responses/Error_01_Double_R5.rsp            		/epoc32/winscw/c/system/tocsp/responses/error_01_double_r5.rsp
+
+../test/responses/ca_1ext_usage_not_ocspsigning_resp.dat	/epoc32/winscw/c/system/tocsp/responses/ca_1ext_usage_not_ocspsigning_resp.dat
+../test/responses/ca_2ext_usage_not_ocspsigning_resp.dat	/epoc32/winscw/c/system/tocsp/responses/ca_2ext_usage_not_ocspsigning_resp.dat
+../test/responses/ca_2ext_usage_ocspsigning_bad_sign_resp.dat	/epoc32/winscw/c/system/tocsp/responses/ca_2ext_usage_ocspsigning_bad_sign_resp.dat
+../test/responses/ca_2ext_usage_ocspsigning_bad_name_resp.dat	/epoc32/winscw/c/system/tocsp/responses/ca_2ext_usage_ocspsigning_bad_name_resp.dat
+../test/responses/ca_2ext_usage_ocspsigning_resp.dat		/epoc32/winscw/c/system/tocsp/responses/ca_2ext_usage_ocspsigning_resp.dat
+../test/responses/ca_no_ext_usage_resp.dat					/epoc32/winscw/c/system/tocsp/responses/ca_no_ext_usage_resp.dat
+../test/responses/multi_cert_resp.dat						/epoc32/winscw/c/system/tocsp/responses/multi_cert_resp.dat
+../test/responses/no_cert_resp.dat							/epoc32/winscw/c/system/tocsp/responses/no_cert_resp.dat
+../test/responses/no_certresp_signedby_delegate.dat		/epoc32/winscw/c/system/tocsp/responses/no_certresp_signedby_delegate.dat
+../test/responses/multiple_response.dat					/epoc32/winscw/c/system/tocsp/responses/multiple_response.dat
+../test/responses/wrong_ca_cert_resp.dat					/epoc32/winscw/c/system/tocsp/responses/wrong_ca_cert_resp.dat
+../test/responses/ca_delg_wrong_key.dat					/epoc32/winscw/c/system/tocsp/responses/ca_delg_wrong_key.dat
+
+../test/responses/ca_direct_good_wrong_key.dat		/epoc32/winscw/c/system/tocsp/responses/ca_direct_good_wrong_key.dat
+../test/responses/ca_direct_multi_cert_inc_right.dat	/epoc32/winscw/c/system/tocsp/responses/ca_direct_multi_cert_inc_right.dat
+../test/responses/ca_direct_multi_cert_no_right.dat	/epoc32/winscw/c/system/tocsp/responses/ca_direct_multi_cert_no_right.dat
+../test/responses/ca_direct_revoked.dat		/epoc32/winscw/c/system/tocsp/responses/ca_direct_revoked.dat
+../test/responses/ca_direct_wrong_cert.dat		/epoc32/winscw/c/system/tocsp/responses/ca_direct_wrong_cert.dat
+../test/responses/ca_direct_wrong_resp_name.dat	/epoc32/winscw/c/system/tocsp/responses/ca_direct_wrong_resp_name.dat
+
+../test/responses/openssl/response01.dat		/epoc32/winscw/c/system/tocsp/responses/openssl/response01.dat
+../test/responses/openssl/response02.dat		/epoc32/winscw/c/system/tocsp/responses/openssl/response02.dat
+../test/responses/openssl/response03.dat		/epoc32/winscw/c/system/tocsp/responses/openssl/response03.dat
+../test/responses/openssl/response04.dat		/epoc32/winscw/c/system/tocsp/responses/openssl/response04.dat
+../test/responses/openssl/response05.dat		/epoc32/winscw/c/system/tocsp/responses/openssl/response05.dat
+../test/responses/openssl/response06.dat		/epoc32/winscw/c/system/tocsp/responses/openssl/response06.dat
+../test/responses/openssl/response07.dat		/epoc32/winscw/c/system/tocsp/responses/openssl/response07.dat
+../test/responses/openssl/response08.dat		/epoc32/winscw/c/system/tocsp/responses/openssl/response08.dat
+../test/responses/openssl/response09.dat		/epoc32/winscw/c/system/tocsp/responses/openssl/response09.dat
+../test/responses/openssl/response10.dat		/epoc32/winscw/c/system/tocsp/responses/openssl/response10.dat
+../test/responses/openssl/response11.dat		/epoc32/winscw/c/system/tocsp/responses/openssl/response11.dat
+../test/responses/openssl/response12.dat		/epoc32/winscw/c/system/tocsp/responses/openssl/response12.dat
+../test/responses/openssl/no_aia_no_ocspext.dat	/epoc32/winscw/c/system/tocsp/responses/openssl/no_aia_no_ocspext.dat
+
+../test/requests/openssl/request01.dat			/epoc32/winscw/c/system/tocsp/requests/openssl/request01.dat
+../test/requests/openssl/request02.dat			/epoc32/winscw/c/system/tocsp/requests/openssl/request02.dat
+../test/requests/openssl/request03.dat			/epoc32/winscw/c/system/tocsp/requests/openssl/request03.dat
+../test/requests/openssl/request04.dat			/epoc32/winscw/c/system/tocsp/requests/openssl/request04.dat
+../test/requests/openssl/request05.dat			/epoc32/winscw/c/system/tocsp/requests/openssl/request05.dat
+../test/requests/openssl/request06.dat			/epoc32/winscw/c/system/tocsp/requests/openssl/request06.dat
+../test/requests/openssl/request07.dat			/epoc32/winscw/c/system/tocsp/requests/openssl/request07.dat
+../test/requests/openssl/request08.dat			/epoc32/winscw/c/system/tocsp/requests/openssl/request08.dat
+../test/requests/openssl/request09.dat			/epoc32/winscw/c/system/tocsp/requests/openssl/request09.dat
+../test/requests/openssl/request10.dat			/epoc32/winscw/c/system/tocsp/requests/openssl/request10.dat
+../test/requests/openssl/request11.dat			/epoc32/winscw/c/system/tocsp/requests/openssl/request11.dat
+../test/requests/openssl/request12.dat			/epoc32/winscw/c/system/tocsp/requests/openssl/request12.dat
+
+// OCSP tests - end
+
+// ROMKIT includes
+../inc/ocsptests.iby 		/epoc32/rom/include/ocsptests.iby
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/group/ocsp.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+/**
+@file
+
+@SYMPurpose ocsp.dll Implements OCSP protocol
+*/
+
+TARGET        ocsp.dll
+TARGETTYPE    DLL
+
+CAPABILITY All
+
+UID    0x1000008d 0x1000A404
+VENDORID 0x70000001
+
+MW_LAYER_SYSTEMINCLUDE_SYMBIAN
+USERINCLUDE     ../inc
+
+DEFFILE ocsp_v2.def
+
+SOURCEPATH .
+SOURCE	../src/certid.cpp
+SOURCE	../src/client.cpp
+SOURCE	../src/directauthorisation.cpp
+SOURCE	../src/delegateauthorisation.cpp
+SOURCE	../src/cadirectauthorisation.cpp
+SOURCE	../src/panic.cpp
+SOURCE	../src/parameters.cpp
+SOURCE	../src/request.cpp
+SOURCE	../src/requestencoder.cpp
+SOURCE	../src/response.cpp
+SOURCE	../src/responsecertinfo.cpp
+SOURCE	../src/responsedecoder.cpp
+SOURCE	../src/transaction.cpp
+SOURCE	../src/validator.cpp
+SOURCE	../src/ocsputils.cpp
+
+LIBRARY ocspcommon.lib
+LIBRARY euser.lib asn1.lib crypto.lib x509.lib random.lib
+LIBRARY cryptography.lib
+LIBRARY hash.lib x500.lib pkixcertbase.lib
+LIBRARY ctframework.lib efsrv.lib estor.lib 
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/group/ocspcommon.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+/**
+@file
+
+@SYMPurpose ocspcommon.dll Implements functionality common to OCSP and OCSPTransport (repository file reading methods)
+*/
+
+TARGET        ocspcommon.dll
+TARGETTYPE    DLL
+
+CAPABILITY All
+
+UID    0x1000008d 0x1000A405	
+VENDORID 0x70000001
+
+MW_LAYER_SYSTEMINCLUDE_SYMBIAN
+USERINCLUDE 	../inc
+
+DEFFILE ocspcommon.def
+
+SOURCEPATH .
+SOURCE	../src/ocsppolicy.cpp
+
+LIBRARY euser.lib
+LIBRARY efsrv.lib
+LIBRARY estor.lib
+LIBRARY secsettingsclient.lib
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/group/securitysrv_ocsp.mrp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,13 @@
+component	securitysrv_ocsp
+source	\sf\mw\securitysrv\pkiutilities\ocsp
+binary	\sf\mw\securitysrv\pkiutilities\ocsp\group all
+exports	\sf\mw\securitysrv\pkiutilities\ocsp\group
+
+notes_source	\component_defs\release.src
+
+ipr E
+ipr T       \sf\mw\securitysrv\pkiutilities\ocsp\test
+
+
+  
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/certid.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,60 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Used in cert info objects for requests and responses.
+// Declare certID object, representing the CertID data structure from
+// the OCSP spec. Used in cert info objects for requests and responses.
+// 
+//
+
+/**
+ @file 
+ @internalTechnology 
+*/
+ 
+#ifndef __OCSP_CERTID_H__
+#define __OCSP_CERTID_H__
+
+#include <hash.h>
+
+class CASN1EncBase;
+class CX509Certificate;
+
+// CertID, used in requests and responses
+NONSHARABLE_CLASS(COCSPCertID) : public CBase
+	{
+public:
+	// Make from certificates - subject mustn't be deleted in our lifetime
+	static COCSPCertID* NewL(const CX509Certificate& aSubject, const CX509Certificate& aIssuer);
+
+	// Make from binary data - which mustn't be deleted in our lifetime
+	static COCSPCertID* NewL(const TDesC8& aBinaryData);
+
+	// Construct ASN1 encoding object for the CertID data
+	CASN1EncBase* EncoderLC() const;
+
+    TPtrC8 SerialNumber() const;
+
+	TBool operator==(const COCSPCertID& aRhs) const;
+
+private:
+	void ConstructL(const CX509Certificate& aSubject, const CX509Certificate& aIssuer);
+	void ConstructL(const TDesC8& aBinaryData);
+
+private:
+	TBuf8<SHA_HASH> iIssuerNameHash;
+	TBuf8<SHA_HASH> iIssuerKeyHash;
+	TPtrC8 iSerialNumber; // Refers to the input certificate or input binary data
+	};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/log.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,106 @@
+// Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// This header contains definitions for logging commands.
+// 
+//
+
+/**
+ @file 
+ @internalComponent
+*/
+
+#ifndef __OCSP_LOG_H__
+#define __OCSP_LOG_H__
+
+#include <e32debug.h>
+
+namespace OCSP
+{
+
+#ifdef _DEBUG
+
+#define DEBUG_PRINTF(a) {OCSP::DebugPrintf(__LINE__, __FILE__, a);}
+#define DEBUG_PRINTF2(a, b) {OCSP::DebugPrintf(__LINE__, __FILE__, a, b);}
+#define DEBUG_PRINTF3(a, b, c) {OCSP::DebugPrintf(__LINE__, __FILE__, a, b, c);}
+#define DEBUG_PRINTF4(a, b, c, d) {OCSP::DebugPrintf(__LINE__, __FILE__, a, b, c, d);}
+#define DEBUG_PRINTF5(a, b, c, d, e) {OCSP::DebugPrintf(__LINE__, __FILE__, a, b, c, d, e);}
+
+#define DEBUG_CODE_SECTION(a) TRAP_IGNORE({ a; }) 
+
+// UTF-8 overload of the DebufPrintf method. Should be used by default,
+// since it's cheaper both in CPU cycles and stack space.
+
+inline void DebugPrintf(TInt aLine, char* aFile, TRefByValue<const TDesC8> aFormat, ...)
+	{
+	VA_LIST list;
+	VA_START(list, aFormat);
+	
+	TTime now;
+	now.HomeTime();
+	
+	TBuf8<1024> buffer;
+	_LIT8(KSwiLogPrefix, "[OCSP] ");
+	_LIT8(KSwiLineFileFormat, "%Ld Line: % 5d, File: %s -- ");
+	buffer.Append(KSwiLogPrefix);
+	buffer.AppendFormat(KSwiLineFileFormat, now.Int64(), aLine, aFile);
+	buffer.AppendFormatList(aFormat, list);
+	buffer.Append(_L8("\r\n"));
+	
+	RDebug::RawPrint(buffer);
+	
+	VA_END(list);
+	}
+	
+// Unicode DebufPrintf overload
+
+inline void DebugPrintf(TInt aLine, char* aFile, TRefByValue<const TDesC16> aFormat, ...)
+	{
+	VA_LIST list;
+	VA_START(list, aFormat);
+	
+	TTime now;
+	now.HomeTime();
+	
+	TBuf8<256> header;
+	_LIT8(KSwiLogPrefix, "[SWI] ");
+	_LIT8(KSwiLineFileFormat, "%Ld Line: % 5d, File: %s -- ");
+	header.Append(KSwiLogPrefix);
+	header.AppendFormat(KSwiLineFileFormat, now.Int64(), aLine, aFile);
+	
+	TBuf<1024> buffer;
+	buffer.Copy(header);
+	buffer.AppendFormatList(aFormat, list);
+	buffer.Append(_L("\r\n"));
+	
+	RDebug::RawPrint(buffer);
+	
+	VA_END(list);
+	}
+
+#else
+
+#define DEBUG_PRINTF(a)
+#define DEBUG_PRINTF2(a, b)
+#define DEBUG_PRINTF3(a, b, c)
+#define DEBUG_PRINTF4(a, b, c, d)
+#define DEBUG_PRINTF5(a, b, c, d, e)
+
+#define DEBUG_CODE_SECTION(a)
+
+#endif
+
+
+} // namespace Swi
+
+#endif // __OCSP_LOG_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/ocsp.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,28 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#ifndef __OCSP_IBY__
+#define __OCSP_IBY__
+
+// Online Certificate Status Protocol( OCSP ) implementation
+
+file=ABI_DIR\BUILD_DIR\ocsp.dll		System\Libs\ocsp.dll
+file=ABI_DIR\BUILD_DIR\ocsptransport.dll		System\Libs\ocsptransport.dll
+file=ABI_DIR\BUILD_DIR\ocspcommon.dll			System\Libs\ocspcommon.dll
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/ocsp_v2.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,137 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// ocsp.h
+// Header specifying client interface to the OCSP module.
+// 
+//
+
+#ifndef __OCSP_H__
+#define __OCSP_H__
+
+/**
+ * @file
+ * @publishedPartner
+ * @released
+ */
+
+#include <e32base.h>
+#include <signed.h>
+#include <f32file.h>
+#include <hash.h>
+#include <x500dn.h>
+#include <x509cert.h>
+#include <ct/rmpointerarray.h>
+#include <cctcertinfo.h>
+#include <asn1enc.h>
+#include <asn1dec.h>
+
+// Enums placed in OCSP namespace
+namespace OCSP
+	{
+	// Globally-reserved error codes - range is -7601 to -7649
+	enum 
+		{
+		KErrTransportFailure	= -7601,
+		KErrInvalidURI			= -7602,
+		KErrNoCertificates		= -7603,
+		KErrTransportTimeout	= -7604,
+		KErrServerNotFound		= -7605
+		};
+
+	/**
+	 * What we think of the response, or why we haven't got one
+	 * 
+	 */
+	enum TStatus 
+		{
+		// Error in communication with server
+		ETransportError = 1,
+
+		// Internal problem processing response
+		EClientInternalError = 2,
+
+		// No OCSP server specified
+		ENoServerSpecified = 3,
+
+		// Invalid sever URI
+		EInvalidURI = 4,
+		
+		// Timeout error
+		ETimeOut = 5,
+		
+		// Problems understanding the response
+		EMalformedResponse = 10,
+		EUnknownResponseType = 11,
+		EUnknownCriticalExtension = 12,
+
+		// Unsuccessful responses from server
+		EMalformedRequest = 20,
+		EServerInternalError = 21,
+		ETryLater = 22,
+		ESignatureRequired = 23,
+		EClientUnauthorised = 24,
+			
+		// Response validation failures
+		EMissingCertificates = 30,
+		EResponseSignatureValidationFailure = 31,
+		
+		// Time problems
+		EThisUpdateTooLate = 40,
+		EThisUpdateTooEarly = 41,
+		ENextUpdateTooEarly = 42,
+		ECertificateNotValidAtValidationTime = 43,
+
+		// Nonce error
+		ENonceMismatch = 50,
+
+		// Response sufficiently valid to use - clients to decide if
+		// missing nonce is sufficiently serious to require rejection
+		EMissingNonce = 51,
+		
+		EValid = 100,
+		};
+	
+	/**
+	 * What does the response say about the certificates?
+	 * IMPORTANT: Do not change the order these are in
+	 *
+	 */
+	enum TResult
+		{
+		EGood = 10, EUnknown = 20, ERevoked = 30
+		};
+	}
+		
+class TOCSPOutcome
+	{
+public:
+	TOCSPOutcome(OCSP::TStatus aStatus, OCSP::TResult aResult)
+		: iStatus(aStatus), iResult(aResult) {};
+
+	TOCSPOutcome()
+		: iStatus(OCSP::EClientInternalError), iResult(OCSP::EUnknown) {};
+
+	TBool operator==(const TOCSPOutcome& aRhs) const
+		{ return iStatus == aRhs.iStatus && iResult == aRhs.iResult; }
+
+	OCSP::TStatus iStatus;
+	OCSP::TResult iResult;
+	};
+
+
+#ifndef SYMBIAN_ENABLE_SPLIT_HEADERS
+#include <ocsprequestandresponse.h>
+#endif
+
+#endif // __OCSP_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/ocsppolicy.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,84 @@
+// Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// This file contains classes providing functionality to read the OCSP policy repository.
+// 
+//
+
+/**
+ @file
+ @internalTechnology
+*/
+
+#ifndef __OCSPPOLICY_H__
+#define __OCSPPOLICY_H__
+
+#include <e32base.h>
+
+// Security settings.
+#include <SecSettings/SecSettingsclient.h>
+
+#include <securityerr.h>
+
+// Following settings are read from the OCSP repository.
+//   KGenerateResponseForMissingUri = True/False
+//   KEnableHttpGETMethod = True/False
+//
+
+// Key for the setting - KGenerateResponseForMissingUri.
+const TUint32 KGenerateResponseForMissingUri = 0x1;
+
+// Key for the setting - KEnableHttpGetMethod.
+const TUint32 KEnableHttpGetMethod = 0x2;
+
+/*
+ * COcspPolicy class - Implementation to read the OCSP central repository
+ * settings.
+ */
+class COcspPolicy : public CBase
+	{
+public:
+	/**
+	 * This function returns the setting for KGenerateResponseForMissingUri
+	 */
+	IMPORT_C TBool IsGenerateResponseForMissingUriEnabled() const;
+
+	/**
+	 * This function returns the setting for KEnableHttpGETMethod
+	 */
+	IMPORT_C TBool IsHttpGETMethodEnabled() const;
+
+
+	/**
+  	 * This function is used to access the instance of this class. 
+	 * TLS is used to store pointer of the instance.
+  	 */
+	IMPORT_C static COcspPolicy* NewL();
+
+private:	
+	COcspPolicy();
+
+
+	/**
+	 * The second-phase constructor. It reads the settings from
+	 * the repository.
+	 */
+	void ConstructL();
+
+private:
+	TBool iGenerateResponseForMissingUri;
+	TBool iEnableHttpGETMethod;
+	};
+
+
+#endif // __OCSPPOLICY_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/ocsprequestandresponse.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,867 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// ocsp.h
+// Header specifying client interface to the OCSP module.
+// 
+//
+
+#ifndef OCSPREQUESTANDRESPONSE_H
+#define OCSPREQUESTANDRESPONSE_H
+
+/**
+ * @file
+ * @internalTechnology
+ */
+
+#include <e32base.h>
+#include <signed.h>
+#include <f32file.h>
+#include <hash.h>
+#include <x500dn.h>
+#include <x509cert.h>
+#include <ct/rmpointerarray.h>
+#include <cctcertinfo.h>
+#include <asn1enc.h>
+#include <asn1dec.h>
+
+#ifdef SYMBIAN_ENABLE_SPLIT_HEADERS
+#include "ocsp.h"
+#endif
+
+#define KOCSPNonceBytes 16
+
+// Default values for transport parameters
+const TUint KTransportDefaultRequestRetryCount 	= 1;	// No retry
+const TInt KTransportDefaultRequestTimeout 		= -1;	// Timeout disabled
+
+class COCSPRequestCertInfo;
+class COCSPResponseCertInfo;
+class COCSPCertID;
+class MOCSPTransport;
+class COCSPResponse;
+class COCSPTransportHandler;
+class MOCSPAuthorisationScheme;
+class COCSPTransaction;
+class COCSPValidator;
+class COCSPRequestCertInfo;
+class COCSPResponseDecoder;
+
+class CASN1EncBase;
+class CASN1EncContainer;
+class TASN1DecGeneric;
+
+class CX509Certificate;
+class CX509CertChain;
+class CPKIXCertChainBase;
+class COCSPParameters;
+
+
+/**
+ * Represents an OCSP protocol request.
+ */
+
+class COCSPRequest : public CBase
+	{
+public:
+
+	/**
+	 * Get the nonce used in the request.  Returns NULL if a nonce was not used.
+	 */
+
+	IMPORT_C const TDesC8* Nonce() const;
+
+	/**
+	 * Get the number of certificates used in a response
+	 */
+	
+	IMPORT_C TInt CertCount() const;
+
+	/**
+	 * Get a COCSPRequestCertInfo object containing details about one of the
+	 * certificates present in the request.
+	 */
+
+	IMPORT_C const COCSPRequestCertInfo& CertInfo(TUint aIndex) const;
+	
+public:
+
+	// Not exported
+	static COCSPRequest* NewLC(TBool aUseNonce);
+	static COCSPRequest* NewL(TBool aUseNonce);
+	
+	~COCSPRequest();
+	void AddCertificateL(const CX509Certificate& aSubject,
+						 const CX509Certificate& aIssuer);
+
+private:
+
+	COCSPRequest();
+	void ConstructL(TBool aUseNonce);
+
+	HBufC8* iNonce;
+	RPointerArray<const COCSPRequestCertInfo> iCertInfos;
+	};
+
+/**
+ * Information about a certificate sent as part of an OCSP request.
+ */
+
+class COCSPRequestCertInfo : public CBase
+	{
+public:
+
+	/**
+	 * Get the certificate present in the request.
+	 */
+	
+	IMPORT_C const CX509Certificate& Subject() const;
+
+	/**
+	 * Get the issuer of the certificate present in the request.
+	 */
+	
+	IMPORT_C const CX509Certificate& Issuer() const;
+
+public:
+
+	// Not exported
+	static COCSPRequestCertInfo* NewLC(
+		const CX509Certificate& aSubject,
+		const CX509Certificate& aIssuer);
+
+	~COCSPRequestCertInfo();
+
+	const COCSPCertID& CertID() const;
+
+ private:
+	
+	COCSPRequestCertInfo(const CX509Certificate& aIssuer,
+						 const CX509Certificate& aSubject);
+	void ConstructL();
+
+private:
+
+	const CX509Certificate& iSubject;
+	const CX509Certificate& iIssuer;
+	COCSPCertID* iCertID;
+	};
+
+
+/**
+ * Represents an OCSP protocol response.
+ */
+
+class COCSPResponse : public CSignedObject
+	{
+public:
+
+	/**
+	 * Get the number of certificates statuses present in the response.
+	 */
+
+	IMPORT_C TInt CertCount() const;
+
+	/**
+	 * Get a COCSPResponseCertInfo object containing details about one of the
+	 * certificate statuses present in the response.
+	 */
+
+	IMPORT_C const COCSPResponseCertInfo& CertInfo(TUint aIndex) const;
+
+	/**
+	 * Get the producedAt time for the response.
+	 */
+
+	IMPORT_C TTime ProducedAt() const;
+
+	/**
+	 * Get the archiveCutoff time for the response, or NULL if it was not present.
+	 */
+
+	IMPORT_C const TTime* ArchiveCutoff() const;
+
+public:
+
+	// This class is created and initialised by the response decoder
+	friend class COCSPResponseDecoder;
+	
+	~COCSPResponse();
+
+	/**
+	 * Get the index for the given cert, or KErrNotFound.
+	 */
+	
+	TInt Find(const COCSPCertID& aCertID) const;
+
+	// Enums to use in DataElementEncoding
+	enum
+		{
+		ECertificateChain,
+		ENonce,
+		EResponderIDName,    // Only one of the ResponderIDs won't be NULL
+		EResponderIDKeyHash
+		};
+
+  	// From CSignedObject
+  	const TPtrC8* DataElementEncoding(const TUint aIndex) const;
+
+private:
+
+	COCSPResponse();
+
+  	// From CSignedObject
+	const TPtrC8 SignedDataL() const;
+	void InternalizeL(RReadStream& aStream);
+
+private:
+
+	// Time of response, and of archiveCutoff extension (if present)
+	TTime iProducedAt;
+	TTime* iArchiveCutoff;
+
+	// Value of nonce in response extension (if present)
+	TPtrC8 iNonce;
+
+	// Point to the signing certificates in the response
+	TPtrC8 iSigningCerts;
+
+	// Point to the signed portion of the data
+	TPtrC8 iSignedData;
+
+	// There are two ways the responder ID can be specified - only
+	// one of these will be used
+	TPtrC8 iResponderIDName;
+	TPtrC8 iResponderIDKeyHash;
+
+	RPointerArray<COCSPResponseCertInfo> iCertInfos;
+	};
+
+
+/**
+ * Information about a certificate status, as given in OCSP response
+ * singleResponse data item.
+ */
+
+class COCSPResponseCertInfo : public CBase
+	{
+public:
+	
+	IMPORT_C OCSP::TResult Status() const;
+	IMPORT_C TTime ThisUpdate() const;
+	IMPORT_C const TTime* NextUpdate() const;     // NULL if nextUpdate not set
+	IMPORT_C const TTime* RevocationTime() const; // NULL if not revoked
+
+public:
+	
+	static COCSPResponseCertInfo* NewLC(CArrayPtr<TASN1DecGeneric>& aItems);
+	~COCSPResponseCertInfo();
+	COCSPCertID& CertID() const;
+	
+private:
+	void ConstructL(CArrayPtr<TASN1DecGeneric>& aItems);
+
+private:
+	OCSP::TResult iStatus;
+
+	TTime iThisUpdate;
+	TTime* iNextUpdate;
+	TTime* iRevocationTime;
+
+	COCSPCertID* iCertID;
+	};
+
+/**
+	Utility class contains functions common to all validation
+	schemes.
+ */
+namespace OCSPUtils
+	{
+	TBool IsAIAForOCSPPresentL(const CX509Certificate& aCert);
+	
+	TBool DoesResponderIdMatchCertL( const COCSPResponse& aResponse, 
+											const CX509Certificate& aResponderCert);
+	TBool DoesDNNameMatchL( 	const COCSPResponse& aResponse, const CX509Certificate& aCert);
+	TBool DoesIssuerKeyMatchL(const COCSPResponse& aResponse, const CX509Certificate& aCert);
+	TBool IsResponseSignedByCertL( COCSPResponse* aResponse, const CX509Certificate& aCert);
+	TBool DoesCertHaveOCSPNoCheckExt( const CX509Certificate& aCert);
+	TDesC8* ServerUriL(	const CX509Certificate& aCert, const COCSPParameters* aParameters );
+	TBool IsUriAvailableL( const CX509Certificate& aCert, const COCSPParameters* aParameters );
+	TDesC8* GetAIAL(const CX509Certificate& aCert);
+	TBool DoesCertHaveOCSPSigningExtL(const CX509Certificate& aCert);
+	CX509Certificate* GetResponderCertLC(const TDesC8& aEncodedCerts);
+	}
+
+// Base class interface for authorisation schemes, for plugging into the validator object
+class MOCSPAuthorisationScheme
+	{
+public:
+	virtual ~MOCSPAuthorisationScheme() {};
+
+	virtual void ValidateL(
+		OCSP::TStatus& aOCSPStatus, COCSPResponse& aResponse,
+		const TTime aValidationTime, TRequestStatus& aStatus,
+		const COCSPRequest& aRequest) = 0;
+
+	virtual void CancelValidate() = 0;
+	// Returns the responder certificate. This method shall return valid responder
+	// certificate for delegate and direct schemes, for the cadirect scheme although
+	// the CA cert is the response cert but it returns NULL as the need for retrieving
+	// this certificate is to further send it for OCSP checking, this logic is only valid 
+	// for delegate and direct schemes.
+	virtual const CX509Certificate* ResponderCert() const = 0;
+	};
+
+
+class CPKIXValidationResultBase;
+class CCertAttributeFilter;
+class MCertStore;
+
+class COCSPDelegateAuthorisationScheme : public CActive, public MOCSPAuthorisationScheme
+/**
+	Implement part of S2.2.2 of RFC 2560.
+	
+	"a CA Designated Responder (Authorized Responder) who holds
+	a specially marked certificate issued directly by the CA,
+	indicating that the responder may issue OCSP responses for
+	that CA."
+*/
+	{
+public:
+	IMPORT_C static COCSPDelegateAuthorisationScheme* NewLC(MCertStore& aCertStore);
+	virtual ~COCSPDelegateAuthorisationScheme();
+	
+	virtual void ValidateL(
+		OCSP::TStatus& aOCSPStatus, COCSPResponse& aResponse,
+		const TTime aValidationTime, TRequestStatus& aStatus,
+		const COCSPRequest& aRequest);
+	
+	virtual void CancelValidate();
+	const CX509Certificate* ResponderCert() const;
+	
+protected:
+	virtual void RunL();
+	virtual void DoCancel();
+	TInt RunError(TInt aError);
+	
+private:
+	COCSPDelegateAuthorisationScheme(MCertStore& aCertStore);
+	void ConstructL();
+	
+	void ValidateDelegateCertL(const TDesC8& aResponseCertChain, const TTime aValidationTime);
+	void OnChainValidationL();
+	
+	// searches on the basis of the issuer's subject name
+	void ValidateFromRootsL();
+	
+	void OnRetrieveNextL();
+	void OnRetrievingEntryL();
+	
+private:
+
+	enum TDelegateAuthState
+	{
+	EOnChainValidation,
+	ERetrieveNext,
+	ERetrievingEntry,
+	};
+	/**
+		This is a required argument for CPKIXCertChainBase, even
+		though no certificates are used from the store.
+	 */
+	MCertStore& iCertStore;
+	/**
+		Pointer to client's OSCP status.  This object sets the
+		status according to the result of the validation.  If
+		the validation cannot be carried out, the default value
+		is OCSP::EResponseSignatureValidationFailure.
+	 */
+	OCSP::TStatus* iOCSPStatus;
+	/**
+		Pointer to client's request status.  This is recorded
+		on the call to Validate() and used to notify the client
+		of completion later.
+	 */
+	TRequestStatus* iClientStatus;
+	/**
+		Array used to hold pointer to issuer cert.  This contains
+		the pointer to the CA.
+	 */
+	RPointerArray<CX509Certificate> iRespSignIntCert;
+	/**
+		This object is used to chain the response signer back
+		to the CA.
+	 */
+	CPKIXCertChainBase* iRespSignCertChainBase;
+	/**
+		The cert chain stores the validation result in
+		this object.
+		
+		@see iRespSignCertChain;
+	 */
+	CPKIXValidationResultBase* iPKIXResultBase;
+	/**
+		Response from OCSP server.  Once it has been established
+		that the certificate sent with the response is an authorised
+		responder for the CA, the response is checked to ensure
+		that it really is signed by that certificate.
+		
+		This is not const because, if DSA is used, then
+		SetParametersL() will be called on the response before
+		the signature is verified.
+	 */
+	COCSPResponse* iResponse;
+	const COCSPRequest* iRequest;
+	CCertAttributeFilter* iCertFilter;
+	RMPointerArray<CCTCertInfo> iCertStoreEntries;
+	TDelegateAuthState	iState;
+	HBufC8* iEncodedCert;
+	const CX509Certificate* iResponseCert;
+	TInt iCertCount;
+	TTime iValidationTime;
+	TBool iValidateFromResponse;
+	
+	};
+
+class COCSPCaDirectAuthorisationScheme : public CBase, public MOCSPAuthorisationScheme
+/**
+	Implement part of S2.2 of RFC 2560.
+	
+	"The key used to sign the response MUST belong to one of the following...
+
+	-- the CA who issued the certificate in question"
+*/
+	{
+public:
+	IMPORT_C static COCSPCaDirectAuthorisationScheme* NewLC();
+	const CX509Certificate* ResponderCert() const;
+	
+private:
+	virtual void ValidateL(
+		OCSP::TStatus& aOCSPStatus, COCSPResponse& aResponse,
+		const TTime aValidationTime, TRequestStatus& aStatus,
+		const COCSPRequest& aRequest);
+	virtual void CancelValidate();
+
+	TBool DoValidateL(
+		const COCSPRequest& aRequest, COCSPResponse& aResponse);
+	TBool CertChainMatchesCertL(
+		const TDesC8& aCertChainData, const CX509Certificate& aCert);
+	};
+
+// Authorisation scheme taking a cert store UID, and allowing those cert chains
+// with a root cert in the cert store valid for that UID
+	
+	/**
+	Implement part of S2.2 of RFC 2560.
+	
+	"The key used to sign the response MUST belong to one of the following...
+
+	-- a Trusted Responder whose public key is trusted by the requester"
+*/
+class COCSPDirectAuthorisationScheme : public CActive, public MOCSPAuthorisationScheme
+	{
+public:
+	IMPORT_C static COCSPDirectAuthorisationScheme* NewLC(const TUid& aCertStoreUid, MCertStore& aCertStore);
+
+	~COCSPDirectAuthorisationScheme();
+
+	// From MOCSPAuthorisationScheme
+	void ValidateL(OCSP::TStatus& aOCSPStatus, COCSPResponse& aResponse, 
+		const TTime aValidationTime, TRequestStatus& aStatus,
+		const COCSPRequest& aRequest);
+	void CancelValidate();
+	
+	const CX509Certificate* ResponderCert() const;
+	
+protected:
+	virtual void DoCancel();
+	virtual void RunL();
+	virtual TInt RunError(TInt aError);
+	
+private:
+	void ConstructL();
+	
+	COCSPDirectAuthorisationScheme(const TUid& aCertStoreUid, MCertStore& aCertStore);
+
+	TBool ValidateSignatureL();
+	void ValidateFromRoots();
+	void ValidateCertChainL(); 
+	void StartValidateL();
+	void OnValidateCertChainL();
+	void OnListCertEntries();
+	void OnRetrieveNextL();
+	void OnRetrievingEntryL();
+
+private:
+	TUid iCertStoreUid;
+
+	COCSPResponse* iResponse;
+
+	CPKIXCertChainBase* iCertChain;
+
+	TRequestStatus* iClientStatus;
+	CPKIXValidationResultBase* iPKIXResult;
+	OCSP::TStatus* iOCSPStatus;
+
+	enum TStatus
+		{
+		EValidateCertChain, // waiting for cert chain validation to complete
+		EListCertEntries,   // waiting listing to complete
+		ERetrieveNext,      // get next cert entry
+		ERetrievingEntry,   // waiting for entry retrieval to complete
+		};
+	TStatus iState;
+
+	MCertStore& iCertStore;
+	
+	CCertAttributeFilter* iCertFilter;
+	RMPointerArray<CCTCertInfo> iCertStoreEntries;
+	HBufC8* iEncodedCertBuf;
+	TPtr8* iEncodedCertPtr;
+
+	RFs iFs;
+	TInt iCurEntry; // while async processing 509 certs, points to the current one
+
+	TTime iValidationTime;
+	const COCSPRequest* iRequest;
+	const CX509Certificate* iResponseCert;
+	};
+
+
+/**
+ * Interface through which the OCSP module sends requests to the outside world.
+ * Normally, the appropriate concrete objects are made automatically, depending
+ * on the URI, and so clients don't have to deal with this.  However, clients
+ * can override the automatically created object by specifying their own
+ * transport object instead.
+ */
+
+class MOCSPTransport
+	{
+public:
+
+	virtual ~MOCSPTransport() {};
+
+	/**
+	 * Send request data to a URI. This is an asynchronous method.
+	 * @param aURI			Target URI for sending the request
+	 * @param aRequest		Request packet
+	 * @param aTimeout		Request timeout in milliseconds (ignored if feature not supported)
+	 * @param aStatus		The request status object. On request completion, indicates the status
+	 */
+	virtual void SendRequest(const TDesC8& aURI,
+							 const TDesC8& aRequest,
+							 const TInt aTimeout,
+							 TRequestStatus& aStatus) = 0;
+
+	/**
+	 * Cancel the request.
+	 */
+	
+	virtual void CancelRequest() = 0;
+
+	// The following methods will only be called after the aStatus above is completed
+
+	/**
+	 * Get the response data.  Panic if completion gave an error.
+	 */
+	
+	virtual TPtrC8 GetResponse() const = 0;	
+	};
+
+
+/**
+ * Specifies paremeters needed to perform revocation checking.  The important
+ * things to set are the certificates to be checked all - all the other
+ * parameters have defaults.
+ */
+
+class COCSPParameters : public CBase
+	{
+public:
+	
+	/**
+	 * Create a new parameters object.
+	 */
+
+	IMPORT_C static COCSPParameters* NewL();
+	IMPORT_C static COCSPParameters* NewLC();
+	
+	/**
+	 * Add a certificate chain to be checked.  Does not take ownership -
+	 * certificates must not be destroyed until the OCSP check complete.
+	 */
+
+	IMPORT_C void AddCertificatesL(const CX509CertChain& aChain);
+
+	/**
+	 * Add a certificate to be checked.  Does not take ownership - certificates
+	 * must not be destroyed until the OCSP check complete.
+	 */
+
+	IMPORT_C void AddCertificateL(const CX509Certificate& aSubject, const CX509Certificate& aIssuer);
+
+	/**
+	 * Set whether or not to use a nonce.  By default this is turned on.
+	 */
+
+	IMPORT_C void SetUseNonce(TBool aUseNonce);
+
+	/**
+	 * Set the URI of the OCSP responder to use.  The descriptor is copied.
+	 *
+	 * @param aURI The URI of the responder to use.
+	 * @param aUseAIA Indicates whether to use the responder specified in
+	 * certifcate AuthorityInfoAccess extensions in preference to the one given
+	 * here.
+	 */
+
+	IMPORT_C void SetURIL(const TDesC8& aURI, TBool aUseAIA);
+
+	/**
+	 * Set the transport to use.  This method must be called - if no transport
+	 * is set COCSPClient::NewL will leave with KErrArgument.  This object takes
+	 * ownership.
+	 */
+
+	IMPORT_C void SetTransport(MOCSPTransport* aTransport);
+
+	/**
+	 * Set the retry count for failed send request attempts.
+	 * A default value of 1 (no retry) is used.
+	 * 
+	 * @param aRetryCount		Retry count
+	 */
+	IMPORT_C void SetRetryCount(const TUint aRetryCount);
+
+	/**
+	 * Set the request timeout.
+	 * A default value of -1 (default transport timeout) is used.
+	 * 
+	 * @param aTimeout			Request timeout in milliseconds
+	 */
+	IMPORT_C void SetTimeout(const TInt aTimeout);
+
+	/**
+	 * Add an authorisation scheme - takes ownership if it doesn't leave.
+	 * Clients must specify at least one such scheme, used to validate the signature
+	 * on the response.
+	 */
+
+	IMPORT_C void AddAuthorisationSchemeL(MOCSPAuthorisationScheme* aScheme);
+
+	IMPORT_C void AddAllAuthorisationSchemesL(const TUid& aCertStoreUid, MCertStore& aCertStore);
+
+	/**
+	 * Specify the authorisation time (optional - uses producedAt time from response otherwise).
+	 */
+
+	IMPORT_C void SetValidationTimeL(const TTime& aValidationTime);
+
+	/**
+	 * Specify the maximum age of the thisUpdate field in seconds (zero => don't check).
+	 */
+
+	IMPORT_C void SetMaxStatusAgeL(TUint aMaxAge);
+
+	/**
+	 * Specify how much leeway we allow when comparing times.
+	 */
+
+	IMPORT_C void SetTimeLeewayL(TUint aLeewaySeconds);
+	
+	IMPORT_C void SetOCSPCheckForResponderCert(const TBool aResponderCertCheck);
+	
+	IMPORT_C void SetCheckCertsWithAiaOnly(const TBool aCheckCertsWithAiaOnly);
+	
+	IMPORT_C void SetUseAIA(const TBool aUseAIA);
+	
+public:
+	
+	// Not exported
+
+	~COCSPParameters();
+	TUint CertCount() const;
+	const CX509Certificate& SubjectCert(TUint aIndex) const;
+	const CX509Certificate& IssuerCert(TUint aIndex) const;
+	TBool UseNonce() const;
+	const TDesC8& DefaultURI() const;
+	TBool UseAIA() const;
+	MOCSPTransport* Transport() const;
+	TUint AuthSchemeCount() const;
+	MOCSPAuthorisationScheme& AuthScheme(TUint aIndex) const;
+	const TTime* ValidationTime() const;
+	const TUint* MaxStatusAge() const;
+	const TUint* TimeLeeway() const;
+	TBool GenerateResponseForMissingUri() const;
+
+	TUint RetryCount() const;
+	TInt Timeout() const;
+	TBool ReponderCertCheck() const;
+	const CX509Certificate& CACert(TUint aIndex) const;
+	TBool CheckCertsWithAiaOnly() const;
+	
+private:
+	void ConstructL();
+	COCSPParameters();
+	
+#ifdef _DEBUG
+	/** Panic codes used by this functions in this class. */
+	enum TPanic
+	{
+		/** AddAllAuthorisationSchemesL() called when already added at least one. */
+		EAAASAlreadyHaveSchemes = 0x10
+	};
+	static void Panic(TPanic aPanic);
+#endif
+private:
+
+	RPointerArray<CX509Certificate>			iSubjectCerts;
+	RPointerArray<CX509Certificate>			iIssuerCerts;	
+	TBool									iUseNonce;
+	HBufC8*									iDefaultURI;
+	MOCSPTransport*							iTransport;
+	TBool									iUseAIA;
+	RPointerArray<MOCSPAuthorisationScheme> iAuthSchemes;
+	TTime*									iValidationTime;
+	TUint*									iMaxStatusAge;
+	TUint*									iTimeLeeway;
+	TBool									iGenerateResponseForMissingUri;
+	
+	TBool									iResponderCertCheck;
+	TUint									iRetryCount;
+	TInt									iTimeout;
+	TBool									iCheckCertsWithAiaOnly;
+	};
+
+
+/**
+ * Checks the revocation state of one or more certificates.
+ *
+ * The current implementation makes one OCSP request for every certificate
+ * checked - future impelementations may check multiple certificates with a
+ * single request.
+ */
+
+class COCSPClient : public CActive
+	{
+public:
+
+	/**
+	 * Create a new OCSP client.
+	 * 
+	 * @param aParams An object describing the parameters for the check.  This
+	 * method takes ownership if it does not leave.
+	 */
+
+	IMPORT_C static COCSPClient* NewL(const COCSPParameters* aParams);
+	
+	~COCSPClient();
+
+	/**
+	 * Start the checker - this is an asynchronous method.
+	 */
+
+	IMPORT_C void Check(TRequestStatus& aStatus);
+
+	/**
+	 * Cancel checking.
+	 */
+
+	IMPORT_C void CancelCheck(void);
+
+	/**
+	 * Get the summary result of the check.  If any certificates were revoked,
+	 * this returns ERevoked.  If no certificates were revoked, but if there
+	 * were any errors communicating with ocsp servers or any certs had unknown
+	 * status, this returns EUnknown.  Otherwise it returns EGood. 
+	 * Panics if the check has not been run, or is not complete.
+	 */
+
+	IMPORT_C OCSP::TResult SummaryResult(void) const;
+
+	/**
+	 * Get the number of transactions made.
+	 * Panics if the check has not been run, or is not complete.
+	 */
+
+	IMPORT_C TInt TransactionCount(void) const;
+
+	/** 
+	 * Get the request object for a specified transaction.
+	 * Panics if the check has not been run, is not complete, or the index is invalid.
+	 */
+
+	IMPORT_C const COCSPRequest& Request(TInt aIndex) const;
+
+	/**
+	 * Get the outcome for an individual transaction.
+	 */
+
+	IMPORT_C const TOCSPOutcome& Outcome(TInt aIndex) const;
+
+	/** 
+	 * Get the response object for a specified transaction.  If there was an
+	 * error sending the request, this may return NULL for the corresponding
+	 * response.
+	 * Panics if the check has not been run, is not complete, or the index is invalid.
+	 */
+
+	IMPORT_C const COCSPResponse* Response(TInt aIndex) const;
+	
+	IMPORT_C TBool CertsAvailableForOCSPCheck();
+	
+protected:
+	virtual void RunL();
+	virtual TInt RunError(TInt aErr);
+	virtual void DoCancel();
+	
+private:
+	
+	enum TState
+		{
+		EInitial,
+		ESendingRequest,		// Request is being sent to server
+		EValidatingResponse,	// Request is being validated
+		EHaveResult,			// Validation complete
+		EError,					// We got an error
+		};
+		
+	COCSPClient();
+	void ConstructL(const COCSPParameters* aParams);
+	void Destroy();
+	void DoCheck();
+	void SendRequest();
+	void DoSendRequestL();
+	void ValidateResponseL();
+	void HandleResponseReceivedL();
+	void HandleResponseValidatedL();
+	void HandleTransactionErrorL(OCSP::TStatus aStatus);
+	
+	TState							iState;	
+	TRequestStatus*					iClientStatus;
+	const COCSPParameters*			iParams;
+	const TDesC8*					iURI;
+	MOCSPTransport*					iTransport;
+	COCSPTransaction*				iTransaction;
+	RPointerArray<COCSPRequest>		iRequests;
+	RPointerArray<COCSPResponse>	iResponses;
+	COCSPValidator*					iValidator;
+	RArray<TOCSPOutcome>			iOutcomes;
+	OCSP::TResult					iSummaryResult;
+	
+	};
+
+
+#endif // OCSPREQUESTANDRESPONSE_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/ocsptests.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,172 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef __OCSPTESTS_IBY__
+#define __OCSPTESTS_IBY__
+
+define ZDRIVE \epoc32\winscw\c
+
+//OCSP tests
+file = ABI_DIR\BUILD_DIR\tocsp.exe 	System\Programs\tocsp.exe
+
+// DEF139848 Fix - Different ROMs need the inclusion or exclusion of tcertcommon.dll. So, this is being controlled by
+// a MACRO.
+#ifndef TCERTCOMMON_DLL_INCLUDED
+file = ABI_DIR\BUILD_DIR\tcertcommon.dll 	System\Programs\tcertcommon.dll
+#endif
+
+ECOM_PLUGIN(tocsphttpfilter.dll, tocsphttpfilter.rsc)
+
+data = ZDRIVE\system\tocsp\scripts\Valicert.txt			System\TOCSP\scripts\Valicert.txt attrib=r
+data = ZDRIVE\system\tocsp\scripts\CertCo.txt			System\TOCSP\scripts\CertCo.txt attrib=r
+
+
+//OCSP tests TMS support
+
+data = ZDRIVE\system\TOCSP\scripts\openssl.script 	        System\TOCSP\scripts\openssl.script attrib=r
+data = ZDRIVE\system\tocsp\scripts\XCert-local.script		System\TOCSP\scripts\XCert-local.script attrib=r
+data = ZDRIVE\system\tocsp\scripts\XCert-oom.script		System\TOCSP\scripts\XCert-oom.script attrib=r
+data = ZDRIVE\system\tocsp\scripts\OpenSSL-local.script	System\TOCSP\scripts\OpenSSL-local.script attrib=r
+
+
+data = ZDRIVE\system\tocsp\scripts\Error.script			System\TOCSP\scripts\Error.script attrib=r
+data = ZDRIVE\system\tocsp\scripts\defaultpolicy.script	System\TOCSP\scripts\defaultpolicy.script attrib=r
+data = ZDRIVE\system\tocsp\scripts\httpinterface.script	system\tocsp\scripts\httpinterface.script attrib=r
+
+data = ZDRIVE\system\TOCSP\scripts\openssl.ini 	        System\TOCSP\scripts\openssl.ini attrib=r
+data = ZDRIVE\system\tocsp\scripts\XCert-local.ini		System\TOCSP\scripts\XCert-local.ini attrib=r
+data = ZDRIVE\system\tocsp\scripts\XCert-oom.ini		System\TOCSP\scripts\XCert-oom.ini attrib=r
+data = ZDRIVE\system\tocsp\scripts\OpenSSL-local.ini	System\TOCSP\scripts\OpenSSL-local.ini attrib=r
+
+
+data = ZDRIVE\system\tocsp\scripts\Error.ini			System\TOCSP\scripts\Error.ini attrib=r
+data = ZDRIVE\system\tocsp\scripts\defaultpolicy.ini	System\TOCSP\scripts\defaultpolicy.ini attrib=r
+data = ZDRIVE\system\tocsp\scripts\httpinterface.ini	system\tocsp\scripts\httpinterface.ini attrib=r
+
+//
+data = ZDRIVE\system\tocsp\responses\response.n1	System\TOCSP\responses\response.n1 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.n2	System\TOCSP\responses\response.n2 attrib=r
+
+data = ZDRIVE\system\tocsp\responses\response.000	System\TOCSP\responses\response.000 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.001	System\TOCSP\responses\response.001 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.002	System\TOCSP\responses\response.002 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.003	System\TOCSP\responses\response.003 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.004	System\TOCSP\responses\response.004 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.005	System\TOCSP\responses\response.005 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.006	System\TOCSP\responses\response.006 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.007	System\TOCSP\responses\response.007 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.008	System\TOCSP\responses\response.008 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.009	System\TOCSP\responses\response.009 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.010	System\TOCSP\responses\response.010 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.011	System\TOCSP\responses\response.011 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.012	System\TOCSP\responses\response.012 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.013	System\TOCSP\responses\response.013 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.014	System\TOCSP\responses\response.014 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.015	System\TOCSP\responses\response.015 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.016	System\TOCSP\responses\response.016 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.018	System\TOCSP\responses\response.018 attrib=r
+data = ZDRIVE\system\tocsp\responses\vs_explicit_version.dat	System\TOCSP\responses\vs_explicit_version.dat attrib=r
+data = ZDRIVE\system\tocsp\responses\response.019	System\TOCSP\responses\response.019 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.020	System\TOCSP\responses\response.020 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.021	System\TOCSP\responses\response.021 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.022	System\TOCSP\responses\response.022 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.023	System\TOCSP\responses\response.023 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.024	System\TOCSP\responses\response.024 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.025	System\TOCSP\responses\response.025 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.026	System\TOCSP\responses\response.026 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.027	System\TOCSP\responses\response.027 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.028	System\TOCSP\responses\response.028 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.029	System\TOCSP\responses\response.029 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.030	System\TOCSP\responses\response.030 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.031	System\TOCSP\responses\response.031 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.032	System\TOCSP\responses\response.032 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.033	System\TOCSP\responses\response.033 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.034	System\TOCSP\responses\response.034 attrib=r
+data = ZDRIVE\system\tocsp\responses\response.035	System\TOCSP\responses\response.035 attrib=r
+
+data = ZDRIVE\system\tocsp\responses\XCert_00_Good_RSA_XCert.rsp              System\TOCSP\responses\XCert_00_Good_RSA_XCert.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_01_Revoked_RSA_XCert.rsp           System\TOCSP\responses\XCert_01_Revoked_RSA_XCert.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_02_Suspended_RSA_XCert.rsp         System\TOCSP\responses\XCert_02_Suspended_RSA_XCert.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_03_Unknown_RSA_XCert.rsp           System\TOCSP\responses\XCert_03_Unknown_RSA_XCert.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_04_Good_DSA_XCert.rsp              System\TOCSP\responses\XCert_04_Good_DSA_XCert.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_05_Revoked_DSA_XCert.rsp           System\TOCSP\responses\XCert_05_Revoked_DSA_XCert.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_06_Suspended_DSA_XCert.rsp         System\TOCSP\responses\XCert_06_Suspended_DSA_XCert.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_07_Unknown_DSA_XCert.rsp           System\TOCSP\responses\XCert_07_Unknown_DSA_XCert.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_08_All_RSA_XCert.rsp               System\TOCSP\responses\XCert_08_All_RSA_XCert.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_09_All_DSA_XCert.rsp               System\TOCSP\responses\XCert_09_All_DSA_XCert.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_10_Expired_Subject_and_Issuer.rsp  System\TOCSP\responses\XCert_10_Expired_Subject_and_Issuer.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_11_Expired_Signing.rsp             System\TOCSP\responses\XCert_11_Expired_Signing.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_12_Expired_Subject.rsp             System\TOCSP\responses\XCert_12_Expired_Subject.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_14_Expired_subject_valid_time.rsp  System\TOCSP\responses\XCert_14_Expired_subject_valid_time.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_15_Expired_unspecified.rsp         System\TOCSP\responses\XCert_15_Expired_unspecified.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_16_ThisUpdateTooEarly.rsp          System\TOCSP\responses\XCert_16_ThisUpdateTooEarly.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_20_Nonce_Off.rsp                   System\TOCSP\responses\XCert_20_Nonce_Off.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_22_BadSig_DSA_XCert.rsp            System\TOCSP\responses\XCert_22_BadSig_DSA_XCert.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_23_ResultCombination1.rsp          System\TOCSP\responses\XCert_23_ResultCombination1.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_24_ResultCombination2.rsp          System\TOCSP\responses\XCert_24_ResultCombination2.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_25_ResultCombination3.rsp          System\TOCSP\responses\XCert_25_ResultCombination3.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\XCert_26_ResultCombination4.rsp          System\TOCSP\responses\XCert_26_ResultCombination4.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\Error_00_Single_R5.rsp					  System\TOCSP\responses\Error_00_Single_R5.rsp attrib=r
+data = ZDRIVE\system\tocsp\responses\Error_01_Double_R5.rsp					  System\TOCSP\responses\Error_01_Double_R5.rsp attrib=r
+
+data = ZDRIVE\system\tocsp\responses\ca_1ext_usage_not_ocspsigning_resp.dat		System\TOCSP\responses\ca_1ext_usage_not_ocspsigning_resp.dat
+data = ZDRIVE\system\tocsp\responses\ca_2ext_usage_not_ocspsigning_resp.dat		System\TOCSP\responses\ca_2ext_usage_not_ocspsigning_resp.dat
+data = ZDRIVE\system\tocsp\responses\ca_2ext_usage_ocspsigning_bad_sign_resp.dat	System\TOCSP\responses\ca_2ext_usage_ocspsigning_bad_sign_resp.dat
+data = ZDRIVE\system\tocsp\responses\ca_2ext_usage_ocspsigning_bad_name_resp.dat	System\TOCSP\responses\ca_2ext_usage_ocspsigning_bad_name_resp.dat
+data = ZDRIVE\system\tocsp\responses\ca_2ext_usage_ocspsigning_resp.dat			System\TOCSP\responses\ca_2ext_usage_ocspsigning_resp.dat
+data = ZDRIVE\system\tocsp\responses\ca_no_ext_usage_resp.dat					System\TOCSP\responses\ca_no_ext_usage_resp.dat
+data = ZDRIVE\system\tocsp\responses\multi_cert_resp.dat						System\TOCSP\responses\multi_cert_resp.dat
+data = ZDRIVE\system\tocsp\responses\no_cert_resp.dat							System\TOCSP\responses\no_cert_resp.dat
+data = ZDRIVE\system\tocsp\responses\multiple_response.dat						System\TOCSP\responses\multiple_response.dat
+data = ZDRIVE\system\tocsp\responses\wrong_ca_cert_resp.dat						System\TOCSP\responses\wrong_ca_cert_resp.dat
+data = ZDRIVE\system\tocsp\responses\ca_delg_wrong_key.dat						System\TOCSP\responses\ca_delg_wrong_key.dat
+
+data = ZDRIVE\system\tocsp\responses\ca_direct_good_wrong_key.dat		System\TOCSP\responses\ca_direct_good_wrong_key.dat
+data = ZDRIVE\system\tocsp\responses\ca_direct_multi_cert_inc_right.dat	System\TOCSP\responses\ca_direct_multi_cert_inc_right.dat
+data = ZDRIVE\system\tocsp\responses\ca_direct_multi_cert_no_right.dat	System\TOCSP\responses\ca_direct_multi_cert_no_right.dat
+data = ZDRIVE\system\tocsp\responses\ca_direct_revoked.dat				System\TOCSP\responses\ca_direct_revoked.dat
+data = ZDRIVE\system\tocsp\responses\ca_direct_wrong_cert.dat			System\TOCSP\responses\ca_direct_wrong_cert.dat
+data = ZDRIVE\system\tocsp\responses\ca_direct_wrong_resp_name.dat		System\TOCSP\responses\ca_direct_wrong_resp_name.dat
+data = ZDRIVE\system\tocsp\responses\no_certresp_signedby_delegate.dat	System\TOCSP\responses\no_certresp_signedby_delegate.dat
+
+data = ZDRIVE\system\tocsp\responses\OpenSSL\response01.dat					System\TOCSP\responses\OpenSSL\response01.dat attrib=r
+data = ZDRIVE\system\tocsp\responses\OpenSSL\response02.dat					System\TOCSP\responses\OpenSSL\response02.dat attrib=r
+data = ZDRIVE\system\tocsp\responses\OpenSSL\response03.dat					System\TOCSP\responses\OpenSSL\response03.dat attrib=r
+data = ZDRIVE\system\tocsp\responses\OpenSSL\response04.dat					System\TOCSP\responses\OpenSSL\response04.dat attrib=r
+data = ZDRIVE\system\tocsp\responses\OpenSSL\response05.dat					System\TOCSP\responses\OpenSSL\response05.dat attrib=r
+data = ZDRIVE\system\tocsp\responses\OpenSSL\response06.dat					System\TOCSP\responses\OpenSSL\response06.dat attrib=r
+data = ZDRIVE\system\tocsp\responses\OpenSSL\response07.dat					System\TOCSP\responses\OpenSSL\response07.dat attrib=r
+data = ZDRIVE\system\tocsp\responses\OpenSSL\response08.dat					System\TOCSP\responses\OpenSSL\response08.dat attrib=r
+data = ZDRIVE\system\tocsp\responses\OpenSSL\response09.dat					System\TOCSP\responses\OpenSSL\response09.dat attrib=r
+data = ZDRIVE\system\tocsp\responses\OpenSSL\response10.dat					System\TOCSP\responses\OpenSSL\response10.dat attrib=r
+data = ZDRIVE\system\tocsp\responses\OpenSSL\response11.dat					System\TOCSP\responses\OpenSSL\response11.dat attrib=r
+data = ZDRIVE\system\tocsp\responses\OpenSSL\response12.dat					System\TOCSP\responses\OpenSSL\response12.dat attrib=r
+
+data = ZDRIVE\system\tocsp\requests\OpenSSL\request01.dat					System\TOCSP\requests\OpenSSL\request01.dat attrib=r
+data = ZDRIVE\system\tocsp\requests\OpenSSL\request02.dat					System\TOCSP\requests\OpenSSL\request02.dat attrib=r
+data = ZDRIVE\system\tocsp\requests\OpenSSL\request03.dat					System\TOCSP\requests\OpenSSL\request03.dat attrib=r
+data = ZDRIVE\system\tocsp\requests\OpenSSL\request04.dat					System\TOCSP\requests\OpenSSL\request04.dat attrib=r
+data = ZDRIVE\system\tocsp\requests\OpenSSL\request05.dat					System\TOCSP\requests\OpenSSL\request05.dat attrib=r
+data = ZDRIVE\system\tocsp\requests\OpenSSL\request06.dat					System\TOCSP\requests\OpenSSL\request06.dat attrib=r
+data = ZDRIVE\system\tocsp\requests\OpenSSL\request07.dat					System\TOCSP\requests\OpenSSL\request07.dat attrib=r
+data = ZDRIVE\system\tocsp\requests\OpenSSL\request08.dat					System\TOCSP\requests\OpenSSL\request08.dat attrib=r
+data = ZDRIVE\system\tocsp\requests\OpenSSL\request09.dat					System\TOCSP\requests\OpenSSL\request09.dat attrib=r
+data = ZDRIVE\system\tocsp\requests\OpenSSL\request10.dat					System\TOCSP\requests\OpenSSL\request10.dat attrib=r
+data = ZDRIVE\system\tocsp\requests\OpenSSL\request11.dat					System\TOCSP\requests\OpenSSL\request11.dat attrib=r
+data = ZDRIVE\system\tocsp\requests\OpenSSL\request12.dat					System\TOCSP\requests\OpenSSL\request12.dat attrib=r
+data = ZDRIVE\system\tocsp\responses\openssl\no_aia_no_ocspext.dat			System\TOCSP\responses\openssl\no_aia_no_ocspext.dat
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/ocsptransport_v2.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,189 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// ocsptransport.h
+// Declare implementations of OCSP transport interface.  Links the OCSP module
+// to the HTTP module.
+// 
+//
+
+/**
+ @file
+ @internalTechnology
+*/
+
+#ifndef __OCSP_TRANSPORT_HTTP_H__
+#define __OCSP_TRANSPORT_HTTP_H__
+
+#include <e32std.h>
+#include <ocsp.h>
+#include <http.h>
+#include <uri8.h>
+#include <callbacktimer.h>
+#include <http/rexplicithttpsession.h>
+#include <ocsprequestandresponse.h>
+
+// Forward declaration
+class CTransportTimer;
+
+/**
+ * OCSP transport object that uses the default transport appropriate to the
+ * request URI.  Currently, only HTTP POST is supported.
+ */
+class COCSPTransportDefault : public CBase, public MOCSPTransport
+	{
+public:
+	/**
+	 * Create a new instance of the transport.
+	 * @leave OCSP::KErrInvalidURI If the URI is not supported.
+	 */
+	IMPORT_C static COCSPTransportDefault* NewL(TUint32& aIap);
+	
+	virtual ~COCSPTransportDefault();
+
+private:
+	COCSPTransportDefault(TUint32& aIap);
+
+	// Methods from MOCSPTransport
+	virtual void SendRequest(const TDesC8& aURI, 
+							const TDesC8& aRequest,
+							const TInt aTimeout,
+							TRequestStatus& iStatus);
+	virtual void CancelRequest();
+	virtual TPtrC8 GetResponse() const;
+
+private:
+	// Use string pool for case-independent comparisons....
+	enum TTransportScheme
+		{
+		ETransportSchemeNotSupported,
+		ETransportSchemeHTTP
+		};
+
+	static TTransportScheme IdentifySchemeL(const TDesC8& aURI);
+
+	void CreateTransportL(const TDesC8& aURI);
+
+private:
+	MOCSPTransport* iTransport;
+	TTransportScheme iScheme;
+	
+	TUint32& iIap;
+	};
+
+
+enum THTTPTransportState
+	{
+	ETransportConnectingState,
+	ETransportSendRequestState
+	};
+
+
+/**
+ * OCSP transport object that send requests via HTTP GET or POST depending on size of the request
+ */
+class COCSPTransportHttp :	public CActive, 
+							public MOCSPTransport,
+							public MHTTPDataSupplier,
+							public MHTTPTransactionCallback,
+							public MTimerObserver
+	{
+public:
+	/**
+	 * Create a new instance of the HTTP POST transport.
+	 */
+	IMPORT_C static COCSPTransportHttp* NewL(const TDesC8& aUri, TUint32& aIap);
+	
+	~COCSPTransportHttp();
+
+private:
+	COCSPTransportHttp(TUint32& aIap);
+	
+	void ConstructL(const TDesC8& aUri);
+
+	// Methods from MOCSPTransport
+	void SendRequest(const TDesC8& aURI, 
+					const TDesC8& aRequest,
+					const TInt aTimeout,
+					TRequestStatus& iStatus);
+	void CancelRequest();
+	TPtrC8 GetResponse() const;
+
+	// From CActive
+	void RunL();
+	void DoCancel();
+	TInt RunError(TInt aError);
+
+	// Methods from MHTTPDataSupplier
+	TBool GetNextDataPart(TPtrC8& aDataPart);
+	void ReleaseData();
+	TInt OverallDataSize();
+	TInt Reset();
+
+	// Methods from MHTTPTransactionCallback
+	void MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent);
+	TInt MHFRunError(TInt aError, RHTTPTransaction aTransaction, const THTTPEvent& aEvent);
+
+	// Methods from MTransportTimer
+	void TimerRun(TInt aError);
+
+private:
+	// Internal methods
+	void InstallHttpFilterL();
+	void DoSendRequestL(const TDesC8& aURI, 
+						const TDesC8& aRequest);
+	void AddHttpHeadersL();
+	void ProcessHeadersL();
+	void ProcessDataL();
+	void CheckDataCompleteL() const;
+	void SetIAPL();
+	void Complete(TInt aError);
+	void AbortTransaction(TInt aError);
+
+private:
+	TRequestStatus* iCallBack;
+
+	// Data to send, from OCSP module
+	TPtrC8 iOCSPRequest;
+
+	TUriParser8 iURI;
+
+	RExplicitHTTPSession iHTTPSession;
+	RHTTPTransaction iHTTPTransaction;
+
+	// request data
+	HBufC8* iUri;
+	HBufC8* iRequest;
+
+	// The data in the response
+	HBufC8* iResponseData;
+	TInt iResponseLength;
+	
+	TUint32& iIap;
+	THTTPTransportState iState;
+
+	// ETrue if HTTP GET method support should be enabled (default is EFalse)
+	TBool iUseHTTPGETMethod;
+
+	// Timer class
+	CCallbackTimer* iTimer;
+
+	// Flag to indicate whether we were able to contact the responder
+	TBool iServerFound;
+
+	// Reponse timeout out value in Milliseconds
+	TInt iTimeout;
+	};
+
+
+#endif // __OCSP_TRANSPORT_HTTP_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/oids.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,42 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Define OIDs we use in OCSP - comment out the ones we don't use
+// 
+//
+
+/**
+ @file 
+ @internalComponent 
+*/
+
+#ifndef __OCSP_OIDS_H__
+#define __OCSP_OIDS_H__
+
+// OCSP OIDs
+
+_LIT(KOCSPOidBasic,				"1.3.6.1.5.5.7.48.1.1");
+_LIT(KOCSPOidNonce,				"1.3.6.1.5.5.7.48.1.2");
+//_LIT(KOCSPOidCrl,				"1.3.6.1.5.5.7.48.1.3");
+_LIT(KOCSPOidResponse,			"1.3.6.1.5.5.7.48.1.4");
+_LIT(KOCSPOidNoCheck,			"1.3.6.1.5.5.7.48.1.5");
+_LIT(KOCSPOidArchiveCutoff,		"1.3.6.1.5.5.7.48.1.6");
+_LIT(KOCSPOidServiceLocator,	"1.3.6.1.5.5.7.48.1.7");
+_LIT(KOCSPOidOCSPSigning,		"1.3.6.1.5.5.7.3.9");
+
+const TUint KOCSPMaxOidEncodingLength = 20;
+
+#endif // __OCSP_OIDS_H__
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/panic.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// The panic method and OCSP panic code declarations
+// 
+//
+
+/**
+ @file 
+ @internalComponent 
+*/
+
+#ifndef __OCSP_PANIC_H__
+#define __OCSP_PANIC_H__
+
+#include <e32def.h>
+
+enum TOCSPPanics
+	{
+	KErrNoCertificates,
+	KErrNoAuthorisationSchemes
+	};
+
+
+GLDEF_C void Panic(TInt aPanic);
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/requestencoder.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,71 @@
+// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Header specifying class that encodes OCSP requests
+// 
+//
+
+/**
+ @file 
+ @internalComponent 
+*/
+
+#ifndef __OCSP_REQUESTENCODER_H__
+#define __OCSP_REQUESTENCODER_H__
+
+#include <ocsp.h>
+#include "ocsprequestandresponse.h"
+/**
+ * Constructs the ASN1 DER respresentation of an OCSP request.
+ */
+
+NONSHARABLE_CLASS(COCSPRequestEncoder) : public CBase
+	{
+public:
+
+	~COCSPRequestEncoder();
+
+	/**
+	 * Create a new request encoder object.
+	 */
+	
+	static COCSPRequestEncoder* NewL(const COCSPRequest& aRequest);
+
+	/**
+	 * Get the encoding of the request.
+	 * The data is owned by this object.
+	 */
+
+	const TDesC8& Encoding() const;
+
+private:
+
+	COCSPRequestEncoder();
+	void ConstructL(const COCSPRequest& aRequest);
+	
+	CASN1EncBase* MakeOCSPRequestEncLC(const COCSPRequest& aRequest);
+ 	CASN1EncBase* MakeTBSRequestEncLC(const COCSPRequest& aRequest);
+	CASN1EncBase* MakeRequestListEncLC(const COCSPRequest& aRequest);
+	CASN1EncBase* MakeCertRequestEncLC(const COCSPCertID& aCertId);
+	CASN1EncBase* MakeRequestExtensionsEncLC(const COCSPRequest& aRequest);
+	CASN1EncBase* MakeResponseTypeExtnEncLC();
+	CASN1EncBase* MakeNonceExtnEncLC(const COCSPRequest& aRequest);
+
+	static void AddAndPopChildL(CASN1EncContainer& aParent, CASN1EncBase* aChild);
+
+private:
+
+	HBufC8* iEncoding;
+	};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/responsedecoder.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,74 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// ocsp.h
+// Header specifying client interface to the OCSP module.
+// 
+//
+
+/**
+ @file 
+ @internalComponent 
+*/
+
+#ifndef __OCSP_RESPONSEDECODER_H__
+#define __OCSP_RESPONSEDECODER_H__
+
+#include <e32base.h>
+
+class COCSPResponse;
+class TASN1DecGeneric;
+
+/**
+ * Handles decoding an OCSP response and creating a COCSPResponse object.
+ */
+
+NONSHARABLE_CLASS(COCSPResponseDecoder) : public CBase
+	{
+public:
+
+	/**
+	 * Create a new decoder object and decoder an ocsp response.
+	 * Can leave with one of the OCSP::TStatus codes.
+	 */
+	
+	static COCSPResponseDecoder* NewL(const TDesC8& aEncoding);
+
+	~COCSPResponseDecoder();
+
+	COCSPResponse* TakeResponse(); // Will return null if response was invalid
+
+private:
+
+	COCSPResponseDecoder();
+	void ConstructL(const TDesC8& aEncoding);
+
+	// Decoding methods
+	void DecodeOCSPResponseL(const TDesC8& aEncoding);
+	void DecodeResponseBytesL(const TDesC8& aEncoding);
+	void DecodeBasicOCSPResponseL(const TDesC8& aEncoding);
+	void DecodeResponseDataL(const TDesC8& aEncoding);
+	void DecodeCertificatesL(const TDesC8& aEncoding);
+	void DecodeResponseExtensionsL(const TDesC8& aEncoding);
+	void DecodeResponseExtensionL(const TDesC8& aEncoding);
+	void DecodeResponsesL(const TDesC8& aEncoding);
+	void DecodeSingleResponseL(const TDesC8& aEncoding);
+
+	CArrayPtr<TASN1DecGeneric>* DecodeSequenceLC(const TDesC8& aEncoding);
+	CArrayPtr<TASN1DecGeneric>* DecodeSequenceLC(const TDesC8& aEncoding,
+		const TInt aMinTerms, const TInt aMaxTerms);
+
+	COCSPResponse* iResponse;
+	};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/securitypolicy.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,578 @@
+// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// This class wraps up the security policy for native software installation.
+//
+
+
+
+/**
+ @file
+ @internalComponent
+*/
+
+#ifndef __SECURITYPOLICY_H__
+#define __SECURITYPOLICY_H__
+
+#include <e32base.h>
+
+// file duplicated from swi\\inc\\swi
+namespace Swi
+{
+
+_LIT(KSwisPolicyFile, "z:\\system\\data\\swipolicy.ini");
+
+_LIT8(KAllowUnsigned, "AllowUnsigned");
+_LIT8(KMandatePolicies, "MandatePolicies");
+_LIT8(KDRMEnabled, "DRMEnabled");
+_LIT8(KDRMIntent, "DRMIntent");
+_LIT8(KMandateCodeSigningExtension, "MandateCodeSigningExtension");
+_LIT8(KOid, "Oid");
+_LIT8(KOcspMandatory, "OcspMandatory");
+_LIT8(KOcspEnabled, "OcspEnabled");
+_LIT8(KAllowGrantUserCaps, "AllowGrantUserCapabilities");
+_LIT8(KUserCapabilities, "UserCapabilities");
+_LIT8(KAllowOrphanedOverwrite, "AllowOrphanedOverwrite");	// This flag allows orphaned files to be overwritten when set
+_LIT8(KAllowPackagePropagate, "AllowPackagePropagate");  // Allows SWI to write stub SIS files to removable media cards
+_LIT8(KApplicationShutdownTimeout, "ApplicationShutdownTimeoutSeconds");  // Timeout for shutting down Apps during install/uninstall
+_LIT8(KRunWaitTimeout, "RunWaitTimeoutSeconds");  // Timeout to allow completion of apps/exes launched with RunWait option
+_LIT8(KAllowRunOnInstallUninstall, "AllowRunOnInstallUninstall");
+_LIT8(KReplacePath, "ReplacePath");
+_LIT8(KDeletePreinstalledFilesOnUninstall, "DeletePreinstalledFilesOnUninstall");
+_LIT8(KPhoneTsyName, "PhoneTsyName");
+_LIT8(KAllowOverwriteOnRestore, "AllowOverwriteOnRestore");
+/** When true this flag allows orphaned files residing in private/xxxxxxxx/import, /resource or /sys/bin directories to be
+	overwritten or eclipsed under user permission.
+ */	
+_LIT8(KAllowProtectedOrphanOverwrite, "AllowProtectedOrphanOverwrite");
+/**
+When true this flag allows to delay the uninstallation of embedded packages 
+until all their dependent packages have been uninstalled.
+*/
+_LIT8(KRemoveOnlyWithLastDependent, "RemoveOnlyWithLastDependent");
+/**
+	If defined in the ini file, this specifies the ECOM plugin which is used
+	to filter the OCSP request HTTP headers.
+ */
+_LIT8(KOcspHttpHeaderFilter, "OcspHttpHeaderFilter");
+
+// This flag defines whether a SIS file will be considered compatible with the device if no target devices are listed in the package.
+_LIT8(KSISCompatibleIfNoTargetDevices, "SISCompatibleIfNoTargetDevices");
+_LIT8(KAlternativeCodeSigningOid, "AlternativeCodeSigningOID");
+
+_LIT8(KMaxNumOfLogEntries , "MaxNumOfLogEntries");
+
+
+NONSHARABLE_CLASS(CPathReplaceEntry) : public CBase
+/**
+	Used internally by CSecurityPolicy to manage replacement
+	key, value pairs.
+
+	@internalComponent
+ */
+	{
+public:
+	CPathReplaceEntry(HBufC* aFindPath, HBufC* aReplacePath);
+	virtual ~CPathReplaceEntry();
+	
+public:
+	/** Drive-qualified directory to match on target LHS. */
+	HBufC*const iFindPath;
+	/** Drive-qualified replacement directory. */
+	HBufC*const iReplacePath;
+	};
+
+/**
+ * This class represents some settings that control the behaviour
+ * when installing a SIS file. The settings are stored in a resource
+ * files and are retrieved at construction time.
+ *
+ * This class is implemented as a Singleton class. So only one instance 
+ * of this class will be created per thread (Per Thread because TLS is used to
+ * store the instance of this class)
+ */
+class CSecurityPolicy : public CBase
+	{
+public:
+	~CSecurityPolicy();	
+	
+	/**
+	 * This function checks if the installer should allow unisgned SIS files
+	 * to be installed.
+	 * @return ETrue Unsigned SIS file may be installed.
+	 * @return EFalse Unsigned SIS files must not be installed.
+	 */
+	IMPORT_C TBool AllowUnsigned() const;
+	
+	/**
+	 * This function checks if the end-entity certificates corresponding to
+	 * the private keys used to sign the SIS file must contain the 
+	 * codesigning extension.
+	 * @return ETrue The certificates must contain the codesigning extension. 
+	 * If they don't the SIS file will not be installed.
+	 * @return EFalse It doesn't matter whether the certificates contain
+	 * this extension or not.
+	 */
+	IMPORT_C TBool MandateCodesigningExtension() const;
+	
+	/**
+	 * This function checks if all the certificates (except the root) in the
+	 * chains corresponding to the private keys used to sign the SIS file must
+	 * have a Policy extension containing one of the OID defined in the resource 
+	 * file. 
+     * @return ETrue The certificates must contain one of the OID defined in
+     * the resource file. If they don't the SIS file will not be installed.
+     * @return EFalse The presence or absence of the OID don't affect
+     * the installation. The installer may still display this 
+     * information to the user.
+	 */
+	IMPORT_C TBool MandateCertificatePolicies() const;
+
+	/**
+	 * ROM time specified extension OIDs which are compulsory for SWI
+	 * certificates.
+	 * 
+	 * @return A list of OIDs which are mandatory for SWI certificates
+	 */
+	IMPORT_C const RPointerArray<HBufC> Oids() const;
+
+	/**
+	 * Returns a boolean flag to indicate whether DRM is enabled.
+	 *
+	 * @return ETrue if DRM is enabled, EFalse otherwise 
+	 */
+	IMPORT_C TBool DrmEnabled() const;
+	
+	/**
+	 * Returns an integer indicating which DRM intent should be used
+	 * for evaluation and execution of rights.
+	 */
+	IMPORT_C TInt DrmIntent() const;
+
+	/**
+	 * This function returns whether OCSP is enabled during Software Install.
+	 *
+	 * @return ETrue if OSCP is enabled, EFalse otherwise.
+	 */
+	IMPORT_C TBool OcspEnabled() const;
+	
+	/**
+	 * This function returns whether OCSP is mandatory during Software Install.
+	 *
+	 * @return ETrue if OSCP is enabled, EFalse otherwise.
+	 */
+	IMPORT_C TBool OcspMandatory() const;
+	
+	/**
+	 * This function returns whether Software Install should allow the
+	 * granting of user capabilities, during install.
+	 *
+	 * @return ETrue if user capabilities are allowed to be granted,
+	 *			  EFalse otherwise.
+	 */
+	IMPORT_C TBool AllowGrantUserCaps() const;
+
+	/**
+	 * This function returns a list of capabilities which Software Install
+	 * considers to be user capabilities. This list is read from the 
+	 * policy ini file.
+	 *
+	 * @return The list of capabilities Software Install considers to be 
+	 *			  user capabilities.
+	 */
+	 IMPORT_C TCapabilitySet UserCapabilities() const;
+
+	/**
+	 *	This function returns whether Software Install should ask the user
+	 * if orphaned files should be overwritten during install.
+	 *
+	 * @return ETrue if the user should be asked about orphaned files,
+	 *			  EFalse otherwise.
+	 */
+	IMPORT_C TBool AllowOrphanedOverwrite() const;
+	
+	/** This function returns whether Software Install should create
+	SIS stub files on removable media when a SIS file is installed to the 
+	removable media.
+	@return ETrue if stubs are to be created, EFalse otherwise
+	*/
+	IMPORT_C TBool AllowPackagePropagate() const;
+
+	/**
+	 * This function returns an integer indicating the maximum allowed
+	 * shutdown time for applications which are shut down during an upgrade
+	 * or uninstall.
+	 * @return Timeout in microseconds for apps shut down during upgrade
+	 * 			or uninstall.
+	 */
+	IMPORT_C TInt ApplicationShutdownTimeout() const;
+	
+	/**
+	 * This function returns an integer indicating the maximum time to wait
+	 * for completion of execution of files launched with the RunWait file
+	 * option during an install/uninstall.
+	 * @return Timeout in microseconds for apps shut down during upgrade
+	 * 			or uninstall.
+	 */
+	IMPORT_C TInt RunWaitTimeout() const;
+	
+	/**
+	 * This function returns a boolean indicating whether a SIS file with
+	 * no target devices listed should be considered compatible with
+	 * the device.
+	 * @return ETrue if SIS files with no target devices listed are to
+	 *			be considered compatible, EFalse otherwise.
+	 */
+	IMPORT_C TBool SISCompatibleIfNoTargetDevices() const;
+
+	/**
+	 * This function returns a boolean indicating whether the applications contained in
+	 * the SIS file are allowed to run when being installed or uninstalled.
+	 *
+	 * @return ETrue if SIS files with no target devices listed are to
+	 *			be considered compatible, EFalse otherwise.
+	 */
+	IMPORT_C TBool AllowRunOnInstallUninstall() const;
+
+	IMPORT_C TUint32 OcspHttpHeaderFilter() const;
+
+	IMPORT_C HBufC* ResolveTargetFileNameLC(
+		const TDesC& aMmpName, TText aDrive) const;
+	IMPORT_C HBufC* ResolveTargetFileNameL(
+		const TDesC& aMmpName, TText aDrive) const;
+
+	IMPORT_C TBool DeletePreinstalledFilesOnUninstall() const;
+
+	/** When true this flag allows orphaned files residing in
+	 * /private/xxxxxxxx/import, /resource or /sys/bin directories to be
+	 * overwritten or eclipsed (under user permission).
+	 * A file is considered orphaned if it does not belong to any installed
+	 * package in the registry. This value defaults to true;
+	 *
+	 * @return ETrue if the Software Install should overwrite or eclipse
+	 * orphaned files in protected directories, EFalse otherwise.
+	 */
+	IMPORT_C TBool AllowProtectedOrphanOverwrite() const;
+
+ 	/**
+	This function is used to retrieve a list of alternate code signing 
+ 	OIDs. These values are in addition to the OID existing in 
+ 	securitydefs.h. Allows additional user defined OID to be 
+ 	specified for code signing.
+ 	@return A list of the alternative code oid references
+ 	*/	
+	IMPORT_C const RPointerArray<HBufC> AlternativeCodeSigningOid() const;
+	
+	/**
+	This function is used to retrieve the value of iRemoveOnlyWithLastDependent member.
+	When true an embedded package can be uninstalled only if the last dependent has been uninstalled  
+	*/
+	IMPORT_C TBool RemoveOnlyWithLastDependent() const;
+	
+	IMPORT_C static void ReleaseResource();
+	
+	/**
+  	 * This function is used to access the instance of this class. If
+  	 * the instance is not created then this will create the instance
+  	 * and return. TLS is used to store pointer of the instance.
+  	 *
+  	 * ReleaseResource function should be by the owner of this instance
+  	 * after the use of this class.
+  	 */
+	IMPORT_C static CSecurityPolicy* GetSecurityPolicyL();
+	
+	/**
+	 * This function gets the maximum number of entries  allowed in the log file 
+	 * SisRegistryServer produce logfile , during install,Uninstall and Upgrade.
+	 *
+	 * @return maximum number of entries in logfile, 0 if no entries or 
+	 * 		   logging is disabled,
+	 *		   
+	 */
+	
+	IMPORT_C TInt MaxNumOfLogEntries() const;
+
+	IMPORT_C const TDesC& PhoneTsyName() const;
+	
+	/**
+	Indicates whether the restore process should overwrite an application that is already installed
+	if the same item appears in the backup e.g. if the system drive has not been reformatted.
+	@return ETrue, if the restore process should overwrite applications; otherwise, EFalse is returned.
+	*/
+	IMPORT_C TBool AllowOverwriteOnRestore() const;
+private:	
+	CSecurityPolicy();
+	
+	/**
+	 * The second-phase constructor. It reads the settings from
+	 * the resource file.
+	 */
+	void ConstructL();
+
+	/**
+	Retrieves the next line of text from a buffer. Blank lines are skipped.
+
+	@param aBuffer The buffer to parse.
+	@param aPos    The position to start reading from. This IN/OUT parameter
+	               should be initialised to zero on the first call.
+    @param aLine   An out parameter that will be set to point to the next line
+                   of text IF found.
+    @return        Whether a line of text was successfully read.
+	*/
+	TBool ReadLineL(const TDesC8& aBuffer, TInt& aPos, TPtrC8& aLine) const; 
+
+	/**
+	 * This function adds a user capability to iUserCapabilities from
+	 * a descriptor containing the name of the capability to add.
+	 */
+	void AddUserCapability(const TDesC8& aCapabilityName);
+
+	void ReadReplacementPathsL(const TDesC8& aLine);
+	
+	/**
+	 * This function adds an alternative oid to iAlternativeCodeSigningOids from
+	 * a descriptor containing the alternative oid to add. Does not allow any duplication.
+	 */
+	void AddAlternativeCodeSigningOidL(const TDesC8& aAlternativeCodeSigningOid);
+	 
+private:
+	TBool iIsInitialized;
+
+	/**
+	 * This is set to ETrue if the installer must accept to install unsigned
+	 * SIS file. It is set to EFalse if only SIS files that are signed are
+	 * allowed to be installed.
+	 */
+	TBool iAllowUnsigned;
+	
+	/**
+	 * This is set to ETrue if the end-entity certificates corresponding 
+	 * to the private keys used to sign the SIS files must have a codesigning
+	 * extension. If this is set and the certificates don't have this extension
+	 * the SIS file will not be installed.
+	 * If this is set to EFalse then the certificates may or may not have a
+	 * a codesigning extension.
+	 */
+	TBool iMandateCodesigningExtension;
+	
+	/**
+	 * This is set to ETrue if all the certificates (except the root) in the
+	 * chains corresponding to the private keys used to sign the SIS file must
+	 * have a Policy extension containing one of the OID defined in the resource 
+	 * file. 
+	 * This is set to EFalse if the presence of OID doesn't affect the 
+	 * installation.
+	 */
+	TBool iMandateCertificatePolicies;
+	
+	/**
+	 * A List of custom OIDs which are mandatory for certificates used to
+	 * sign applications.
+	 *
+	 */
+	RPointerArray<HBufC> iCustomOids;
+	
+	/**
+	 * A boolean flag to indicate whether DRM is enabled.
+	 */
+	TBool iDrmEnabled;
+	
+	/**
+	 * The DRM intent to execute and evaluate if DRM is enabled. 
+	 */
+	TInt iDrmIntent;
+
+	/**
+	 * This is set to ETrue if OCSP is enabled, and software Install will
+	 * carry out an OCSP check during the installation. Failure of the OCSP
+	 * check does not necessarily cause installation to fail.
+	 */
+	TBool iOcspEnabled;
+	
+	/**
+	 * This is set to ETrue if ocsp check success is mandatory before install
+	 * can be carried out.	
+	 */
+	TBool iOcspMandatory;
+	
+	/**
+	 * This is set to ETrue if Software Install will allow the user to grant
+	 * user capabilities to an executable, which are not signed for.
+	 */
+	TBool iAllowGrantUserCaps;
+	
+	/**
+	 *	User capabilities, read from the policy file.
+	 */
+	TCapabilitySet iUserCapabilities;
+
+	/**
+	 * This flag if set indicates that an orphaned file can be overwritten 
+	 * during the install. The user is asked before the old file is deleted.
+	 * A file is considered orphaned if it does not belong to any installed
+	 * package in the registry.
+	 */
+	TBool iAllowOrphanedOverwrite;
+	
+	/**
+	* This flag is set if SWI is allows to write sis stub files to removable
+	* media cards. If a normal SIS file is installed on a removable device
+	* appending the stub allows it to be in-place installed when the media
+	* card is placed into another Symbian OS device 
+	*/
+	TBool iAllowPackagePropagate;
+	
+	/**
+	 * The time in microseconds to allow applications to shutdown during
+	 * uninstall or upgrade operations.  Applications which handle shut down
+	 * events are sent such an event; the upgrade/uninstall operation will
+	 * abort if they fail to shut down within this time.
+	 */
+	TInt iApplicationShutdownTimeout;
+	
+	/**
+	 * The time in microseconds to wait for the completion of execution of
+	 * files launched with the RunWait file option during an install/uninstall.
+	 */
+	TInt iRunWaitTimeout;
+
+	/**
+	 * This is set to ETrue if  SIS files with no target devices listed are to
+	 * be considered compatible.
+	 */
+	TBool iSISCompatibleIfNoTargetDevices;
+
+	/**
+ 	 * This is set to ETrue if applications are allowed to run when being installed 
+ 	 * or uninstalled.
+ 	 */	
+ 	TBool iAllowRunOnInstallUninstall;
+
+	/** Set of replacement paths. */
+	RPointerArray<CPathReplaceEntry> iReplEntries;
+	
+	
+	/**
+		ECOM plugin which implements HTTP header filter for OCSP requests.
+		Zero means no plugin was specified.
+	 */
+	TUint32 iOcspHttpHeaderFilter;
+
+	/**
+	 * This is set to ETrue if pre-installed files are to be deleted on
+	 * on uninstall, if the stub sis file used to install the package
+	 * is not read-only.
+	 */
+	TBool iDeletePreinstalledFilesOnUninstall;
+
+	/** Reference count used by RSecPolHandle. */
+	mutable TInt iRefCount;
+	
+	/**
+	 * This member indicates whether Software Install should allow 
+	 * orphaned files in private directories to be overwritten or
+	 * eclipsed during install.
+	 *
+	 */
+	TBool iAllowProtectedOrphanOverwrite;
+	
+	/**
+	A list of alternative OIDs for code signing.
+	*/
+	RPointerArray<HBufC> iAlternativeCodeSigningOids;
+	
+	/**
+	Set this option to ETrue to delay the uninstallation of embedded packages 
+	until all their dependent packages have been uninstalled.
+	*/
+	TBool iRemoveOnlyWithLastDependent;
+
+	/**
+	* The maximum number of log entries allowed.  Zero if logging disabled.
+	*/
+	TInt iMaxNumOfLogEntries; 
+	
+	/**
+	Whether the restore process should overwrite applications on writeable media if they
+	already exist.
+	*/
+	TBool iAllowOverwriteOnRestore;
+	
+	// 50 equivalent to KCommsDbSvrMaxFieldLength
+	TBuf<50> iPhoneTsyName;
+
+	friend class RSecPolHandle;
+
+#ifdef _DEBUG	
+	enum TPanic
+		{
+		ERRPFindPathNoDelim = 0x10, ERRPFindTooShort, ERRPFindNoLeadBackslash,
+			ERRPFindNoTrailBackslash, ERRPRepTooShort, ERRPRepInvalidDrive,
+			ERRPNoRepColonBackslash, ERRPRepNoTrailBackslash
+		};
+	static void Panic(TPanic aPanic);
+#endif
+	};
+
+class RSecPolHandle
+/**
+	This handle class provides access to a single
+	immutable instance of CSecurityPolicy.  This
+	instance is reference counted and stored in
+	sisregistryclient's thread-local storage.
+	
+	An instance of this object can be used in place
+	of CSecurityPolicy::NewL(), but has the advantage
+	that, providing it is opened once, the policy
+	object can be accessed without continually re-reading
+	and parsing the ini file, or maintaining a complex
+	web of references or pointers.
+ */
+	{
+public:
+	IMPORT_C RSecPolHandle();
+	IMPORT_C void OpenL();
+	IMPORT_C void OpenLC();
+	IMPORT_C void Close();
+	
+	inline const CSecurityPolicy& operator()() const;
+	
+private:
+#ifdef _DEBUG
+	enum TPanic
+		{
+		EOpnAlreadyOpen = 0x10
+		};
+	static void Panic(TPanic aPanic);
+#endif
+private:
+	/** Reference counted policy object. */
+	const CSecurityPolicy* iSecPol;
+	};
+
+
+inline const CSecurityPolicy& RSecPolHandle::operator()() const
+/**
+	Accessor function provides access to the security policy
+	object which this handle reference counts.
+
+	@return					const reference to underlying
+							CSecurityPolicy object.
+ */
+	{
+	return *iSecPol;
+	}
+
+} // namespace SWI
+
+#endif // __SECURITYPOLICY_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/tcertutils.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,241 @@
+// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// tcertuils.h
+// 
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+
+
+#ifndef __TCERTUTILS_H__
+#define __TCERTUTILS_H__
+
+#include <e32base.h>
+#include <x509cert.h>
+#include <unifiedcertstore.h>
+#include <pkixcertchain.h>
+#include "t_output.h"
+
+/**
+CCertUtils provides various functions often used in tests.
+This class has changed because the functions are asynchronous now. 
+The function are no longer static as we need an instance to serve as
+an active object.
+*/
+class CCertUtils : public CActive
+	{
+public:
+	/**
+	 * This enumeration enumerates all the states used for the
+	 * RunL function.
+	 */
+	enum TState
+		{
+		EAddCACerts,
+
+		EAddCert,
+		EAddCACertGetCAEntry,
+		EAddCACertSetApplications,
+		EAddCACertSetTrust,
+		EAddCACertFinished,
+
+		ERemoveCertsGetCACerts,
+		ERemoveCertsCACertsRetrieved,
+		ERemoveCertsRemoveCACerts,
+		ERemoveCertsGetUserCerts,
+		ERemoveCertsUserCertsRetrieved,
+		ERemoveCertsRemoveUserCerts,
+		ERemoveCertsFinished
+		};	
+	
+public:
+	IMPORT_C static CCertUtils* NewL(RFs& aFs);
+	IMPORT_C static CCertUtils* NewLC(RFs& aFs);
+	/**
+	The destructor destroys all the members of CCertUtils but only destroys
+	iStoreManager if the CCertStoreManager instance was created by this CCertUtils
+	instance. It doesn't destroy it if it was passed as an argument in the 
+	constructor.
+	*/
+	IMPORT_C virtual ~CCertUtils();
+
+
+	/**
+	Certificate handling functions
+	*/
+	IMPORT_C void AddCertL(const TDesC& aLabel, 
+							TCertificateFormat aFormat,
+							TCertificateOwnerType aCertificateOwnerType, 
+							TInt aTrustedUsage, 
+							const TDesC& aCertificatePath, 
+							const TDesC& aCertificateFileName, 
+							TRequestStatus& aStatus);
+							
+	IMPORT_C void AddCert(const TDesC& aLabel, 
+							TCertificateFormat aFormat,
+							TCertificateOwnerType aCertificateOwnerType, 
+							TInt aTrustedUsage, 
+							const TDesC& aCertificatePath, 
+							const TDesC& aCertificateFileName, 
+							CUnifiedCertStore& aUnifiedCertStore, 
+							TRequestStatus& aStatus);
+						
+	IMPORT_C void AddCACertsL(const CDesCArray& aRoots, 
+							const CDesCArray& aLabels,
+							TCertificateFormat aFormat, 
+							TInt aTrustedUsage, 
+							const TDesC& aPath, 
+							TRequestStatus& aStatus);
+							
+	IMPORT_C void AddCACertsL(const CDesCArray& aRoots, 
+							const CDesCArray& aLabels,
+							TCertificateFormat aFormat, 
+							TInt aTrustedUsage, 
+							const TDesC& aPath, 
+							CUnifiedCertStore& aUnifiedCertStore, 
+							TRequestStatus& aStatus);
+							
+	IMPORT_C void RemoveCertsL(TRequestStatus& aStatus);
+	IMPORT_C void RemoveCertsL(CUnifiedCertStore& aUnifiedCertStore, 
+							TRequestStatus& aStatus);
+
+	IMPORT_C static CCertificate* CertFromFileLC(const TDesC& aFilename, 
+							const TDesC& aPathname, 
+							RFs& aFs, 
+							TCertificateFormat aFormat);
+							
+	IMPORT_C static CCertificate* CertFromFileL(const TDesC& aFilename,
+							const TDesC& aPathname, 
+							RFs& aFs, 
+							TCertificateFormat aFormat);
+							
+	IMPORT_C static void WriteError(TValidationError aError, Output& aOut);
+	IMPORT_C static TPtrC MapError(TValidationError aError);
+	IMPORT_C static TValidationError MapError(const TDesC& aError);
+	IMPORT_C static TPtrC ParseElement(const TDesC& aBuf, const TDesC& aStart, const TDesC& aEnd, TInt& aPos, TInt& aError);
+
+	IMPORT_C HBufC* DiagnosticLC() const;
+	IMPORT_C void AddApplicationL(const TDesC& aName, TUid aUid) const;
+	IMPORT_C void RemoveApplicationL(TUid aUid) const;
+
+private:
+	/**
+	This constructor constructs a CCertUtils instance without initializing
+	iStoreManager. A store manager will be created if one is needed and
+	will be destroyed by the destructor.
+	@param aFs A file server session. The file server session must have opened.
+	*/
+	CCertUtils(RFs& aFs);
+	void ConstructL();
+
+	//Virtual from CActive
+	void RunL();
+	void DoCancel();
+    TInt RunError(TInt aError);
+
+
+private:
+	// The following functions handle the different RunL states
+	void HandleEAddCACertsL();
+
+	void HandleEAddCACertL();
+	void HandleEAddCACertGetCAEntry();
+	void HandleEAddCACertSetApplicationsL();
+	void HandleEAddCACertSetTrust();
+	void HandleEAddCACertFinishedL();
+	
+	void HandleERemoveCertsGetCACerts();
+	void HandleERemoveCertsCACertsRetrieved();
+	void HandleERemoveCertsRemoveCACerts();
+	void HandleERemoveCertsGetUserCerts();
+	void HandleERemoveCertsUserCertsRetrieved();
+	void HandleERemoveCertsRemoveUserCerts();
+	void HandleERemoveCertsFinished();
+
+
+private:
+	/**
+	File Server Sessioin
+	*/
+	RFs& iFs;
+
+	/**
+	The state used to know what RunL should do
+	*/
+	TState iState;
+	
+	/**
+	The store managers will be used for certificate store operations,
+	*/
+	CUnifiedCertStore* iUnifiedCertStore;
+	CUnifiedCertStore* iCreatedUnifiedCertStore;
+	
+	/**
+	These members are used to store the arguments of the functions
+	because most of the things are handled in a RunL.
+	*/
+	const CDesCArray* iRoots;					// Used by AddCertsL
+	const CDesCArray* iLabels;					// Used by AddCertsL
+	TCertificateFormat iFormat;
+	TInt iTrustedUsage;							// Used by AddCertsL, AddCert
+	RArray<TUid> iTrusters;						// Used by AddCertsL, AddCert
+	const TDesC* iPath;							// Used by AddCertsL, AddCert
+	TRequestStatus* iOriginalRequestStatus;		// Used by AddCertsL, AddCert
+	TInt iIndex;								// Used by AddCertsL to know 
+												// which certificate to add next
+												// Used by RemoveCerts
+	CCertUtils* iSecondCertUtils;				// Used by AddCertsL to add each individual
+												// certificate
+	const TDesC* iLabel;						// Used by AddCert
+	TCertificateOwnerType iCertificateOwnerType;
+	const TDesC* iCertificateFileName;			// Used by AddCert 
+	CCertificate* iCertificate;					// Used by AddCACert
+	MCTWritableCertStore *iStore;				// Used by AddCACert
+	TPtrC8 iEncoding;							// Used by AddCACert
+
+	HBufC* iCertData;
+	HBufC* iLabelData;
+
+	/**
+	This is a filter used by the GetCACerts function. We use the filter constructed
+	by the constructor with no argument, the filter doesn't filter anything.
+	*/
+	CCertAttributeFilter* iCAFilter;				// Used by RemoveCerts
+	RMPointerArray<CCTCertInfo> iCACertStoreEntries;	// Used by RemoveCerts
+	
+	/**
+	This is a filter used by the GetUserCerts function. We use the filter constructed
+	by the constructot with no argument, the filter doesn't filter anything.
+	*/
+	CCertAttributeFilter* iUserFilter;			// Used by RemoveCerts
+	RMPointerArray<CCTCertInfo> iUserCertStoreEntries; // Used by RemoveCerts
+
+public:
+	/**
+	A diagnostic variable for when an error occurs. It stores the state at which
+	the error occurred.
+	*/
+	TState iDiagnosticState;
+	
+	/** 
+	A diagnostic variable for when an error occurs. It is an info message set
+	to whatever is relevant for the error.
+	*/
+	TBuf<400> iDiagnosticMessage;
+	};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/transaction.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,108 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Header file for OCSP transaction object
+// 
+//
+
+/**
+ @file 
+ @internalComponent 
+*/
+
+#ifndef __OCSP_TRANSACTION_H__
+#define __OCSP_TRANSACTION_H__
+
+#include <ocsp.h>
+#include <e32base.h>
+#include "ocsprequestandresponse.h"
+
+class COCSPRequestEncoder;
+class COCSPResponseDecoder;
+
+/**
+ * OCSP Transaction object, used to send the request to the server and get the
+ * response back again.
+ */
+
+NONSHARABLE_CLASS(COCSPTransaction) : public CActive
+	{
+public:
+	// Does not take ownership of the transport object
+	static COCSPTransaction* NewL(const TDesC8& aURI, 
+								  MOCSPTransport& aTransport, const TUint aRetryCount, const TInt aTimeout);
+
+	~COCSPTransaction();
+
+	/**
+	 * Asynchronous interface to send the reqest.  Can complete with one of the
+	 * status codes from OCSP::TStatus if there's a problem decoding the
+	 * response.
+	 */
+	
+	void SendRequest(COCSPRequest& aRequest, TRequestStatus& aStatus);
+	
+	void CancelRequest();
+
+	/**
+	 * Get the response and relinquish ownership of it.  Returns NULL unless
+	 * SendRequest completed successfully.
+	 */	
+
+	COCSPResponse* TakeResponse();
+
+private:
+	// From CActive
+	void RunL();
+	void DoCancel();
+	TInt RunError(TInt aError);
+
+private:
+	COCSPTransaction(MOCSPTransport& aTransport, const TUint aRetryCount, const TInt aTimeout);
+	void ConstructL(const TDesC8& aURI);
+
+	void CompleteClient(const TInt aStatus);
+
+private:
+
+	enum TState
+		{
+		ESendRequest,
+		EFinished
+		};
+
+	MOCSPTransport& iTransport;
+	HBufC8* iURI;
+
+	TState iState;
+	
+	// Client TRequestStatus, for the asynchronous SendRequestL
+	TRequestStatus* iClientRequestStatus;
+
+	// Request object to send
+	COCSPRequest* iRequest;
+
+	// Request encoder.  We own this.
+	COCSPRequestEncoder* iRequestEncoder;
+
+	// Response object, NULL unless response data received OK
+	COCSPResponseDecoder* iResponseDecoder;
+
+	// Remaining number of times to send request on failed response (1 means no retry)
+	TUint iRetryCount;
+
+	// Timeout value (passed on to the transport layer)
+	TInt iTimeout;
+	};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/inc/validator.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,156 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// request.h
+// Header for OCSP validator object.
+// 
+//
+
+/**
+ @file 
+ @internalComponent 
+*/
+
+#ifndef __OCSP_VALIDATOR_H__
+#define __OCSP_VALIDATOR_H__
+
+#include <ocsp.h>
+#include "ocsprequestandresponse.h"
+/**
+ * Validator.  Used to verify the legitimacy of an OCSP response, and the
+ * certificates therein.  May specify time for certificate validation - if
+ * omitted, the producedAt time in the response is used instead.
+ */
+
+NONSHARABLE_CLASS(COCSPValidator) : public CActive
+	{
+public:
+	static COCSPValidator* NewL( const COCSPParameters& aParameters);
+	
+	~COCSPValidator();
+
+	/**
+	 * Specify Authorisation scheme(s) - doesn't take ownership
+	 */
+	
+	void AddAuthorisationSchemeL(MOCSPAuthorisationScheme& aScheme);
+
+	/**
+	 * Specify the authorisation time (NULL => use producedAt from response)
+	 * Default is to use producedAt.
+	 */
+	
+	void SetValidationTimeL(const TTime* aValidationTime);
+
+	/**
+	 * Specify the permissable maximum age of the thisUpdate field in
+	 * seconds. zero => don't check, default is 30 days. 
+	 */
+
+	void SetMaxStatusAge(TUint aMaxAge);
+
+	/**
+	 * Specify how much leeway we allow when comparing times - if we're using
+	 * the device clock, this allows for the fact that it may be out by a
+	 * certain amount.  Default is 5 seconds.
+	 */
+	
+	void SetTimeLeeway(TUint aLeewaySeconds);
+
+	/**
+	 * Validate a request/response pair, setting aOutcome to the result.
+	 * This is an asynchronous method.
+	 */
+	
+	void Validate(const COCSPRequest& aRequest, COCSPResponse& aResponse,
+				  TOCSPOutcome& aOutcome, TRequestStatus& aStatus);
+		
+protected:
+	virtual void DoCancel();
+	virtual void RunL();
+	virtual TInt RunError(TInt aError);
+
+ private:
+ 	void ConstructL();
+	COCSPValidator( const COCSPParameters& aParameters);
+
+	void DoValidateL(const COCSPRequest& aRequest, COCSPResponse& aResponse,
+					 TOCSPOutcome& aOutcome, TRequestStatus& aStatus);
+
+	// Specific validation areas - return false if we should give up now.
+	TBool IsResponseWellFormed(); // Checks correct certs present in response.
+	TBool ValidateTimeL();
+	TBool ValidateNonce();
+
+	void ProcessSchemeValidationL();
+	void CheckSchemeValidationL();
+	void FinalResponseValidationL();
+	
+	TTime ValidationTime() const;
+
+	TBool TimeIsBeforeL(const TTime& aBefore, const TTime& aAfter);
+	
+	 void SendResponderCertL();
+	 void ValidateResponderCertL();
+	 
+	 OCSP::TResult CheckOCSPStatus(const COCSPResponse* aResponse) const;
+	 
+private:
+
+	// Array of integers, giving for each cert in the response the corresponding position in
+	// the request
+	RArray<TInt> iRequestIndex;
+	
+	const COCSPRequest* iRequest;
+	COCSPResponse* iResponse;
+
+	// User-supplied time for validation
+	TTime* iValidationTime;
+
+	// How old to allow thisUpdate to be
+	TUint iMaxStatusAge;
+
+	// Authorisation objects
+	RPointerArray<MOCSPAuthorisationScheme> iAuthorisationScheme;
+
+	TOCSPOutcome* iOutcome;
+	TRequestStatus* iValidationStatus;
+
+	enum TState
+		{
+		EValidating,
+		EWaitingResponse,
+		EValidateResponderCert,
+		};
+
+	TState iState;
+
+	// index of the last authorisation scheme we used
+	TInt iIndexScheme; 
+
+	TUint iLeewaySeconds;
+	
+	TBool iResponderCertCheck;
+	TBool iUseNonce;
+	// ownership lies with the relevant auth scheme
+	const CX509Certificate* iResponderCert;
+	const CX509Certificate* iIssuerCert;
+	COCSPRequest* iResponderCertRequest;
+	COCSPResponse* iResponderCertResponse;
+	COCSPTransaction* iTransaction;
+	// ownership lies with COCSPClient
+	const COCSPParameters* iParameters;
+	MOCSPAuthorisationScheme* iSchemeInUse;
+	};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/cadirectauthorisation.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,134 @@
+// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Define methods for authorisation scheme based on the CA who issued the certificate
+// issues and signs the response.
+// 
+//
+
+#include "ocsp.h"
+#include "panic.h"
+#include <pkixcertchain.h>
+#include <asn1dec.h>
+#include <x509keys.h>
+#include <x509cert.h>
+#include "ocsprequestandresponse.h"
+
+
+EXPORT_C COCSPCaDirectAuthorisationScheme* COCSPCaDirectAuthorisationScheme::NewLC()
+	{
+	COCSPCaDirectAuthorisationScheme* self = new(ELeave) COCSPCaDirectAuthorisationScheme();
+	CleanupStack::PushL(self);
+	return self;
+	}
+
+/**
+	Validate the response if it is signed by the CA.  The response can
+	optionally contain a copy of the CA's certificate.
+*/
+void COCSPCaDirectAuthorisationScheme::ValidateL(OCSP::TStatus& aOCSPStatus,
+	COCSPResponse& aResponse, const TTime /* aValidationTime */, TRequestStatus& aStatus,
+	const COCSPRequest& aRequest)
+	{
+	TRequestStatus* validatorReqStatus = &aStatus;
+	aOCSPStatus = OCSP::EResponseSignatureValidationFailure;
+
+	// the OCSP requests are constructed in
+	// COCSPClient::ConstructL that exactly one certificate
+	// and its signer are sent in each request.
+	// (RFC 2560 S4.1.1 allows multiple pairs)
+	
+	// check the response is actually signed by the CA
+	// this effectively tests the same condition.
+	// By assuming there is only one request / response pair,
+	// there is no need to iterate through each response, which
+	// simplifies this scheme's implementation.
+
+	if (DoValidateL(aRequest, aResponse ))
+		{
+		aOCSPStatus = OCSP::EValid;
+		}
+	User::RequestComplete(validatorReqStatus, KErrNone);
+	};
+
+/**
+	Checks if the response is signed by the CA.
+	If the response has a certificate chain, it must contain
+	exactly the CA cert.  It is acceptable for the response
+	to have no certificate chain.
+
+	The responder ID in the certificate must match the CA cert,
+	and the whole response must be signed by the CA cert's signer.
+*/
+TBool COCSPCaDirectAuthorisationScheme::DoValidateL(
+	const COCSPRequest& aRequest, COCSPResponse& aResponse)
+{
+	// check the response contains either zero or one certificates.
+	// If the response contains a certificate, then it must be the
+	// same as the CA.
+
+	// get the intermediate which signed the EE
+	const CX509Certificate& caCert = aRequest.CertInfo(0).Issuer();
+	
+	// Retrieves the chain from the response of the responder certificate
+	// whic signed the response.
+	const TPtrC8* certChainData = aResponse.DataElementEncoding(COCSPResponse::ECertificateChain);
+	if (certChainData != 0)
+		{
+		if (! CertChainMatchesCertL(*certChainData, caCert))
+			return EFalse;
+		}
+
+	return
+			OCSPUtils::DoesResponderIdMatchCertL(aResponse, caCert)
+		&&	OCSPUtils::IsResponseSignedByCertL(&aResponse, caCert);
+}
+
+/**
+	Checks whether the encoded cert chain contains exactly
+	one cert which matches the supplied cert.
+
+	This is used to verify that, when a cert chain is sent with
+	the response, it contains exactly the CA cert.
+
+	@param	aCertChainData	DER-encoded certificate chain data
+							extracted from response.
+	@param	aCert			Certificate to look for.
+	@return					ETrue if the certificate chain contains
+							exactly one response which matches
+							aCert; EFalse otherwise.
+ */
+TBool COCSPCaDirectAuthorisationScheme::CertChainMatchesCertL(
+	const TDesC8& aCertChainData, const CX509Certificate& aCert)
+	{
+	// here we cannot assume that the response contains only the CA certificate,
+	// which signed the response as that can be a subordinate CA, so the chain
+	// can be like RCA(root CA) -> ICA(intermediate CA) -> SCA (sub-ordinate CA)
+	// we need to retrieve the SCA for this verification.
+	CX509Certificate* respCert = OCSPUtils::GetResponderCertLC(aCertChainData);
+	TBool match = aCert.IsEqualL(*respCert);
+	CleanupStack::PopAndDestroy(respCert);
+	return match;
+	}
+
+/**
+	This is a no-op because this implementation is not an
+	active object.
+ */
+void COCSPCaDirectAuthorisationScheme::CancelValidate()
+	{}
+
+const CX509Certificate* COCSPCaDirectAuthorisationScheme::ResponderCert() const	
+	{
+	return NULL;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/certid.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,171 @@
+// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Define certID object, as used in the OCSP spec.  Used both to code data
+// for the request, and decoded data from the response.
+// 
+//
+
+#include "certid.h"
+#include "bigint.h"
+
+
+#include <asn1dec.h>
+#include <asn1enc.h>
+#include <x509cert.h>
+
+COCSPCertID* COCSPCertID::NewL(const CX509Certificate& aSubject, const CX509Certificate& aIssuer)
+	{
+	COCSPCertID* self = new (ELeave) COCSPCertID;
+	CleanupStack::PushL(self);
+	self->ConstructL(aSubject, aIssuer);
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+
+void COCSPCertID::ConstructL(const CX509Certificate& aSubject, const CX509Certificate& aIssuer)
+	{
+	CSHA1* sha1 = CSHA1::NewL();
+	CleanupStack::PushL(sha1);
+
+	// Hash of DER encoding of IssuerName from subject cert (including tag and length)
+	const TPtrC8* issuerNameDER = aSubject.DataElementEncoding(CX509Certificate::EIssuerName);
+	if (!issuerNameDER)
+		{
+		User::Leave(KErrArgument);
+		}
+
+	iIssuerNameHash.Copy(sha1->Hash(*issuerNameDER));
+
+	// We'll ignore the 'number of unused bits' octet, since this is what everyone does, even
+	// though strictly speaking the OCSP spec says to include it.  This has been discussed on
+	// the PKIX mailing list.
+	sha1->Reset();
+	TPtrC8 subjectPublicKeyContents(aIssuer.PublicKey().KeyData());
+	iIssuerKeyHash.Copy(sha1->Hash(subjectPublicKeyContents));
+
+	CleanupStack::PopAndDestroy(sha1);
+
+	// Set serial number from subject
+	iSerialNumber.Set(aSubject.SerialNumber());
+	}
+
+
+COCSPCertID* COCSPCertID::NewL(const TDesC8& aBinaryData)
+	{
+	COCSPCertID* self = new (ELeave) COCSPCertID();
+	CleanupStack::PushL(self);
+	self->ConstructL(aBinaryData);
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+
+void COCSPCertID::ConstructL(const TDesC8& aBinaryData)
+	{
+	// Check the tag
+	TASN1DecGeneric decGen(aBinaryData);
+	decGen.InitL();
+	if (decGen.Tag() != EASN1Sequence)
+		{
+		User::Leave(KErrArgument);
+		}
+
+	// Decode the sequence into 4 bits
+	TASN1DecSequence decSeq;
+	CArrayPtr<TASN1DecGeneric>* items = decSeq.DecodeDERLC(decGen, 4, 4);
+
+	// First part - the hash algorithm - check for SHA1, no more needed
+	CX509AlgorithmIdentifier* algID = CX509AlgorithmIdentifier::NewLC(items->At(0)->Encoding());
+	if (algID->Algorithm() != ESHA1)
+		{
+		User::Leave(KErrArgument);
+		}
+	CleanupStack::PopAndDestroy(algID);
+
+	// Next parts - issuerNameHash and issuerKeyHash
+	TASN1DecOctetString decOS;
+
+	HBufC8* temp = decOS.DecodeDERL(*items->At(1));
+	iIssuerNameHash.Copy(*temp);
+	delete temp;
+
+	temp = decOS.DecodeDERL(*items->At(2));
+	iIssuerKeyHash.Copy(*temp);
+	delete temp;
+
+	// Lastly, the certificate serial number - just copy a reference to the encoded data
+	iSerialNumber.Set(items->At(3)->GetContentDER());
+
+	CleanupStack::PopAndDestroy(); // items
+	}
+
+
+// Construct ASN1 encoding object for the CertID data
+CASN1EncBase* COCSPCertID::EncoderLC() const
+	{
+	CASN1EncSequence* certID = CASN1EncSequence::NewLC();
+
+	// AlgId is a sequence, containing oid and null (both specific to SHA1)
+	CASN1EncSequence* algEnc = CASN1EncSequence::NewLC();
+	CASN1EncObjectIdentifier* algOidEnc = CASN1EncObjectIdentifier::NewLC(KSHA1);
+	algEnc->AddChildL(algOidEnc);
+	CleanupStack::Pop(); // algOidEnc, now owned by algEnc
+	CASN1EncNull* nullEnc = CASN1EncNull::NewLC();
+	algEnc->AddChildL(nullEnc);
+	CleanupStack::Pop(); // nullEnc, now owned by algEnc
+	certID->AddChildL(algEnc);
+	CleanupStack::Pop(); // algEnc, now owned by certID
+
+	// issuerNameHash
+	CASN1EncOctetString* name = CASN1EncOctetString::NewLC(iIssuerNameHash);
+	certID->AddChildL(name);
+	CleanupStack::Pop(); // name, now owned by certID
+
+	// issuerKeyHash
+	CASN1EncOctetString* issuer = CASN1EncOctetString::NewLC(iIssuerKeyHash);
+	certID->AddChildL(issuer);
+	CleanupStack::Pop(); // issuer, now owned by certID
+
+	// serialNumber
+	RInteger serialNumber = RInteger::NewL(iSerialNumber);
+	CleanupStack::PushL(serialNumber);
+	CASN1EncBigInt* snEnc = CASN1EncBigInt::NewLC(serialNumber);
+	certID->AddChildL(snEnc);
+	CleanupStack::Pop(); // snEnc, now owned by certID;
+	CleanupStack::PopAndDestroy(); // serialNumber
+
+	return certID;
+	}
+
+
+TBool COCSPCertID::operator==(const COCSPCertID& aRhs) const
+	{
+	if (iIssuerNameHash == aRhs.iIssuerNameHash
+		&& iIssuerKeyHash == aRhs.iIssuerKeyHash
+		&& iSerialNumber == aRhs.iSerialNumber)
+		{
+		return ETrue;
+		}
+	else
+		{
+		return EFalse;
+		}
+	}
+
+
+TPtrC8 COCSPCertID::SerialNumber() const
+	{
+	return iSerialNumber;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/client.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,360 @@
+// Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+#include "transaction.h"
+#include "validator.h"
+#include "panic.h"
+#include <ocsp.h>
+#include <x509certext.h>
+#include <x509certchain.h>
+#include <x509cert.h>
+#include <asn1dec.h>
+
+EXPORT_C COCSPClient* COCSPClient::NewL(const COCSPParameters* aParams)
+	{
+	COCSPClient* self = new (ELeave) COCSPClient();
+	CleanupStack::PushL(self);
+	self->ConstructL(aParams);
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+COCSPClient::COCSPClient() :
+	CActive(EPriorityNormal)
+	{
+	CActiveScheduler::Add(this);
+	}
+
+void COCSPClient::ConstructL(const COCSPParameters* aParams)
+	{
+	__ASSERT_ALWAYS(aParams, Panic(KErrArgument));
+
+	// Caller must supply transport
+	if (!aParams->Transport())
+		{
+		User::Leave(KErrArgument);
+		}
+
+	// Range check request timeout and retry values to avoid later panics
+	if (aParams->Timeout() < KTransportDefaultRequestTimeout)
+		{
+		User::Leave(KErrArgument);
+		}
+	if (aParams->RetryCount() < KTransportDefaultRequestRetryCount)
+		{
+		User::Leave(KErrArgument);
+		}
+
+	iParams = aParams; // Take ownership
+	
+	// Make a request for every certificate
+	for (TUint i = 0 ; i < aParams->CertCount() ; ++i)
+		{
+		// Following are the condition in which the request would not be 
+		// added for ocsp check:
+		// If CheckCertsWithAiaOnly is enabled and certificate does 
+		// not contain AIA extension.
+		//					Or
+		// CheckCertsWithAiaOnly is disabled and 
+		// GenerateResponseFromMissingURI is disabled and 
+		// AIA is absent and
+		// Global OCSP URL is absent
+		
+		if (! (	(	aParams->CheckCertsWithAiaOnly() && 
+					!OCSPUtils::IsAIAForOCSPPresentL( aParams->SubjectCert(i) )
+				) || 
+				(	!aParams->CheckCertsWithAiaOnly() 
+					&& !aParams->GenerateResponseForMissingUri() 
+					&& !OCSPUtils::IsAIAForOCSPPresentL(aParams->SubjectCert(i)) 
+					&& aParams->DefaultURI() == KNullDesC8()
+				)
+			   )
+			)
+			{
+			COCSPRequest* request = COCSPRequest::NewLC(aParams->UseNonce());
+			request->AddCertificateL(aParams->SubjectCert(i), aParams->IssuerCert(i));
+			User::LeaveIfError(iRequests.Append(request));
+			CleanupStack::Pop(request);
+			}
+			
+		}
+	iValidator = COCSPValidator::NewL(*aParams);
+	}
+
+
+COCSPClient::~COCSPClient()
+	{
+	Cancel();
+	delete iParams;
+	delete iURI;
+	delete iTransport;
+	delete iTransaction;
+	delete iValidator;
+	iRequests.ResetAndDestroy();
+	iResponses.ResetAndDestroy();
+	iOutcomes.Close();
+	}
+
+EXPORT_C OCSP::TResult COCSPClient::SummaryResult(void) const
+	{
+	__ASSERT_ALWAYS(iState == EHaveResult, Panic(KErrNotReady));
+	return iSummaryResult;
+	}
+
+EXPORT_C TInt COCSPClient::TransactionCount(void) const
+	{
+	__ASSERT_ALWAYS(iState == EHaveResult, Panic(KErrNotReady));
+	return iResponses.Count();
+	}
+
+EXPORT_C const COCSPRequest& COCSPClient::Request(TInt aIndex) const
+	{
+	__ASSERT_ALWAYS(iState == EHaveResult, Panic(KErrNotReady));
+	__ASSERT_ALWAYS(aIndex >= 0 && aIndex < iRequests.Count(), Panic(KErrNotFound));
+	return *(iRequests[aIndex]);
+	}
+
+EXPORT_C const TOCSPOutcome& COCSPClient::Outcome(TInt aIndex) const
+	{
+	__ASSERT_ALWAYS(iState == EHaveResult, Panic(KErrNotReady));
+	__ASSERT_ALWAYS(aIndex >= 0 && aIndex < iOutcomes.Count(), Panic(KErrNotFound));
+	return iOutcomes[aIndex];
+	}
+
+EXPORT_C const COCSPResponse* COCSPClient::Response(TInt aIndex) const
+	{
+	__ASSERT_ALWAYS(iState == EHaveResult, Panic(KErrNotReady));
+	__ASSERT_ALWAYS(aIndex >= 0 && aIndex < iResponses.Count(), Panic(KErrNotFound));
+	return iResponses[aIndex];
+	}
+
+EXPORT_C void COCSPClient::Check(TRequestStatus& aStatus)
+	{
+	__ASSERT_ALWAYS(iState == EInitial, Panic(KErrInUse));
+
+	iClientStatus = &aStatus;
+	TInt err = KErrNone;
+
+	if (iRequests.Count() == 0)
+		{
+		err = OCSP::KErrNoCertificates;
+		}
+
+	if (err == KErrNone)
+		{
+		aStatus = KRequestPending;
+		DoCheck();
+		}
+
+	if (err != KErrNone)
+		{
+		User::RequestComplete(iClientStatus, err);
+		iState = EError;
+		}
+	}
+
+EXPORT_C void COCSPClient::CancelCheck()
+	{
+	Cancel();
+	}
+
+EXPORT_C TBool COCSPClient::CertsAvailableForOCSPCheck()
+	{
+	return iRequests.Count();
+	}
+
+TInt COCSPClient::RunError(TInt aError)
+	{
+	User::RequestComplete(iClientStatus, aError);
+	iState = EError;
+	return KErrNone;
+	}
+
+void COCSPClient::DoCancel()
+	{
+	if (iTransaction)
+		{
+		iTransaction->CancelRequest();
+		}
+	
+	iValidator->Cancel();
+	if (iClientStatus)
+		{
+		User::RequestComplete(iClientStatus, KErrCancel);
+		}
+	}	
+
+void COCSPClient::DoCheck()
+	{
+	iSummaryResult = OCSP::EGood;
+	SendRequest();
+	}
+
+void COCSPClient::RunL()
+	{
+	switch (iState)
+		{
+		case ESendingRequest:
+			HandleResponseReceivedL();
+			break;
+			
+		case EValidatingResponse:
+			User::LeaveIfError(iStatus.Int());
+			HandleResponseValidatedL();
+			break;
+						
+		default:
+			Panic(KErrCorrupt);
+			break;
+		}
+	}
+
+/**
+ * Receive the response, if the response was received correctly, 
+ * perform validation based on the scheme in use.
+ */
+void COCSPClient::HandleResponseReceivedL()
+	{
+	TInt status = iStatus.Int();
+	
+	if (status == KErrNone)
+		{
+		COCSPResponse* response = iTransaction->TakeResponse();
+		CleanupStack::PushL(response);
+		User::LeaveIfError(iResponses.Append(response));
+		CleanupStack::Pop(response);
+		ValidateResponseL();
+		}
+	else if (status > 0)
+		{
+		HandleTransactionErrorL(static_cast<OCSP::TStatus>(status));
+		}
+	else if ((status == OCSP::KErrTransportFailure) || (status == OCSP::KErrServerNotFound))
+		{
+		HandleTransactionErrorL(OCSP::ETransportError);
+		}
+	else if (status == OCSP::KErrInvalidURI)
+		{
+		HandleTransactionErrorL(OCSP::EInvalidURI);
+		}
+	else if (status == OCSP::KErrTransportTimeout)
+		{
+		HandleTransactionErrorL(OCSP::ETimeOut);
+		}
+	else
+		{
+		User::Leave(status);		   
+		}
+	}
+
+/**
+ * Called when there's an error getting a response, and it's one of our non-fatal errors.
+ * We record the error and continue checking.
+ */
+
+void COCSPClient::HandleTransactionErrorL(OCSP::TStatus aStatus)
+	{
+	User::LeaveIfError(iOutcomes.Append(TOCSPOutcome(aStatus, OCSP::EUnknown)));
+	User::LeaveIfError(iResponses.Append(NULL));
+	HandleResponseValidatedL();
+	}
+
+/**
+ * Following is the sequence followed in this method:
+ * 1. Check the result for validation of the current response and update the Summary result accordingly.
+ * 2. If delegate certificate has to be checked further initiate the same.
+ * 3. if all request have not been processed then start validation for the next request.
+ * 4. If all request have been processed complete the original client request.
+ */
+void COCSPClient::HandleResponseValidatedL()
+	{
+	TInt index = iOutcomes.Count() - 1;
+	const TOCSPOutcome& outcome = iOutcomes[index];
+
+	if (outcome.iResult > iSummaryResult)
+		{
+		iSummaryResult = outcome.iResult;
+		}
+	
+	if (iResponses.Count() < iRequests.Count())
+		{
+		SendRequest();
+		}
+	else
+		{
+		iState = EHaveResult;
+		User::RequestComplete(iClientStatus, KErrNone);	
+		}
+	}
+
+void COCSPClient::SendRequest()
+	{
+	TRAPD(error, DoSendRequestL());
+
+	// Handle errors in RunL
+	if (error != KErrNone)
+		{
+		TRequestStatus* status = &iStatus;
+		User::RequestComplete(status, error);
+		}
+
+	iState = ESendingRequest;
+	SetActive();
+	}
+
+void COCSPClient::DoSendRequestL()
+	{
+	// Determine the next request to send by the number of responses received
+	TInt index = iResponses.Count();
+	COCSPRequest& request = *(iRequests[index]);
+	
+	TDesC8* uri = NULL;
+	TRAPD(error, uri = OCSPUtils::ServerUriL(request.CertInfo(0).Subject(),iParams));
+	
+	if(error == KErrArgument)
+		{
+		TRequestStatus* status = &iStatus;
+		User::RequestComplete(status, OCSP::ENoServerSpecified);
+		return;
+		}
+	
+	User::LeaveIfError(error);
+	CleanupStack::PushL(uri);
+	
+	// if state is valid it means that uri has been retrieved.
+	__ASSERT_ALWAYS(uri != NULL, Panic(OCSP::EInvalidURI));
+	MOCSPTransport& transport = *iParams->Transport();
+	
+	delete iTransaction;
+	iTransaction = NULL;
+	iTransaction = COCSPTransaction::NewL(*uri, transport, iParams->RetryCount(), iParams->Timeout());
+	iTransaction->SendRequest(request, iStatus);
+	CleanupStack::PopAndDestroy(uri);		
+	}
+
+/**
+ * Each response received has to undergo validation based on RFC 2560 guidelines.
+ */
+void COCSPClient::ValidateResponseL()
+	{
+	TInt index = iResponses.Count() - 1;
+
+	User::LeaveIfError(iOutcomes.Append(TOCSPOutcome()));
+	__ASSERT_ALWAYS(iOutcomes.Count() == iResponses.Count(), Panic(KErrCorrupt));
+
+	iState = EValidatingResponse;
+	iValidator->Validate(*(iRequests[index]), *(iResponses[index]), iOutcomes[index], iStatus);
+	SetActive();
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/delegateauthorisation.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,399 @@
+// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+#include <asn1dec.h>
+#include <x509certext.h>
+#include "oids.h"
+#include "pkixcertchain.h"
+#include "ocsp.h"
+#include <mcertstore.h>
+#include <ccertattributefilter.h>
+#include "ocsprequestandresponse.h"
+
+const TInt CERT_SIZE = 1000;
+
+EXPORT_C COCSPDelegateAuthorisationScheme* COCSPDelegateAuthorisationScheme::NewLC(
+	MCertStore& aCertStore)
+/**
+	Factory function allocates new instance of
+	COCSPDelegateAuthorisationScheme.
+	
+	@param	aCertStore		Cert store interface.  This is used to
+							construct a certificate chain builder with
+							CPKIXCertChainBase::NewL().  Certificates from
+							the store are not used for validation if the response 
+							contains the responder certificate. If it does not contain 
+							the responder cert then validation would be done from store.
+	@return					New instance of COCSPDelegateAuthorisationScheme.
+							Leaves if cannot successfully construct.  The new
+							object is placed on the cleanup stack.
+ */
+	{
+	COCSPDelegateAuthorisationScheme* scheme =
+		new(ELeave) COCSPDelegateAuthorisationScheme(aCertStore);
+	CleanupStack::PushL(scheme);
+	scheme->ConstructL();
+	
+	return scheme;
+	}
+
+COCSPDelegateAuthorisationScheme::COCSPDelegateAuthorisationScheme(
+	MCertStore& aCertStore)
+/**
+	Initializes the CActive base class object and adds
+	this object to the active scheduler.
+	
+	@param	aCertStore		Cert store interface.  This is only used to
+							construct a certificate chain builder with
+							CPKIXCertChainBase::NewL().  Certificates from
+							the store are not used for validation if the response 
+							contains the responder certificate. If it does not contain 
+							the responder cert then validation would be done from store.
+ */
+:	CActive(EPriorityStandard),
+	iCertStore(aCertStore)
+	{
+	CActiveScheduler::Add(this);
+	}
+
+void COCSPDelegateAuthorisationScheme::ConstructL()
+/**
+	Strictly, none of the resources owned by this object
+	are required for all of its lifetime need to be preserved
+	between validations.
+	
+	Some of the resources, such as the CPKIXCertChain
+	instance have to be reallocated for every validation.
+	
+	The resources which can be allocated for the lifetime
+	of this object are allocated here.  This improves performance
+	and simplifies the validation process, at a RAM cost.
+ */
+	{
+	// iRespSignCertChainBase is the array of intermediate
+	// certificates which CPKIXCertChain will use to
+	// chain (T->I) to (I->E).  Because only immediate
+	// delegates are supported, there will only be one
+	// intermediate (or trusted root from CPKIXCertChain's
+	// point-of-view.)  Therefore the array can be
+	// sized here.
+	
+	// RPointerArray<> doesn't have a Reserve() function.
+	const CX509Certificate* nullCert = 0;
+	User::LeaveIfError(iRespSignIntCert.Append(nullCert));
+	
+	iCertFilter = CCertAttributeFilter::NewL();
+	iCertFilter->SetOwnerType(ECACertificate);
+	iCertFilter->SetFormat(EX509Certificate);
+
+	}
+
+COCSPDelegateAuthorisationScheme::~COCSPDelegateAuthorisationScheme()
+/**
+	Cancels any outstanding validation and frees all resources
+	owned by this object.
+ */
+	{
+	delete iCertFilter;
+	iCertStoreEntries.Close();
+	iRespSignIntCert.Close();
+	
+	delete iEncodedCert;
+	delete iResponseCert;
+	
+	delete iPKIXResultBase;
+	delete iRespSignCertChainBase;
+	
+	}
+
+/**
+	Implement MOCSPAuthorisationScheme.
+	
+	Validate the response if it is signed by an	immediate delegate of the intermediate entity.
+	I.e. if the request has the form
+		(T->I) (I->E)
+	
+	where T is trusted (at least for the purposes of this validation) and I is an intermediate, 
+	the response can be signed by R if (I->R).
+	
+	I is the CA, and can be equal to T, i.e. the certificate which is being tested for 
+	revocation can be signed by a root certificate.
+	
+	R must be immediately signed by I, and must have id-kp-OCSPSigning in its extended key usage.
+	(RFC 2560 S4.2.2.2)
+ */
+void COCSPDelegateAuthorisationScheme::ValidateL(
+	OCSP::TStatus& aOCSPStatus, COCSPResponse& aResponse,
+	const TTime aValidationTime, TRequestStatus& aStatus,
+	const COCSPRequest& aRequest)
+	{
+	// store the client status, so that it can be used for request
+	// completion later.
+	iClientStatus = &aStatus;
+	aStatus = KRequestPending;
+	
+	// By assuming there is only one request / response pair,
+	// there is no need to iterate through each response, which
+	// simplifies this scheme's implementation.
+	// the OCSP requests are constructed in
+	// COCSPClient::ConstructL() such that exactly one certificate
+	// and its signer are sent in each request.
+	// (RFC 2560 S4.1.1 allows multiple pairs)
+	
+	iResponse = &aResponse;
+	iRequest = &aRequest;
+	
+	iValidationTime = aValidationTime;
+	
+	// This default value is changed once the whole validation 
+	// process has completed successfully else the default value 
+	// is returned on failure.
+	aOCSPStatus = OCSP::EResponseSignatureValidationFailure;
+	iOCSPStatus = &aOCSPStatus;
+	
+	// set this to false before starting the scheme validation
+	// for multiple certificates are being validated through 
+	// this scheme.
+	iValidateFromResponse = EFalse;
+	
+	// This authentication scheme supports 2 ways of validation:
+	// 1. If the response contains responder cert then validation 
+	// would be performed against the responder cert included in response. 
+	// This validation would also check whether the responder cert has been 
+	// issued by the CA cert which issued the certificate in question.
+	// 2. If the response does not contain responder cert, search for it 
+	// in the store based on the ResponderId which is included in the 
+	// response. If the responder cert is found in the store which has signed
+	// the response then authorize the response, in both the cases we check whether 
+	// responder cert has been issued by the CA which issued the cert in question, 
+	// and the CA should be present in the store.
+	const TPtrC8* certChainData = aResponse.DataElementEncoding(COCSPResponse::ECertificateChain);
+	if (certChainData == 0)		// no signing certs
+		{
+		ValidateFromRootsL();
+		}
+	else
+		{
+		iValidateFromResponse = ETrue;
+		ValidateDelegateCertL(*certChainData, iValidationTime);
+		}
+	}
+
+/**
+	Initialize this object to validate the certificate which was sent with the 
+	response against the CA which was used	to sign the certificate in question.
+	
+	@param	aResponseCertChain	DER-encoded cert chain that	was either sent with the response.
+								or was retrieved from the store as a single certificate.
+	@param 	aValidationTime		Time to be used for chain validation of the delegate certificate.
+	@post If successful, asynchronous validation will be set up.
+ */
+
+void COCSPDelegateAuthorisationScheme::ValidateDelegateCertL(
+	const TDesC8& aResponseCertChain, const TTime aValidationTime)
+	{
+	// the response received can contain a chain of certificate, we need to extract the 
+	// responder certificate from the chain for further processing. If the certificate has been
+	// retrieved from store then there would be no chain but the delegate certificate would be
+	// retrieved.
+	CX509Certificate* decodedResponseCert = OCSPUtils::GetResponderCertLC(aResponseCertChain);
+	CleanupStack::Pop(decodedResponseCert);
+	
+	delete iResponseCert;
+	iResponseCert = NULL;
+	iResponseCert = decodedResponseCert;
+	
+	// First check the responder certificate in accordance to RFC 2560 for the following:
+	// 1. Does it contain extension id-kp-OCSPSigning
+	// 2. The responder id in the response matches the response certificate.
+	// 3. The response is signed by the responder certificate
+	if( OCSPUtils::DoesCertHaveOCSPSigningExtL(*iResponseCert) 
+		&&	OCSPUtils::DoesResponderIdMatchCertL(*iResponse, *iResponseCert)
+		&&	OCSPUtils::IsResponseSignedByCertL(iResponse, *iResponseCert) )
+		{
+		// construct a certificate chain containing the X -> R with T -> I as the intermediate.
+		delete iPKIXResultBase;
+		iPKIXResultBase = NULL;
+		iPKIXResultBase = CPKIXValidationResultBase::NewL();
+		
+		// get the intermediate which signed the EE
+		const CX509Certificate& caCert = iRequest->CertInfo(0).Issuer();
+		
+		// use the intermediate cert as the trusted root for
+		// the purpose of building the chain.  ("Intermediate"
+		// in this context is the certificate which signed the EE.)
+		iRespSignIntCert[0] = CONST_CAST(CX509Certificate*,&caCert);
+		
+		delete iRespSignCertChainBase;
+		iRespSignCertChainBase = NULL;
+		iRespSignCertChainBase = CPKIXCertChainBase::NewL(iCertStore, iResponseCert->Encoding(), iRespSignIntCert);
+		
+		// attempt to validate the chain.  I.e. test that X = I.
+		iRespSignCertChainBase->ValidateL(*iPKIXResultBase, aValidationTime, iStatus);
+		
+		iState = EOnChainValidation;
+		SetActive();
+		}
+	else
+		{
+		if(iValidateFromResponse)
+			{
+			User::RequestComplete(iClientStatus, KErrNone);
+			return;
+			}
+		// this means that we are trying to retrieve the responder certificate from the store
+		// and perform validation against it. As this certificate is not the valid responder
+		// hence set the state to retrieve the next certificate from the store.
+		else
+			{
+			iState = ERetrieveNext;
+			TRequestStatus* status = &iStatus;
+			User::RequestComplete(status,KErrNone);
+			SetActive();
+			return;
+			}
+		}
+	}
+
+void COCSPDelegateAuthorisationScheme::CancelValidate()
+/**
+	Implement MOCSPAuthorisationScheme.  This is an active
+	object, and this function just calls Cancel().  See
+	DoCancel() for information about the cancellation process.
+	
+	@see DoCancel
+ */
+	{
+	ASSERT(iRespSignCertChainBase != 0);
+	iRespSignCertChainBase->CancelValidate();
+	}
+
+void COCSPDelegateAuthorisationScheme::RunL()
+	{
+	User::LeaveIfError(iStatus.Int());
+	switch(iState)
+		{
+		//Response validation after chain building.
+		case EOnChainValidation:
+			OnChainValidationL();
+			break;
+		
+		// state used to allocate sufficient memory for retrieving the next certificate
+		case ERetrieveNext:
+			OnRetrieveNextL();
+			break;
+
+		// state used to retrieve the next certificate
+		case ERetrievingEntry:
+			OnRetrievingEntryL();
+			break;
+		}
+	}
+
+void COCSPDelegateAuthorisationScheme::OnChainValidationL()
+	{	
+	TValidationError error = iPKIXResultBase->Error().iReason;
+	if (error != EValidatedOK)
+		{
+		User::Leave(error);
+		}
+	*iOCSPStatus = OCSP::EValid;
+	User::RequestComplete(iClientStatus, KErrNone);
+	}
+
+void COCSPDelegateAuthorisationScheme::DoCancel()
+/**
+	If a validation request is outstanding, then it is cancelled.
+	This objects client, i.e. the owner of the TRequestStatus which
+	was passed to Validate(), is completed with KErrCancel.
+ */
+	{
+	// object should be waiting for the chain builder to complete.  
+	// Therefore there must be a valid client request status pointer 
+	// and an instance of CPKIXCertChain.
+	
+	iRespSignCertChainBase->CancelValidate();
+	
+	if (iClientStatus)
+		{		
+		User::RequestComplete(iClientStatus, KErrCancel);
+		}
+	}
+
+TInt COCSPDelegateAuthorisationScheme::RunError(TInt aError)
+	{
+	User::RequestComplete(iClientStatus, aError);
+	return KErrNone;
+	}
+
+/**
+ * Initiates request to retrieve the responder certificate from store.
+ */
+void COCSPDelegateAuthorisationScheme::ValidateFromRootsL()
+	{
+	iCertCount = -1;
+	
+	iCertStoreEntries.Close();
+	iCertStore.List(iCertStoreEntries, *iCertFilter, iStatus);
+	
+	delete iEncodedCert;
+	iEncodedCert = NULL;
+	iEncodedCert = HBufC8::NewL(CERT_SIZE);
+	
+	iState = ERetrieveNext;
+	SetActive();
+	}
+
+/**
+ * For list of certificate entries in the store retrieve each certificate.
+ */
+void COCSPDelegateAuthorisationScheme::OnRetrieveNextL()
+	{
+	if(++iCertCount < iCertStoreEntries.Count() )
+		{
+		iState = ERetrievingEntry;
+		TInt size = iCertStoreEntries[iCertCount]->Size();
+		if( size > iEncodedCert->Des().MaxLength() )
+			{
+			delete iEncodedCert;
+			iEncodedCert = NULL;
+			iEncodedCert = HBufC8::NewL(size);
+			}
+		TPtr8 encodedCertDesc = iEncodedCert->Des();
+		iCertStore.Retrieve(*iCertStoreEntries[iCertCount],	encodedCertDesc,iStatus);
+		SetActive();
+		}
+	else
+		{
+		User::RequestComplete(iClientStatus,OCSP::EResponseSignatureValidationFailure);	
+		}
+	}
+
+/**
+ * Once the certificate has been retrieved from the store, it should be sent for chain validation.
+ * This intermediate state is required so that we can retrieve the certificate from the store.
+ */
+void COCSPDelegateAuthorisationScheme::OnRetrievingEntryL()
+	{
+	ValidateDelegateCertL(*iEncodedCert, iValidationTime);
+	}
+
+/**
+ * Returns the responder certificate.
+ */
+const CX509Certificate* COCSPDelegateAuthorisationScheme::ResponderCert() const	
+	{
+	return iResponseCert;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/directauthorisation.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,321 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Define methods for authorisation scheme based on locally configured
+// authoritive root certs
+// 
+//
+
+#include "ocsp.h"
+#include "panic.h"
+#include <pkixcertchain.h>
+#include <asn1dec.h>
+#include <x509keys.h>
+#include <x509cert.h>
+#include <mcertstore.h>
+#include <ccertattributefilter.h>
+#include "ocsprequestandresponse.h"
+
+EXPORT_C COCSPDirectAuthorisationScheme* COCSPDirectAuthorisationScheme::NewLC(const TUid& aCertStoreUid, MCertStore& aCertStore)
+	{
+	COCSPDirectAuthorisationScheme* self = new(ELeave) COCSPDirectAuthorisationScheme(aCertStoreUid, aCertStore);
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+	}
+
+COCSPDirectAuthorisationScheme::COCSPDirectAuthorisationScheme(const TUid& aCertStoreUid, MCertStore& aCertStore) :
+	CActive(CActive::EPriorityStandard),
+	iCertStoreUid(aCertStoreUid),
+	iCertStore(aCertStore)
+	{
+	CActiveScheduler::Add(this);
+	}
+
+
+COCSPDirectAuthorisationScheme::~COCSPDirectAuthorisationScheme()
+	{
+	Cancel();
+	delete iCertChain;
+	delete iPKIXResult; 
+	delete iCertFilter;
+	delete iEncodedCertBuf;
+	delete iEncodedCertPtr;
+	iFs.Close();
+	iCertStoreEntries.Close();
+	delete iResponseCert;
+	}
+
+
+void COCSPDirectAuthorisationScheme::ConstructL()
+	{
+	iPKIXResult = CPKIXValidationResultBase::NewL();
+	
+	User::LeaveIfError(iFs.Connect());
+	
+	iCertFilter = CCertAttributeFilter::NewL();
+	iCertFilter->SetOwnerType(ECACertificate);
+	iCertFilter->SetUid(iCertStoreUid);
+	iCertFilter->SetFormat(EX509Certificate);
+	}
+
+/**
+ * Starts the process of validating the response.
+ * The initial value of the OCSP Status is set to signature validation failure.
+ */
+void COCSPDirectAuthorisationScheme::ValidateL(OCSP::TStatus& aOCSPStatus,
+	COCSPResponse& aResponse, const TTime aValidationTime, TRequestStatus& aStatus,
+	const COCSPRequest& aRequest)
+	{
+	iValidationTime = aValidationTime;
+
+	iClientStatus = &aStatus;
+	*iClientStatus = KRequestPending;
+
+	iResponse = &aResponse;
+	iRequest = &aRequest;
+	
+	iOCSPStatus = &aOCSPStatus;
+	*iOCSPStatus = OCSP::EResponseSignatureValidationFailure;
+	
+	// this object needs to be deleted if the same COCSPDirectAuthorisationScheme
+	// object is used for validating more than one certificate via COCSPValidator
+	delete iCertChain;
+	iCertChain = NULL;
+		
+	StartValidateL();
+	}
+
+
+void COCSPDirectAuthorisationScheme::ValidateFromRoots()
+//
+// Certs for the chain were not included in the response.
+// See if any of the root certs for the given Uid can do the job.
+//
+	{
+	iCertStore.List(iCertStoreEntries, *iCertFilter, iStatus);
+	iState = EListCertEntries;
+	}
+
+/**
+ * If response contains responder's certificate, chain validation would be done till the CA 
+ * certificate which should be located in the store.
+ */
+void COCSPDirectAuthorisationScheme::ValidateCertChainL()
+	{
+	__ASSERT_DEBUG(iCertChain, Panic(KErrCorrupt));
+
+	iCertChain->ValidateL(*iPKIXResult, iValidationTime, iStatus);
+	iState = EValidateCertChain;
+	}
+
+TBool COCSPDirectAuthorisationScheme::ValidateSignatureL()
+	{
+	__ASSERT_DEBUG(iCertChain, Panic(KErrCorrupt));
+
+	// Validate against first cert in chain - must exist
+	const CX509Certificate& eeCert = iCertChain->Cert(0);
+
+	return	OCSPUtils::DoesResponderIdMatchCertL(*iResponse, eeCert)
+		&&	OCSPUtils::IsResponseSignedByCertL(iResponse, eeCert);
+	}
+
+void COCSPDirectAuthorisationScheme::OnValidateCertChainL()
+// Called when cert chain validation completes
+	{
+	if (iPKIXResult->Error().iReason == EValidatedOK)
+		{
+		if (ValidateSignatureL())
+			{
+			delete iResponseCert;
+			iResponseCert = NULL;
+			iResponseCert = CX509Certificate::NewL(iCertChain->Cert(0));
+			*iOCSPStatus = OCSP::EValid;
+			}
+		}
+	User::RequestComplete(iClientStatus, KErrNone);
+	}
+		
+
+void COCSPDirectAuthorisationScheme::OnListCertEntries()
+// Called when listing cert store entries completes
+	{
+	// trigger transitory state to start getting entries
+	iCurEntry = -1;
+	iState = ERetrieveNext;
+	TRequestStatus* status = &iStatus;
+	User::RequestComplete(status, KErrNone);
+	SetActive();
+	}
+
+
+void COCSPDirectAuthorisationScheme::OnRetrieveNextL()
+// Transitory state to retrieve next entry triggered
+	{
+	delete iEncodedCertBuf;
+	iEncodedCertBuf = 0;
+	delete iEncodedCertPtr;
+	iEncodedCertPtr = 0;
+	if (++iCurEntry < iCertStoreEntries.Count())
+	// still more entries, get next one
+		{
+		CCTCertInfo* certInfo = iCertStoreEntries[iCurEntry];
+		ASSERT(certInfo);
+
+		iEncodedCertBuf = HBufC8::NewL(certInfo->Size());
+		iEncodedCertPtr = new(ELeave) TPtr8(iEncodedCertBuf->Des());
+
+		iCertStore.Retrieve(*certInfo, *iEncodedCertPtr, iStatus);
+		
+		iState = ERetrievingEntry;
+		
+		SetActive();
+		}
+	else
+	// no more entries, bad news
+		{
+		User::RequestComplete(iClientStatus, KErrNone);
+		}
+	}
+
+void COCSPDirectAuthorisationScheme::OnRetrievingEntryL()
+// Called when retrieving an entry completes.
+	{
+	CX509Certificate* cert = CX509Certificate::NewLC(*iEncodedCertPtr);
+	
+	if (	OCSPUtils::DoesResponderIdMatchCertL(*iResponse, *cert)
+		&&	OCSPUtils::IsResponseSignedByCertL(iResponse, *cert)
+		&&	cert->ValidityPeriod().Valid(iValidationTime))
+	// found a good one, job finished
+		{
+		delete iResponseCert;
+		iResponseCert = NULL;
+		CleanupStack::Pop(cert);
+		iResponseCert = cert;
+		*iOCSPStatus = OCSP::EValid;
+		User::RequestComplete(iClientStatus, KErrNone);
+		}
+	else
+	// wasn't good, try next one
+		{
+		iState = ERetrieveNext;
+		TRequestStatus* status = &iStatus;
+		User::RequestComplete(status, KErrNone);
+		SetActive();
+		CleanupStack::PopAndDestroy(cert);
+		}
+	
+	}
+
+void COCSPDirectAuthorisationScheme::RunL()
+//
+// Handles transitions from one state to the next
+//
+	{
+	User::LeaveIfError(iStatus.Int());
+
+	switch (iState)
+		{
+	case EValidateCertChain:
+		OnValidateCertChainL();
+		break;
+	case EListCertEntries:
+		OnListCertEntries();
+		break;
+	case ERetrieveNext:
+		OnRetrieveNextL();
+		break;
+	case ERetrievingEntry:
+		OnRetrievingEntryL();
+		break;
+	
+	default:
+		ASSERT(FALSE);
+		}
+	}
+
+void COCSPDirectAuthorisationScheme::DoCancel()
+//
+// Cancel
+//
+	{
+	switch (iState)
+		{
+	case EValidateCertChain:
+		ASSERT(iCertChain);
+		iCertChain->CancelValidate();
+		break;
+	case EListCertEntries:
+		iCertStore.CancelList();
+		break;
+	case ERetrieveNext:
+		// nothing to do, this is a transitory state
+		break;
+	case ERetrievingEntry:
+		iCertStore.CancelRetrieve();
+		break;
+	default:
+		ASSERT(FALSE);
+		}
+	if (iClientStatus)
+		{
+		User::RequestComplete(iClientStatus, KErrCancel);
+		}
+	}
+
+
+TInt COCSPDirectAuthorisationScheme::RunError(TInt aError)
+	{
+	if(aError == KErrArgument)
+		{
+		User::RequestComplete(iClientStatus, KErrNone);
+		}
+	else
+		{
+		User::RequestComplete(iClientStatus, aError);
+		}
+	return KErrNone;
+	}
+
+/**
+ * If the response contains the certificate which signed the response, create the certificate chain
+ * till the responder certificate. Otherwise validate directly from root certificates contained 
+ * in the store initialized by the client.
+ */
+void COCSPDirectAuthorisationScheme::StartValidateL()
+	{
+	const TPtrC8* certChainData = iResponse->DataElementEncoding(COCSPResponse::ECertificateChain);
+	
+	// Cert chain data was included in response
+	if (certChainData)
+		{
+		iCertChain = CPKIXCertChainBase::NewL(iCertStore, *certChainData, iCertStoreUid);
+		ValidateCertChainL();
+		}
+	else
+		{
+		// No cert chain in response - validate directly from root certs
+		ValidateFromRoots();
+		}
+	SetActive();
+	}
+
+void COCSPDirectAuthorisationScheme::CancelValidate()
+	{
+	CActive::Cancel();
+	}
+
+const CX509Certificate* COCSPDirectAuthorisationScheme::ResponderCert() const	
+	{
+	return iResponseCert;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/ocsppolicy.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,100 @@
+// Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+#include "ocsppolicy.h"
+
+#include <f32file.h>
+#include <s32file.h>
+
+
+// OCSP policy repository UID
+static const TUid KUidOCSPRepository = { 0x2002B28B };
+
+// Default values for the settings
+const TBool KDefaultGenerateResponseForMissingUri 	= ETrue;
+const TBool KDefaultEnableHttpGETMethod 			= EFalse;
+
+EXPORT_C COcspPolicy* COcspPolicy::NewL()
+	{
+	COcspPolicy* self = new(ELeave)COcspPolicy();
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+EXPORT_C TBool COcspPolicy::IsGenerateResponseForMissingUriEnabled() const
+	{
+	return iGenerateResponseForMissingUri;
+	}
+
+EXPORT_C TBool COcspPolicy::IsHttpGETMethodEnabled() const
+	{
+	return iEnableHttpGETMethod;
+	}
+
+COcspPolicy::COcspPolicy()
+	: iGenerateResponseForMissingUri(KDefaultGenerateResponseForMissingUri),
+	iEnableHttpGETMethod(KDefaultEnableHttpGETMethod)
+	{
+	}
+
+/*
+ * Leaves with KErrNotFound if the OCSP repository is not found and 
+ * default values for the settings are retained if the settings are missing 
+ * in the repository.
+ * Otherwise, the settings are set to the read values from the repository.
+ */ 
+void COcspPolicy::ConstructL()
+	{
+    // Session to access OCSP Central Repository Server.
+	SecuritySettingsServer::RSecSettingsSession SecSettingsSession;
+
+    // Connect to the Central Repository server.
+	User::LeaveIfError(SecSettingsSession.Connect());
+
+	CleanupClosePushL(SecSettingsSession);
+    
+	// Read-in the values of the settings - GenerateResponseForMissingUri and 
+	// EnableHttpGETMethod from the OCSP Central Repository. 
+	// These will retain the default values if any error occurs.
+
+	TInt value = 1;
+
+	TRAPD(err, (value = SecSettingsSession.SettingValueL(KUidOCSPRepository, KGenerateResponseForMissingUri)));
+	
+	if( err == KErrNone )
+	{
+		iGenerateResponseForMissingUri = value;
+	}
+	else if( err != KErrSettingNotFound )
+	{
+		User::Leave(err);
+	}
+
+	TRAP(err, (value = SecSettingsSession.SettingValueL(KUidOCSPRepository, KEnableHttpGetMethod)));
+
+	if ( err == KErrNone )
+	{
+		iEnableHttpGETMethod = value;
+	}
+	else if( err != KErrSettingNotFound )
+	{
+		User::Leave(err);
+	}	
+
+	CleanupStack::PopAndDestroy(&SecSettingsSession);
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/ocsputils.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,293 @@
+// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Define generic methods which can be used accross the ocsp component.
+// 
+//
+
+#include <asymmetrickeys.h>
+#include <ocsp.h>
+#include "oids.h"
+#include <x509certext.h>
+#include "ocsprequestandresponse.h"
+
+namespace OCSPUtils
+	{
+	/**
+		Checks whether the supplied certificate matches the responder
+		ID in the supplied response.  This implements S3.2.3 of RFC2560.
+		Note this does <em>not</em> mean the response is signed by the
+		certificate's subject.  It just checks that the certificate's
+		name, or a hash of its key, is present in the response's plaintext.
+		
+		@param	aResponse		Response whose responder ID should describe
+								<var>aCert</var>.
+		@param	aCert			Certificate whose name or key should be
+								in the response.
+		@return ETrue if the response's responder ID matches <var>aCert</var>,
+			EFalse otherwise.
+	 */
+	TBool DoesResponderIdMatchCertL( const COCSPResponse& aResponse, 
+												const CX509Certificate& aResponderCert)
+		{	
+		return (DoesIssuerKeyMatchL(aResponse,aResponderCert) || DoesDNNameMatchL(aResponse,aResponderCert));
+		}
+	
+	TBool DoesDNNameMatchL( 	const COCSPResponse& aResponse, const CX509Certificate& aCert)
+		{
+		TBool result = EFalse;
+		const TPtrC8* nameData = aResponse.DataElementEncoding(COCSPResponse::EResponderIDName);
+		if (nameData)
+			{
+			CX500DistinguishedName* name = CX500DistinguishedName::NewLC(*nameData);
+			if (aCert.SubjectName().ExactMatchL(*name))
+				{
+				result = ETrue;
+				}
+			CleanupStack::PopAndDestroy(name);
+			}
+		return result;
+		}
+	
+	TBool DoesIssuerKeyMatchL(const COCSPResponse& aResponse, const CX509Certificate& aCert)
+		{
+		TBool result = EFalse;
+		// check the responder's issuer key and verify that it is the same as the issuer cert
+		const TPtrC8* keyHash = aResponse.DataElementEncoding(COCSPResponse::EResponderIDKeyHash);
+		const TPtrC8* keyEncoding = aCert.DataElementEncoding(CX509Certificate::ESubjectPublicKeyInfo);
+		if (!keyHash || !keyEncoding)
+			{
+			return result;
+			}
+		
+		TASN1DecSequence decSeq;
+		TInt pos = 0;
+		CArrayPtrFlat<TASN1DecGeneric>* seq = decSeq.DecodeDERLC(*keyEncoding, pos, 2, KMaxTInt);
+	
+		TASN1DecBitString decBitStr;
+		HBufC8* toHashData = decBitStr.ExtractOctetStringL(*seq->At(1));
+		CleanupStack::PushL(toHashData);
+		
+		CSHA1* hashAlg = CSHA1::NewL();
+		CleanupStack::PushL(hashAlg);
+		TPtrC8 certKeyHash = hashAlg->Hash(*toHashData);
+		
+		if (certKeyHash == *keyHash)
+			{
+			// Public key hashes match
+			result = ETrue;
+			}
+		CleanupStack::PopAndDestroy(3, seq); // hashAlg, toHashData, seq
+			
+		return result;
+		}
+	
+	TBool IsResponseSignedByCertL(
+		COCSPResponse* aResponse, const CX509Certificate& aCert)
+	/**
+		Checks whether the supplied response is signed by the supplied
+		certificate.
+		
+		@param	aResponse		Response which should be signed by aCert.
+		@param	aCert			Candidate certificate which may have been
+								used to sign <var>aResponse</var>.
+		@return ETrue if <var>aCert</var> is used to sign <var>aResponse</var>,
+			EFalse otherwise.  Note <code>COCSPResponse</code> derives
+			from <code>CSignedObject</code>.
+	 */
+		{
+		if (aCert.PublicKey().AlgorithmId() == EDSA)
+			{
+			TX509KeyFactory factory;
+			CDSAParameters* theDSAParams = factory.DSAParametersL(aCert.PublicKey().EncodedParams());
+			CleanupStack::PushL(theDSAParams);
+			
+			CSigningKeyParameters* params = CSigningKeyParameters::NewLC();
+			params->SetDSAParamsL(*theDSAParams);
+					
+			aResponse->SetParametersL(*params);
+			CleanupStack::PopAndDestroy(2, theDSAParams);
+			}
+		
+		return aResponse->VerifySignatureL(aCert.PublicKey().KeyData());
+		}
+	
+	TBool DoesCertHaveOCSPNoCheckExt(const CX509Certificate& aCert)
+	/**
+		Test whether the supplied certificate has id-pkix-ocsp-nocheck
+		in an extendedKeyUsage extension.  
+		
+		@param	aCert		Certificate to test for id-kp-OCSPSigning.
+								
+		@return				ETrue if the supplied certificate has an
+							extendedKeyUsage extension which contains
+							id-pkix-ocsp-nocheck.
+	 */
+		{
+		return aCert.Extension(KOCSPOidNoCheck) != NULL;
+		}
+	
+	/**
+	 * Determine the URI of the OCSP server to use for a certificate.  Checks to see
+	 * if there is an authority info access extension containing an access
+	 * description with method oid id-ad-ocsp. If so, it copies the access
+	 * description into a new descriptor which it stores in iURI.  Otherwise it
+	 * returns iDefaultURI, which may be null.
+	 */
+	
+	TDesC8* ServerUriL(const CX509Certificate& aCert, const COCSPParameters* aParameters )
+		{
+		
+		TDesC8* uri = NULL;
+		
+		// check whether AIA is present or not:
+		// if present and UseAIA is enabled the get the AIA extension.
+		// if AIA is absent the else if part will handle it
+		// if present and UseAIA is disabled, means that iUseGlobalOCSPUri is enabled,
+		// do not leave with an error in this case the next case will handle this condition.
+		if( aParameters->UseAIA() && OCSPUtils::IsAIAForOCSPPresentL(aCert) )
+			{
+			uri = OCSPUtils::GetAIAL(aCert);
+			}
+		else if( aParameters->DefaultURI() != KNullDesC8())
+			{
+			uri = aParameters->DefaultURI().AllocL();
+			}
+		// the extension is absent and iUseGlobalOCSPUri is disabled, it has reached this case
+		// where neither is there an AIA in the cert nor is the global ocsp responder available,
+		// this should leave with EInvalidURI but this has been done to maintain backward compatibility.
+		else
+			{
+			User::Leave(KErrArgument);
+			}
+		return uri;
+		}
+	
+	// check whether AIA is present or not:
+	// if present and UseAIA is enabled then return true.
+	// if default uri is not null return true.
+	TBool IsUriAvailableL(const CX509Certificate& aCert, const COCSPParameters* aParameters )
+		{
+		return  ( aParameters->UseAIA() && OCSPUtils::IsAIAForOCSPPresentL(aCert) ) || 
+				 ( aParameters->DefaultURI() != KNullDesC8() ) ;
+		}
+	
+	TBool IsAIAForOCSPPresentL(const CX509Certificate& aCert)
+		{
+		TBool found = EFalse;
+		const CX509CertExtension* ext = aCert.Extension(KAuthorityInfoAccess);
+		
+		if(ext)
+			{
+			CX509AuthInfoAccessExt* auth = CX509AuthInfoAccessExt::NewLC(ext->Data());
+			for (TInt i = 0 ; i < auth->AccessDescriptions().Count() ; ++i)
+				{
+				const CX509AccessDescription* desc = auth->AccessDescriptions()[i];
+				if (desc->Method() == KAccessMethodOCSP && desc->Location().Tag() == EX509URI )
+					{
+					found = ETrue;
+					break;
+					}
+				} // end of for
+			CleanupStack::PopAndDestroy(auth);
+			}
+		return found;
+		}
+	
+	TDesC8* GetAIAL(const CX509Certificate& aCert)
+		{
+		TDesC8*	uri = NULL;
+		
+		const CX509CertExtension* ext = aCert.Extension(KAuthorityInfoAccess);
+		
+		if (ext)
+			{
+			CX509AuthInfoAccessExt* auth = CX509AuthInfoAccessExt::NewLC(ext->Data());
+			for (TInt i = 0 ; i < auth->AccessDescriptions().Count() ; ++i)
+				{
+				const CX509AccessDescription* desc = auth->AccessDescriptions()[i];
+				if (desc->Method() == KAccessMethodOCSP)
+					{
+					const CX509GeneralName& gn = desc->Location();
+					if (gn.Tag() == EX509URI)
+						{
+						// Decode the general name rather than using CX509IPBaseURI, 
+						// as this currently rejects some URIs
+						TASN1DecIA5String encStr;
+						TInt pos = 0;
+						HBufC* suri = encStr.DecodeDERL(gn.Data(), pos);
+						CleanupStack::PushL(suri);
+						HBufC8* buf = HBufC8::NewL(suri->Length());
+						uri = buf;
+						buf->Des().Copy(*suri);
+						CleanupStack::PopAndDestroy(suri);
+						break;
+						}
+					}
+				}
+			CleanupStack::PopAndDestroy(auth);
+			}
+		return uri;
+		}
+	
+	/**
+		Test whether the supplied certificate has id-kp-OCSPSigning
+		in an extendedKeyUsage extension.  This tests whether the
+		certificate is a trusted responder, as defined in RFC 2560 S4.2.2.2.
+			
+		@param	aCert			Certificate to test for id-kp-OCSPSigning.
+								This should be the certificate which was
+								immediately signed by the CA which issued
+								the certificate in question.
+		@return					ETrue iff the supplied certificate has an
+								extendedKeyUsage extension which contains
+								id-kp-OCSPSigning.
+	*/
+		
+	TBool DoesCertHaveOCSPSigningExtL(const CX509Certificate& aCert)
+		{
+		TBool found = EFalse;
+		// check has extended key usage
+		const CX509CertExtension* ekuExt = aCert.Extension(KExtendedKeyUsage);
+		if (ekuExt != NULL)
+			{	
+			// get set of extended key usages
+			const TDesC8& extData = ekuExt->Data();
+			CX509ExtendedKeyUsageExt* extUses = CX509ExtendedKeyUsageExt::NewLC(extData);
+			
+			// check if id-kp-OCSPSigning is one of the uses
+			const CArrayPtrFlat<HBufC>& usages = extUses->KeyUsages();
+			TInt usageCount = usages.Count();
+			for (TInt i = 0; i < usageCount; ++i)
+				{
+				if (*usages[i] == KOCSPOidOCSPSigning)
+					{
+					found = ETrue;
+					break;
+					}
+				}
+			CleanupStack::PopAndDestroy(extUses);
+			}
+		return found;
+		}
+	
+	
+	CX509Certificate* GetResponderCertLC(const TDesC8& aEncodedCerts)
+		{
+		// This specifies the position of the certificate which is to be retrieved from
+		// the encoded certificate chain. As responder certificate would always be the 
+		// end entity certificate, here we are retrieving the first one from the chain.
+		TInt pos = 0;
+		return CX509Certificate::NewLC(aEncodedCerts, pos);
+		}
+	} // OCSPUtils namespace
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/panic.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// The panic method
+// 
+//
+
+#include "panic.h"
+
+#include <e32std.h>
+
+GLDEF_C void Panic(TInt aPanic)
+	{
+	User::Panic(_L("OCSP"), aPanic);
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/parameters.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,306 @@
+// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+#include "panic.h"
+#include "log.h"
+#include <ocsp.h>
+#include <x509certchain.h>
+#include <ocsppolicy.h>
+#include "ocsprequestandresponse.h"
+
+EXPORT_C COCSPParameters* COCSPParameters::NewL()
+	{
+	COCSPParameters* self = NewLC();
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+EXPORT_C COCSPParameters* COCSPParameters::NewLC()
+	{
+	COCSPParameters* self = new (ELeave) COCSPParameters();
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+	}
+
+COCSPParameters::COCSPParameters() :
+	iUseNonce(ETrue),
+	iUseAIA(ETrue),
+	iGenerateResponseForMissingUri(ETrue),
+	iResponderCertCheck(EFalse), // should be turned off by default
+	iRetryCount(KTransportDefaultRequestRetryCount),
+	iTimeout(KTransportDefaultRequestTimeout),
+	iCheckCertsWithAiaOnly(EFalse) // should be turned off by default
+	{}
+
+void COCSPParameters::ConstructL()
+	{
+	DEBUG_PRINTF(_L8("Reading policy."));
+	iDefaultURI = KNullDesC8().AllocL();
+	
+	COcspPolicy* ocspPolicy = COcspPolicy::NewL();
+	iGenerateResponseForMissingUri = ocspPolicy->IsGenerateResponseForMissingUriEnabled();
+
+	delete ocspPolicy;
+
+	DEBUG_PRINTF2(_L8("Generate response when no AIA URI and no default OCSP URI: %d."), iGenerateResponseForMissingUri);
+	}
+
+COCSPParameters::~COCSPParameters()
+	{
+	iSubjectCerts.Close();
+	iIssuerCerts.Close();
+	delete iDefaultURI;
+	delete iTransport;
+	iAuthSchemes.ResetAndDestroy();
+	delete iValidationTime;
+	delete iMaxStatusAge;
+	delete iTimeLeeway;
+	}
+
+EXPORT_C void COCSPParameters::AddCertificateL(const CX509Certificate& aSubject, const CX509Certificate& aIssuer)
+	{
+	User::LeaveIfError(iSubjectCerts.Append(&aSubject));
+	User::LeaveIfError(iIssuerCerts.Append(&aIssuer));
+	}
+
+EXPORT_C void COCSPParameters::AddCertificatesL(const CX509CertChain& aChain)
+	{
+	TInt numCerts = aChain.Count();
+	if (numCerts >= 2)
+		{
+		// Go through all but last cert (last = root)
+		const CX509Certificate* issuerCert = &aChain.Cert(0);
+		const CX509Certificate* subjectCert = NULL;
+		for (TInt index = 1; index < numCerts; ++index)
+			{
+			subjectCert = issuerCert;
+			issuerCert = &aChain.Cert(index);
+
+			AddCertificateL(*subjectCert, *issuerCert);
+			}
+		}
+	}
+
+EXPORT_C void COCSPParameters::SetUseNonce(TBool aUseNonce)
+	{
+	iUseNonce = aUseNonce;
+	}
+
+EXPORT_C void COCSPParameters::SetURIL(const TDesC8& aURI, TBool aUseAIA)
+	{
+	delete iDefaultURI;
+	iDefaultURI = NULL;
+	iDefaultURI = aURI.AllocL();
+	iUseAIA = aUseAIA;
+	}
+
+EXPORT_C void COCSPParameters::SetTransport(MOCSPTransport* aTransport)
+	{
+	delete iTransport;
+	iTransport = aTransport;
+	}
+
+EXPORT_C void COCSPParameters::SetRetryCount(const TUint aRetryCount)
+	{
+	iRetryCount = aRetryCount;
+	}
+
+EXPORT_C void COCSPParameters::SetTimeout(const TInt aTimeout)
+	{
+	iTimeout = aTimeout;
+	}
+
+EXPORT_C void COCSPParameters::AddAuthorisationSchemeL(MOCSPAuthorisationScheme* aScheme)
+	{
+	__ASSERT_ALWAYS(aScheme, ::Panic(KErrArgument));
+	User::LeaveIfError(iAuthSchemes.Append(aScheme));
+	}
+
+EXPORT_C void COCSPParameters::AddAllAuthorisationSchemesL(const TUid& aCertStoreUid, MCertStore& aCertStore)
+/**
+	This function adds all of the currently supported authorisation schemes
+	to this object.  It is more convenient than having the client to allocate
+	each scheme.
+
+	This function allocates the authorisation schemes defined in RFC2560 S2.2 -
+	direct authorisation, CA delegate, and CA direct.
+
+	@param	aCertStoreUid	UID of trusted root certificates.  E.g.,
+							KCertStoreUIDForSWInstallOCSPSigning.
+	@param	aCertStore		Certificate store which contains the
+							the trust anchors used to validate the
+							response.	
+	@pre No authorisation schemes should have been added to this object before
+		this function is called.
+	@see AddAuthorisationSchemeL
+ */
+	{
+	__ASSERT_DEBUG(iAuthSchemes.Count() == 0, Panic(EAAASAlreadyHaveSchemes));
+
+	COCSPDirectAuthorisationScheme* directScheme =
+		COCSPDirectAuthorisationScheme::NewLC(aCertStoreUid, aCertStore);
+	AddAuthorisationSchemeL(directScheme);
+	CleanupStack::Pop(directScheme);
+
+	COCSPDelegateAuthorisationScheme* caDelgScheme =
+		COCSPDelegateAuthorisationScheme::NewLC(aCertStore);
+	AddAuthorisationSchemeL(caDelgScheme);
+	CleanupStack::Pop(caDelgScheme);
+
+	COCSPCaDirectAuthorisationScheme* caDirectScheme = COCSPCaDirectAuthorisationScheme::NewLC();
+	AddAuthorisationSchemeL(caDirectScheme);
+	CleanupStack::Pop(caDirectScheme);
+	}
+
+EXPORT_C void COCSPParameters::SetValidationTimeL(const TTime& aValidationTime)
+	{
+	delete iValidationTime;
+	iValidationTime = NULL;
+	iValidationTime = new (ELeave) TTime(aValidationTime);
+	}
+
+EXPORT_C void COCSPParameters::SetMaxStatusAgeL(TUint aMaxAge)
+	{
+	delete iMaxStatusAge;
+	iMaxStatusAge = NULL;
+	iMaxStatusAge = new (ELeave) TUint(aMaxAge);
+	}
+
+EXPORT_C void COCSPParameters::SetTimeLeewayL(TUint aLeewaySeconds)
+	{
+	delete iTimeLeeway;
+	iTimeLeeway = NULL;
+	iTimeLeeway = new (ELeave) TUint(aLeewaySeconds);
+	}
+
+EXPORT_C void COCSPParameters::SetCheckCertsWithAiaOnly(const TBool aCheckCertsWithAiaOnly)
+	{
+	iCheckCertsWithAiaOnly = aCheckCertsWithAiaOnly;
+	}
+
+EXPORT_C void COCSPParameters::SetOCSPCheckForResponderCert(const TBool aResponderCertCheck)
+	{
+	iResponderCertCheck = aResponderCertCheck;
+	}
+
+EXPORT_C void COCSPParameters::SetUseAIA(const TBool aUseAIA)
+	{
+	iUseAIA = aUseAIA;
+	}
+
+TUint COCSPParameters::CertCount() const
+	{
+	return iSubjectCerts.Count();
+	}
+
+const CX509Certificate& COCSPParameters::SubjectCert(TUint aIndex) const
+	{
+	return *iSubjectCerts[aIndex];
+	}
+
+const CX509Certificate& COCSPParameters::IssuerCert(TUint aIndex) const
+	{
+	return *iIssuerCerts[aIndex];
+	}
+
+TBool COCSPParameters::UseNonce() const
+	{
+	return iUseNonce;
+	}
+
+const TDesC8& COCSPParameters::DefaultURI() const
+	{
+	return static_cast<TDesC8&>(*iDefaultURI);
+	}
+
+TBool COCSPParameters::UseAIA() const
+	{
+	return iUseAIA;
+	}
+
+MOCSPTransport* COCSPParameters::Transport() const
+	{
+	return iTransport;
+	}
+
+TUint COCSPParameters::AuthSchemeCount() const
+	{
+	return iAuthSchemes.Count();
+	}
+
+MOCSPAuthorisationScheme& COCSPParameters::AuthScheme(TUint aIndex) const
+	{
+	// Modified so when backported to typhoon this stil compiles, required because of the
+	// RArrayPointer operator[] changes,
+	return const_cast<MOCSPAuthorisationScheme&>(*iAuthSchemes[aIndex]);
+	}
+
+const TTime* COCSPParameters::ValidationTime() const
+	{
+	return iValidationTime;
+	}
+
+const TUint* COCSPParameters::MaxStatusAge() const
+	{
+	return iMaxStatusAge;
+	}
+
+const TUint* COCSPParameters::TimeLeeway() const
+	{
+	return iTimeLeeway;
+	}
+
+TBool COCSPParameters::GenerateResponseForMissingUri() const
+	{
+	return iGenerateResponseForMissingUri;
+	}
+
+TUint COCSPParameters::RetryCount() const
+	{
+	return iRetryCount;
+	}
+
+TInt COCSPParameters::Timeout() const
+	{
+	return iTimeout;
+	}
+
+TBool COCSPParameters::ReponderCertCheck() const
+	{
+	return iResponderCertCheck;
+	}
+
+TBool COCSPParameters::CheckCertsWithAiaOnly() const
+	{
+	return iCheckCertsWithAiaOnly;
+	}
+
+#ifdef _DEBUG
+
+void COCSPParameters::Panic(COCSPParameters::TPanic aPanic)
+/**
+	Halt the current thread with the supplied panic code.
+	The thread is halted with category "OCSPParam" and the supplied
+	reason.
+
+	@param	aPanic			Panic reason.
+ */
+	{
+	_LIT(KPanicCat, "OCSPParam");
+	User::Panic(KPanicCat, aPanic);
+	}
+
+#endif	// #ifdef _DEBUG
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/request.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,142 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Object encapsulating the OCSP request - uses ASN1 encoding
+// 
+//
+
+#include "ocsp.h"
+#include "panic.h"
+#include "oids.h"
+#include "certid.h"
+
+#include <bigint.h>
+#include <x509cert.h>
+#include <x509certchain.h>
+#include <random.h>
+#include "ocsprequestandresponse.h"
+
+// COCSPRequest methods
+COCSPRequest* COCSPRequest::NewLC(TBool aUseNonce)
+	{
+	COCSPRequest* self = new (ELeave) COCSPRequest;
+	CleanupStack::PushL(self);
+	self->ConstructL(aUseNonce);
+	return self;
+	}
+
+COCSPRequest* COCSPRequest::NewL(TBool aUseNonce)
+	{
+	COCSPRequest* self = COCSPRequest::NewLC(aUseNonce);
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+COCSPRequest::COCSPRequest()
+	{}
+
+void COCSPRequest::ConstructL(TBool aUseNonce)
+	{
+	if (aUseNonce)
+		{
+		// Make nonce data
+		iNonce = HBufC8::NewL(KOCSPNonceBytes);
+		TPtr8 des = iNonce->Des();
+		des.SetLength(KOCSPNonceBytes);
+		TRandom::RandomL(des);
+		}
+	}
+
+
+COCSPRequest::~COCSPRequest()
+	{
+	iCertInfos.ResetAndDestroy();
+	delete iNonce;
+	}
+
+
+void COCSPRequest::AddCertificateL(const CX509Certificate& aSubject,
+								   const CX509Certificate& aIssuer)
+	{
+	COCSPRequestCertInfo* certInfo = COCSPRequestCertInfo::NewLC(aSubject, aIssuer);
+	User::LeaveIfError(iCertInfos.Append(certInfo));
+	CleanupStack::Pop(certInfo);
+	}
+
+
+EXPORT_C const TDesC8* COCSPRequest::Nonce() const
+	{
+	return iNonce;
+	}
+
+
+EXPORT_C TInt COCSPRequest::CertCount() const
+	{
+	return iCertInfos.Count();
+	}
+
+
+EXPORT_C const COCSPRequestCertInfo& COCSPRequest::CertInfo(TUint aIndex) const
+	{
+	return *iCertInfos[aIndex];
+	}
+
+
+// COCSPRequestCertInfo methods
+
+
+COCSPRequestCertInfo* COCSPRequestCertInfo::NewLC(const CX509Certificate& aSubject,
+												  const CX509Certificate& aIssuer)
+	{
+	COCSPRequestCertInfo* self = new (ELeave) COCSPRequestCertInfo(aSubject, aIssuer);
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+	}
+
+
+COCSPRequestCertInfo::COCSPRequestCertInfo(const CX509Certificate& aSubject, const CX509Certificate& aIssuer) :
+	iSubject(aSubject),
+	iIssuer(aIssuer)
+	{
+	}
+
+
+void COCSPRequestCertInfo::ConstructL()
+	{
+	iCertID = COCSPCertID::NewL(iSubject, iIssuer);
+	}
+
+
+COCSPRequestCertInfo::~COCSPRequestCertInfo()
+	{
+	delete iCertID;
+	}
+
+
+EXPORT_C const CX509Certificate& COCSPRequestCertInfo::Subject() const
+	{
+	return iSubject;
+	}
+
+
+EXPORT_C const CX509Certificate& COCSPRequestCertInfo::Issuer() const
+	{
+	return iIssuer;
+	}
+
+
+const COCSPCertID& COCSPRequestCertInfo::CertID() const
+	{
+	return *iCertID;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/requestencoder.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,220 @@
+// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Implementation for OCSP request encoder object
+// 
+//
+
+#include "requestencoder.h"
+#include "certid.h"
+#include "oids.h"
+#include "ocsp.h"
+#include "panic.h"
+#include <asn1enc.h>
+
+COCSPRequestEncoder* COCSPRequestEncoder::NewL(const COCSPRequest& aRequest)
+	{
+	COCSPRequestEncoder* self = new (ELeave) COCSPRequestEncoder();
+	CleanupStack::PushL(self);
+	self->ConstructL(aRequest);
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+
+COCSPRequestEncoder::COCSPRequestEncoder()
+	{
+	}
+
+
+COCSPRequestEncoder::~COCSPRequestEncoder()
+	{
+	delete iEncoding;
+	}
+
+
+const TDesC8& COCSPRequestEncoder::Encoding() const
+	{
+	return *iEncoding;
+	}
+
+
+void COCSPRequestEncoder::ConstructL(const COCSPRequest& aRequest)
+	{
+	// Get encoder
+	CASN1EncBase* encoder = MakeOCSPRequestEncLC(aRequest);
+	
+	// Make buffer
+	TUint length = encoder->LengthDER();
+	iEncoding = HBufC8::NewMaxL(length);
+	TPtr8 buf = iEncoding->Des();
+	
+	// Write data
+	TUint position = 0;
+	encoder->WriteDERL(buf, position);
+	
+	CleanupStack::PopAndDestroy(encoder);
+	}
+
+
+// Static helper method - encapsulates a commonly-dupliciated peice of code
+void COCSPRequestEncoder::AddAndPopChildL(CASN1EncContainer& aParent, CASN1EncBase* aChild)
+	{
+	if (aChild)
+		{
+		aParent.AddChildL(aChild);
+		CleanupStack::Pop(aChild); // Now owned by aParent
+		}
+	}
+
+
+CASN1EncBase* COCSPRequestEncoder::MakeOCSPRequestEncLC(const COCSPRequest& aRequest)
+	{
+	CASN1EncSequence* ocspRequest = CASN1EncSequence::NewLC();
+
+	CASN1EncBase* tbsRequest = MakeTBSRequestEncLC(aRequest);
+	AddAndPopChildL(*ocspRequest, tbsRequest);
+
+	return ocspRequest;
+	}
+
+
+CASN1EncBase* COCSPRequestEncoder::MakeTBSRequestEncLC(const COCSPRequest& aRequest)
+	{
+	CASN1EncSequence* tbsRequest = CASN1EncSequence::NewLC();
+
+	// version - int 0, explicitly tagged as 0
+	// Excluded, since this is the default value, and we're using DER
+
+	// Skip GeneralName - we don't support that, and it is optional
+
+	// Cert requestList
+	CASN1EncBase* requestList = MakeRequestListEncLC(aRequest);
+	AddAndPopChildL(*tbsRequest, requestList);
+
+	// Global request extensions - optional, explicitly tagged [2]
+	CASN1EncBase* extensions = MakeRequestExtensionsEncLC(aRequest);
+	if (extensions)
+		{
+		CleanupStack::Pop(extensions); // Will be owned by explicit tag
+		CASN1EncExplicitTag* taggedExtensions = CASN1EncExplicitTag::NewLC(extensions, 2);
+		AddAndPopChildL(*tbsRequest, taggedExtensions);
+		}
+
+	return tbsRequest;
+	}
+
+
+CASN1EncBase* COCSPRequestEncoder::MakeRequestListEncLC(const COCSPRequest& aRequest)
+	{
+	CASN1EncSequence* requestList = CASN1EncSequence::NewLC();
+
+	// Request objects - one for each cert
+	TUint numCerts = aRequest.CertCount();
+	ASSERT(numCerts > 0);
+
+	for (TUint index = 0; index < numCerts; ++index)
+		{
+		const COCSPCertID& certId = aRequest.CertInfo(index).CertID();
+		CASN1EncBase* certEnc = MakeCertRequestEncLC(certId);
+		AddAndPopChildL(*requestList, certEnc);
+		}
+
+	return requestList;
+	}
+
+
+// Make encoder for the request object for a particular cert
+CASN1EncBase* COCSPRequestEncoder::MakeCertRequestEncLC(const COCSPCertID& aCertId)
+	{
+	CASN1EncSequence* request = CASN1EncSequence::NewLC();
+
+	// CertID
+	CASN1EncBase* certIdEnc = aCertId.EncoderLC();
+	AddAndPopChildL(*request, certIdEnc);
+
+	return request;
+	}
+
+
+CASN1EncBase* COCSPRequestEncoder::MakeRequestExtensionsEncLC(const COCSPRequest& aRequest)
+	{
+	CASN1EncSequence* extns = CASN1EncSequence::NewLC();
+
+	// Nonce extension (if present)
+	CASN1EncBase* nonceExtn = MakeNonceExtnEncLC(aRequest);
+	AddAndPopChildL(*extns, nonceExtn);
+
+	// Response type extentions
+	CASN1EncBase* responseTypeExtn = MakeResponseTypeExtnEncLC();
+	AddAndPopChildL(*extns, responseTypeExtn);
+
+	return extns;
+	}
+
+
+// Response type.  Is a sequence, with OID, default bool, and octet string
+// for contents.  In this case the octet string contains a sequence
+// of OIDs specifying the acceptable response types.
+CASN1EncBase* COCSPRequestEncoder::MakeResponseTypeExtnEncLC()
+	{
+	CASN1EncSequence* extn = CASN1EncSequence::NewLC();
+
+	// OID
+	CASN1EncObjectIdentifier* oid = CASN1EncObjectIdentifier::NewLC(KOCSPOidResponse);
+	AddAndPopChildL(*extn, oid);
+
+	// Skip Critical flag since we want default value FALSE and this is DER
+
+	// Acceptable responses - takes a bit of work, so bear with it...
+
+	// First, make sequence containing the OID for our response type
+	CASN1EncSequence* responses = CASN1EncSequence::NewLC();
+	CASN1EncObjectIdentifier* basic = CASN1EncObjectIdentifier::NewLC(KOCSPOidBasic);
+	AddAndPopChildL(*responses, basic);
+
+	// Second, encode this into a descriptor
+	TBuf8<KOCSPMaxOidEncodingLength> buf(responses->LengthDER());
+	TUint pos = 0;
+	responses->WriteDERL(buf, pos);
+	CleanupStack::PopAndDestroy(responses); // Finished with that now
+
+	// Third, make Octet string encoder from this data + add to extn
+	CASN1EncOctetString* value = CASN1EncOctetString::NewLC(buf);
+	AddAndPopChildL(*extn, value);
+
+	return extn;
+	}
+
+
+CASN1EncBase* COCSPRequestEncoder::MakeNonceExtnEncLC(const COCSPRequest& aRequest)
+	{
+	CASN1EncSequence* extn = NULL;
+
+	if (aRequest.Nonce())
+		{
+		extn = CASN1EncSequence::NewLC();
+
+		// OID
+		CASN1EncObjectIdentifier* oid = CASN1EncObjectIdentifier::NewLC(KOCSPOidNonce);
+		AddAndPopChildL(*extn, oid);
+		
+		// Skip Critical flag since we want default value FALSE and this is DER
+		
+		// Place nonce into extension
+		CASN1EncOctetString* value = CASN1EncOctetString::NewLC(*aRequest.Nonce());
+		AddAndPopChildL(*extn, value);
+		}
+		
+	return extn;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/response.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,116 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Object encapsulating the OCSP response - uses ASN1 encoding
+// 
+//
+
+
+#include "ocsp.h"
+#include "oids.h"
+#include "panic.h"
+#include "certid.h"
+
+#include <asn1dec.h>
+#include <x509cert.h>
+#include <x500dn.h>
+#include "ocsprequestandresponse.h"
+
+COCSPResponse::COCSPResponse()
+	{
+	}
+
+
+COCSPResponse::~COCSPResponse()
+	{
+	delete iArchiveCutoff;
+	iCertInfos.ResetAndDestroy();
+	}
+
+
+EXPORT_C TInt COCSPResponse::CertCount() const
+	{
+	return iCertInfos.Count();
+	}
+
+
+EXPORT_C const COCSPResponseCertInfo& COCSPResponse::CertInfo(TUint aIndex) const
+	{
+	return *iCertInfos[aIndex];
+	}
+
+
+const TPtrC8 COCSPResponse::SignedDataL() const
+	{
+	return iSignedData;	
+	}
+
+
+const TPtrC8* COCSPResponse::DataElementEncoding(const TUint aIndex) const
+	{
+	const TPtrC8* result = NULL;
+	
+	switch (aIndex)
+		{
+		case ECertificateChain:
+			result = iSigningCerts.Length() ? &iSigningCerts : NULL;
+			break;
+		case ENonce:
+			result = iNonce.Length() ? &iNonce : NULL;
+			break;
+		case EResponderIDName:
+			result = iResponderIDName.Length() ? &iResponderIDName : NULL;
+			break;
+		case EResponderIDKeyHash:
+			result = iResponderIDKeyHash.Length() ? &iResponderIDKeyHash : NULL;
+			break;
+		default:
+			Panic(KErrArgument);	
+		}
+
+	return result;
+	}
+
+
+void COCSPResponse::InternalizeL(RReadStream& /* aStream */)
+	{
+	Panic(KErrNotSupported);	
+	}
+
+
+EXPORT_C TTime COCSPResponse::ProducedAt() const
+	{
+	return iProducedAt;
+	}
+
+
+EXPORT_C const TTime* COCSPResponse::ArchiveCutoff() const
+	{
+	return iArchiveCutoff;
+	}
+
+
+TInt COCSPResponse::Find(const COCSPCertID& aCertID) const
+	{
+	TInt count = CertCount();
+	for (TInt index = 0; index < count; ++index)
+		{
+		const COCSPCertID& responseCertID = CertInfo(index).CertID();
+		if (responseCertID == aCertID)
+			{
+			return index;
+			}
+		}
+	
+	return KErrNotFound;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/responsecertinfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,167 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Implement response cert info object methods
+// 
+//
+
+#include "certid.h"
+#include <ocsp.h>
+
+#include <asn1dec.h>
+#include "ocsprequestandresponse.h"
+
+const TUint KNextUpdateTag = 0;
+const TUint KSingleExtensionsTag = 1;
+
+const TUint KGoodTag = 0;
+const TUint KRevokedTag = 1;
+const TUint KUnknownTag = 2;
+
+COCSPResponseCertInfo* COCSPResponseCertInfo::NewLC(CArrayPtr<TASN1DecGeneric>& aItems)
+	{
+	COCSPResponseCertInfo* self = new (ELeave) COCSPResponseCertInfo;
+	CleanupStack::PushL(self);
+	self->ConstructL(aItems);
+	return self;
+	}
+
+
+COCSPResponseCertInfo::~COCSPResponseCertInfo()
+	{
+	delete iNextUpdate;
+	delete iRevocationTime;
+	delete iCertID;
+	}
+
+
+EXPORT_C OCSP::TResult COCSPResponseCertInfo::Status() const
+	{
+	return iStatus;
+	}
+
+
+EXPORT_C TTime COCSPResponseCertInfo::ThisUpdate() const
+	{
+	return iThisUpdate;
+	}
+
+
+EXPORT_C const TTime* COCSPResponseCertInfo::NextUpdate() const
+	{
+	return iNextUpdate;
+	}
+
+
+EXPORT_C const TTime* COCSPResponseCertInfo::RevocationTime() const
+	{
+	return iRevocationTime;
+	}
+
+
+COCSPCertID& COCSPResponseCertInfo::CertID() const
+	{
+	return *iCertID;
+	}
+
+
+void COCSPResponseCertInfo::ConstructL(CArrayPtr<TASN1DecGeneric>& aItems)
+	{
+	// The CertID
+	iCertID = COCSPCertID::NewL(aItems.At(0)->Encoding());
+	
+	// The cert status - implicitly tagged
+	TASN1DecGeneric& statusDec = *aItems.At(1);
+	switch(statusDec.Tag())
+		{
+		case KGoodTag:
+			iStatus = OCSP::EGood;
+			break;
+		case KRevokedTag:
+			{
+			iStatus = OCSP::ERevoked;
+
+			// Get revocation time
+			TASN1DecSequence seqDec;
+			CArrayPtr<TASN1DecGeneric>* revokedInfo = seqDec.DecodeDERLC(statusDec, 1, 2);
+			TASN1DecGeneric& revocationTimeDec = *revokedInfo->At(0);
+			if (revocationTimeDec.Tag() != EASN1GeneralizedTime)
+				{
+				User::Leave(OCSP::EMalformedResponse);
+				}
+
+			TASN1DecGeneralizedTime decGT;
+			iRevocationTime = new (ELeave) TTime(decGT.DecodeDERL(revocationTimeDec));
+
+			CleanupStack::PopAndDestroy(revokedInfo);
+			break;
+			}
+		case KUnknownTag:
+			iStatus = OCSP::EUnknown;
+			break;
+		default:
+			User::Leave(OCSP::EMalformedResponse);
+		}
+		
+	// Carry on with thisUpdate
+	TASN1DecGeneralizedTime decGT;
+	iThisUpdate = decGT.DecodeDERL(*aItems.At(2));
+
+	// Optional bits...
+	TInt numItems = aItems.Count();
+	if (numItems > 3)
+		{
+		TInt nextItem = 3;
+
+		// Maybe nextUpdate is there too
+		TASN1DecGeneric& item4 = *aItems.At(3);
+		if (item4.Tag() == KNextUpdateTag)
+			{
+			++nextItem;
+			TASN1DecGeneralizedTime decGT;
+			TInt pos = 0;
+			iNextUpdate = new (ELeave) TTime (decGT.DecodeDERL(item4.GetContentDER(), pos));
+			}
+
+		// Check for extensions - we don't support any, but we need to leave if there are any marked 'critical'
+		if (nextItem < numItems)
+			{
+			TASN1DecGeneric& extnList = *aItems.At(nextItem);
+			if (extnList.Tag() == KSingleExtensionsTag)
+				{
+				// OK, we've got extensions, with an explicit tag.  Loop through them...
+				TASN1DecSequence decSeq;
+				TInt pos = 0;
+				CArrayPtr<TASN1DecGeneric>* extns = decSeq.DecodeDERLC(extnList.GetContentDER(), pos);
+				TInt numExts = extns->Count();
+				for (TInt extIndex = 0; extIndex < numExts; ++extIndex)
+					{
+					TASN1DecGeneric& ext = *extns->At(extIndex);
+					CArrayPtr<TASN1DecGeneric>* terms = decSeq.DecodeDERLC(ext);
+
+					// Check critical flag (may be absent - default value false
+					if (terms->Count() == 3)
+						{
+						TASN1DecBoolean boolDec;
+						if (boolDec.DecodeDERL(*terms->At(1)))
+							{
+							User::Leave(OCSP::EUnknownCriticalExtension);
+							}
+						}
+					CleanupStack::PopAndDestroy(); // Clean up 'terms'
+					}
+				CleanupStack::PopAndDestroy(); // Clean up 'extns'
+				}
+			}
+		}
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/responsedecoder.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,435 @@
+// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// requestencoder.cpp
+// Implementation for OCSP response decoder object.
+// See RFC2560 S4.2.1 for response specification.
+// 
+//
+
+#include "responsedecoder.h"
+#include "oids.h"
+#include <ocsp.h>
+#include <asn1dec.h>
+#include <x509cert.h>
+#include "ocsprequestandresponse.h"
+
+// Enum values in DER encoding of response status
+enum
+	{
+	ESuccessfulEncoding = 0,
+	EMalformedRequestEncoding = 1,
+	EInternalErrorEncoding = 2,
+	ETryLaterEncoding = 3,
+	ESigRequiredEncoding = 5,
+	EUnauthorisedEncoding = 6
+	};
+
+
+// Tag values in DER encoded response data
+const TUint KResponseBytesTag = 0;
+const TUint KCertificatesTag = 0;
+
+/** Version tag number in ResponseData, RFC2560, S4.2.1. */
+const TUint KOcspResponseVersionTag = 0;
+
+/**
+	Supported OCSP response Version, RFC2560, S4.2.1.
+	This is the integer value in Version, which means response
+	format version 1.
+ */
+const TUint KOcspResponseVersion1 = 0;
+
+const TUint KResponderIDNameTag = 1;
+const TUint KResponderIDKeyHashTag = 2;
+const TUint KResponseExtensionsTag = 1;
+
+
+COCSPResponseDecoder* COCSPResponseDecoder::NewL(const TDesC8& aEncoding)
+	{
+	COCSPResponseDecoder* self = new (ELeave) COCSPResponseDecoder;
+	CleanupStack::PushL(self);
+	self->ConstructL(aEncoding);
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+
+COCSPResponseDecoder::COCSPResponseDecoder()
+	{
+	}
+
+
+COCSPResponseDecoder::~COCSPResponseDecoder()
+	{
+	delete iResponse;
+	}
+
+
+void COCSPResponseDecoder::ConstructL(const TDesC8& aEncoding)
+	{
+	iResponse = new (ELeave) COCSPResponse;
+	
+	// Populate CSignedObject data members
+	iResponse->iKeyFactory = new (ELeave) TX509KeyFactory; // Unconventional class name
+	iResponse->iEncoding = aEncoding.AllocL();
+	
+	TRAPD(error, DecodeOCSPResponseL(aEncoding));
+	if (error == KErrArgument || error == KErrNotSupported)
+		{
+		// These arise from problems parsing the data in X509 or ASN1
+		error = OCSP::EMalformedResponse;
+		}
+	
+	if (error != KErrNone)
+		{
+		// Errors and our status codes go back to the client
+		delete iResponse;
+		iResponse = NULL;
+		User::Leave(error);
+		}
+	}
+
+
+COCSPResponse* COCSPResponseDecoder::TakeResponse()
+	{
+	COCSPResponse* result = iResponse;
+	iResponse = NULL;
+	return result;
+	}
+
+
+CArrayPtr<TASN1DecGeneric>* COCSPResponseDecoder::DecodeSequenceLC(const TDesC8& aEncoding)
+	{
+	CArrayPtr<TASN1DecGeneric>* items = NULL;
+	
+	// Check we've got a sequence
+	TASN1DecGeneric decGen(aEncoding);
+	decGen.InitL();
+	if (decGen.Tag() != EASN1Sequence)
+		{
+		User::Leave(KErrArgument);
+		}
+	else
+		{
+		// Decode the sequence		
+		TASN1DecSequence decSeq;
+		items = decSeq.DecodeDERLC(decGen);
+		}
+	return items;
+	}
+
+
+CArrayPtr<TASN1DecGeneric>* COCSPResponseDecoder::DecodeSequenceLC(const TDesC8& aEncoding,
+															const TInt aMinTerms,
+															const TInt aMaxTerms)
+	{
+	CArrayPtr<TASN1DecGeneric>* items = DecodeSequenceLC(aEncoding);
+	TInt count = items->Count();
+	if (count < aMinTerms || count > aMaxTerms)
+		{
+		User::Leave(KErrArgument);
+		}
+
+	return items;
+	}
+
+
+void COCSPResponseDecoder::DecodeOCSPResponseL(const TDesC8& aEncoding)
+	{
+	CArrayPtr<TASN1DecGeneric>* items = DecodeSequenceLC(aEncoding, 1, 2);
+	
+	// Use integer decoding for enumerated
+	TASN1DecInteger decInt;
+	TInt status = decInt.DecodeDERShortL(*items->At(0));
+	if (status == ESuccessfulEncoding)
+		{
+		if (items->Count() != 2)
+			{
+			User::Leave(OCSP::EMalformedResponse);
+			}
+		
+		// Check tag on second part is [0]
+		// We ignore any other parts in the sequence after that
+		TASN1DecGeneric& responseBytesDec = *items->At(1);
+		if (responseBytesDec.Tag() != KResponseBytesTag)
+			{
+			User::Leave(OCSP::EMalformedResponse);
+			}
+		
+		// It's OK, so decode the response bytes object therein
+		DecodeResponseBytesL(responseBytesDec.GetContentDER());
+		}
+	else
+		{
+		if (items->Count() != 1)
+			{
+			User::Leave(KErrArgument);
+			}
+		
+		switch (status)
+			{
+			case EMalformedRequestEncoding:
+				User::Leave(OCSP::EMalformedRequest);
+			case EInternalErrorEncoding:
+				User::Leave(OCSP::EServerInternalError);
+				break;
+			case ETryLaterEncoding:
+				User::Leave(OCSP::ETryLater);
+				break;
+			case ESigRequiredEncoding:
+				User::Leave(OCSP::ESignatureRequired);
+				break;
+			case EUnauthorisedEncoding:
+				User::Leave(OCSP::EClientUnauthorised);
+				break;
+			default:
+				User::Leave(OCSP::EMalformedResponse);
+			}
+		}
+		CleanupStack::PopAndDestroy(); // items
+	}
+
+
+void COCSPResponseDecoder::DecodeResponseBytesL(const TDesC8& aEncoding)
+	{
+	CArrayPtr<TASN1DecGeneric>* items = DecodeSequenceLC(aEncoding, 2, 2);
+
+	TASN1DecObjectIdentifier decOid;
+	HBufC* oid = decOid.DecodeDERL(*items->At(0));
+	CleanupStack::PushL(oid);
+	if (*oid != KOCSPOidBasic)
+		{
+		User::Leave(OCSP::EUnknownResponseType);
+		}
+
+	TASN1DecGeneric& response = *items->At(1);
+	if (response.Tag() != EASN1OctetString)
+		{
+		User::Leave(OCSP::EMalformedResponse);
+		}
+
+	DecodeBasicOCSPResponseL(response.GetContentDER());
+
+	CleanupStack::PopAndDestroy(2); // oid, items
+	}
+
+
+void COCSPResponseDecoder::DecodeBasicOCSPResponseL(const TDesC8& aEncoding)
+	{
+	CArrayPtr<TASN1DecGeneric>* items = DecodeSequenceLC(aEncoding, 3, 4);
+
+	// First, the ResponseData object
+	DecodeResponseDataL(items->At(0)->Encoding());
+
+	// Continue, with the AlgorithmIdentifier
+	iResponse->iSigningAlgorithm = CX509SigningAlgorithmIdentifier::NewL(items->At(1)->Encoding());
+	
+	// Now move on to the signature
+	TASN1DecBitString encBS;
+	iResponse->iSignature = encBS.ExtractOctetStringL(*items->At(2));
+	
+	// And finally, the certs (if they're there)
+	if (items->Count() == 4)
+		{
+		// Check explicit tag [0]
+		TASN1DecGeneric& certsDec = *items->At(3);
+		if (certsDec.Tag() != KCertificatesTag)
+			{
+			User::Leave(OCSP::EMalformedResponse);
+			}
+		
+		// It's OK, so decode the response bytes object therein
+		DecodeCertificatesL(certsDec.GetContentDER());
+		}
+
+	CleanupStack::PopAndDestroy(); // Cleans up items
+	}
+
+
+void COCSPResponseDecoder::DecodeCertificatesL(const TDesC8& aEncoding)
+	{
+	TASN1DecGeneric dec(aEncoding);
+	dec.InitL();
+	if (dec.Tag() != EASN1Sequence)
+		{
+		User::Leave(OCSP::EMalformedResponse);
+		}
+	
+	// Just stores a reference to the encoding
+	iResponse->iSigningCerts.Set(dec.GetContentDER());
+	}
+
+
+void COCSPResponseDecoder::DecodeResponseDataL(const TDesC8& aEncoding)
+	{
+	// This is the signed data
+	iResponse->iSignedData.Set(aEncoding);
+	
+	// version and responseExtensions are optional
+	CArrayPtr<TASN1DecGeneric>* items = DecodeSequenceLC(aEncoding, 3, 5);
+	
+	TInt seqIndex = 0;		// index of currently-parsed item
+	TASN1DecGeneric& item0 = *items->At(0);
+	
+	// If a version number is supplied, it must be the default version, v1,
+	// which is encoded as an integer with value zero.  (The version should
+	// not be sent at all if it has the default value - S11.5, ITU-Y X.690
+	// (07/2002) ASN.1 encoding rules - but some servers can still send it.)
+	if (item0.Class() == EContextSpecific && item0.Tag() == KOcspResponseVersionTag)
+		{
+		TASN1DecGeneric vDecGen(item0.GetContentDER());
+		vDecGen.InitL();
+		if (!(vDecGen.Class() == EUniversal && vDecGen.Tag() == EASN1Integer))
+			{
+			User::Leave(OCSP::EMalformedResponse);
+			}
+		
+		TASN1DecInteger vDecInt;
+		TInt version = vDecInt.DecodeDERShortL(vDecGen);
+		if (version != KOcspResponseVersion1)
+			{
+			User::Leave(OCSP::EMalformedResponse);
+			}
+		++seqIndex;
+		}
+	
+	TASN1DecGeneric& respIdDecGen = *items->At(seqIndex++);
+	switch (respIdDecGen.Tag())
+		{
+		case KResponderIDNameTag:
+			// Set to Name DER encoding
+			iResponse->iResponderIDName.Set(respIdDecGen.GetContentDER());
+			break;
+		case KResponderIDKeyHashTag:
+			{
+			// Set to KeyHash to value within the octet string
+			TASN1DecGeneric keyHashDecGen(respIdDecGen.GetContentDER());
+			keyHashDecGen.InitL();
+			iResponse->iResponderIDKeyHash.Set(keyHashDecGen.GetContentDER());
+			break;
+			}
+		default:
+			User::Leave(OCSP::EMalformedResponse);
+		}
+	
+	
+	// ProducedAt is a GeneralizedTime
+	TASN1DecGeneralizedTime decGT;
+	iResponse->iProducedAt = decGT.DecodeDERL(*items->At(seqIndex++));
+	
+	// Now the responses themselves
+	DecodeResponsesL(items->At(seqIndex++)->Encoding());
+	
+	// Continue if extensions exist
+	if (seqIndex < items->Count())
+		{
+		// Check tag on responseExtensions
+		TASN1DecGeneric& extDecGen = *items->At(seqIndex++);
+		if (extDecGen.Tag() != KResponseExtensionsTag)
+			{
+			User::Leave(OCSP::EMalformedResponse);
+			}
+		
+		DecodeResponseExtensionsL(extDecGen.GetContentDER());
+		}
+	CleanupStack::PopAndDestroy(items);
+	}
+
+
+void COCSPResponseDecoder::DecodeResponseExtensionsL(const TDesC8& aEncoding)
+	{
+	CArrayPtr<TASN1DecGeneric>* items = DecodeSequenceLC(aEncoding);
+	TInt count = items->Count();
+	for (TInt index = 0; index < count; ++index)
+		{
+		DecodeResponseExtensionL(items->At(index)->Encoding());
+		}
+	
+	CleanupStack::PopAndDestroy(); // items
+	}
+
+
+void COCSPResponseDecoder::DecodeResponseExtensionL(const TDesC8& aEncoding)
+	{
+	CArrayPtr<TASN1DecGeneric>* items = DecodeSequenceLC(aEncoding, 2, 3);
+	
+	// Get oid
+	TASN1DecGeneric& oid = *items->At(0);
+	if (oid.Tag() != EASN1ObjectIdentifier)
+		{
+		User::Leave(OCSP::EMalformedResponse);
+		}
+	
+	TASN1DecObjectIdentifier oidDec;
+	HBufC* oidVal = oidDec.DecodeDERL(oid);
+	CleanupStack::PushL(oidVal);
+	
+	TBool critical = EFalse; // Default value of critical flag
+	if (items->Count() == 3)
+		{
+		// The critical flag is specified - what does it say?
+		TASN1DecBoolean decBool;
+		critical = decBool.DecodeDERL(*items->At(1));
+		}
+	
+	TASN1DecGeneric& extnVal = items->Count() == 3 ? *items->At(2) : *items->At(1);
+	if (extnVal.Tag() != EASN1OctetString)
+		{
+		User::Leave(OCSP::EMalformedResponse);
+		}
+	
+	// Check oid to decide what to do
+	if (*oidVal == KOCSPOidNonce)
+		{
+		iResponse->iNonce.Set(extnVal.GetContentDER());
+		}
+	else if (*oidVal == KOCSPOidArchiveCutoff)
+		{
+		TASN1DecGeneralizedTime decGT;
+		TInt pos = 0;
+		iResponse->iArchiveCutoff = new (ELeave) TTime(decGT.DecodeDERL(extnVal.GetContentDER(), pos));
+		}
+	else if (critical)
+		{
+		// Didn't understand extension, and it was critical!  Erk!
+		User::Leave(OCSP::EUnknownCriticalExtension);
+		}
+	
+	CleanupStack::PopAndDestroy(2); // oidVal, items
+	}
+
+
+void COCSPResponseDecoder::DecodeResponsesL(const TDesC8& aEncoding)
+	{
+	CArrayPtr<TASN1DecGeneric>* items = DecodeSequenceLC(aEncoding);
+	TInt count = items->Count();
+	for (TInt index = 0; index < count; ++index)
+		{
+		DecodeSingleResponseL(items->At(index)->Encoding());
+		}
+
+	CleanupStack::PopAndDestroy(); // items
+	}
+
+
+void COCSPResponseDecoder::DecodeSingleResponseL(const TDesC8& aEncoding)
+	{
+	CArrayPtr<TASN1DecGeneric>* items = DecodeSequenceLC(aEncoding, 3, 5);
+
+	COCSPResponseCertInfo* response = COCSPResponseCertInfo::NewLC(*items);
+	User::LeaveIfError(iResponse->iCertInfos.Append(response));
+	CleanupStack::Pop(response); // Now owned through iSingleResponses
+
+	CleanupStack::PopAndDestroy(); // Clean up items
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/transaction.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,186 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Implementation for OCSP Transaction object.
+// 
+//
+
+#include "transaction.h"
+#include "requestencoder.h"
+#include "responsedecoder.h"
+#include "ocsp.h"
+#include "panic.h"
+
+#include <x509cert.h>
+#include <x509certchain.h>
+
+COCSPTransaction* COCSPTransaction::NewL(const TDesC8& aURI, 
+										 MOCSPTransport& aTransport, const TUint aRetryCount, const TInt aTimeout)
+	{
+	COCSPTransaction* self = new (ELeave) COCSPTransaction(aTransport, aRetryCount, aTimeout);
+	CleanupStack::PushL(self);
+	self->ConstructL(aURI);
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+COCSPTransaction::COCSPTransaction(MOCSPTransport& aTransport, const TUint aRetryCount, const TInt aTimeout) :
+	CActive(EPriorityNormal),
+	iTransport(aTransport),
+	iRetryCount(aRetryCount),
+	iTimeout(aTimeout)
+	{
+	CActiveScheduler::Add(this);
+	}
+
+
+void COCSPTransaction::ConstructL(const TDesC8& aURI)
+	{
+	iURI = aURI.AllocL();
+	}
+
+
+COCSPTransaction::~COCSPTransaction()
+	{
+	Cancel();
+	delete iURI;
+	delete iRequestEncoder;
+	delete iResponseDecoder;
+	}
+
+
+// Create the request, then send it off
+void COCSPTransaction::SendRequest(COCSPRequest& aRequest, TRequestStatus& aStatus)
+	{
+	__ASSERT_ALWAYS(!iRequest, Panic(KErrInUse));
+	iClientRequestStatus = &aStatus;
+	aStatus = KRequestPending;
+
+	iRequest = &aRequest;
+	iState = ESendRequest;
+	SetActive();
+
+	TRequestStatus* status = &iStatus;
+	User::RequestComplete(status, KErrNone);
+	}
+
+
+// Safe regardless of whether we have a request outstanding
+void COCSPTransaction::CancelRequest()
+	{
+	Cancel();
+	}
+
+
+COCSPResponse* COCSPTransaction::TakeResponse()
+	{
+	__ASSERT_ALWAYS(iResponseDecoder, Panic(KErrNotReady));
+	return iResponseDecoder->TakeResponse();
+	}
+
+
+void COCSPTransaction::CompleteClient(const TInt aStatus)
+	{
+	User::RequestComplete(iClientRequestStatus, aStatus);
+	}
+
+
+void COCSPTransaction::RunL()
+	{
+	TInt err = iStatus.Int();
+	switch (iState)
+		{
+		case ESendRequest:
+			__ASSERT_ALWAYS(err == KErrNone, Panic(KErrCorrupt));
+			iRequestEncoder = COCSPRequestEncoder::NewL(*iRequest);
+			iTransport.SendRequest(*iURI, iRequestEncoder->Encoding(), iTimeout, iStatus);
+			iState = EFinished;
+			SetActive();			  
+			break;
+
+		case EFinished:
+			{
+			// Depending on the error retry the request
+			// Retry if
+			// 		- More attempts remaining AND 
+			//		- error is OCSP::KErrTransportTimeout OR
+			// 		- error is OCSP::KErrTransportFailure (HTTP response malformed) OR
+			//		- invalid response received (OCSPReponse malformed) OR 
+			//		- OCSPResponseStatus is OCSP::EServerInternalError OR
+			//		- OCSPResponseStatus is OCSP::ETryLater
+			//
+			// We won't retry if 
+			//		- error is OCSP::KErrInvalidURI OR
+			//		- error is OCSP::KErrServerNotFound
+
+			TBool retryNeeded = EFalse;
+			TInt errDecode = KErrNone;
+			if ((err == OCSP::KErrTransportTimeout) || (err == OCSP::KErrTransportFailure))
+				{
+				retryNeeded = ETrue;
+				}
+			else if (err == KErrNone)
+				{
+				TRAP(errDecode, iResponseDecoder = COCSPResponseDecoder::NewL(iTransport.GetResponse()));
+				if ((errDecode == OCSP::EMalformedResponse) || 
+						(errDecode == OCSP::EServerInternalError) || (errDecode == OCSP::ETryLater))
+					{
+					retryNeeded = ETrue;
+					}
+				}
+
+			--iRetryCount;
+			if (retryNeeded && iRetryCount > 0)
+				{
+				__ASSERT_ALWAYS(iResponseDecoder == NULL, Panic(KErrCorrupt));
+				iTransport.SendRequest(*iURI, iRequestEncoder->Encoding(), iTimeout, iStatus);
+				SetActive();
+				}
+			else
+				{
+				// If retry is not needed and there was an error (including +ve) then pass it up else complete normally
+				if (err != KErrNone)
+					{
+					User::Leave(err);
+					}
+				if (errDecode != KErrNone)
+					{
+					User::Leave(errDecode);
+					}
+				CompleteClient(KErrNone);
+				}
+			}
+			break;
+
+		default:
+			Panic(KErrCorrupt);
+		}
+	}
+
+
+TInt COCSPTransaction::RunError(TInt aError)
+	{
+	CompleteClient(aError);
+	return KErrNone;
+	}
+
+
+void COCSPTransaction::DoCancel()
+	{
+	iTransport.CancelRequest();
+	if (iClientRequestStatus)
+		{
+		CompleteClient(KErrCancel);
+		}
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/src/validator.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,556 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Define methods for validating a response.
+// 
+//
+
+#include "validator.h"
+#include "ocsp.h"
+#include "panic.h"
+#include "transaction.h"
+#include <x509cert.h>
+
+// We allow a certain amount of leeway when checking times.  This specifies the
+// default value.
+const TInt KDefaultLeewaySeconds = 5 * 60; // 5 minutes
+
+// The spec says we must check that the thisUpdate field is "sufficiently
+// recent".  This specifies the default value for the maximum age we tolerate
+// (in seconds).
+const TInt KDefaultMaxStatusAge = 30 * 24 * 60 * 60; // 30 days
+
+COCSPValidator* COCSPValidator::NewL( const COCSPParameters& aParameters)
+	{
+	COCSPValidator* self = new (ELeave) COCSPValidator(aParameters);
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	CleanupStack::Pop(self);
+	CActiveScheduler::Add(self);
+	return self;
+	}
+
+
+COCSPValidator::~COCSPValidator()
+	{
+	Cancel();
+
+	iAuthorisationScheme.Close();
+	iRequestIndex.Close();
+	
+	delete iValidationTime;
+	delete iResponderCertRequest;
+	delete iResponderCertResponse;
+	delete iTransaction;
+	}
+
+
+COCSPValidator::COCSPValidator( const COCSPParameters& aParameters) :
+	CActive(CActive::EPriorityStandard),
+	iMaxStatusAge(KDefaultMaxStatusAge),
+	iLeewaySeconds(KDefaultLeewaySeconds),
+	iResponderCertCheck(EFalse),
+	iUseNonce(ETrue),
+	iParameters(&aParameters)
+	{}
+
+void COCSPValidator::ConstructL() 
+	{
+	for (TUint j = 0 ; j < iParameters->AuthSchemeCount() ; ++j)
+		{
+		User::LeaveIfError(iAuthorisationScheme.Append(&iParameters->AuthScheme(j)));
+		}
+	if (iParameters->ValidationTime())
+		{
+		iValidationTime = new (ELeave) TTime(*iParameters->ValidationTime());
+		}
+	if (iParameters->MaxStatusAge())
+		{
+		iMaxStatusAge = *iParameters->MaxStatusAge();
+		}
+	if (iParameters->TimeLeeway())
+		{
+		iLeewaySeconds = *iParameters->TimeLeeway();
+		}
+	iResponderCertCheck = iParameters->ReponderCertCheck();
+	iUseNonce = iParameters->UseNonce();
+	}
+
+void COCSPValidator::Validate(const COCSPRequest& aRequest, COCSPResponse& aResponse,
+									   TOCSPOutcome& aOutcome, TRequestStatus& aStatus)
+	{
+    TRAPD(err, DoValidateL(aRequest, aResponse, aOutcome, aStatus));
+    
+    if (err != KErrNone)
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete(status, err);
+        }
+	}
+
+void COCSPValidator::DoValidateL(const COCSPRequest& aRequest, COCSPResponse& aResponse,
+								 TOCSPOutcome& aOutcome, TRequestStatus& aStatus)
+	{
+	iRequest = &aRequest;
+	iResponse = &aResponse;
+
+	iValidationStatus = &aStatus;
+	aStatus = KRequestPending;
+
+	iOutcome = &aOutcome;
+	iOutcome->iStatus = OCSP::EClientInternalError;
+	// this has been set to EUnknown at client side, but still making sure that this 
+	// value is being used.
+	iOutcome->iResult = OCSP::EUnknown;
+	
+	if ( !IsResponseWellFormed())
+		{
+		User::RequestComplete(iValidationStatus, KErrNone);
+		return;
+		}
+	
+	// points to the current scheme being used for validation of the certificate
+	// in question.
+	iIndexScheme = -1;
+	ProcessSchemeValidationL();
+	}
+
+TBool COCSPValidator::IsResponseWellFormed()
+	{
+	// Check the certificates in the response were indeed those we asked for
+	// Make lookup table indexing request/response while we're at it
+
+	TInt numResponseCerts = iResponse->CertCount();
+	TInt numRequestCerts = iRequest->CertCount();
+
+	if (numRequestCerts < numResponseCerts)
+		{
+		iOutcome->iStatus = OCSP::EMalformedResponse;
+		return EFalse;
+		}
+	else if (numRequestCerts > numResponseCerts)
+		{
+		iOutcome->iStatus = OCSP::EMissingCertificates;
+		return EFalse;
+		}
+	
+	// Check each cert to verify that each request has a corresponding response present.
+	// In process, set up array giving the position in the request of each cert in the response
+	iRequestIndex.Reset();
+		
+	for (TInt requestIndex = 0; requestIndex < numRequestCerts; ++requestIndex)
+		{
+		// This is what we're after
+		const COCSPCertID& requestCertID = iRequest->CertInfo(requestIndex).CertID();
+
+		// This is where it is in the response
+		TInt responseIndex = iResponse->Find(requestCertID);
+
+		if (responseIndex < 0)
+			{
+			iOutcome->iStatus = OCSP::EMissingCertificates;
+			return EFalse;
+			}
+		iRequestIndex.Append(responseIndex);
+		}
+	// All found
+	return ETrue;
+	}
+
+void COCSPValidator::ProcessSchemeValidationL()
+	{
+	TInt count = iAuthorisationScheme.Count();
+	__ASSERT_ALWAYS(count, Panic(KErrNoAuthorisationSchemes));
+	if (++iIndexScheme < count)
+		{
+		iSchemeInUse = iAuthorisationScheme[iIndexScheme];
+		TTime validationTime = ValidationTime();
+		iSchemeInUse->ValidateL(iOutcome->iStatus, *iResponse, validationTime, iStatus, *iRequest);
+		iState = EWaitingResponse;
+		SetActive();
+		}
+	else
+		{
+		User::RequestComplete(iValidationStatus, KErrNone);
+		}
+	}
+
+// Get status of least trusted cert
+void COCSPValidator::FinalResponseValidationL()
+	{
+	// Do nonce last so can still trust rest of validation if nonce is missing.
+	if(ValidateTimeL())
+		{
+		ValidateNonce();
+		}
+	
+	if (iOutcome->iStatus == OCSP::EMissingNonce || 
+		iOutcome->iStatus == OCSP::EValid )
+		{
+		iOutcome->iResult = CheckOCSPStatus(iResponse);
+		}
+	else
+		{
+		// If the response is not valid, result is always unknown
+		iOutcome->iResult = OCSP::EUnknown;
+		}
+	
+	if(iResponderCertCheck)
+		{
+		iResponderCert = iSchemeInUse->ResponderCert();
+	 	
+	 	if(iResponderCert != NULL)
+	 		{
+	 		iIssuerCert = &iRequest->CertInfo(0).Issuer();
+	 		SendResponderCertL();
+	 		}
+	 	else
+			{
+			User::RequestComplete(iValidationStatus, KErrNone);
+			}
+		}
+	else
+		{
+		User::RequestComplete(iValidationStatus, KErrNone);
+		}
+	}
+
+TBool COCSPValidator::ValidateTimeL()
+	{
+	const TTime validationTime = ValidationTime();
+	const TTime producedAt = iResponse->ProducedAt();
+	
+	// For each certificate request, do the following:
+	// 1. Check thisUpdate
+	// 2. Check producedAt 
+	TInt numCerts = iRequest->CertCount();
+	for (TInt requestIndex = 0; requestIndex < numCerts; ++requestIndex)
+		{
+		const COCSPResponseCertInfo& responseCertInfo = iResponse->CertInfo(iRequestIndex[requestIndex]);
+		const TTime thisUpdate = responseCertInfo.ThisUpdate();
+		const TTime* nextUpdate = responseCertInfo.NextUpdate();
+
+		// Check validity interval of response includes validation time
+		// and producedAt time (if different).  Give iLeewaySeconds second's lee-way.
+
+		// 4.2.2.1 "Responses whose thisUpdate time is later than the local
+		// system time SHOULD be considered unreliable"
+		if (TimeIsBeforeL(validationTime, thisUpdate))
+			{
+			iOutcome->iStatus = OCSP::EThisUpdateTooLate;
+			return EFalse;
+			}
+
+		// Check producedAt later than thisUpdate.  This is not mandated by the spec.
+		if (TimeIsBeforeL(producedAt, thisUpdate))
+			{
+			iOutcome->iStatus = OCSP::EThisUpdateTooLate;
+			return EFalse;
+			}
+		
+		if (nextUpdate)
+			{
+			// 4.2.2.1 "Responses whose nextUpdate value is earlier than the
+			// local system time value SHOULD be considered unreliable"
+			// 3.2.6 "OCSP clients shall confirm that ... nextUpdate is greater
+			// than the current time."
+			if (TimeIsBeforeL(*nextUpdate, validationTime))
+				{
+				iOutcome->iStatus = OCSP::ENextUpdateTooEarly;
+				return EFalse;
+				}
+
+			// Check nextUpdate later than producedAt.  This is not mandated by the spec.
+			if (TimeIsBeforeL(*nextUpdate, producedAt))
+				{
+				iOutcome->iStatus = OCSP::ENextUpdateTooEarly;
+				return EFalse;
+				}
+			}
+		
+		// 3.2.5 "OCSP clients SHALL confirm that ... thisUpdate is sufficiently
+		// recent"
+		if (iMaxStatusAge)
+			{
+			TTimeIntervalSeconds difference;
+
+			User::LeaveIfError(validationTime.SecondsFrom(thisUpdate, difference));
+			const TTimeIntervalSeconds maxUpdateAge(iMaxStatusAge + iLeewaySeconds);	
+			if (difference > maxUpdateAge)
+				{
+				iOutcome->iStatus = OCSP::EThisUpdateTooEarly;
+				return EFalse;
+				}	
+			}
+
+		// Check certificate validity period against validation time.
+		// 
+		// Strictly speaking, the OCSP protcol is about checking revocation
+		// rather then checking whether a certificate has just expired.
+		// However, it's difficult to check this on a device when you don't have
+		// an accurate value for the current time.  We do the check here for
+		// completeness, and trust the time given to us by the ocsp server.  If
+		// we are using a nonce, as we will be most of the time, we can
+		// guarantee that the producedAt time is current.
+
+		const CX509Certificate& cert = iRequest->CertInfo(requestIndex).Subject();
+		const CValidityPeriod& validityPeriod = cert.ValidityPeriod();
+
+		if (!validityPeriod.Valid(validationTime))
+			{
+			iOutcome->iStatus = OCSP::ECertificateNotValidAtValidationTime;
+			return EFalse;
+			}
+
+		} // Continue with next cert
+
+	// If we've got this far, we're fine
+	return ETrue;
+	}
+
+TBool COCSPValidator::ValidateNonce()
+	{
+	const TDesC8* requestNonce = iRequest->Nonce();
+	const TPtrC8* responseNonce = iResponse->DataElementEncoding(COCSPResponse::ENonce);
+	
+	if (requestNonce)
+		{
+		if (responseNonce)
+			{
+			if (*requestNonce == *responseNonce)
+				{
+				return ETrue;
+				}
+			else
+				{
+				iOutcome->iStatus = OCSP::ENonceMismatch;
+				return EFalse;
+				}
+			}
+		else
+			{
+			iOutcome->iStatus = OCSP::EMissingNonce;
+			return EFalse;
+			}
+		}
+	else
+		{
+		if (responseNonce)
+			{
+			// Shouldn't have a nonce!
+			iOutcome->iStatus = OCSP::EMalformedResponse;
+			return EFalse;
+			}
+		else
+			{
+			// No nonces - fine
+			return ETrue;
+			}
+		}
+	}
+
+// Return true if first argument is iLeewaySeconds or more before the second
+// argument.  Hence it is conservative, and should be always used "positively"
+// to check for error conditions.
+TBool COCSPValidator::TimeIsBeforeL(const TTime& aBefore, const TTime& aAfter)
+	{
+	TTimeIntervalSeconds difference;
+	const TTimeIntervalSeconds leeway(iLeewaySeconds);	
+
+	User::LeaveIfError(aAfter.SecondsFrom(aBefore, difference));
+	return (difference > leeway);
+	}
+
+void COCSPValidator::RunL()
+	{
+	User::LeaveIfError(iStatus.Int());
+
+	switch (iState)
+		{
+	case EWaitingResponse:
+		CheckSchemeValidationL();
+		break;
+	case EValidating:
+		ProcessSchemeValidationL();
+		break;
+	case EValidateResponderCert:
+		ValidateResponderCertL();
+		break;
+	default:
+		ASSERT(FALSE);
+		}
+	}
+
+void COCSPValidator::DoCancel()
+	{
+	TInt count = iAuthorisationScheme.Count();
+	__ASSERT_ALWAYS(count, Panic(KErrNoAuthorisationSchemes));
+	if (iState == EWaitingResponse)
+		{
+		ASSERT(iSchemeInUse != NULL);
+		iSchemeInUse->CancelValidate();
+		}
+	User::RequestComplete(iValidationStatus, KErrCancel);
+	}
+
+TInt COCSPValidator::RunError(TInt aError)
+	{
+	User::RequestComplete(iValidationStatus, aError);
+	return KErrNone;
+	}
+
+void COCSPValidator::CheckSchemeValidationL()
+	{
+	// If any scheme says it's OK, we're happy, otherwise we'll return
+	// with whatever the last scheme said.
+	if (iOutcome->iStatus == OCSP::EValid)
+		{
+		FinalResponseValidationL();
+		}
+	else
+		{
+		iState = EValidating;
+		// Fire off AO
+		TRequestStatus* status = &iStatus;
+		User::RequestComplete(status, KErrNone);
+		SetActive();
+		}
+	}
+
+TTime COCSPValidator::ValidationTime() const
+	{
+	__ASSERT_ALWAYS(iResponse, Panic(KErrNotReady));
+	if (iValidationTime)
+		{
+		return *iValidationTime;
+		}
+	else
+		{
+		TTime gmt;
+		
+		// if secure time is not available then fall back to the insecure version.
+		if(gmt.UniversalTimeSecure() == KErrNoSecureTime)
+			{
+			gmt.UniversalTime();
+			}
+		return gmt;
+		}
+	}
+
+/**
+ * For the response in question there can be more than one authentication scheme initialized.
+ * We need to find out whether the schemes initialized contain at least delegate or direct auth scheme,
+ * if any of them is present we can send the request for validation for responder certificate, as 
+ * validation of responder certificate should only work for these 2 schemes.
+ * 
+ * If we get a valid scheme, following would be the sequence of operation:
+ * 1. Retrieve the responder certificate and the issuer(should be the CA who issued the certificate
+ * in question) who has issued the responder certificate.
+ * 2. Check whether the responder certificate contains the id-pkix-ocsp-nocheck, if present there is no need for 
+ * 	 sending it for OCSP check, if not present send it for OCSP check.
+ 
+ * Send the responder certificate for OCSP checking. Here we would use the existing parameters
+ * for creating the responder certificate request, as this check is an extension of the original 
+ * certificate OCSP check.
+ */
+ void COCSPValidator::SendResponderCertL()
+ 	{
+ 	if( OCSPUtils::DoesCertHaveOCSPNoCheckExt(*iResponderCert))
+ 		{
+ 		User::RequestComplete(iValidationStatus, KErrNone);
+ 		return;
+ 		}
+ 	
+ 	iResponderCertRequest = COCSPRequest::NewL(iUseNonce);
+ 	iResponderCertRequest->AddCertificateL(*iResponderCert, *iIssuerCert);
+ 	 	
+ 	// Only add further requests if there is:
+ 	// a URI (either AIA URI or default URI) 
+ 	TDesC8* uri = NULL;
+ 	TRAPD(error, uri = OCSPUtils::ServerUriL(iResponderCertRequest->CertInfo(0).Subject(),iParameters));
+ 
+	if(error == KErrArgument)
+ 		{
+		iOutcome->iStatus = OCSP::ENoServerSpecified;
+		TRequestStatus* status = &iStatus;
+		User::RequestComplete(status, OCSP::ENoServerSpecified);
+		iState = EValidateResponderCert;
+	 	SetActive();
+	 	return;
+ 		}
+	
+	User::LeaveIfError(error);
+	CleanupStack::PushL(uri);
+ 	
+ 	// if state is valid it means that uri has been retrieved.
+	__ASSERT_ALWAYS(uri != NULL, Panic(OCSP::EInvalidURI));
+	MOCSPTransport& transport = *iParameters->Transport();
+	delete iTransaction;
+	iTransaction = NULL;
+	iTransaction = COCSPTransaction::NewL(*uri, transport, iParameters->RetryCount(), iParameters->Timeout());
+	iTransaction->SendRequest(*iResponderCertRequest, iStatus);
+	CleanupStack::PopAndDestroy(uri);
+	iState = EValidateResponderCert;
+ 	SetActive();
+ 	}
+
+ /**
+  * Receive the response for responder certificate OCSP check.
+  * Leave if there is any problem with the received response.
+  * If the response is well formed then send it for further validation.
+  */
+ void COCSPValidator::ValidateResponderCertL()
+ 	{
+ 	TInt status = iStatus.Int();
+ 	
+ 	if (status == KErrNone)
+ 		{
+ 		iResponderCertResponse = iTransaction->TakeResponse();
+ 		}
+ 	else if (status == OCSP::KErrTransportFailure)
+ 		{
+ 		User::Leave(OCSP::ETransportError);
+ 		}
+ 	else if (status == OCSP::KErrInvalidURI)
+ 		{
+ 		User::Leave(OCSP::EInvalidURI);
+ 		}
+ 	else
+ 		{
+ 		User::Leave(status);		   
+ 		}
+	
+ 	iOutcome->iResult = CheckOCSPStatus(iResponderCertResponse);
+ 	if(iOutcome->iResult != OCSP::EGood )
+ 		{
+ 		// as the responder certificate is either revoked or unknown the final status returned
+ 		// should be unknown.
+ 		iOutcome->iResult = OCSP::EUnknown;
+ 		}
+ 	User::RequestComplete(iValidationStatus, KErrNone);
+ 	
+ 	}
+
+ OCSP::TResult COCSPValidator::CheckOCSPStatus(const COCSPResponse* aResponse) const
+	{
+	OCSP::TResult result = OCSP::EGood;
+	TInt numCerts = aResponse->CertCount();
+	for (TInt index = 0; index < numCerts; ++index)
+		{
+		const COCSPResponseCertInfo& info = aResponse->CertInfo(index);
+	
+		OCSP::TResult certStatus = info.Status();
+		result = certStatus > result? certStatus : result;
+		}
+	return result;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/TEFparser.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,356 @@
+//
+// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+
+#include <s32file.h>
+#include "bautils.h" 
+#include "TEFparser.h"
+#include "utf.h" 
+
+_LIT(KReturn, "\r");
+_LIT(KNewline, "\n");
+_LIT(KOpenBrk, "[");
+_LIT(KCloseBrk, "]");
+_LIT(KSpace, " ");
+_LIT(KTab, "\t");
+
+_LIT(KIniExtension, ".ini");
+_LIT(KScriptFile, ".script");
+_LIT(KDot, ".");
+
+#define KIniSectionIdLength 512
+
+
+EXPORT_C TBool TEFparser::FileType(const TDesC& aBuf)
+	{
+	
+	TInt pos1 = aBuf.Find(KDot);
+	
+	TPtrC fileType = aBuf.Mid(pos1);
+	
+	if(fileType == KScriptFile)
+		{
+		return ETrue;
+		}
+	else
+		{
+		return EFalse;
+		}
+	}
+
+EXPORT_C TInt TEFparser::ReadFileLC(RFs& aFs, 
+										const TDesC& aScriptFilepath,
+										TPtrC& aScriptFileContents )
+	{
+	
+	RFile scriptFile;
+	TInt err = scriptFile.Open(aFs, aScriptFilepath, EFileStream | EFileRead | EFileShareAny);
+	if (err != KErrNone)
+		{	
+		return KErrNotFound;
+		}
+	// gets size of ini file
+	TInt size;
+	scriptFile.Size(size);
+	scriptFile.Close();
+			
+	// reads ini into iTestInput
+	HBufC* scriptFileH16 = HBufC::NewLC(size);
+	HBufC8* scriptFileH = HBufC8::NewLC(size);
+	
+	//RBuf scriptFileR;
+	TPtr8 pInput = scriptFileH->Des(); 
+	TPtr pInput16 = scriptFileH16->Des(); 
+	
+	pInput.SetLength(size); 
+	
+	RFileReadStream stream;
+	User::LeaveIfError(stream.Open(aFs, aScriptFilepath, EFileStream | EFileRead | EFileShareReadersOnly));
+	CleanupClosePushL(stream);
+	stream.ReadL(pInput,size);
+	
+//	stream.ReadL(pInput, size);
+	
+	pInput16.Copy(pInput);
+	//scriptFileR.Assign(scriptFileH16);
+	
+	aScriptFileContents.Set(*scriptFileH16);
+	
+	CleanupStack::PopAndDestroy(2); // stream, testInput
+	
+	return KErrNone;
+	}
+
+EXPORT_C TPtrC TEFparser::GetRunTestStep(TPtrC& aBuf, 
+									const TDesC& aTag,
+									TInt& aPos,
+									TInt& aError)
+	{
+	TInt endPos = 0;
+	TInt startPos = 0;
+	TInt tempPos = 0;
+	
+	TPtrC data = aBuf.Mid(aPos);
+	
+	tempPos = data.Find(aTag);
+	
+	if (tempPos != KErrNotFound)
+		{
+		tempPos += aTag.Length();
+//			
+		TPtrC temprunStepData = data.Mid(tempPos);		
+//		
+		endPos = temprunStepData.Find(KNewline);
+		if (endPos == KErrNotFound)
+			{
+			endPos = temprunStepData.Find(KReturn);
+			}
+		if (endPos == KErrNotFound)
+			{
+			endPos = temprunStepData.Length();
+			}
+//		
+		TInt len = 0;
+		len = (endPos - startPos) + 1;
+		TPtrC runStepData = temprunStepData.Mid(startPos,len);
+		aPos += tempPos + runStepData.Length();
+		aError = KErrNone;
+		return Trim(runStepData);
+		}
+	else
+		{
+		aError = KErrNotFound;
+		return TPtrC();
+		}
+
+	}
+
+EXPORT_C TPtrC TEFparser::Trim(const TDesC& aBuf)
+	{
+	TInt startPos = 0;
+	TInt endPos = 0;
+	TInt i = 0, j = 0;
+		
+	for(i = 0; i < aBuf.Length() ; i ++)
+		{
+		TPtrC tmpChar = aBuf.Mid(i,1);
+		if(tmpChar != KSpace && tmpChar != KTab && tmpChar != KReturn && tmpChar != KNewline )
+			{
+			startPos = i;
+			break;
+			}
+		}
+	for(j = aBuf.Length()-1; j >= 0 ; j --)
+		{
+		TPtrC tmpChar1 = aBuf.Mid(j,1);
+		if(tmpChar1 != KSpace && tmpChar1 != KTab && tmpChar1 != KReturn && tmpChar1 != KNewline )
+			{
+			endPos = j;
+			break;
+			}
+		}
+	if(endPos < startPos)
+		{
+		endPos = aBuf.Length();
+		}
+	
+//	TInt len = aBuf.Length() - (startPos + endPos);
+	return aBuf.Mid(startPos, endPos - startPos + 1);
+	
+	}
+
+EXPORT_C TInt TEFparser::GetIniFileInfo(TDesC& aBuf, 
+											  TPtrC& aIniFileName, 
+											  TPtrC& aIniSectionName)
+	{
+	TInt pos =0;
+	TInt startPos = 0, endPos = 0;
+	
+	
+	TPtrC temp = aBuf.Mid(pos);
+	
+	endPos = temp.Find(KIniExtension);
+	endPos += 4;
+	
+	if (endPos != KErrNotFound)
+		{
+		TInt len = endPos - startPos;
+		TPtrC iniFileName = temp.Mid(startPos, len);
+		aIniFileName.Set(iniFileName);
+		
+		TPtrC iniSectionName = temp.Mid(iniFileName.Length());
+		aIniSectionName.Set(Trim(iniSectionName));
+		
+		return KErrNone;
+		}
+	else
+		{
+		return KErrNotFound;
+		}
+	
+	}
+
+EXPORT_C TInt TEFparser::GetiniPath( TDesC& aBuf, 
+									const TDesC& aScriptPath,
+									TDes& aIniFilePath)
+	{
+	
+	TInt err = KErrNone;	
+	TInt endPos = aScriptPath.LocateReverse('\\');
+	if (endPos == KErrNotFound)
+		{
+		err = KErrNotFound;
+		}
+	else
+		{
+		aIniFilePath.Copy(aBuf);
+		aIniFilePath.Insert(0, aScriptPath.Left(endPos+1));
+		}
+	return err;
+	}
+
+EXPORT_C TInt TEFparser::GetSectionData(TDesC& aScriptFilepath, TPtrC& aSectiontag, TDesC16 &aTocspTestFile, RFs& aFs)
+	{
+	
+	TInt err = KErrNone;	
+	TInt pos = 0;
+	RFile file;
+	
+	// open the .ini file
+	if (BaflUtils::FolderExists(aFs, aScriptFilepath))
+		{		
+		if (BaflUtils::FileExists( aFs, aScriptFilepath ))
+			{	
+			file.Open(aFs, aScriptFilepath, EFileRead | EFileShareAny);
+			
+			TFileText aLineReader;
+			TBuf<256> iLine;
+			TBuf<256> tempsectID;
+
+			// create the section name to search for
+			tempsectID.Copy(KOpenBrk);
+			tempsectID.Append(aSectiontag);
+			tempsectID.Append(KCloseBrk);
+			
+			// read the ini file a line at a time until you find the the section name
+			aLineReader.Set(file);		
+			TInt foundTag = -1;
+			while (err != KErrEof && foundTag != 0)
+				{
+				err = aLineReader.Read(iLine);
+				if (err != KErrEof)
+					foundTag =  iLine.Find(tempsectID);
+				}
+			
+			// create the next open bracket to search for		
+			TBuf<2> tempopenBrk;
+			tempopenBrk.Copy(KOpenBrk);
+			
+			RFile testfile;	
+			err = KErrNone;
+			foundTag = -1;
+
+			// while not at the end of the file and not found the next open bracket
+			while (err != KErrEof && foundTag != 0)
+				{
+
+				// get the next line of the .ini file
+				err = aLineReader.Read(iLine);
+				if (err != KErrEof)
+					{
+
+					// if the line of the file doesn't contain an open bracket, we are still in the section body
+					foundTag =  iLine.Find(tempopenBrk);
+					if (BaflUtils::FolderExists(aFs, aTocspTestFile) && foundTag != 0)
+						{		
+						// open the test file we are going to write all our section info into
+						if (BaflUtils::FileExists( aFs, aTocspTestFile ))
+							{	
+							testfile.Open(aFs, aTocspTestFile, EFileWrite|EFileShareAny);
+							testfile.Seek(ESeekEnd, pos);
+							}
+						else
+							{	
+							User::LeaveIfError(testfile.Create(aFs, aTocspTestFile, EFileWrite|EFileShareAny));
+							testfile.Open(aFs, aTocspTestFile, EFileWrite|EFileShareAny);
+							}
+						// append to line of the file end of line characters
+						iLine.Append(_L("\r\n"));
+
+						// write line of the code out to the test file in UNICODE format 
+						TPtrC8 tmpPoint((TText8*)iLine.Ptr(),iLine.Size());
+						testfile.Write(tmpPoint); 
+						
+						testfile.Flush();							
+						}
+					testfile.Close();
+					}
+				}
+			}
+		}
+		return KErrNone;
+
+	}
+
+EXPORT_C TPtrC TEFparser::ParseNthElement(const TDesC& aBuf, TInt aWordPos)
+
+ {
+ 
+	 TInt startPos = KErrNotFound, endPos = KErrNotFound;
+	 TInt wordCounter =0 ;
+	 TBool inWord = EFalse;
+	 TInt i =0;
+	 
+	 for(i = 0; i < aBuf.Length() ; i ++)
+	  {
+	  	TPtrC tmpChar = aBuf.Mid(i,1);
+	  	if(tmpChar == KSpace || tmpChar == KTab || tmpChar == KReturn || tmpChar == KNewline )
+	  	{
+	  	if(inWord)
+	  		{
+	  		  if(wordCounter == aWordPos)
+	  		  {
+	    	   endPos =i-1;
+	    	   break;
+	    	   }
+	  		 inWord = EFalse;
+	    	}   
+	   }
+	  else
+	   {
+	   	if(inWord == EFalse)
+	   		{
+	   		wordCounter ++;
+	   		inWord = ETrue;
+	   		if(wordCounter == aWordPos)
+	   			{
+	   			startPos =i;
+	   			}
+	   		 }
+	   	 }
+	  } 
+	 if(startPos < 0 || endPos < 0)
+	 {
+	  endPos = aBuf.Length();
+	  return aBuf.Mid(startPos,(endPos-startPos));
+	 }
+	 else
+	 {
+	  return aBuf.Mid(startPos,(endPos-startPos+1));
+	 }
+}
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/TEFparser.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,70 @@
+// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Test transport object.  May be used in place of the automatically-constructed
+// transport object from OCSP.DLL
+// Allows a file to be specified, the contents of which will be returned as the response.
+// 
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+
+#ifndef TEFPARSER_H_
+#define TEFPARSER_H_
+
+
+
+#include <e32base.h>
+#include <f32file.h>
+
+class CTOCSPLogger;
+
+class TEFparser
+	{
+public:
+	
+//	Checks if the input test script is a .script file
+	IMPORT_C static TBool FileType(const TDesC& aBuf);
+	
+//	Reads the file
+	IMPORT_C static TInt ReadFileLC(RFs& aFs, const TDesC& aScriptFilepath, TPtrC& aScriptFileContents);
+	
+//	Searches and gets the first RUN_TESTSTEP from the .script file
+	IMPORT_C static TPtrC GetRunTestStep(TPtrC& aBuf, const TDesC& aTag, TInt& aPos, TInt& aError);
+	
+//	Gets ini file name and sectionname from the RUN_TESTSTEp
+	IMPORT_C static TInt GetIniFileInfo(TDesC& aBuf, TPtrC& aIniFileName, TPtrC& aIniSectionName);
+	
+//	Generates the ini file path from .script file path taken from command line
+	IMPORT_C static TInt GetiniPath(TDesC& aBuf, const TDesC& aScriptPath, TDes& aIniFilePath);
+
+//	Searches the .ini file with section name to fetch the setion data
+	IMPORT_C static TInt GetSectionData(TDesC& aScriptFilepath, TPtrC& aSectiontag, TDesC16 &aTocspTestFile, RFs& aFs);
+	
+//	Trims data of its spaces and newline
+	IMPORT_C static TPtrC Trim(const TDesC& aBuf);
+	
+//	Gets the nth word from a data block
+	IMPORT_C static TPtrC ParseNthElement(const TDesC& aBuf, TInt aWordPos);
+	
+	
+
+private:
+	
+
+	};
+
+#endif /*TEFPARSER_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/command.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1459 @@
+// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+#include "command.h"
+#include "engine.h"
+#include "panic.h"
+#include "logger.h"
+#include "result.h"
+
+#include "TEFparser.h"
+#include <f32file.h>
+#include <utf.h>
+
+// Define the commands the user can use in the input script
+
+// *****************  General  ************************
+
+// Comment prefix for input file
+_LIT(KTOCSPCommandComment,		"REM");
+
+// Print remaining text to console
+_LIT(KTOCSPCommandPrint,		"PRINT");
+
+// Bail out at this point
+_LIT(KTOCSPCommandAbort,		"ABORT");
+
+// NOTE: Skips CAN be nested
+// Skip everything unil KTOCSPCommandEndSkip
+_LIT(KTOCSPCommandSkip,			"SKIP");
+
+// Stop skipping - does nothing if not skipping
+_LIT(KTOCSPCommandEndSkip,		"ENDSKIP");
+
+// ************ Configuring the request ***************
+
+// Start a new OCSP request/response transaction
+// Has exactly one parameter - the name of the test (which must not include spaces)
+_LIT(KTOCSPCommandStart,		"START");
+
+// Set the URI of the server
+_LIT(KTOCSPCommandSetURI,		"SETURI");
+
+
+// Parameter is a file from which to read a cert
+_LIT(KTOCSPCommandCert,			"REQUESTCERT");
+
+// Parameter is ON or OFF
+_LIT(KTOCSPCommandNonce,        "NONCE");
+
+// ************ Handling the communication *************
+
+// Set transport scheme for communication
+// Parameter DEFAULT means let the OCSP module deal with the transport
+// Parameter TEST means use the test harness server
+_LIT(KTOCSPCommandSetTransport,	"TRANSPORT");
+
+// ******* Configuring + performing the validation ********
+
+// Set transport retry count
+// Takes one parameter, the retry count (1 means no retry)
+// NOTE: This command must appear after the TRANSPORT command
+_LIT(KTOCSPCommandSetTransportRetry, "TRANSPORTRETRY");
+
+// Set transport timeout
+// Takes one parameter, the timeout value in milliseconds
+// NOTE: This command must appear after the TRANSPORT command
+_LIT(KTOCSPCommandSetTransportTimeout, "TRANSPORTTIMEOUT");
+
+// Set validation date, parameters are YYYY MM DD HH MM - optional
+_LIT(KTOCSPCommandValidationDate, "VALIDATIONDATE");
+
+// Parameter is a file containing a cert to be set as valid for authorisation of
+// the response.  Can call more than once.
+_LIT(KTOCSPCommandDirectAuthorisation, "AUTHORISATIONCERT");
+
+// No parameters - tells test client to use ca delegate authorisation.
+// (See RFC2560 S2.2, S4.2.2.2)
+_LIT(KTOCSPCommandCADelegateAuthorisation, "CADELEGATE");
+
+// No parameters - tells test client to use direct signing by ca.
+// see (RFC 2560 S2.2)
+_LIT(KTOCSPCommandCADirectAuthorisation, "CADIRECT");
+
+// No parameters - tells test client to use all schemes
+// see (RFC 2560 S2.2)
+_LIT(KTOCSPCommandAllAuthorisationSchemes, "ALLSCHEMES");
+
+// Set the maximum allowable age of the status returned.  Parameter is in
+// seconds, or "OFF" to disable checking.
+_LIT(KTOCSPCommandSetMaxStatusAge, "SETMAXSTATUSAGE");
+
+// Set http filter parameters
+// The parameters to FILTERPARAMS command are:
+// numDelayResp countDropResp countCorruptHTTPDataHeader countCorruptHTTPDataBodySizeLarge countCorruptHTTPDataBodySizeSmall countCorruptOCSPData countInternalErrorResp countTryLaterResp
+// where:
+// 		numDelayResp - Delays response by specified number of milliseconds
+//		countDropResp - Drops specified number of responses
+//		countCorruptHTTPDataHeader - Corrupts specified number of responses (content-type in header is corrupted)
+//		countCorruptHTTPDataBodySizeLarge - Corrupts specified number of responses (body is of larger size than expected)
+//		countCorruptHTTPDataBodySizeSmall - Corrupts specified number of responses (body is of smaller size than expected)
+//		countCorruptOCSPData - Corrupts specified number of responses (OCSPResponse data is corrupted)
+//		countInternalErrorResp - Returns an "internalError" response for specified number of requests
+//		countTryLaterResp - Returns a "tryLater" response for specified number of requests
+//		countSigValidateFailure - Causes a signature validation failure by corrupting the Responder ID
+// NOTE: This command must appear after the TRANSPORT command
+_LIT(KTOCSPCommandSetFilterParams, "FILTERPARAMS");
+
+
+// Cancel the OCSP check after its issued
+// The parameter is the time in milliseconds to wait before issuing the cancel
+// Note that this command must appear before the CHECK command
+_LIT(KTOCSPCommandCancel, "CANCEL");
+
+// Run the OCSP check
+_LIT(KTOCSPCommandCheck, "CHECK");
+
+// Tests that the revocation check was cancelled
+_LIT(KTOCSPCommandTestCancel, "TESTCANCEL");
+
+// Tests that the summary result is as expected.  Takes one parameter, the
+// expected result.
+_LIT(KTOCSPCommandTestSummary, "TESTSUMMARY");
+
+// Tests that the outcome for a certificate is as expected.  Takes three
+// paramters, the certificate index, the expected status and the expected result
+_LIT(KTOCSPCommandTestOutcome, "TESTOUTCOME");
+
+// Tests that the outcome for the tranport is as expected. Takes four
+// paramters, the retry count number (0 means first attempt), the expected HTTP method, 
+// and the range of time in milliseconds (min max) within which each request should complete
+// NOTE: The usage of this command assumes only one certificate is being
+// checked for revocation per test case! (also means CHECKRESPONDERCERT command cannot be used with this)
+_LIT(KTOCSPCommandTestTransport, "TESTTRANSPORT");
+
+// Tests that the outcome for the retry attempts is as expected. 
+// Takes one paramter, the retry count (1 means single attempt ie. no retry)
+// NOTE: The usage of this command assumes only one certificate is being
+// checked for revocation per test case! (also means CHECKRESPONDERCERT command cannot be used with this)
+_LIT(KTOCSPCommandTestTransportRetry, "TESTTRANSPORTRETRY");
+
+// Log the reponses to a file.  The filename is the only parameter.
+// This command must be placed after the CHECK command
+_LIT(KTOCSPCommandLogResponse, "LOGRESPONSE");
+
+// Log the requests to a file.  The filename is the only parameter.
+// This command must be placed before the TRANSPORT command
+_LIT(KTOCSPCommandLogRequest, "LOGREQUEST");
+
+// End a test
+_LIT(KTOCSPCommandEnd, "END");
+
+// parameter for setting whether the ocsp status check 
+// for responder certificate should be done or not.
+_LIT(KTOCSPCheckResponderCert, "CHECKRESPONDERCERT");
+
+_LIT(KTOCSPAddCertToStore, "ADDCERTTOSTORE");
+
+_LIT(KTOCSPUseAIA, "USEAIA");
+
+_LIT(KTOCSPCheckCertsWithAiaOnly, "CHECKCERTSWITHAIAONLY");
+
+_LIT(KTOCSPExpectedError, "EXPECTEDERROR");
+
+// ************* Parameter definitions *****************
+
+// Default transport (currently only HTTP)
+_LIT(KTOCSPDefaultTransport,		"DEFAULT");
+
+_LIT(KTOCSPTestTransport,			"TEST");
+
+_LIT(KTOCSPOcspSupportTransport,	"OCSPSUPPORT");
+
+// Generic parameter for toggle of settings.
+_LIT(KTOCSPOn,  "ON");
+_LIT(KTOCSPOff, "OFF");
+
+_LIT(KTOCSPEnable,  "ENABLE");
+_LIT(KTOCSPDisable, "DISABLE");
+_LIT(KTOCSPEnableDisable,"ENABLE|DISABLE");
+
+
+CTOCSPCommand* CTOCSPCommand::NewL(CTOCSPLogger& aLog,
+								   CTOCSPResult& aResult,	
+								   TInt aTransaction)
+	{
+	CTOCSPCommand* self = new (ELeave) CTOCSPCommand(aLog, aResult, aTransaction);
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+ 
+CTOCSPCommand::CTOCSPCommand(CTOCSPLogger& aLog,
+							 CTOCSPResult& aResult,
+							 TInt aTransaction) :
+	CActive(EPriorityNormal),
+	iResult(aResult),
+	iLog(aLog),
+	iTestToProcess(aTransaction)
+	{
+	CActiveScheduler::Add(this);
+	}
+
+
+void CTOCSPCommand::ConstructL()
+	{
+	iEngine = CTOCSPEngine::NewL(iLog);
+	}
+
+
+CTOCSPCommand::~CTOCSPCommand()
+	{
+    Cancel();
+	delete iEngine;
+	iTokens.Close();
+	}
+
+
+void CTOCSPCommand::ResetL()
+    {
+	FinishedTestL();
+    iTestIndex = 0;
+    iTestToProcess = 0;
+    }
+
+
+TInt CTOCSPCommand::CurrentTransaction() const
+    {
+    return iTestIndex;
+    }
+
+
+TBool CTOCSPCommand::ProcessCommand(const TDesC& aLine, TRequestStatus& aStatus)
+	{
+	iOriginalRequestStatus = &aStatus;
+
+    TBool result = ETrue;
+    TRAPD(err, result = DoProcessCommandL(aLine));
+    if (err != KErrNone)
+        {
+        Cancel();
+        User::RequestComplete(iOriginalRequestStatus, err);
+        }
+
+    return result;
+    }
+
+
+TBool CTOCSPCommand::DoProcessCommandL(const TDesC& aLine)
+	{
+	*iOriginalRequestStatus = KRequestPending;
+
+	if (!iVerbose)
+		{
+		iLog.LogL(_L("."), ETrue);
+		}
+
+	TLex lex(aLine);
+
+    // Empty line
+    if (lex.Eos())
+        {
+        User::RequestComplete(iOriginalRequestStatus, KErrNone);
+        return ETrue;
+        }
+
+    TPtrC command = lex.NextToken();
+
+    // Handle skipping commands
+	if (command == KTOCSPCommandSkip)
+		{
+		++iSkipping;
+		}
+	else if (command == KTOCSPCommandEndSkip)
+		{
+        --iSkipping;
+		if (iSkipping < 0)
+			{
+            User::RequestComplete(iOriginalRequestStatus, KErrCorrupt);
+			return ETrue;
+			}
+		}
+
+	LogCommandL(aLine);
+
+	if (iSkipping)
+		{
+		User::RequestComplete(iOriginalRequestStatus, KErrNone);
+        return ETrue;
+		}
+
+	if (command == KTOCSPCommandSkip || command == KTOCSPCommandEndSkip)
+		{
+		User::RequestComplete(iOriginalRequestStatus, KErrNone);
+        return ETrue;
+		}
+
+	if (command == KTOCSPCommandStart)
+		{
+		++iTestIndex;
+		}
+
+    // Don't process any tests except the ones we're interested in
+    if (iTestToProcess != 0 && iTestToProcess != iTestIndex)
+        {   
+		User::RequestComplete(iOriginalRequestStatus, KErrNone);
+        return ETrue;
+        }
+
+	// Handle comment and print commands
+	if (command == KTOCSPCommandComment)
+		{
+		// Remark - nothing to do except move on to next line
+		User::RequestComplete(iOriginalRequestStatus, KErrNone);
+        return ETrue;
+		}
+	else if (command == KTOCSPCommandPrint)
+		{
+		lex.SkipSpace();
+		PrintCommandL(lex.Remainder());
+        return ETrue;
+		}
+
+    // Now split the rest of the command into tokens
+	iTokens.Reset();
+	while (!lex.Eos())
+		{
+		User::LeaveIfError(iTokens.Append(lex.NextToken()));
+		}
+    
+    // Check commands that don't have to occur in tests
+	if (command == KTOCSPCommandAbort)
+		{
+		User::RequestComplete(iOriginalRequestStatus, KErrNone);
+		return EFalse;
+		}
+	else if (command == KTOCSPCommandStart)
+        {
+		StartCommandL();
+		}
+	else if (command == KTOCSPCommandEnd)
+        {
+		EndCommandL();
+		}
+	else
+		{
+		return ProcessTestCommandL(command);
+		}
+
+	return ETrue;
+	}
+
+
+TBool CTOCSPCommand::ProcessTestCommandL(const TDesC& command)
+	{
+	if (!iInsideTest)
+		{
+		iLog.LogL(_L("Command cannot occur outside test: "));
+		iLog.LogL(command);
+		iLog.NewLineL();
+		User::Leave(KErrCorrupt);
+		}
+
+    // Check the other commands that can only occur in tests
+	if (command == KTOCSPCommandSetURI)
+		{
+		SetURICommandL();
+		}
+	else if (command == KTOCSPCommandSetTransport)
+		{
+		SetTransportCommandL();
+		}
+	else if (command == KTOCSPCommandSetTransportRetry)
+		{
+		SetTransportRetryCommandL();
+		}
+	else if (command == KTOCSPCommandSetTransportTimeout)
+		{
+		SetTransportTimeoutCommandL();
+		}
+	else if (command == KTOCSPCommandCert)
+		{
+		CertCommandL();
+		}
+	else if (command == KTOCSPCommandValidationDate)
+		{
+		ValidationDateCommandL();
+		}
+	else if (command == KTOCSPCommandDirectAuthorisation)
+		{
+		DirectAuthorisationCommandL();
+		}
+	else if (command == KTOCSPCommandCADelegateAuthorisation)
+		{
+		CADelegateAuthorisationCommandL();
+		}
+	else if (command == KTOCSPCommandCADirectAuthorisation)
+		{
+		CADirectAuthorisationCommandL();
+		}
+	else if (command == KTOCSPCommandAllAuthorisationSchemes)
+		{
+		AllAuthorisationSchemesCommandL();
+		}
+	else if (command == KTOCSPCommandSetMaxStatusAge)
+		{
+		SetMaxStatusAgeCommandL();
+		}
+	else if (command == KTOCSPCommandSetFilterParams)
+		{
+		SetFilterParamsCommandL();
+		}
+	else if (command == KTOCSPCommandCancel)
+		{
+		CancelCommandL();
+		}
+	else if (command == KTOCSPCommandCheck)
+		{
+		CheckCommand();
+		}
+	else if (command == KTOCSPCommandTestCancel)
+		{
+		TestCancelCommand();
+		}
+	else if (command == KTOCSPCommandTestSummary)
+		{
+		TestSummaryCommandL();
+		}
+	else if (command == KTOCSPCommandTestOutcome)
+		{
+		TestOutcomeCommandL();
+		}
+	else if (command == KTOCSPCommandTestTransport)
+		{
+		TestTransportCommandL();
+		}
+	else if (command == KTOCSPCommandTestTransportRetry)
+		{
+		TestTransportRetryCommandL();
+		}
+	else if (command == KTOCSPCommandNonce)
+		{
+		SetNonceCommandL();
+		}
+	else if (command == KTOCSPCommandLogResponse)
+		{
+		LogResponseCommandL();
+		}
+	else if (command == KTOCSPCommandLogRequest)
+		{
+		LogRequestCommandL();
+		}
+	else if (command == KTOCSPCheckResponderCert)
+		{
+		SetResponderCertCheck();
+		}
+	else if(command == KTOCSPAddCertToStore)
+		{
+		AddCertToStoreL();
+		}
+	else if(command ==  KTOCSPCheckCertsWithAiaOnly )
+		{
+		SetCheckCertsWithAiaOnly();
+		}
+	else if(command  == KTOCSPUseAIA)
+		{
+		SetUseAIAL();
+		}
+	else if(command == KTOCSPExpectedError)
+		{
+		LogErrorL();
+		}
+	else
+		{
+		UnknownCommandL(command);
+		}
+
+	return ETrue;
+	}
+
+void CTOCSPCommand::LogErrorL()
+	{
+	if (iTokens.Count() != 1)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	TLex expectedErrorLex(iTokens[0]);
+	TInt expectedError = 0;
+	User::LeaveIfError(expectedErrorLex.Val(expectedError));
+
+	iTestResult = (expectedError == iError)?ETrue:EFalse;
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+
+	}
+
+void CTOCSPCommand::RunL()
+	{
+	TInt err = iStatus.Int();
+
+	// The engine does not get a chance to process the cancel notification so we handle it here
+	if (err == KErrCancel)
+		{
+		// Cancel expected
+		iCheckCancelled = ETrue;
+		}
+	else
+		{
+		User::LeaveIfError(err);
+		}
+
+	switch (iState)
+		{
+		case EEngineStart:
+		case EEngineEnd:
+		case EDirectAuthorisationCommand:
+		case ECheckCommand:			
+			User::RequestComplete(iOriginalRequestStatus, KErrNone);
+			break;
+
+		default:
+            User::Panic(_L("TOCSP"), 1);
+			break;
+		}
+	}
+
+TInt CTOCSPCommand::RunError(TInt aError)
+    {
+    iError = aError;
+    User::RequestComplete(iOriginalRequestStatus, KErrNone);
+    return KErrNone;
+    }
+
+void CTOCSPCommand::DoCancel()
+	{
+	switch (iState)
+		{
+		case EEngineStart:
+		case EEngineEnd:
+		case EDirectAuthorisationCommand:
+		case ECheckCommand:
+			iEngine->Cancel();
+			break;
+			
+		default:
+            User::Panic(_L("TOCSP"), 1);
+			break;
+		}
+	}
+
+void CTOCSPCommand::LogCommandL(const TDesC& aLine)
+	{
+	if (iVerbose)
+		{
+		// To file only
+		if (iSkipping)
+			{
+			iLog.LogL(_L("Skipped: "), EFalse);
+			}
+		else
+			{
+			iLog.LogL(_L("Input: "), EFalse);
+			}
+
+		iLog.LogL(aLine, EFalse);		
+		
+		TInt match;
+		_LIT(KMatch,"*START*");
+		match = aLine.Match(KMatch);
+		if (match==0)
+			{
+		iTmsId.Copy(TEFparser::ParseNthElement(aLine,2));
+		
+		TBuf<64> timeBuf;
+		TTime time;
+		time.UniversalTime();
+		TDateTime dateTime = time.DateTime();
+		_LIT(KDateFormat,"%02d:%02d:%02d:%03d "); 
+		timeBuf.AppendFormat(KDateFormat,dateTime.Hour(),dateTime.Minute(),dateTime.Second(),(dateTime.MicroSecond()/1000));
+		
+		iLog.LogL(_L("\r\n"));
+		iLog.LogL(timeBuf);	
+		iLog.LogL(_L("Command = START_TESTCASE "));
+		iLog.LogL(iTmsId);
+			}	        
+		iLog.LogL(_L("\n"));
+		}
+	}
+
+
+void CTOCSPCommand::UnknownCommandL(const TDesC& aCommand)
+	{
+	// Log to screen and file
+	iLog.LogL(_L("Unrecognised command \""), ETrue);
+	iLog.LogL(aCommand);
+	iLog.LogL(_L("\" - aborting\n"));
+	
+	User::RequestComplete(iOriginalRequestStatus, KErrCorrupt);
+	}
+
+
+void CTOCSPCommand::PrintCommandL(const TDesC& aMess)
+	{
+	if (iVerbose)
+		{
+		// To screen and file
+		iLog.LogL(aMess, ETrue);
+		iLog.LogL(_L("\n"), ETrue);
+		}
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+
+void CTOCSPCommand::StartCommandL()
+	{
+	if (iInsideTest)
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Misplaced START command: not inside test\n"));
+			}
+		User::Leave(KErrCorrupt);
+		}
+
+	if (iTokens.Count() != 1)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	iInsideTest = ETrue;
+	iTestResult = ETrue;
+	iTransportSet = EFalse;
+
+	iResult.NewTestL(iTokens[0]);
+
+	if (iVerbose)
+		{
+		iLog.LogL(_L("Test: "));
+		iLog.LogL(iTokens[0]);
+		iLog.NewLineL();
+		}
+
+	iEngine->StartL(iStatus);
+	iState = EEngineStart;
+	SetActive();
+	}
+
+
+void CTOCSPCommand::EndCommandL()
+	{
+	if (!iInsideTest)
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Misplaced END command: not inside test\n"));
+			}
+		User::Leave(KErrCorrupt);
+		}
+
+	iInsideTest = EFalse;
+	iCheckCancelled = EFalse;
+	FinishedTestL();
+
+	if (iVerbose)
+		{
+		iLog.NewLineL();
+		}
+
+	iEngine->EndL(iStatus);
+	iState = EEngineEnd;
+	SetActive();
+	}
+
+
+void CTOCSPCommand::SetURICommandL()
+	{
+	TInt tokenCount = iTokens.Count();
+	
+	if (tokenCount < 1 || tokenCount > 3) 
+		{
+		WrongNumberOfArgumentsL();
+		}
+	
+	// Need to convert from unicode (as in file) to 8-bit (as used by OCSP)
+	TBuf8<256> uri8;
+	uri8.Copy(iTokens[0]);
+	_LIT8(KNull,"NULL");
+	if(uri8.Compare(KNull) == 0)
+		{
+		uri8.FillZ();
+		}
+	if(tokenCount == 3 )
+		{
+		if(iTokens[1].Compare(KTOCSPUseAIA) != 0 )
+			{
+			InvalidArgumentL(KTOCSPUseAIA);
+			}
+		if(iTokens[2].Compare(KTOCSPEnable) == 0)
+			{
+			iEngine->SetURIL(uri8, ETrue);
+			}
+		else if(iTokens[2].Compare(KTOCSPDisable) == 0)
+			{
+			iEngine->SetURIL(uri8, EFalse);
+			}
+		else
+			{
+			InvalidArgumentL(KTOCSPUseAIA,KTOCSPEnableDisable);
+			}
+		}
+	else
+		{
+		// default value
+		iEngine->SetURIL(uri8, ETrue);
+		}
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::SetTransportCommandL()
+	{
+	if (iTokens.Count() == 0)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	TPtrC parameter = iTokens[0];
+	if (parameter == KTOCSPDefaultTransport)
+		{
+		if (iTokens.Count() != 1)
+			{
+			WrongNumberOfArgumentsL();
+			}
+		iEngine->SetDefaultTransportL();
+		}
+	else if (parameter == KTOCSPTestTransport)
+		{
+		if (iTokens.Count() < 2 || iTokens.Count() > 3)
+			{
+			WrongNumberOfArgumentsL();
+			}
+
+		iEngine->SetTestTransportL(iTokens[1], iTokens.Count() == 3 ? &iTokens[2] : NULL);
+		}
+	else if (parameter == KTOCSPOcspSupportTransport)
+		{
+		if (iTokens.Count() != 1)
+			{
+			WrongNumberOfArgumentsL();
+			}
+
+		iEngine->SetOcspSupportTransportL();
+		}
+	iTransportSet = ETrue;
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::SetTransportRetryCommandL()
+	{
+	if (!iTransportSet)
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Command sequence error: TRANSPORTRETRY must appear after TRANSPORT command\n"));
+			}
+		User::Leave(KErrCorrupt);
+		}
+
+	if (iTokens.Count() != 1)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	TInt retryCount = 0;
+	TLex lex(iTokens[0]);
+	if ((lex.Val(retryCount) != KErrNone) || (retryCount < 0))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid retry count in TRANSPORTRETRY command\n"));
+			}
+		User::Leave(KErrArgument);
+		}
+
+	iEngine->SetTransportRetryCount(static_cast<TUint>(retryCount));
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::SetTransportTimeoutCommandL()
+	{
+	if (!iTransportSet)
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Command sequence error: TRANSPORTTIMEOUT must appear after TRANSPORT command\n"));
+			}
+		User::Leave(KErrCorrupt);
+		}
+
+	if (iTokens.Count() != 1)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	TInt timeout = 0;
+	TLex lex(iTokens[0]);
+	if ((lex.Val(timeout) != KErrNone) || (timeout < -1))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid timeout in TRANSPORTTIMEOUT command\n"));
+			}
+		User::Leave(KErrArgument);
+		}
+
+	iEngine->SetTransportTimeout(timeout);
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::SetNonceCommandL()
+	{
+	if (iTokens.Count() != 1)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	TPtrC param = iTokens[0];
+	if (param == KTOCSPOn)
+		{
+		iEngine->SetNonce(ETrue);
+		}
+	else if (param == KTOCSPOff)
+		{
+		iEngine->SetNonce(EFalse);
+		}
+	else
+		{
+		User::Leave(KErrArgument);
+		}
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+
+void CTOCSPCommand::CertCommandL()
+	{
+	if (iTokens.Count() != 2)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	TPtrC subjectCert = iTokens[0];
+	TPtrC issuerCert = iTokens[1];
+
+	// Open file server session
+	RFs session;
+	User::LeaveIfError(session.Connect());
+	CleanupClosePushL(session);
+
+	HBufC8* subjectData = 0;
+	TRAPD(err, subjectData = Input::ReadFileL(subjectCert, session));
+	CleanupStack::PushL(subjectData);
+	if (err != KErrNone)
+		{
+		if (err != KErrNoMemory && iVerbose)
+			{
+			iLog.LogL(_L("Error opening "));
+			iLog.LogL(subjectCert);
+			}
+		User::Leave(err);
+		}
+
+	HBufC8* issuerData = 0;
+	TRAP(err, issuerData = Input::ReadFileL(issuerCert, session));
+	CleanupStack::PushL(issuerData);
+	if (err != KErrNone)
+		{
+		if (err != KErrNoMemory && iVerbose)
+			{
+			iLog.LogL(_L("Error opening "));
+			iLog.LogL(issuerCert);
+			}
+		User::Leave(err);
+		}
+
+	// Engine will actually read + own the cert
+	iEngine->AddCertL(*subjectData, *issuerData);
+
+	CleanupStack::PopAndDestroy(3); // issuerData, subjectData, close session
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+
+void CTOCSPCommand::ValidationDateCommandL()
+	{
+	if (iTokens.Count() != 5)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	iEngine->SetValidationTimeL(ParseTimeL(0));
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+/**
+ * Parse a series of input tokens representing a time - format is:
+ * YEAR MONTH DAY HOUR MINUTE
+ */
+
+TTime CTOCSPCommand::ParseTimeL(TInt aStartToken)
+	{
+	TLex lexer;
+	TInt year, month, day, hour, minute;
+
+	lexer.Assign(iTokens[aStartToken++]);
+	User::LeaveIfError(lexer.Val(year));
+
+	lexer.Assign(iTokens[aStartToken++]);
+	User::LeaveIfError(lexer.Val(month));
+
+	lexer.Assign(iTokens[aStartToken++]);
+	User::LeaveIfError(lexer.Val(day));
+
+	lexer.Assign(iTokens[aStartToken++]);
+	User::LeaveIfError(lexer.Val(hour));
+
+	lexer.Assign(iTokens[aStartToken]);
+	User::LeaveIfError(lexer.Val(minute));
+
+	// Internal month and day are 0-based
+	TDateTime dateTime(year, TMonth(--month), --day, hour, minute, 0, 0);
+
+	return dateTime;
+	}
+
+
+void CTOCSPCommand::SetMaxStatusAgeCommandL()
+	{
+	if (iTokens.Count() != 1)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	if (iTokens[0] == KTOCSPOff)
+		{
+		iEngine->SetMaxStatusAgeL(0);
+		}
+	else
+		{
+		TLex lexer;
+		lexer.Assign(iTokens[0]);
+		TUint seconds;
+		User::LeaveIfError(lexer.Val(seconds));
+		iEngine->SetMaxStatusAgeL(seconds);
+		}
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::SetFilterParamsCommandL()
+	{
+	if (iTokens.Count() != 9)
+		{
+		WrongNumberOfArgumentsL();
+		}
+	TInt numDelayResp = 0, countDropResp = 0;
+	TInt countCorruptHTTPDataHeader = 0, countCorruptHTTPDataBodySizeLarge = 0, countCorruptHTTPDataBodySizeSmall = 0;
+	TInt countCorruptOCSPData = 0;
+	TInt countInternalErrorResp = 0, countTryLaterResp = 0;
+	TInt countSigValidateFailure = 0;
+
+	TLex lex(iTokens[0]);
+	if ((lex.Val(numDelayResp) != KErrNone) || (numDelayResp < -1))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid numDelayResp in FILTERPARAMS command\n"));
+			}
+		User::Leave(KErrArgument);
+		}
+
+	lex = iTokens[1];
+	if ((lex.Val(countDropResp) != KErrNone) || (countDropResp < -1))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid countDropResp in FILTERPARAMS command\n"));
+			}
+		User::Leave(KErrArgument);
+		}
+
+	lex = iTokens[2];
+	if ((lex.Val(countCorruptHTTPDataHeader) != KErrNone) || (countCorruptHTTPDataHeader < -1))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid countCorruptHTTPDataHeader in FILTERPARAMS command\n"));
+			}
+		User::Leave(KErrArgument);
+		}
+
+	lex = iTokens[3];
+	if ((lex.Val(countCorruptHTTPDataBodySizeLarge) != KErrNone) || (countCorruptHTTPDataBodySizeLarge < -1))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid countCorruptHTTPDataBodySizeLarge in FILTERPARAMS command\n"));
+			}
+		User::Leave(KErrArgument);
+		}
+
+	lex = iTokens[4];
+	if ((lex.Val(countCorruptHTTPDataBodySizeSmall) != KErrNone) || (countCorruptHTTPDataBodySizeSmall < -1))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid countCorruptHTTPDataBodySizeSmall in FILTERPARAMS command\n"));
+			}
+		User::Leave(KErrArgument);
+		}
+
+	lex = iTokens[5];
+	if ((lex.Val(countCorruptOCSPData) != KErrNone) || (countCorruptOCSPData < -1))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid countCorruptOCSPData in FILTERPARAMS command\n"));
+			}
+		User::Leave(KErrArgument);
+		}
+
+	lex = iTokens[6];
+	if ((lex.Val(countInternalErrorResp) != KErrNone) || (countInternalErrorResp < -1))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid countInternalErrorResp in FILTERPARAMS command\n"));
+			}
+		User::Leave(KErrArgument);
+		}
+
+	lex = iTokens[7];
+	if ((lex.Val(countTryLaterResp) != KErrNone) || (countTryLaterResp < -1))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid countTryLaterResp in FILTERPARAMS command\n"));
+			}
+		User::Leave(KErrArgument);
+		}
+
+	lex = iTokens[8];
+	if ((lex.Val(countSigValidateFailure) != KErrNone) || (countSigValidateFailure < -1))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid countSigValidateFailure in FILTERPARAMS command\n"));
+			}
+		User::Leave(KErrArgument);
+		}
+
+	iEngine->SetFilterParameters(numDelayResp, countDropResp,
+			countCorruptHTTPDataHeader, countCorruptHTTPDataBodySizeLarge, countCorruptHTTPDataBodySizeSmall,
+			countCorruptOCSPData, 
+			countInternalErrorResp, countTryLaterResp, countSigValidateFailure);
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+// Pass a certificate (file) to be used as a root cert for validation of the response
+void CTOCSPCommand::DirectAuthorisationCommandL()
+	{
+	iState = EDirectAuthorisationCommand;
+	
+	switch (iTokens.Count())
+		{
+	case 1:
+		// since CA Delegate support was added, the script
+		// cannot assume that direct authorisation is always
+		// used.  Therefore, the special case of
+		// "AUTHORISATIONCERT AUTHCERTNONE" is used to indicate that
+		// direct authorisation should be used, even if no
+		// certs are supplied.
+		if (iTokens[0] != KAuthCertNone)
+			User::Leave(KErrArgument);
+		
+		iEngine->UseDirectAuthorisation();
+		User::RequestComplete(iOriginalRequestStatus, KErrNone);
+		return;
+		
+	case 2:
+		iCert.Set(iTokens[0]);
+		iLabel.Set(iTokens[1]);
+		break;
+		
+	default:
+		WrongNumberOfArgumentsL();
+		}
+
+	iEngine->AddDirectAuthorisationCert(iCert, iLabel, iStatus);
+	SetActive();
+	}
+
+void CTOCSPCommand::CADelegateAuthorisationCommandL()
+/**
+	Instruct engine to use CA delegate authorisation.
+ */
+	{
+	if (iTokens.Count() != 0)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	iEngine->UseCADelegateAuthorisation();
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::CADirectAuthorisationCommandL()
+/**
+	Instruct engine to expect the response is signed
+	directly by the CA.
+ */
+	{
+	if (iTokens.Count() != 0)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	iEngine->UseCADirectAuthorisation();
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::AllAuthorisationSchemesCommandL()
+/**
+	Instruct engine to expect allocate all supported
+	authorisation schemes.
+
+	The script will have to specify which authorisation certs
+	are supported for direct authorisation with AUTHORISATIONCERT,
+	later in the script.
+ */
+	{
+	if (iTokens.Count() != 0)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	iEngine->UseAllAuthorisationSchemes();
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::CancelCommandL()
+	{
+	if (iTokens.Count() != 1)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	TLex timeLex(iTokens[0]);
+	TInt time = 0;
+	User::LeaveIfError(timeLex.Val(time));
+
+	iEngine->SetCancelTime(time);
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::CheckCommand()
+	{
+	iState = ECheckCommand;
+	iEngine->Check(iStatus);
+	SetActive();
+	}
+
+void CTOCSPCommand::TestCancelCommand()
+	{
+	iTestResult = iTestResult && iCheckCancelled;
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::TestSummaryCommandL()
+	{
+	if (iTokens.Count() != 1)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	TLex expectedResultLex(iTokens[0]);
+	TInt expectedResult = 0;
+	User::LeaveIfError(expectedResultLex.Val(expectedResult));
+
+	iTestResult = iTestResult && iEngine->TestSummaryL(STATIC_CAST(OCSP::TResult, expectedResult));
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+
+void CTOCSPCommand::TestOutcomeCommandL()
+	{
+	if (iTokens.Count() != 3)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	TLex certIndexLex(iTokens[0]);
+	TInt certIndex = 0;
+	User::LeaveIfError(certIndexLex.Val(certIndex));
+
+	TLex expectedStatusLex(iTokens[1]);
+	TInt expectedStatus = 0;
+	User::LeaveIfError(expectedStatusLex.Val(expectedStatus));
+
+	TLex expectedResultLex(iTokens[2]);
+	TInt expectedResult = 0;
+	User::LeaveIfError(expectedResultLex.Val(expectedResult));
+
+	TOCSPOutcome expectedOutcome(STATIC_CAST(OCSP::TStatus, expectedStatus), STATIC_CAST(OCSP::TResult, expectedResult));
+
+	iTestResult = iTestResult && iEngine->TestOutcomeL(certIndex, expectedOutcome);
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::TestTransportCommandL()
+	{
+	if (iTokens.Count() != 4)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	TLex lex(iTokens[0]);
+	TInt retryCountNum = 0;
+	if ((lex.Val(retryCountNum) != KErrNone) || (retryCountNum < 0))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid request number in TESTTRANSPORT command"), ETrue);
+			}
+		User::Leave(KErrArgument);
+		}
+
+	// Check the method name supplied (do a case insensitive compare)
+	TPtrC ptrHttpMethod = iTokens[1];
+	if (ptrHttpMethod.CompareC(_L("GET"), 2, NULL) && 
+			ptrHttpMethod.CompareC(_L("POST"), 2, NULL))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid HTTP method name in TESTTRANSPORT command"), ETrue);
+			}
+		User::Leave(KErrArgument);
+		}
+
+	// Get the response time range
+	TInt expRespTimeRangeMin = 0;
+	TInt expRespTimeRangeMax = 0;
+	lex = iTokens[2];
+	if (lex.Val(expRespTimeRangeMin) != KErrNone)
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid range (min) for response time in TESTTRANSPORT command"), ETrue);
+			}
+		User::Leave(KErrArgument);
+		}
+
+	lex = iTokens[3];
+	if ((lex.Val(expRespTimeRangeMax) != KErrNone) || expRespTimeRangeMax < expRespTimeRangeMin)
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid range (max) for response time in TESTTRANSPORT command"), ETrue);
+			}
+		User::Leave(KErrArgument);
+		}
+
+	iTestResult = iTestResult && iEngine->TestTransportL(retryCountNum, ptrHttpMethod,  
+															expRespTimeRangeMin, expRespTimeRangeMax);
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::TestTransportRetryCommandL()
+	{
+	if (iTokens.Count() != 1)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+	TLex lex(iTokens[0]);
+	TInt retryCount = 0;
+	if ((lex.Val(retryCount) != KErrNone) || (retryCount < 0))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Invalid request count in TESTTRANSPORTRETRY command"), ETrue);
+			}
+		User::Leave(KErrArgument);
+		}
+
+	iTestResult = iTestResult && iEngine->TestTransportRetryL(retryCount);
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::LogResponseCommandL()
+	{
+	if (iTokens.Count() != 1)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+    iEngine->LogResponseL(iTokens[0]);
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+
+void CTOCSPCommand::LogRequestCommandL()
+	{
+	if (iTokens.Count() != 1)
+		{
+		WrongNumberOfArgumentsL();
+		}
+
+    iEngine->LogRequestL(iTokens[0]);
+
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+
+void CTOCSPCommand::SetVerbose(TBool aVerbose)
+	{
+	iVerbose = aVerbose;
+	iEngine->SetVerbose(aVerbose);
+	}
+
+
+void CTOCSPCommand::FinishedTestL()
+	{	
+	TBuf<64> timeBuf;
+	TTime time;
+	time.UniversalTime();
+	TDateTime dateTime = time.DateTime();
+	_LIT(KDateFormat,"%02d:%02d:%02d:%03d "); 
+	timeBuf.AppendFormat(KDateFormat,dateTime.Hour(),dateTime.Minute(),dateTime.Second(),(dateTime.MicroSecond()/1000));	
+		
+	iLog.LogL(_L("\r\n"));
+	iLog.LogL(timeBuf);	
+	iLog.LogL(_L("Command = END_TESTCASE "), EFalse);
+	iLog.LogL(iTmsId, ETrue);
+	iLog.LogL(_L(" ***TestCaseResult = "), ETrue);
+	
+	iResult.ResultL(iTestResult);
+	if (iVerbose)
+		{
+		if (iTestResult)
+			{
+			iLog.LogL(_L("PASS\n"), ETrue);
+			}
+		else
+			{
+			iLog.LogL(_L("FAIL\n"), ETrue);
+			}
+		}
+	}
+
+
+void CTOCSPCommand::WrongNumberOfArgumentsL()
+	{
+	iLog.LogL(_L("Wrong number of arguments for command"), ETrue);
+	User::Leave(KErrArgument);
+	}
+
+void CTOCSPCommand::InvalidArgumentL(const TDesC& aCommand, const TDesC& aCommandOptions )
+	{
+	iLog.LogL(_L("Invalid input for:"), ETrue);
+	iLog.LogL(aCommand, ETrue);
+	iLog.LogL(_L(", Expected:"), ETrue);
+	iLog.LogL(aCommandOptions, ETrue);
+	User::Leave(KErrArgument);
+	}
+
+void CTOCSPCommand::InvalidArgumentL(const TDesC& aCommand)
+	{
+	iLog.LogL(_L("Invalid input:"), ETrue);
+	iLog.LogL(aCommand, ETrue);
+	User::Leave(KErrArgument);
+	}
+
+void CTOCSPCommand::SetResponderCertCheck()
+	{
+	iEngine->SetReponderCertCheck();
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::AddCertToStoreL()
+{
+	if(iTokens.Count()!= 2)
+		{
+		WrongNumberOfArgumentsL();
+		}
+	
+	TPtrC certFileName = iTokens[0];
+	TPtrC certLabel = iTokens[1];
+	
+	iEngine->AddCertToStore(certFileName, certLabel, ECACertificate, iStatus);
+	
+	iState = EEngineEnd;
+	SetActive();
+}
+
+void CTOCSPCommand::SetCheckCertsWithAiaOnly()
+	{
+	iEngine->SetCheckCertsWithAiaOnly(ETrue);
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
+
+void CTOCSPCommand::SetUseAIAL()
+	{	
+	if (iTokens.Count() != 1) 
+		{
+		WrongNumberOfArgumentsL();
+		}
+	
+	if(iTokens[0].Compare(KTOCSPEnable) == 0)
+		{
+		iEngine->SetUseAIA(ETrue);
+		}
+	else if(iTokens[0].Compare(KTOCSPDisable) == 0)
+		{
+		iEngine->SetUseAIA(EFalse);
+		}
+	else
+		{
+		InvalidArgumentL(KTOCSPUseAIA,KTOCSPEnableDisable);
+		}
+	
+	User::RequestComplete(iOriginalRequestStatus, KErrNone);
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/command.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,168 @@
+// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Takes a line from a script file representing a command and its parameters,
+// interprets it and applies them to the engine
+// 
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+
+#ifndef __TOCSP_COMMAND_H__
+#define __TOCSP_COMMAND_H__
+
+#include <e32base.h>
+#include <ocsp.h>
+#include "t_input.h"
+
+class CTOCSPEngine;
+class CTOCSPResult;
+class CTOCSPLogger;
+class RFs;
+
+class CTOCSPCommand : public CActive
+	{
+public:
+	static CTOCSPCommand* NewL(CTOCSPLogger& aLog,
+							   CTOCSPResult& aResult,
+							   TInt aTransaction = 0);
+	~CTOCSPCommand();
+
+	// Return False means abort, True means carry on as normal
+	TBool ProcessCommand(const TDesC& aLine, TRequestStatus& aStatus);
+
+    // Reset internal state after processing a whole script
+	// Need to call this to make sure last test result is recorded
+    void ResetL();
+
+    // Get the index of the current transaction we're processing
+    TInt CurrentTransaction() const;
+
+	/** Set whether to print informational messages. */
+	void SetVerbose(TBool aVerbose);
+
+private:
+	void RunL();
+	void DoCancel();
+    TInt RunError(TInt aError);
+
+private:
+	CTOCSPCommand(CTOCSPLogger& aLog,
+				  CTOCSPResult& aResult,
+				  TInt aTransaction);
+
+	void ConstructL();
+
+	TBool DoProcessCommandL(const TDesC& aLine);    
+	TBool ProcessTestCommandL(const TDesC& command);
+
+	// Command functions
+	void UnknownCommandL(const TDesC& aCommand);
+	void PrintCommandL(const TDesC& aMess);
+
+	void StartCommandL();
+	void EndCommandL();
+	void SetURICommandL();
+
+
+	void CertCommandL();
+	void SetTransportCommandL();
+	void SetTransportRetryCommandL();
+	void SetTransportTimeoutCommandL();
+	void SetNonceCommandL();
+
+	void CancelCommandL();
+
+	void ValidationDateCommandL();
+	void DirectAuthorisationCommandL();
+	void CADelegateAuthorisationCommandL();
+	void CADirectAuthorisationCommandL();
+	void AllAuthorisationSchemesCommandL();
+	void SetMaxStatusAgeCommandL();
+	void SetFilterParamsCommandL();
+	void CheckCommand();
+	void TestCancelCommand();
+	void TestSummaryCommandL();
+	void TestOutcomeCommandL();
+	void TestTransportCommandL();
+	void TestTransportRetryCommandL();
+
+	void LogResponseCommandL();
+	void LogRequestCommandL();
+
+	void LogCommandL(const TDesC& line);
+	
+	void FinishedTestL();
+
+	void WrongNumberOfArgumentsL();
+
+	TTime ParseTimeL(TInt aStartToken);
+	
+	void SetResponderCertCheck();
+	void AddCertToStoreL();
+	void SetCheckCertsWithAiaOnly();
+	void SetUseAIAL();
+	
+	void InvalidArgumentL(const TDesC& aCommand, const TDesC& aCommandOptions);
+	void InvalidArgumentL(const TDesC& aCommand);
+	void LogErrorL();
+	
+private:
+	enum TState 
+		{
+		EEngineStart,
+		EEngineEnd,
+		EDirectAuthorisationCommand,
+		ECheckCommand
+		};
+
+private:
+	TState iState;
+	TRequestStatus* iOriginalRequestStatus;
+
+	CTOCSPResult& iResult;
+
+	CTOCSPLogger& iLog;
+
+	CTOCSPEngine* iEngine;
+
+	RArray<TPtrC> iTokens;
+
+	TInt iSkipping;
+
+	TBool iInsideTest;
+    TInt iTestIndex;
+    TInt iTestToProcess;
+
+	TBool iTestResult;
+
+	TPtrC iCert;
+	TPtrC iLabel;
+
+	TBool iVerbose;
+	TBool iTransportSet;
+
+	// Contains result of cancellation (ETrue if revocation successfully cancelled)
+	TBool iCheckCancelled;
+	TInt iError;
+	TBuf<128> iTmsId;
+
+	};
+
+/** Use direct authorisation without supplying an authorising cert. */
+_LIT(KAuthCertNone, "AUTHCERTNONE");
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/comms.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,52 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Contains utilities such as a global comms init function for starting c32
+// and loading device drivers for test code
+// 
+//
+
+#include "comms.h"
+
+#include <e32base.h>
+#include <c32comm.h>
+
+#if defined (__WINS__)
+#define PDD_NAME		_L("ECDRV")
+#else
+#define PDD_NAME		_L("EUART1")
+#define PDD2_NAME		_L("EUART2")
+#define PDD3_NAME		_L("EUART3")
+#define PDD4_NAME		_L("EUART4")
+#endif
+
+#define LDD_NAME		_L("ECOMM")
+
+void InitCommsL(void)
+	{
+	TInt ret = User::LoadPhysicalDevice(PDD_NAME);
+	User::LeaveIfError(ret == KErrAlreadyExists ? KErrNone : ret);
+
+#ifndef __WINS__
+	User::LoadPhysicalDevice(PDD2_NAME);
+	User::LoadPhysicalDevice(PDD3_NAME);
+	User::LoadPhysicalDevice(PDD4_NAME);
+#endif
+
+	ret = User::LoadLogicalDevice(LDD_NAME);
+	User::LeaveIfError(ret == KErrAlreadyExists ? KErrNone : ret);
+
+	ret = StartC32();
+	User::LeaveIfError(ret == KErrAlreadyExists ? KErrNone : ret);
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/comms.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,30 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// command.h
+// Declare comms initialisation function
+// 
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+
+#ifndef __TOCSP_COMMS_H__
+#define __TOCSP_COMMS_H__
+
+void InitCommsL(void);
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/engine.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1123 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+#include "engine.h"
+#include "transport.h"
+#include "panic.h"
+#include "logger.h"
+#include "main.h"
+#include "requestlogger.h"
+#include "testfilterparameters.h"
+#include <miscutil.h>
+
+#include <ocsp.h>
+#include <x509cert.h>
+
+#include <ocsptransport.h>
+
+#include "ocspsupporttransport.h"
+
+// Log file created by the transport filter
+_LIT(KFilterLogFileName, "\\tocsphttpfilter.log");
+
+const TInt KTimeMilliToMicro = 1000;
+
+CTOCSPEngine* CTOCSPEngine::NewL(CTOCSPLogger& aLog)
+	{
+	CTOCSPEngine* self = new (ELeave) CTOCSPEngine(aLog);
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+
+CTOCSPEngine::CTOCSPEngine(CTOCSPLogger& aLog) :
+	CActive(EPriorityNormal),
+	iLog(aLog)
+	{
+	CActiveScheduler::Add(this);
+	}
+
+
+void CTOCSPEngine::ConstructL()
+	{
+	// Open file server session
+	User::LeaveIfError(iFs.Connect());
+	iCertUtils = CCertUtils::NewL(iFs);
+
+	// Create cancellation timer
+	iTimer = CCallbackTimer::NewL(*this);
+	}
+
+CTOCSPEngine::~CTOCSPEngine()
+	{
+    Cancel(); // Calls Reset along the way
+	Destroy();
+	delete iTimer;
+	delete iCertUtils;
+	delete iUnifiedCertStore;
+	iFs.Close();
+	}
+
+// Common code between destructor and ResetL()
+void CTOCSPEngine::Destroy()
+	{
+	delete iParams;
+	iParams = NULL;
+	
+	delete iClient;
+	iClient = NULL;
+	
+	iSubjectCerts.ResetAndDestroy();
+	iIssuerCerts.ResetAndDestroy();
+	iSigningCerts.ResetAndDestroy();
+	iTransportLog.Close();
+
+	delete iRequestLog;
+	iRequestLog = NULL;
+
+	// Not owned
+	iTransport = NULL;
+	}
+
+void CTOCSPEngine::Reset()
+	{
+	Destroy();
+
+	// Delete and reset all the filter parameters
+	DeleteFilterParameters();
+
+	iUseDirectAuthorisation = EFalse;
+	iUseCADelegateAuthorisation = EFalse;
+	iUseCADirectAuthorisation = EFalse;
+	iUseAllSchemes = EFalse;
+
+	iCancelTime = 0;
+	}
+
+
+void CTOCSPEngine::StartL(TRequestStatus& aStatus)
+	{	
+	iParams = COCSPParameters::NewL();	
+	InitDirectAuthL();
+
+	// Delete the transport filter log file
+	TInt err = iFs.Delete(KFilterLogFileName);
+	if ((err != KErrNone) && (err != KErrNotFound))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Failed to delete transport filter log file ("), ETrue);
+			iLog.LogL(KFilterLogFileName);
+			iLog.LogL(_L("). Error: "), ETrue);
+			iLog.LogL(err);
+			}
+		User::Leave(err);
+		}
+
+	iState = EInitCertStore;
+	aStatus = KRequestPending;
+	iOriginalRequestStatus = &aStatus;
+	SetActive();
+		
+	// Initialise unified cert store here if it doesn't already exist
+	if (!iUnifiedCertStore)
+		{
+		iUnifiedCertStore = CUnifiedCertStore::NewL(iFs, ETrue);
+		iUnifiedCertStore->Initialize(iStatus);
+		}
+	else
+		{
+		TRequestStatus* status = &iStatus;
+		User::RequestComplete(status, KErrNone);
+		}
+	}
+
+void CTOCSPEngine::EndL(TRequestStatus& aStatus)
+	{
+	Reset();
+	CleanUpDirectAuthL(aStatus);
+	}
+
+
+void CTOCSPEngine::SetURIL(const TDesC8& aURI, TBool aUseAIA)
+	{
+	iParams->SetURIL(aURI, aUseAIA);
+	}
+
+
+void CTOCSPEngine::SetDefaultTransportL()
+	{
+	iIap = 0;
+	MOCSPTransport* trans = COCSPTransportDefault::NewL(iIap);
+	CleanupStack::PushL(trans);
+	SetTransportL(trans);
+	CleanupStack::Pop(trans);
+	}
+
+
+void CTOCSPEngine::SetTestTransportL(const TDesC& aResponseFile, const TDesC* aRequestFile)
+	{
+	CTOCSPTransport* trans = CTOCSPTransport::NewL(aResponseFile, aRequestFile);
+	CleanupStack::PushL(trans);
+	SetTransportL(trans);
+	CleanupStack::Pop(trans);
+	}
+
+void CTOCSPEngine::SetOcspSupportTransportL()
+	{
+	iIap = 0;
+	Swi::COcspSupportTransport* trans = Swi::COcspSupportTransport::NewL(iIap);
+
+	CleanupStack::PushL(trans);
+	SetTransportL(trans);
+	CleanupStack::Pop(trans);
+	}
+
+void CTOCSPEngine::SetTransportRetryCount(TUint aRetryCount)
+	{
+	__ASSERT_DEBUG(iTransport != NULL, Panic(KErrTOCSPScriptParameterError));
+	iParams->SetRetryCount(aRetryCount);
+	}
+
+void CTOCSPEngine::SetTransportTimeout(TInt aTimeout)
+	{
+	__ASSERT_DEBUG(iTransport != NULL, Panic(KErrTOCSPScriptParameterError));
+	iParams->SetTimeout(aTimeout);
+	}
+
+void CTOCSPEngine::SetTransportL(MOCSPTransport* aTransport)
+	{
+	// To log the request, we wrap the transport in our request logger transport
+	if (iRequestLog)
+		{
+		aTransport = CTOCSPRequestLogger::NewL(*iRequestLog, aTransport);
+		}
+	iTransport = aTransport;
+	iParams->SetTransport(aTransport);
+	}
+
+void CTOCSPEngine::SetFilterParameters(TInt aNumDelayResp, TInt aCountDropResp,
+			TInt countCorruptHTTPDataHeader, TInt countCorruptHTTPDataBodySizeLarge, TInt countCorruptHTTPDataBodySizeSmall, 
+			TInt aCountCorruptOCSPData, 
+			TInt aCountInternalErrorResp, TInt aCountTryLaterResp,
+			TInt aCountSigValidateFailure)
+	{
+	iNumDelayResp = aNumDelayResp;
+	iCountDropResp = aCountDropResp;
+	iCountCorruptHTTPDataHeader = countCorruptHTTPDataHeader;
+	iCountCorruptHTTPDataBodySizeLarge = countCorruptHTTPDataBodySizeLarge;
+	iCountCorruptHTTPDataBodySizeSmall = countCorruptHTTPDataBodySizeSmall;
+	iCountCorruptOCSPData = aCountCorruptOCSPData;
+	iCountInternalErrorResp = aCountInternalErrorResp;
+	iCountTryLaterResp = aCountTryLaterResp;
+	iCountSigValidateFailure = aCountSigValidateFailure;
+	}
+
+void CTOCSPEngine::AddCertL(const TDesC8& aSubject, const TDesC8& aIssuer)
+	{
+	// Create certificate objects and keep hold of them - these are added
+	// to the client later
+
+	CX509Certificate* subject = CX509Certificate::NewLC(aSubject);
+	User::LeaveIfError(iSubjectCerts.Append(subject));
+	CleanupStack::Pop(subject);  // Now owned through iCerts
+
+	CX509Certificate* issuer = CX509Certificate::NewLC(aIssuer);
+	User::LeaveIfError(iIssuerCerts.Append(issuer));
+	CleanupStack::Pop(issuer);  // Now owned through iCerts
+	
+	// Add certificates to parameter
+	iParams->AddCertificateL(*subject, *issuer);
+	}
+
+void CTOCSPEngine::ReadTransportLogL()
+	{
+	// Read and process the transport filter log (if it exists)
+	RFile file;
+	TInt size;
+	if (file.Open(iFs, KFilterLogFileName, EFileShareAny | EFileRead) != KErrNone)
+		{
+		return;
+		}
+
+	CleanupClosePushL(file);
+	file.Size(size);
+	RFileReadStream fileStream(file);
+	CleanupClosePushL(fileStream);
+	RBuf8 logBuffer;
+	logBuffer.CreateL(size);
+	CleanupClosePushL(logBuffer);
+	fileStream.ReadL(logBuffer, size);
+	TInt readPos = 0;
+	TPtrC8 currentLine;
+	while (MiscUtil::ReadNonEmptyLineL(logBuffer, readPos, currentLine))
+		{
+		TLex8 lex(currentLine);
+		TPtrC8 methodName = lex.NextToken();
+
+		// Validate and store the entry
+		TTransportLog logEntry;
+		if (methodName.Length() <= 4)
+			{
+			logEntry.iHttpMethod.Copy(methodName);
+			logEntry.iHttpMethod.UpperCase();
+			}
+
+		// Get the timestamps and calculate transaction duration
+		TInt64 startTime = 0;
+		TInt64 endTime = 0;
+		lex.SkipSpaceAndMark(); User::LeaveIfError(lex.Val(startTime));
+		lex.SkipSpaceAndMark(); User::LeaveIfError(lex.Val(endTime));
+		logEntry.iTransDurationMs = static_cast<TInt64>((endTime - startTime) / KTimeMilliToMicro);
+
+		iTransportLog.AppendL(logEntry);
+		}
+	CleanupStack::PopAndDestroy(3, &file); // fileStream, logBuffer
+	}
+
+TBool CTOCSPEngine::ReadLineL(const TDesC8& aBuffer, TInt& aPos, TPtrC8& aLine) const
+	{
+	TBool endOfBuffer = EFalse;	
+	aLine.Set(NULL, 0);
+
+	TInt bufferLength = aBuffer.Length();	
+	__ASSERT_ALWAYS(aPos >=0 && aPos <= bufferLength, User::Leave(KErrArgument));
+
+	// Skip blank lines
+	while (aPos < bufferLength) 
+		{
+		TChar  c = aBuffer[aPos];
+		if (c != '\r' && c != '\n')
+			{
+			break;
+			}
+		aPos++;
+		}
+
+	// Find the position of the next delimter		
+	TInt endPos = aPos;	
+	while (endPos < bufferLength)
+		{
+		TChar c = aBuffer[endPos];
+		if (c == '\n' || c == '\r') 
+			{
+			break;
+			}	
+		++endPos;
+		}
+
+	if (endPos != aPos)	
+		{
+		TInt tokenLen = endPos - aPos;
+		aLine.Set(&aBuffer[aPos], tokenLen);
+		}
+	else 
+		{
+		return ETrue; // End of buffer
+		}			
+
+	aPos = endPos;
+	return endOfBuffer;
+	}
+
+void CTOCSPEngine::LogResponseDetailsL()
+	{
+	if (iVerbose)
+		{
+		_LIT(KDateFormat, "%F%H:%T %D/%M/%Y");
+		TBuf<32> timeString;
+
+		iLog.LogL(_L("Response details:\n"));
+
+		TTime timeNow;
+		timeNow.UniversalTime();
+		timeNow.FormatL(timeString, KDateFormat);
+		iLog.LogL(_L("  Response generation time == "));
+		iLog.LogL(timeString);
+		iLog.LogL(_L("\n"));
+
+		TBuf<10> indexText;
+
+		for (int i = 0 ; i < iClient->TransactionCount() ; ++i)
+			{
+			const COCSPResponse* response = iClient->Response(i);
+
+			iLog.LogL(_L("  Response "));
+			indexText.Zero();
+			indexText.Num(i);
+			iLog.LogL(indexText);
+			iLog.LogL(_L(":\n"));
+
+			if (response)
+				{
+				response->ProducedAt().FormatL(timeString, KDateFormat);
+				iLog.LogL(_L("    producedAt == "));
+				iLog.LogL(timeString);
+				iLog.NewLineL();
+	
+				TInt count = response->CertCount();
+				for (TInt index = 0; index < count; ++index)
+					{
+					const COCSPResponseCertInfo& certInfo = response->CertInfo(index);
+
+					iLog.LogL(_L("    Cert "));
+					indexText.Zero();
+					indexText.Num(index);
+					iLog.LogL(indexText);
+					iLog.LogL(_L(" Results:"));
+			
+					iLog.LogL(_L("\n      status == "));
+					iLog.LogL(TranslateResultL(certInfo.Status()));
+
+					certInfo.ThisUpdate().FormatL(timeString, KDateFormat);
+					iLog.LogL(_L("\n      thisUpdate == "));
+					iLog.LogL(timeString);
+					iLog.NewLineL();
+
+					if (certInfo.NextUpdate())
+						{
+						timeString.Zero();
+						certInfo.NextUpdate()->FormatL(timeString, KDateFormat);
+						iLog.LogL(_L("      nextUpdate == "));
+						iLog.LogL(timeString);
+						iLog.NewLineL();
+						}
+
+					if (certInfo.RevocationTime())
+						{
+						timeString.Zero();
+						certInfo.RevocationTime()->FormatL(timeString, KDateFormat);
+						iLog.LogL(_L("      revocationTime == "));
+						iLog.LogL(timeString);
+						iLog.NewLineL();
+						}
+					}
+				}
+			else
+				{
+				iLog.LogL(_L("    missing"));			
+				iLog.NewLineL();
+				}
+
+			const TOCSPOutcome& outcome = iClient->Outcome(i);
+			iLog.LogL(_L("    Validation outcome:"));
+			iLog.NewLineL();
+			iLog.LogL(_L("      status == "));
+			iLog.LogL(TranslateStatusL(outcome.iStatus));
+			iLog.NewLineL();
+			iLog.LogL(_L("      result == "));
+			iLog.LogL(TranslateResultL(outcome.iResult));
+			iLog.NewLineL();
+			}
+
+		iLog.LogL(_L("  OCSP Summary result == "));
+		iLog.LogL(TranslateResultL(iClient->SummaryResult()));
+		iLog.NewLineL();
+		}
+	}
+
+
+void CTOCSPEngine::RunL()
+	{
+	TInt err = iStatus.Int();
+	if( KErrNotFound != err && KErrNone != err )
+		{
+		iLog.LogL(_L("Client request completed with code:"));  
+		iLog.LogL(err);
+		iLog.NewLineL();
+		User::LeaveIfError(err);
+		}
+
+	if( KErrNotFound == err )
+		{
+		iLog.LogL(_L("Item not found leave code"));
+		iLog.NewLineL();
+		// Handle error
+		User::Leave(err);
+		}
+
+	switch (iState)
+		{
+		case EInitCertStore:
+			// Remove all certificates so we always start from the same state 
+			iCertUtils->RemoveCertsL(*iUnifiedCertStore, iStatus);
+			iState = ERemovingCerts;
+			SetActive();
+			break;
+			
+		case EAddingCert:
+		case ERemovingCerts:
+			User::RequestComplete(iOriginalRequestStatus, KErrNone);
+			break;
+
+		case EChecking:
+			// Cancel the timer
+			iTimer->Cancel();
+			ReadTransportLogL();
+			LogResponseDetailsL();
+			User::RequestComplete(iOriginalRequestStatus, KErrNone);
+			break;
+
+		default:
+            User::Panic(_L("TOCSP"), 1);
+			break;
+		}
+	}
+
+TInt CTOCSPEngine::RunError(TInt aError)
+    {
+    User::RequestComplete(iOriginalRequestStatus, aError);
+    return KErrNone;
+    }
+
+void CTOCSPEngine::DoCancel()
+	{
+    switch (iState)
+        {
+		case EInitCertStore:
+			if (iUnifiedCertStore)
+				{
+				iUnifiedCertStore->CancelInitialize();
+				}
+			break;
+			
+		case EAddingCert:
+		case ERemovingCerts:
+            iCertUtils->Cancel();
+            break;
+
+		case EChecking:
+            iClient->CancelCheck();
+            break;
+
+		default:
+            User::Panic(_L("TOCSP"), 1);
+			break;
+        }
+
+	Reset();
+    User::RequestComplete(iOriginalRequestStatus, KErrCancel);
+	}
+
+// Implementation of MTimerRun
+void CTOCSPEngine::TimerRun(TInt /*aError*/)
+	{
+	// Cancellation timer expired
+	this->Cancel();
+	}
+
+void CTOCSPEngine::SetValidationTimeL(const TTime& aWhen)
+	{
+	iParams->SetValidationTimeL(aWhen);
+	}
+
+
+void CTOCSPEngine::SetNonce(const TBool aNonce)
+	{
+	iParams->SetUseNonce(aNonce);
+	}
+
+
+void CTOCSPEngine::SetMaxStatusAgeL(TUint aMaxAge)
+	{
+	iParams->SetMaxStatusAgeL(aMaxAge);
+	}
+
+void CTOCSPEngine::InitDirectAuthL()
+	{
+	// Add OCSP test harness to cert store client list
+	TName name(_L("TOCSP"));
+	iCertUtils->AddApplicationL(name, TUid::Uid(KTOCSP_UID));
+	}
+
+void CTOCSPEngine::CleanUpDirectAuthL(TRequestStatus& aStatus)
+	{
+	iOriginalRequestStatus = &aStatus;
+	aStatus = KRequestPending;
+
+	// Should always succeed, as called after InitDirectAuthL
+	iCertUtils->RemoveApplicationL(TUid::Uid(KTOCSP_UID));
+
+	//This should remove the X509Certs, which is the only certificate type used by the test.
+	iCertUtils->RemoveCertsL(*iUnifiedCertStore, iStatus);
+	iState = ERemovingCerts;
+	SetActive();
+	}
+
+void CTOCSPEngine::AddDirectAuthorisationCert(const TDesC& aCert,
+                                              const TDesC& aLabel,
+                                              TRequestStatus& aStatus)
+	{
+    TRAPD(err, DoAddDirectAuthorisationCertL(aCert, aLabel, aStatus));
+    if (err != KErrNone)
+        {
+        Cancel();
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete(status, err);
+        }
+    }
+
+void CTOCSPEngine::DoAddDirectAuthorisationCertL(const TDesC& aCert,
+												 const TDesC& aLabel,
+												 TRequestStatus& aStatus)
+	{
+	TPtrC cert = aCert;
+	HBufC8* certData = ReadDataL(iFs, cert);
+	CleanupStack::PushL(certData);
+
+	// Make and store the certificate
+	CX509Certificate* cert2 = CX509Certificate::NewLC(*certData);
+	User::LeaveIfError(iSigningCerts.Append(cert2));
+	CleanupStack::Pop(cert2);  // Now owned through iCerts
+	CleanupStack::PopAndDestroy(certData);
+	
+	iUseDirectAuthorisation = ETrue;
+
+	iCert = aCert;
+	iLabel = aLabel;	
+
+	iOriginalRequestStatus = &aStatus;
+	aStatus = KRequestPending;
+	iState = EAddingCert;
+
+	iCertUtils->AddCert(iLabel, EX509Certificate, ECACertificate, KTOCSP_UID,
+						KNullDesC, iCert, *iUnifiedCertStore, iStatus);
+	SetActive();
+	}
+
+
+/**
+	Called when "AUTHORISATIONCERT AUTHCERTNONE" is parsed.
+	Sets a flag so an instance of COCSPDirectAuthorisationScheme
+	is allocated in PrepareAuthorisationSchemeL().
+	
+	This function should be used to test direct authorisation
+	without supplying a cert.  When a cert is supplied, use
+	AddDirectAuthorisationCert().
+	
+	@see AddDirectAuthorisationCert
+	@see UseCADelegateAuthorisation
+ */
+void CTOCSPEngine::UseDirectAuthorisation()
+	{
+	iUseDirectAuthorisation = ETrue;	
+	}
+
+/**
+	Called when a "CADELEGATE" command is parsed.  It sets
+	a flag so that an instance of COCSPDelegateAuthorisationScheme
+	is allocated in PrepareAuthorisationSchemeL().
+
+	@see AddDirectAuthorisationCert
+	@see UseCADirectAuthorisation
+ */
+void CTOCSPEngine::UseCADelegateAuthorisation()
+	{
+	iUseCADelegateAuthorisation = ETrue;
+	}
+
+/**
+	Called when "CADIRECT" command is parsed.  It sets
+	a flag so that an instance of COCSPCaDirectAuthorisationScheme
+	is allocated in PrepareAuthorisationSchemeL().
+
+	@see AddDirectAuthorisationCert
+	@see UseCADelegateAuthorisation
+ 	@see UseDirectAuthorisation
+*/
+void CTOCSPEngine::UseCADirectAuthorisation()
+	{
+	iUseCADirectAuthorisation = ETrue;
+	}
+
+/**
+	Called when "ALLSCHEMES" command is parsed.  It sets
+	a flag so that all schemes are allocated in 
+	PrepareAuthorisationSchemeL().
+
+	@see AddDirectAuthorisationCert
+	@see UseCADelegateAuthorisation
+	@see UseCADirectAuthorisation
+*/
+void CTOCSPEngine::UseAllAuthorisationSchemes()
+	{
+	iUseAllSchemes = ETrue;
+	}
+
+void CTOCSPEngine::PrepareAuthorisationL()
+	{
+	if (iUseAllSchemes)
+		{
+		// iUseDirectAuthorisation may also be set because
+		// "AUTHORISATIONCERT" commands have been parsed.
+		ASSERT(!(iUseCADelegateAuthorisation || iUseCADirectAuthorisation));
+
+		// This assumes __SECURITY_PLATSEC_ARCH__ is defined.  This
+		// is the case because AddAllAuthorisationSchemesL() is added
+		// to 9.1 onwards.
+		iParams->AddAllAuthorisationSchemesL(TUid::Uid(KTOCSP_UID), *iUnifiedCertStore);
+		return;
+		}
+
+	if (iUseDirectAuthorisation)
+		{
+		// Register direct authorisation object with OCSP validator
+		COCSPDirectAuthorisationScheme* scheme =  
+			COCSPDirectAuthorisationScheme::NewLC(TUid::Uid(KTOCSP_UID), *iUnifiedCertStore);
+		iParams->AddAuthorisationSchemeL(scheme);
+		CleanupStack::Pop(); // scheme, now owned by client
+		}
+	
+	if (iUseCADelegateAuthorisation)
+		{
+		COCSPDelegateAuthorisationScheme* schemeDel =
+			COCSPDelegateAuthorisationScheme::NewLC(*iUnifiedCertStore);
+		iParams->AddAuthorisationSchemeL(schemeDel);
+		CleanupStack::Pop(schemeDel); // scheme, now owned by client		
+		}
+	
+	if (iUseCADirectAuthorisation)
+		{
+		COCSPCaDirectAuthorisationScheme* schemeCad =
+			COCSPCaDirectAuthorisationScheme::NewLC();
+		iParams->AddAuthorisationSchemeL(schemeCad);
+		CleanupStack::Pop(schemeCad); // scheme, now owned by client		
+		}
+	}
+
+// Set filter parameters
+void CTOCSPEngine::DefineAndSetFilterParametersL()
+	{
+	TUid categoryUid = TUid::Uid(KFilterParametersCategoryUID);
+
+	// Define the parameters
+	RProperty::Define(categoryUid, KFilterParameterNumDelayResp, RProperty::EInt);
+	RProperty::Define(categoryUid, KFilterParameterCountDropResp, RProperty::EInt);
+	RProperty::Define(categoryUid, KFilterParameterCountCorruptHTTPDataHeader, RProperty::EInt);
+	RProperty::Define(categoryUid, KFilterParameterCountCorruptHTTPDataBodySizeLarge, RProperty::EInt);
+	RProperty::Define(categoryUid, KFilterParameterCountCorruptHTTPDataBodySizeSmall, RProperty::EInt);
+	RProperty::Define(categoryUid, KFilterParameterCountCorruptOCSPData, RProperty::EInt);
+	RProperty::Define(categoryUid, KFilterParameterCountInternalErrorResp, RProperty::EInt);
+	RProperty::Define(categoryUid, KFilterParameterCountTryLaterResp, RProperty::EInt);
+	RProperty::Define(categoryUid, KFilterParameterCountSigValidateFailure, RProperty::EInt);
+
+	// and Set them
+	User::LeaveIfError(RProperty::Set(categoryUid, KFilterParameterNumDelayResp, iNumDelayResp));
+	User::LeaveIfError(RProperty::Set(categoryUid, KFilterParameterCountDropResp, iCountDropResp));
+	User::LeaveIfError(RProperty::Set(categoryUid, KFilterParameterCountCorruptHTTPDataHeader, iCountCorruptHTTPDataHeader));
+	User::LeaveIfError(RProperty::Set(categoryUid, KFilterParameterCountCorruptHTTPDataBodySizeLarge, iCountCorruptHTTPDataBodySizeLarge));
+	User::LeaveIfError(RProperty::Set(categoryUid, KFilterParameterCountCorruptHTTPDataBodySizeSmall, iCountCorruptHTTPDataBodySizeSmall));
+	User::LeaveIfError(RProperty::Set(categoryUid, KFilterParameterCountCorruptOCSPData, iCountCorruptOCSPData));
+	User::LeaveIfError(RProperty::Set(categoryUid, KFilterParameterCountInternalErrorResp, iCountInternalErrorResp));
+	User::LeaveIfError(RProperty::Set(categoryUid, KFilterParameterCountTryLaterResp, iCountTryLaterResp));
+	User::LeaveIfError(RProperty::Set(categoryUid, KFilterParameterCountSigValidateFailure, iCountSigValidateFailure));
+	}
+
+void CTOCSPEngine::DeleteFilterParameters()
+	{
+	TUid categoryUid = TUid::Uid(KFilterParametersCategoryUID);
+	RProperty::Delete(categoryUid, KFilterParameterNumDelayResp);
+	RProperty::Delete(categoryUid, KFilterParameterCountDropResp);
+	RProperty::Delete(categoryUid, KFilterParameterCountCorruptHTTPDataHeader);
+	RProperty::Delete(categoryUid, KFilterParameterCountCorruptHTTPDataBodySizeLarge);
+	RProperty::Delete(categoryUid, KFilterParameterCountCorruptHTTPDataBodySizeSmall);
+	RProperty::Delete(categoryUid, KFilterParameterCountCorruptOCSPData);
+	RProperty::Delete(categoryUid, KFilterParameterCountInternalErrorResp);
+	RProperty::Delete(categoryUid, KFilterParameterCountTryLaterResp);
+	RProperty::Delete(categoryUid, KFilterParameterCountSigValidateFailure);
+	// Reset the params
+	iNumDelayResp = iCountDropResp = iCountCorruptHTTPDataHeader = iCountCorruptHTTPDataBodySizeLarge = 
+		iCountCorruptHTTPDataBodySizeSmall = iCountCorruptOCSPData = iCountInternalErrorResp = 
+		iCountTryLaterResp = iCountSigValidateFailure = 0;
+	}
+
+void CTOCSPEngine::SetCancelTime(TInt aTime)
+	{
+	iCancelTime = aTime;
+	}
+
+void CTOCSPEngine::Check(TRequestStatus& aStatus)
+	{
+    TRAPD(err, DoCheckL(aStatus));
+    if (err != KErrNone)
+        {
+        Cancel();
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete(status, err);
+        }
+    }
+
+void CTOCSPEngine::DoCheckL(TRequestStatus& aStatus)
+ 	{
+	iOriginalRequestStatus = &aStatus;
+	aStatus = KRequestPending;
+	iState = EChecking;
+
+	PrepareAuthorisationL();
+
+	// Set filter parameters
+	DefineAndSetFilterParametersL();
+
+	if (iVerbose)
+		{
+		iLog.LogL(_L("Checking...\n"), ETrue);
+		}
+
+	iClient = COCSPClient::NewL(iParams);
+	iParams = NULL; // Client takes ownership
+
+	// Setup cancellation timer
+	if (iCancelTime)
+		{
+		iTimer->After(iCancelTime * KTimeMilliToMicro);
+		}
+	iClient->Check(iStatus);
+	SetActive();
+ 	}
+
+void CTOCSPEngine::LogValidationL(const TOCSPOutcome& aOutcome) const
+	{
+	if (iVerbose)
+		{
+		iLog.LogL(_L("Validation complete:\n  status == "));
+		iLog.LogL(TranslateStatusL(aOutcome.iStatus));
+	
+		// Output summary result
+		iLog.LogL(_L("\n  summary result == "));
+		iLog.LogL(TranslateResultL(aOutcome.iResult));
+		iLog.NewLineL();
+		}
+	}
+
+
+TPtrC CTOCSPEngine::TranslateStatusL(OCSP::TStatus aStatus)
+	{
+	switch ((TInt) aStatus)
+		{
+		case OCSP::ETransportError:
+			return _L("Transport error");
+		case OCSP::ETimeOut:
+			return _L("Request timedout");
+		case OCSP::EClientInternalError:
+			return _L("Client internal error");
+		case OCSP::ENoServerSpecified:
+			return _L("No server specified");
+		case OCSP::EInvalidURI:
+			return _L("Invalid URI");
+		case OCSP::EMalformedResponse:
+			return _L("Malformed response");
+		case OCSP::EUnknownResponseType:
+			return _L("Unknown response type");
+		case OCSP::EUnknownCriticalExtension:
+			return _L("Unknown critical extension");
+		case OCSP::EMalformedRequest:
+			return _L("Server: Malformed request");
+		case OCSP::EServerInternalError:
+			return _L("Server: Internal error");
+		case OCSP::ETryLater:
+			return _L("Server: Try later");
+		case OCSP::ESignatureRequired:
+			return _L("Server: Signature required");
+		case OCSP::EClientUnauthorised:
+			return _L("Server: Client unauthorised");
+		case OCSP::EMissingCertificates:
+			return _L("Missing certificates");
+		case OCSP::EResponseSignatureValidationFailure:
+			return _L("Response signature validation failure");
+		case OCSP::EThisUpdateTooLate:
+			return _L("Time error: This update too late");
+		case OCSP::EThisUpdateTooEarly:
+			return _L("Time error: This update too early");
+		case OCSP::ENextUpdateTooEarly:
+			return _L("Time error: Next update too early");
+		case OCSP::ECertificateNotValidAtValidationTime:
+			return _L("Time error: Not valid at validation time");
+		case OCSP::ENonceMismatch:
+			return _L("Nonce mismatch");			
+		case OCSP::EMissingNonce:
+			return _L("Missing nonce");
+		case OCSP::EValid:
+			return _L("Valid");
+		case TOCSP::ETooManyTransactions:
+			return _L("(test) Too many transactions");
+		case TOCSP::EURIMismatch:
+			return _L("(test) URI mismatch");
+		case TOCSP::ERequestMismatch:
+			return _L("(test) Request mismatch");
+		default:
+			return _L("Unknown");
+		}
+	}
+
+
+TPtrC CTOCSPEngine::TranslateResultL(OCSP::TResult aResult)
+	{
+	switch (aResult)
+		{
+		case OCSP::EGood:
+			return _L("Good");
+		case OCSP::ERevoked:
+			return _L("Revoked");
+		case OCSP::EUnknown:
+			return _L("Unknown");
+		default:
+			return _L("Unknown");
+		}
+	}
+
+
+HBufC8* CTOCSPEngine::ReadDataL(RFs& session, const TDesC& aFileName) const
+	{
+	RFile file;
+	User::LeaveIfError(file.Open(session, aFileName, EFileRead | EFileShareReadersOnly));
+	CleanupClosePushL(file);
+
+	TInt size = 0;
+	User::LeaveIfError(file.Size(size));
+
+	HBufC8* data = HBufC8::NewLC(size);
+	TPtr8 dataPtr = data->Des();
+	User::LeaveIfError(file.Read(dataPtr));
+
+	CleanupStack::Pop(data);
+	CleanupStack::PopAndDestroy(); // Close file;
+	
+	return data;
+	}
+
+
+void CTOCSPEngine::LogRequestL(const TDesC& aFilename)
+    {
+	delete iRequestLog;
+	iRequestLog = NULL;
+
+	iRequestLog = aFilename.AllocL();
+	}
+
+
+void CTOCSPEngine::LogResponseL(const TDesC& aFilename)
+    {
+	RFs fs;
+	User::LeaveIfError(fs.Connect());
+	CleanupClosePushL(fs);
+
+	TInt err = fs.MkDirAll(aFilename);
+	if (err != KErrAlreadyExists)
+		{
+		User::LeaveIfError(err);
+		}
+
+	RFile file;
+	User::LeaveIfError(file.Replace(fs, aFilename, EFileWrite));
+	CleanupClosePushL(file);
+
+	RFileWriteStream writeStream(file);
+	CleanupClosePushL(writeStream);
+
+	writeStream.WriteUint32L(iClient->TransactionCount());
+
+	for (int i = 0 ; i < iClient->TransactionCount() ; ++i)
+		{
+		const COCSPResponse* response = iClient->Response(i);
+		if (response)
+			{
+			const TPtrC8 data = response->Encoding();
+			writeStream.WriteUint32L(data.Length());
+			writeStream.WriteL(data);
+			}
+		else
+			{
+			writeStream.WriteUint32L(0);
+			}
+		}
+
+	CleanupStack::PopAndDestroy(3); // writeStream, file, fs
+    }
+
+
+void CTOCSPEngine::SetVerbose(TBool aVerbose)
+	{
+	iVerbose = aVerbose;
+	}
+
+TBool CTOCSPEngine::TestSummaryL(OCSP::TResult aExpected)
+	{
+	TBool result = iClient->SummaryResult() == aExpected;
+
+	if (iVerbose && !result)
+		{
+		iLog.LogL(_L("Summary result fail: expected "));
+		iLog.LogL(aExpected);
+		iLog.NewLineL();
+		}
+
+	return result;
+	}
+
+TBool CTOCSPEngine::TestOutcomeL(TInt aIndex, const TOCSPOutcome& aExpected)
+	{
+	TBool result = EFalse;
+	// This assumes one-transaction-per-certificate behaviour
+	if(iClient)
+		{
+		result = iClient->Outcome(aIndex) == aExpected;
+		}
+
+	if (iVerbose && !result)
+		{
+		iLog.LogL(_L("Outcome result fail for cert "));
+		iLog.LogL(aIndex);
+		iLog.LogL(_L(":\n"));
+		//iLog.LogL(_L("Expected Result:\n"));
+		iLog.LogL(_L("Expected Status == "));
+		iLog.LogL(TranslateStatusL(aExpected.iStatus));
+		iLog.NewLineL();
+		iLog.LogL(_L("Expected Result == "));
+		iLog.LogL(TranslateResultL(aExpected.iResult));
+		iLog.NewLineL();
+		}
+
+	return result;
+	}
+
+void CTOCSPEngine::SetReponderCertCheck()
+	{
+	iParams->SetOCSPCheckForResponderCert(ETrue);
+	}
+
+void CTOCSPEngine::AddCertToStore(const TDesC& aCertFileName, const TDesC& aLabel, TCertificateOwnerType aCertType, TRequestStatus& aStatus)
+	{
+	iOriginalRequestStatus = &aStatus;
+	aStatus = KRequestPending;
+	iState = EAddingCert;
+	
+	iCert = aCertFileName;
+	iLabel = aLabel;	
+	
+	iCertUtils->AddCert(iLabel, EX509Certificate, aCertType, KTOCSP_UID,
+						KNullDesC, iCert, *iUnifiedCertStore, iStatus);		
+	
+	SetActive();
+	}
+
+TBool CTOCSPEngine::TestTransportL(TInt aRetryCountNum, const TDesC& aExpectedHttpMethod, 
+		TInt aExpectedRespTimeMin, TInt aExpectedRespTimeMax)
+	{
+	// This assumes one-tranaction-per-certificate behaviour
+	// This also assumes test case includes only certificate revocation check request (which 
+	// means CHECKRESPONDERCERT command cannot be used with this)
+	// Ensure we have read the entry from the transport log
+	TBool result = ETrue;
+	if (iTransportLog.Count() < (aRetryCountNum + 1))
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Transport filter log contains insufficient entries: "));
+			iLog.LogL(_L("\n  Expected number of entries: "));
+			iLog.LogL(aRetryCountNum + 1);
+			iLog.LogL(_L("\n  Actual entries: "));
+			iLog.LogL(iTransportLog.Count());
+			iLog.NewLineL();
+			}
+		result = EFalse;
+		}
+
+	TTransportLog& logEntry = iTransportLog[aRetryCountNum];
+	// Convert to 8-bit
+	RBuf8 expectedMethod;
+	expectedMethod.CreateL(aExpectedHttpMethod.Length());
+	CleanupClosePushL(expectedMethod);
+	expectedMethod.Copy(aExpectedHttpMethod);
+	expectedMethod.UpperCase();
+	if (expectedMethod != logEntry.iHttpMethod)
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Transport outcome result failed for send number: "));
+			iLog.LogL(aRetryCountNum);
+			iLog.LogL(_L("\n  Expected method: "));
+			iLog.LogL(expectedMethod);
+			iLog.LogL(_L("\n  Got method: "));
+			iLog.LogL(logEntry.iHttpMethod);
+			iLog.NewLineL();
+			}
+		result = EFalse;
+		}
+	CleanupStack::PopAndDestroy(&expectedMethod);
+
+	// Test the range of response time
+	if (aExpectedRespTimeMin > logEntry.iTransDurationMs || aExpectedRespTimeMax < logEntry.iTransDurationMs)
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Transport outcome result failed for send number: "));
+			iLog.LogL(aRetryCountNum);
+			iLog.LogL(_L("\n  Expected response time range (ms): "));
+			iLog.LogL(aExpectedRespTimeMin);
+			iLog.LogL(_L(" to "));
+			iLog.LogL(aExpectedRespTimeMax);
+			iLog.LogL(_L("\n  Actual response time (ms): "));
+			iLog.LogL(logEntry.iTransDurationMs);
+			iLog.NewLineL();
+			}
+		result = EFalse;
+		}
+	else if (iVerbose)
+		{
+		iLog.LogL(_L("Send number: "));
+		iLog.LogL(aRetryCountNum);
+		iLog.LogL(_L(" Response duration(ms): "));
+		iLog.LogL(logEntry.iTransDurationMs);
+		iLog.NewLineL();
+		}
+
+	return result;
+	}
+
+TBool CTOCSPEngine::TestTransportRetryL(TInt aRetryCount)
+	{
+	// This assumes one-tranaction-per-certificate behaviour
+	// This also assumes test case includes only certificate revocation check request (which means 
+	// CHECKRESPONDERCERT command cannot be used with this)
+	// Check the number of retries
+	TBool result = ETrue;
+	if (iTransportLog.Count() != aRetryCount)
+		{
+		if (iVerbose)
+			{
+			iLog.LogL(_L("Transport retry outcome result failed:"));
+			iLog.LogL(_L("\n  Expected number of retries: "));
+			iLog.LogL(aRetryCount);
+			iLog.LogL(_L("\n  Actual retries: "));
+			iLog.LogL(iTransportLog.Count());
+			iLog.NewLineL();
+			}
+		result = EFalse;
+		}
+
+	return result;
+	}
+
+void CTOCSPEngine::SetCheckCertsWithAiaOnly(TBool aCheckCertsWithAiaOnly)
+	{
+	iParams->SetCheckCertsWithAiaOnly(aCheckCertsWithAiaOnly);
+	}
+
+void CTOCSPEngine::SetUseAIA(TBool aUseAIA)
+	{
+	iParams->SetUseAIA(aUseAIA);
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/engine.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,217 @@
+// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Declase engine for testing OCSP module.  Knows nothing about the details of the
+// script syntax.  Is point of contact between script-reading classes and the
+// actual OCSP module itself.
+// 
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+
+#ifndef __TOCSP_ENGINE_H__
+#define __TOCSP_ENGINE_H__
+
+#include <e32base.h>
+#include <ocsp.h>
+#include <callbacktimer.h>
+#include "tcertutils.h"
+#include "ocsprequestandresponse.h"
+
+class CTOCSPLogger;
+
+class COCSPRequest;
+class COCSPTransaction;
+class COCSPValidator;
+class MOCSPTransport;
+
+class CX509Certificate;
+class CUnifiedCertStore;
+
+class TTransportLog
+	{
+public:
+	TBuf8<4> iHttpMethod;
+	TInt iTransDurationMs;
+	};
+
+class CTOCSPEngine : public CActive, private MTimerObserver
+	{
+public:
+	static CTOCSPEngine* NewL(CTOCSPLogger& aLog);
+	~CTOCSPEngine();
+
+	// COMMANDS TO ACCESS OCSP MODULE
+
+	void StartL(TRequestStatus& aStatus); 	// Delete all old objects, create a new transaction object
+	void EndL(TRequestStatus& aStatus); // Clean up after tests run
+ 	void SetURIL(const TDesC8& aURI, TBool aUseAIA=ETrue);
+
+
+	void SetDefaultTransportL();
+	void SetTestTransportL(const TDesC& aResponseFile, const TDesC* aRequestFile);
+	void SetOcspSupportTransportL();
+	void SetTransportRetryCount(TUint aRetryCount);
+	void SetTransportTimeout(TInt aTimeout);
+
+	void SetNonce(const TBool aNonce);
+	void AddCertL(const TDesC8& aSubject, const TDesC8& aIssuer);
+
+	void SetValidationTimeL(const TTime& aWhen);
+	void AddDirectAuthorisationCert(const TDesC& aCert, const TDesC& aLabel,
+									TRequestStatus& aStatus);
+	void UseDirectAuthorisation();
+	void UseCADelegateAuthorisation();
+	void UseCADirectAuthorisation();
+	void UseAllAuthorisationSchemes();
+	void SetMaxStatusAgeL(TUint aMaxAge);
+		
+	void SetCancelTime(TInt aTime);
+	void Check(TRequestStatus& aStatus);
+	TBool TestSummaryL(OCSP::TResult aExpected);
+	TBool TestOutcomeL(TInt aCertIndex, const TOCSPOutcome& aExpected);
+	TBool TestTransportL(TInt aRetryCountNum, const TDesC& aExpectedHttpMethod,
+						TInt aExpectedRespTimeMin, TInt aExpectedRespTimeMax);
+	TBool TestTransportRetryL(TInt aRetryCount);
+
+    void LogResponseL(const TDesC& aFilename);
+    void LogRequestL(const TDesC& aFilename);
+
+	static TPtrC TranslateStatusL(OCSP::TStatus aStatus);
+	static TPtrC TranslateResultL(OCSP::TResult aResult);
+
+	/** Set whether to print informational messages. */
+	void SetVerbose(TBool aVerbose);
+	
+	void SetReponderCertCheck();
+	void AddCertToStore(const TDesC& aCertFileName, const TDesC& aLabel, 
+						TCertificateOwnerType aCertType, TRequestStatus& aStatus);
+	void SetFilterParameters(TInt aCountDropResp, TInt aNumDelayResp,
+			TInt countCorruptHTTPDataHeader, TInt countCorruptHTTPDataBodySizeLarge, TInt countCorruptHTTPDataBodySizeSmall,
+			TInt aCountCorruptOCSPData,
+			TInt aCountInternalErrorResp, TInt aCountTryLaterResp,
+			TInt aCountSigValidateFailure);
+	void SetCheckCertsWithAiaOnly(TBool aCheckCertsWithAiaOnly);
+	void SetUseAIA(TBool aUseAIA);
+	
+private:
+	CTOCSPEngine(CTOCSPLogger& aLog);
+	void ConstructL();
+	void Destroy();
+	
+	void Reset();
+	void PrepareAuthorisationL();
+	void DefineAndSetFilterParametersL();
+	void DeleteFilterParameters();
+	void LogValidationL(const TOCSPOutcome& aOutcome) const;
+	void LogRequestCompleteL();
+	void ReadTransportLogL();
+	TBool ReadLineL(const TDesC8& aBuffer, TInt& aPos, TPtrC8& aLine) const;
+	void LogResponseDetailsL(void);
+	void InitDirectAuthL();
+	void CleanUpDirectAuthL(TRequestStatus& aStatus);
+	void SetTransportL(MOCSPTransport* aTransport);
+
+	// Implementation of CActive
+	void RunL();
+	void DoCancel();
+    TInt RunError(TInt aError);
+
+    // Implementation of MTimerRun
+	void TimerRun(TInt aError);
+
+
+    HBufC8* ReadDataL(RFs& session, const TDesC& aFileName) const;
+
+	void DoAddDirectAuthorisationCertL(const TDesC& aCert, const TDesC& aLabel, 
+		TRequestStatus& aStatus);
+    void DoCheckL(TRequestStatus& aStatus);
+
+private:
+	enum TState 
+		{
+		EInitCertStore,
+		EAddingCert,
+		ERemovingCerts,
+        EChecking,
+		};
+
+private:
+	RFs iFs;
+	CUnifiedCertStore* iUnifiedCertStore;
+	TState iState;
+	TRequestStatus* iOriginalRequestStatus;
+
+	CTOCSPLogger& iLog;
+
+	// OCSP objects
+	COCSPParameters* iParams;
+	COCSPClient* iClient;
+
+	// Have we added a direct authorisation scheme object?
+	TBool iUseDirectAuthorisation;
+	/** Set to use CA Delegate authorisation when the certificate is checked. */
+	TBool iUseCADelegateAuthorisation;
+	/**
+		When this is set the response is checked to see if it signed
+		by the issuing CA.
+	 */
+	TBool iUseCADirectAuthorisation;
+	/**
+		Set when "ALLSCHEMES" command is parsed.  This uses the
+		COCSPParameters::AddAllAuthorisationSchemesL() function.
+	 */
+	TBool iUseAllSchemes;
+
+	// The cert objects - we own them
+	RPointerArray<CX509Certificate> iSubjectCerts;
+	RPointerArray<CX509Certificate> iIssuerCerts;
+	RPointerArray<CX509Certificate> iSigningCerts;
+
+	CCertUtils* iCertUtils;
+
+	TBuf<100> iCert;
+	TBuf<100> iLabel;
+
+	TBool iVerbose;
+
+	// The filename to log requests to, or null
+	HBufC* iRequestLog;
+	
+	TUint32 iIap;
+
+	MOCSPTransport* iTransport;
+
+	// Http transport filter settings
+	TInt iNumDelayResp;
+	TInt iCountDropResp;
+	TInt iCountCorruptHTTPDataHeader;
+	TInt iCountCorruptHTTPDataBodySizeLarge;
+	TInt iCountCorruptHTTPDataBodySizeSmall;
+	TInt iCountCorruptOCSPData;
+	TInt iCountInternalErrorResp;
+	TInt iCountTryLaterResp;
+	TInt iCountSigValidateFailure;
+
+	// Hold information read from the transport filter log
+	RArray<TTransportLog> iTransportLog;
+
+	// If non-zero the time interval in milliseconds to cancel issued request
+	TInt iCancelTime;
+	CCallbackTimer* iTimer;
+	};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/logger.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,158 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Class to handle output from the test harness.  All output goes to the log file,
+// but screen output can be more controlled.
+// 
+//
+
+#include "logger.h"
+
+#include <e32cons.h>
+
+
+CTOCSPLogger* CTOCSPLogger::NewLC(const TDesC& aLogFile)
+	{
+	CTOCSPLogger* self = new (ELeave) CTOCSPLogger;
+	CleanupStack::PushL(self);
+	self->ConstructL(aLogFile);
+	return self;
+	}
+
+
+CTOCSPLogger* CTOCSPLogger::NewL(const TDesC& aLogFile)
+	{
+	CTOCSPLogger* self = CTOCSPLogger::NewLC(aLogFile);
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+
+CTOCSPLogger::~CTOCSPLogger()
+	{
+	iFile.Close();
+	iSession.Close();
+
+	delete iConsole;
+	}
+
+
+void CTOCSPLogger::ConstructL(const TDesC& aLogFile)
+	{
+	iConsole = Console::NewL(_L("OCSP Test"), TSize(KDefaultConsWidth,KDefaultConsHeight));
+
+	User::LeaveIfError(iSession.Connect());
+
+	TInt err = iSession.MkDirAll(aLogFile);
+	if (err != KErrAlreadyExists)
+		{
+		User::LeaveIfError(err);
+		}
+	User::LeaveIfError(iFile.Replace(iSession, aLogFile, EFileShareExclusive));
+	}
+
+
+void CTOCSPLogger::LogL(const TDesC& aText, const TBool aEcho)
+	{
+	iEcho = aEcho;
+	LogL(aText);
+	}
+
+
+void CTOCSPLogger::LogL(const TDesC8& aText, const TBool aEcho)
+	{
+	iEcho = aEcho;
+	LogL(aText);
+	}
+
+
+void CTOCSPLogger::LogL(const TInt aInt, const TBool aEcho)
+	{
+	iEcho = aEcho;
+	LogL(aInt);
+	}
+
+
+void CTOCSPLogger::LogL(const TDesC& aText)
+	{
+	if (iEcho)
+		{
+		iConsole->Write(aText);
+		}
+
+	// Have to convert to 8-bit for file
+
+	TInt textLen = aText.Length();
+	
+	HBufC8* buf8 = NULL;
+	TRAPD(err, buf8=HBufC8::NewL(textLen));
+	if( KErrNoMemory == err) 
+	{
+		User::CompressAllHeaps();
+			
+		TRAPD(err2, buf8=HBufC8::NewL(textLen));
+		if( KErrNone != err2) 
+		{
+			User::Leave(err2);	
+		}
+		
+	}
+	CleanupStack::PushL(buf8);
+
+	TPtr8 pBuf8(buf8->Des());
+	pBuf8.Copy(aText);
+		
+	User::LeaveIfError(iFile.Write(*buf8));
+	CleanupStack::PopAndDestroy(buf8);
+	}
+
+void CTOCSPLogger::LogL(const TDesC8& aText)
+	{
+	if (iEcho)
+		{
+		// Convert to 16 bit descriptor to write to console
+		RBuf buf16;
+		buf16.CreateL(aText.Length());
+		CleanupClosePushL(buf16);
+		buf16.Copy(aText);
+		iConsole->Write(buf16);
+		CleanupStack::PopAndDestroy(&buf16);
+		}
+
+	User::LeaveIfError(iFile.Write(aText));
+	}
+
+
+void CTOCSPLogger::LogL(const TInt aInt)
+	{
+	TBuf<12> buf;
+	buf.Num(aInt);
+	LogL(buf);
+	}
+
+
+void CTOCSPLogger::NewLineL()
+	{
+	LogL(_L("\n"));
+	}
+
+
+void CTOCSPLogger::PressAnyKeyL()
+	{
+	LogL(_L("[Press any key]\n"));
+
+	if (iEcho)
+		{
+		iConsole->Getch();
+		}
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/logger.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,69 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Class to handle output from the test harness.  All output goes to the log file,
+// but screen output can be more controlled.
+// 
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+
+#ifndef __TOCSP_LOGGER_H__
+#define __TOCSP_LOGGER_H__
+
+#include <e32base.h>
+#include <f32file.h>
+
+/**
+ * This class provides a logging functionality. It logs everything in a file
+ * and optionally displays it on the console.
+ */
+class CTOCSPLogger : public CBase
+	{
+public:
+	static CTOCSPLogger* NewLC(const TDesC& aLogFile);
+	static CTOCSPLogger* NewL(const TDesC& aLogFile);
+	~CTOCSPLogger();
+
+	// Log to the file, and maybe echo to screen.
+	// Sets echo mode from here on
+	void LogL(const TDesC& aText, const TBool aEcho);
+	void LogL(const TDesC8& aText, const TBool aEcho);
+	void LogL(const TInt aInt, const TBool aEcho);
+	
+	// Log to file, and maybe to screen, depending on current echo mode
+	void LogL(const TDesC& aText);
+	void LogL(const TDesC8& aText);
+	void LogL(const TInt aInt);
+	void NewLineL();
+
+	// Prompt user and wait - only if echo is on
+	void PressAnyKeyL();
+
+private:
+	void ConstructL(const TDesC& aLogFile);
+
+private:
+	// We own the console
+	CConsoleBase* iConsole;
+
+	RFs iSession;
+	RFile iFile;
+
+	TBool iEcho;
+	};
+
+#endif // __TOCSP_LOGGER_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/main.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,557 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Top-level test control implementation
+// 
+//
+
+#include "main.h"
+#include "comms.h"
+#include "script.h"
+#include "logger.h"
+#include "result.h"
+#include "panic.h"
+#include "tcertutils.h"
+#include "bautils.h" 
+
+
+_LIT(KRunStep, "RUN_TEST_STEP");
+
+// Optional 3rd argument to turn on OOM tests
+_LIT(KOOMArgument, "OOM");
+
+// First script test to run
+#ifdef _DEBUG
+const TInt KMinTransaction = 1;
+#endif
+
+// First heap fail point to try
+const TInt KMinHeapFailPoint = 1;
+
+// Number of allocations to test for before bailing out
+const TInt KMaxHeapFailPoint = 100000;
+
+// Number of consecutive successful completions before we belive we've finished
+// an OOM test
+const TInt KCompletions = 5;
+
+// Where to find file cert store files
+
+_LIT(KCertStoreCertsFilePath, "\\private\\101f72a6\\cacerts.dat");
+_LIT(KCertStoreClientsFilePath, "\\private\\101f72a6\\certapps.dat");
+
+
+CTOCSPMain* CTOCSPMain::NewLC(const TDesC& aScriptFile, const TDesC& aLogFile)
+	{
+	CTOCSPMain* self = new (ELeave) CTOCSPMain(aScriptFile);
+	CleanupStack::PushL(self);
+	self->ConstructL(aLogFile);
+	return self;
+	}
+
+CTOCSPMain::CTOCSPMain(const TDesC& aScriptFile) :
+	CActive(EPriorityNormal),
+	iScriptFile(aScriptFile)
+	{
+	CActiveScheduler::Add(this);
+	}
+
+void CTOCSPMain::ConstructL(const TDesC& aLogFile)
+	{	
+	iLog = CTOCSPLogger::NewL(aLogFile);
+	User::LeaveIfError(iFs.Connect());
+
+	// this is the name of the test file we will write to from the script
+	iTocspTestFile.Copy(_L("\\system\\tocsp\\tocsptestfile.txt"));
+
+	if (BaflUtils::FolderExists(iFs, iTocspTestFile))
+		{		
+		if (BaflUtils::FileExists( iFs, iTocspTestFile ))
+			{
+			// delete the test file if it exists before starting the tests
+			iFs.Delete(iTocspTestFile);	
+			}
+		}
+	}
+
+CTOCSPMain::~CTOCSPMain()
+	{
+	Cancel();
+	delete iLog;
+	delete iTest;
+	delete iResult;
+	if (BaflUtils::FolderExists(iFs, iTocspTestFile))
+			{		
+			if (BaflUtils::FileExists( iFs, iTocspTestFile ))
+				{
+				// delete the test file if it exists at the end of the tests
+				iFs.Delete(iTocspTestFile);
+				}
+			}
+	iFs.Close();
+	}
+
+void CTOCSPMain::RunNormalTestsL()
+	{
+	iLog->LogL(_L("<html><body><pre>\r\n"), ETrue);
+	TPtrC scriptcontents;
+	TPtrC inicontents;
+	TPtrC runTestStep;
+	TPtrC iniFileName;
+	TPtrC iniSectionName;
+	TBuf<512> iniFilePath;
+	
+	TInt err = KErrNone;
+	TInt pos = 0;
+	
+	iLog->LogL(_L("Starting normal OCSP tests...\n"), ETrue);
+
+    iError = KErrNone;
+
+	ResetTestL();
+
+	__UHEAP_MARK;
+
+//	TBool runStep = EFalse;
+	
+//	To check if the input file is .script file
+//	IF a script file
+//	Reads in the contents of the script file and loads it on 'scriptcontents'
+//	Extracs RUN_TEST_STEP line onto 'runTestStep'
+//	Extracts .ini file name and the appropriate .ini section name
+//	Generates the .ini file path
+//	Reads in the contents of the ini file and loads it on 'inicontents'
+//	Extracts the approritate section part and sets iSectionData
+	
+	iScriptFlag = TEFparser::FileType(iScriptFile);
+	
+	if(iScriptFlag)
+		{
+		do
+			// get the run test step lines from the script file
+			{
+			err = TEFparser::ReadFileLC(iFs, iScriptFile, scriptcontents);
+			runTestStep.Set(TEFparser::GetRunTestStep(scriptcontents, KRunStep, pos, err));
+			if(err == KErrNone)
+				{
+				// get the ini file info for the current test step
+				err = TEFparser::GetIniFileInfo(runTestStep, iniFileName, iniSectionName);
+				if (err == KErrNone)
+					{
+					// get the path to the ini file for the current test step
+					err = TEFparser::GetiniPath(iniFileName, iScriptFile, iniFilePath);
+					if (err == KErrNone)
+						{
+						// get the data in section for of the ini file for the current test step and write it into the
+						// test file
+						err = TEFparser::GetSectionData(iniFilePath, iniSectionName, iTocspTestFile, iFs);
+						if (err != KErrNone)
+							{
+							ReportErrorL();
+							}
+						CleanupStack::PopAndDestroy();
+						}	
+						else
+						{
+							ReportErrorL();
+						}
+					}
+					else
+					{
+						ReportErrorL();
+					}
+				}
+			else
+				{
+				CleanupStack::PopAndDestroy();
+				}
+			}while(err == KErrNone);
+		// execute the tests for the complete test file with all the ini file section data in
+		iResult = CTOCSPResult::NewL();
+		iTest = CTOCSPScript::NewL(*iLog, *iResult, iTocspTestFile);
+		iTest->SetVerbose(ETrue);
+		iState = ERunningNormalTest;
+		iTest->RunTestL(iStatus);
+		SetActive();
+		CActiveScheduler::Start();
+		}
+	else
+		{
+		iResult = CTOCSPResult::NewL();
+		iTest = CTOCSPScript::NewL(*iLog, *iResult, iScriptFile);
+		iTest->SetVerbose(ETrue);
+		iState = ERunningNormalTest;
+		iTest->RunTestL(iStatus);
+		SetActive();
+		CActiveScheduler::Start();
+		}
+		
+	
+	}
+
+void CTOCSPMain::RunOOMTestsL()
+	{
+#ifdef _DEBUG
+	iLog->LogL(_L("\nStarting OCSP OOM tests from script...\n"), ETrue);
+
+    iError = KErrNone;
+
+	iTransaction = KMinTransaction;
+	iFailPoint = KMinHeapFailPoint;
+	iCompletions = 0;
+	ResetTestL();
+	StartNextOOMTestL();
+
+    // Run async code
+	CActiveScheduler::Start();
+
+	ReportErrorL();
+#else
+	iLog->LogL(_L("No OOM tests run on release build.\n"), ETrue);
+	// reports a single test run to satisfy corebuilder log parsing requirements
+	iLog->LogL(_L("0 tests failed out of 1\n"));
+#endif
+	}
+
+// Report any error and raise it to the client
+void CTOCSPMain::ReportErrorL()
+	{
+	if (iError != KErrNone)
+		{	
+		iLog->LogL(_L("Exiting with leave code: "));
+		iLog->LogL(iError);
+		iLog->NewLineL();
+		iLog->LogL(_L("1 tests failed out of 1 (unknown)\n"));
+		}
+	}
+
+TInt CTOCSPMain::RunError(TInt aError)
+	{
+	if (iState == ERunningNormalTest || iState == ERunningOOMTest)
+		{
+		// attempt to clean up after ourselves
+		delete iTest;
+		iTest = NULL;
+
+		delete iResult;
+		iResult = NULL;
+
+		__UHEAP_MARKEND;
+		}
+
+	iError = aError;
+	CActiveScheduler::Stop();	
+	return KErrNone;
+	}
+
+void CTOCSPMain::DoCancel()
+	{
+	switch (iState)
+		{
+		case ERunningNormalTest:
+		case ERunningOOMTest:
+			iTest->Cancel();
+			break;
+
+		default:
+			Panic(KErrCorrupt);
+		}
+	}
+
+void CTOCSPMain::RunL()
+	{
+	switch (iState)
+		{
+		case ERunningNormalTest:
+			FinishedNormalTestL();
+			break;
+
+		case ERunningOOMTest:
+			FinishedOOMTestL();
+			break;
+
+		default:
+			Panic(KErrCorrupt);
+		}
+	}
+
+void CTOCSPMain::FinishedNormalTestL()
+	{
+	delete iTest;
+	iTest = NULL;
+	
+	iLog->NewLineL();
+	if (iStatus == KErrNone)
+		{
+		iLog->LogL(_L("Tests completed OK"), ETrue);
+		iLog->NewLineL();
+		}
+	else
+		{
+		iLog->NewLineL();
+		iLog->LogL(_L("ERROR: Leave code = "), ETrue);
+		iLog->LogL(iStatus.Int());
+		iLog->NewLineL();
+		User::Leave(iStatus.Int());
+		}
+	
+	iResult->LogSummaryL(*iLog);
+
+	delete iResult;
+	iResult = NULL;
+	
+	__UHEAP_MARKEND;
+
+	CActiveScheduler::Stop();
+	}
+
+void CTOCSPMain::StartNextOOMTestL()
+	{
+	if (iFailPoint == 1)
+		{
+		iLog->LogL(_L("*** Testing transaction "), ETrue);
+		iLog->LogL(iTransaction, ETrue);
+		iLog->LogL(_L("\n"), ETrue);
+		}
+
+	iLog->LogL(_L("\n"));
+	iLog->LogL(iFailPoint);
+	iLog->LogL(_L(" "));
+
+	__UHEAP_MARK;
+
+	iResult = CTOCSPResult::NewL();
+	iTest = CTOCSPScript::NewL(*iLog, *iResult, iTocspTestFile, iTransaction);
+
+	iTest->SetVerbose(EFalse);
+	iTest->RunTestL(iStatus);
+	iState = ERunningOOMTest;
+	SetActive();
+
+	__UHEAP_SETFAIL(RHeap::EFailNext, iFailPoint);
+	}
+
+void CTOCSPMain::FinishedOOMTestL()
+	{
+	__UHEAP_SETFAIL(RHeap::ENone, 0);
+
+	TBool more = ETrue;
+
+	if (iTest)
+		{
+		more = CheckOOMTestResultL();
+		}
+
+	delete iTest;
+	iTest = NULL;
+	delete iResult;
+	iResult = NULL;
+
+	__UHEAP_MARKEND;
+
+	if (more)
+		{
+		ResetTestL();
+		StartNextOOMTestL();
+		}
+	else
+		{
+		CActiveScheduler::Stop();
+		}
+	}
+
+TBool CTOCSPMain::CheckOOMTestResultL()
+	{
+	if (iStatus != KErrNone &&
+		iStatus != KErrNoMemory  &&
+		iStatus != KErrDiskFull)
+		{
+		// error, report and exit
+		iLog->LogL(_L("\nHeap fail test (fail at "), ETrue);
+		iLog->LogL(iFailPoint);
+		iLog->LogL(_L(") exited with unexpected return code "));
+		iLog->LogL(iStatus.Int());
+		iLog->LogL(_L("\n"));
+		iLog->LogL(_L("1 tests failed out of 1\n"));
+		User::Leave(iStatus.Int());
+		}
+
+	// Count number of successive successful completions
+	if (iStatus == KErrNone)
+		{
+		++iCompletions;
+		}
+	else
+		{
+		iCompletions = 0;
+		}
+	
+	if (iCompletions == KCompletions)
+		{
+		// finished a round of testing
+		if (iTransaction < iTest->TransactionCount())
+			{
+			// more transactions
+			iFailPoint = KMinHeapFailPoint;
+			++iTransaction;
+			iCompletions = 0;
+			iLog->NewLineL();
+			}
+		else
+			{
+			// we're finished
+			iLog->LogL(_L("0 tests failed out of 1\n"));
+			return EFalse;
+			}
+		}
+	else
+		{
+		// go round again
+		++iFailPoint;
+		if (iFailPoint > KMaxHeapFailPoint)
+			{
+			iLog->LogL(_L("\nHeap fail test exceeded "), ETrue);
+			iLog->LogL(KMaxHeapFailPoint);
+			iLog->LogL(_L(" allocations\n"));
+			iLog->LogL(_L("1 tests failed out of 1\n"));
+			User::Leave(KErrGeneral);		  
+			}
+		}
+
+	return ETrue;
+	}
+
+void CTOCSPMain::ResetTestL()
+	{
+	User::After(5 * 1000 * 1000);
+	// We could use CCertUtils to remove the certs, but it's a lot faster just
+	// to delete the files
+	TDriveUnit sysDrive (RFs::GetSystemDrive());
+	TDriveName driveName(sysDrive.Name());
+	//file cert store files
+	TBuf<128> certStoreFilePath (driveName);
+	certStoreFilePath.Append(KCertStoreCertsFilePath);
+	
+	TInt error;
+	error = iFs.Delete(certStoreFilePath);
+	if (error != KErrNone && error != KErrNotFound && error != KErrPathNotFound)
+	{
+		// Handle a KErrInUse error. We try to delete up to 10 times, 
+		// and wait 1 sec between two attemps
+		if( KErrInUse == error) 
+		{
+			TInt tryCount = 10;
+			do 
+			{
+				User::After(1000000);	
+				error = iFs.Delete(certStoreFilePath);
+				
+			} while(0 != tryCount-- && error != KErrNone);
+			
+			if( 0 == tryCount ) 
+			{
+				User::Leave(error);
+			}
+			
+		}
+		else 
+		{
+			User::Leave(error);	
+		}
+	
+	}
+
+	//file cert store files
+	certStoreFilePath.Copy(driveName);
+	certStoreFilePath.Append(KCertStoreClientsFilePath);
+	
+	error = iFs.Delete(certStoreFilePath);
+	if (error != KErrNone && error != KErrNotFound && error != KErrPathNotFound)
+		{
+		User::Leave(error);
+		}
+	}
+
+LOCAL_C void RunScriptTestL()
+    {
+	// Start comms stuff - only necessary on WINS where this is an executable
+#ifdef __WINS__
+	InitCommsL();
+#endif
+
+	CActiveScheduler* scheduler = new (ELeave) CActiveScheduler();
+	CleanupStack::PushL(scheduler);
+	CActiveScheduler::Install(scheduler);
+
+	// Get command line
+	HBufC* argv = HBufC::NewLC(User::CommandLineLength());
+	TPtr cmd(argv->Des());
+	User::CommandLine(cmd);
+
+	// Validate command line
+	TLex argumentsValidation(cmd);	
+	TInt argc = 0;
+	while (argumentsValidation.NextToken().Length()) argc++;
+
+	if (argc < 2 || argc > 3)
+		{
+		User::Leave(KErrArgument);
+		}
+
+	// Command line had 2 args - OK
+	TLex arguments(cmd);
+	TPtrC inputFile(arguments.NextToken());
+	TPtrC logFile(arguments.NextToken());
+
+	CTOCSPMain *main = CTOCSPMain::NewLC(inputFile, logFile);
+
+	TBool memoryTests = EFalse;
+
+	if (argc == 3)
+		{
+		TPtrC memArg(arguments.NextToken());
+		if (memArg != KOOMArgument)
+			{
+			User::Leave(KErrArgument);
+			}
+		memoryTests = ETrue;
+		}
+
+	if (memoryTests)
+		{
+		main->RunOOMTestsL();
+		}
+	else
+		{
+		main->RunNormalTestsL();
+		}
+
+	CleanupStack::PopAndDestroy(main);
+
+	CleanupStack::PopAndDestroy(argv);
+	CleanupStack::PopAndDestroy(scheduler);
+    }
+
+// Entry point
+GLDEF_C TInt E32Main()
+    {
+	__UHEAP_MARK;
+	CTrapCleanup* cleanup=CTrapCleanup::New();
+
+	TRAPD(error,RunScriptTestL()); 
+	__ASSERT_ALWAYS(!error, User::Panic(_L("OCSP TEST ERROR"), error));
+
+	delete cleanup;
+	__UHEAP_MARKEND;
+	return 0;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/main.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,96 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+ 
+#ifndef __TOCSP_MAIN_H__
+#define __TOCSP_MAIN_H__
+
+#include <e32base.h>
+#include <f32file.h>
+
+#include "TEFparser.h"
+
+/** UID for setting cert applicability. */
+
+const TInt KTOCSP_UID = 0x1000A405;
+
+class CTOCSPLogger;
+class CTOCSPResult;
+class CTOCSPScript;
+class CCertUtils;
+
+/**
+ * Runs OCSP test script.
+ */
+
+class CTOCSPMain : public CActive
+	{
+public:	
+
+	static CTOCSPMain* NewLC(const TDesC& aScriptFile, const TDesC& aLogFile);
+	~CTOCSPMain();
+
+	void RunNormalTestsL();
+	void RunOOMTestsL();
+	const TPtrC& getSectionData() { return iSectionData; };	
+	
+	TBool getScriptFlag() { return iScriptFlag; };
+
+private:
+
+	enum TState
+		{
+		ERunningNormalTest,
+		ERunningOOMTest
+		};
+
+	CTOCSPMain(const TDesC& aScriptFile);
+	void ConstructL(const TDesC& aLogFile);
+	void RunTestsL(TState aState);
+
+	void FinishedNormalTestL();
+	void StartNextOOMTestL();
+	void FinishedOOMTestL();
+	TBool CheckOOMTestResultL();
+	void ResetTestL();
+	void ReportErrorL();
+
+	// Implementation of CActive methods
+	void RunL();
+	TInt RunError(TInt aError);
+	void DoCancel();
+
+	TState			iState;
+	RFs				iFs;
+	CCertUtils*		iCertUtils;
+	const TDesC&	iScriptFile;
+	CTOCSPLogger*	iLog;
+	TInt			iTransaction;
+	TInt			iFailPoint;
+	TInt			iError;
+	CTOCSPResult*	iResult;
+	CTOCSPScript*	iTest;
+	TInt			iCompletions;
+	
+	TPtrC			iSectionData;
+	TBool 			iScriptFlag;
+	TBuf16<256> 	iTocspTestFile;
+	};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/ocspsupport.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,92 @@
+/**
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+
+/**
+ @file
+ @internalTechnology
+*/
+
+#ifndef __OCSPSUPPORT_H__
+#define __OCSPSUPPORT_H__
+
+#include <e32std.h>
+// file duplicated from \\swi\\inc
+namespace Swi
+{
+
+/// The name of the OCSP Support Server
+_LIT(KOcspSupportServerName,"!OCSPSUPPORTSERVER");
+
+/// The name of the OCSP Support Executable
+_LIT(KOcspSupportServerExeName,"OCSPSUPPORT");
+
+/// The name of the OCSP Support Thread
+_LIT(KOcspSupportServerThreadName,"OCSPSUPPORTSERVER-THREAD");
+
+/// The current version of the OCSP Support Server
+const TInt KOcspSupportServerVersionMajor=0;
+const TInt KOcspSupportServerVersionMinor=1;
+const TInt KOcspSupportServerVersionBuild=0;
+
+/**
+ * This class is a handle to the server, which uses HTTP to make the OCSP request
+ */
+class ROcspHandler : public RSessionBase
+	{
+	static const TInt KDefaultBufferSize;
+public:
+	/// Connect to the server	
+	TInt Connect();
+	
+	/// Close the connection tothe server
+	void Close();
+	
+	/// Cancel the OCSP request
+	void CancelRequest();
+	
+	/**
+	 * Get the response data from the OCSP request. This is only valid when SendRequest
+	 * has been called, and completed with no error. Ownership is transferred to client.
+	 *
+	 * @param	aIapOut		The IAP that was used in this request
+	 * @return	The body of the OCSP response
+	 */
+	TPtrC8 GetResponseL(TUint32& aIapOut) const;
+	
+	/**
+	 * Send an OCSP request, using the server.
+	 * @param	aUri		The URI of the server to send the request to.
+	 * @param	aRequest	The request data to send.
+	 * @param	aTimeout	The request timeout value in milliseconds
+	 * @param	aIap		The IAP to use for this OCSP request
+	 * @param	aStatus		Request status. On completion contains an error code.
+	 */
+	void SendRequest(const TDesC8& aUri, const TDesC8& aRequest, const TInt aTimeout, TUint32 aIap, TRequestStatus& aStatus);
+
+private:
+	/// Starts the server which carries out the requests
+	TInt StartServer();
+	
+	
+	mutable HBufC8* iResultData;
+	};
+
+} // namespace Swi
+
+#endif // #ifndef __OCSPSUPPORT_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/ocspsupporttransport.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,68 @@
+/**
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+
+/**
+ @file
+ @internalTechnology
+*/
+
+#ifndef __OCSPSUPPORT_TRANSPORT_H__
+#define __OCSPSUPPORT_TRANSPORT_H__
+
+#include <ocsp.h>
+#include "ocspsupport.h"
+
+// file duplicated from \\swi\\inc
+namespace Swi
+{
+
+/**
+ * This class is a transport used by OCSP. This transport uses client/server framework
+ * to make the request in a separate process and marshalls the data between the processes.
+ * This allows SWIS to use OCSP, which uses HTTP, which cannot be used directly from
+ * the TCB.
+ */
+class COcspSupportTransport :  public CBase, public MOCSPTransport
+	{
+public:
+	IMPORT_C static COcspSupportTransport* NewL(TUint32& aIap);
+	IMPORT_C static COcspSupportTransport* NewLC(TUint32& aIap);
+
+// from MOCSPTransport
+	void SendRequest (const TDesC8 &aURI, const TDesC8 &aRequest, const TInt aTimeout, TRequestStatus &aStatus);
+	void CancelRequest ();
+	TPtrC8 GetResponse () const;
+	
+	~COcspSupportTransport();
+private:
+	COcspSupportTransport(TUint32& aIap);
+	void ConstructL();
+	
+	/// Handle to the server, used to forward the requests.
+	ROcspHandler iOcspHandler;
+	
+	/// Result data
+	mutable HBufC8* iResultData; // needs to be mutable due to MOCSPTransport interface dfn
+	
+	// Selected IAP
+	TUint32& iIap;
+	};
+}
+
+#endif //#ifndef __OCSPSUPPORT_TRANSPORT_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/panic.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// The panic method
+// 
+//
+
+#include "panic.h"
+
+#include "e32std.h"
+
+GLDEF_C void Panic(TInt aPanic)
+	{
+	User::Panic(_L("TOCSP"), aPanic);
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/panic.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// The panic method and TOCSP panic code declarations
+// 
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+
+#ifndef __TOCSP_PANIC_H__
+#define __TOCSP_PANIC_H__
+
+#include <e32def.h>
+
+enum TTOCSPPanics
+	{
+	KErrTOCSPInternalError,
+	KErrTOCSPScriptParameterError
+	};
+
+
+GLDEF_C void Panic(TInt aPanic);
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/readme.txt	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,53 @@
+
+This directory contains all the source code and associated data for testing the
+OCSP module against external OCSP servers.
+
+The executable is called TOCSP.EXE.  It takes the name of a command script as a
+parameter, followed by the name of the log file.  If the third paramteter "OOM"
+is specified, it runs out of memory tests on the script.
+
+This command file must be unicode.  Commands for this file are described in
+command.cpp
+
+Several command files are given, for testing against different servers:
+
+scripts\XCert.txt
+
+  Tests against the XCert OCSP server running internally within Symbian
+  (lon-ocsp01) on http://10.35.2.47:445/ocsp.xuda
+
+scripts\XCert-local.txt
+
+  Tests against logged responses from the XCert OCSP server.  These tests
+  include almost all of the functionality in the XCert.txt script, but can be
+  run without a network connection.  The responses were produced by running the
+  XCert-logging.txt script.
+
+scripts\OpenSSL-local.txt
+
+  Tests against logged requests and responses from an OpenSSL OCSP server.  The
+  responses were produced by running the OpenSSL-logging.txt script in
+  conjunction with a local OpenSSL server, run using the scripts in
+  server/OpenSSL.
+
+scripts\Error.txt
+
+  Tests against a set of pre-computed erroneous OCSP responses, that have been
+  hand-produced (signatures for these come from the 'resign' utility in a
+  subdirectory of this directory)
+
+scripts\Valicert.txt
+
+  These tests are no longer run.  They used to use a Valicert OCSP server
+  running internally within Symbian (cam-security.intra) on 10.178.2.2:133
+
+scripts\CertCo.txt
+
+  These tests are no longer run.  They use to a CertCo OCSP server, hosted by
+  CertCo, on 208.222.33.18:80/ocspv1
+
+These files are copied to Z:\system\tocsp\scripts\. on the EPOC device as part
+of 'abld test export'.  This also copies across all the appropriate test data.
+
+TOCSP sets CACerts.dat itself - you don't need to set it, and the existing one
+gets trashed.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/requestlogger.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,113 @@
+// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// A transport that logs the ocsp requests made to a file and then calls another
+// transport to send the request.
+// 
+//
+
+#include "requestlogger.h"
+
+#include <f32file.h>
+
+CTOCSPRequestLogger* CTOCSPRequestLogger::NewL(const TDesC& aRequestFile, MOCSPTransport* aTransport)
+	{
+	CTOCSPRequestLogger* self = new (ELeave) CTOCSPRequestLogger;
+	CleanupStack::PushL(self);
+	self->ConstructL(aRequestFile, aTransport);
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+
+CTOCSPRequestLogger::CTOCSPRequestLogger()	
+	{
+	}
+
+
+void CTOCSPRequestLogger::ConstructL(const TDesC& aRequestFile, MOCSPTransport* aTransport)
+	{
+	User::LeaveIfError(iFs.Connect());
+
+	TInt err = iFs.MkDirAll(aRequestFile);
+	if (err != KErrAlreadyExists)
+		{
+		User::LeaveIfError(err);
+		}
+
+	User::LeaveIfError(iWriteStream.Replace(iFs, aRequestFile, EFileWrite | EFileShareExclusive));
+
+	// Initially we write a request count of zero, this gets updates as each
+	// request is logged
+	iWriteStream.WriteUint32L(0);
+
+	iTransport = aTransport;
+	}
+
+
+CTOCSPRequestLogger::~CTOCSPRequestLogger()
+	{
+	iWriteStream.Close();
+	iFs.Close();
+	delete iTransport;
+	}
+
+
+void CTOCSPRequestLogger::SendRequest(const TDesC8& aURI,
+									  const TDesC8& aRequest, 
+									  const TInt aTimeout,
+									  TRequestStatus& aStatus)
+	{
+	TRAPD(err, LogRequestL(aURI, aRequest));
+
+	if (err == KErrNone)
+		{
+		iTransport->SendRequest(aURI, aRequest, aTimeout, aStatus);
+		}
+	else
+		{
+		TRequestStatus* status = &aStatus;
+		User::RequestComplete(status, err);
+		}
+	}
+
+void CTOCSPRequestLogger::LogRequestL(const TDesC8& aURI,
+									  const TDesC8& aRequest)
+	{
+	++iTotalRequests;
+
+	MStreamBuf* sink = iWriteStream.Sink();
+
+	sink->SeekL(MStreamBuf::EWrite, EStreamBeginning, 0);
+	iWriteStream.WriteUint32L(iTotalRequests);
+
+	sink->SeekL(MStreamBuf::EWrite, EStreamEnd, 0);
+	iWriteStream.WriteUint32L(aURI.Length());
+	iWriteStream.WriteL(aURI);
+	iWriteStream.WriteUint32L(aRequest.Length());
+	iWriteStream.WriteL(aRequest);
+
+	iWriteStream.CommitL();
+	}
+
+
+void CTOCSPRequestLogger::CancelRequest()
+	{
+	iTransport->CancelRequest();
+	}
+
+
+TPtrC8 CTOCSPRequestLogger::GetResponse() const
+	{
+	return iTransport->GetResponse();
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/requestlogger.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,62 @@
+// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// A transport that logs the ocsp requests made to a file and then calls another
+// transport to send the request.
+// 
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+
+#ifndef __TOCSP_REQUEST_LOGGER_H__
+#define __TOCSP_REQUEST_LOGGER_H__
+
+#include <e32base.h>
+#include <ocsp.h>
+#include <s32file.h>
+#include "ocsprequestandresponse.h"
+
+class CTOCSPRequestLogger : public CBase, public MOCSPTransport
+	{
+public:
+
+	/** Create a new request logger.  Takes ownership of the transport unless it leaves. */
+	static CTOCSPRequestLogger* NewL(const TDesC& aRquesteFile, MOCSPTransport* aTransport);
+
+private:
+
+	// From MOCSPTransport
+	~CTOCSPRequestLogger();
+	void SendRequest(const TDesC8& aURI, const TDesC8& aRequest, const TInt aTimeout, TRequestStatus& aStatus);
+	void CancelRequest();
+	TPtrC8 GetResponse() const;
+
+private:
+
+	CTOCSPRequestLogger();
+	void DoSendRequestL();
+	void ConstructL(const TDesC& aResponseFile, MOCSPTransport* aTransport);
+	void LogRequestL(const TDesC8& aURI, const TDesC8& aRequest);
+
+private:
+
+	RFs				 iFs;
+	RFileWriteStream iWriteStream;
+	TInt			 iTotalRequests;
+	MOCSPTransport*	 iTransport;
+	};
+
+#endif // __TOCSP_TRANSPORT_H__
Binary file pkiutilities/ocsp/test/requests/openssl/request01.dat has changed
Binary file pkiutilities/ocsp/test/requests/openssl/request02.dat has changed
Binary file pkiutilities/ocsp/test/requests/openssl/request03.dat has changed
Binary file pkiutilities/ocsp/test/requests/openssl/request04.dat has changed
Binary file pkiutilities/ocsp/test/requests/openssl/request05.dat has changed
Binary file pkiutilities/ocsp/test/requests/openssl/request06.dat has changed
Binary file pkiutilities/ocsp/test/requests/openssl/request07.dat has changed
Binary file pkiutilities/ocsp/test/requests/openssl/request08.dat has changed
Binary file pkiutilities/ocsp/test/requests/openssl/request09.dat has changed
Binary file pkiutilities/ocsp/test/requests/openssl/request10.dat has changed
Binary file pkiutilities/ocsp/test/requests/openssl/request11.dat has changed
Binary file pkiutilities/ocsp/test/requests/openssl/request12.dat has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/resign/README.TXT	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,9 @@
+
+This directory contains the files for a small EPOC console app called RESIGN.EXE
+
+This app takes filenames of an OCSP response and of a private .key as command line
+parameters.
+
+The purpose of the app is to resign the response using that key.  This can be used
+to re-sign OCSP responses that have been edited, so that the signatures are valid.
+This is used to generate erroneous OCSP responses for error-testing our OCSP client.
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/resign/main.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,67 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// resign.cpp
+// App for resigning OCSP responses.
+// 
+//
+
+#include <e32cons.h>
+#include <f32file.h>
+#include <asn1dec.h>
+#include <asn1enc.h>
+#include <x509cert.h>
+#include <signed.h>
+#include <bigint.h>
+#include <asymmetric.h>
+#include <hash.h>
+#include <bacline.h>
+
+#include "resign.h"
+
+static CConsoleBase* console;
+
+static void RunConsoleL()
+	{
+	__UHEAP_MARK;
+	// Create console
+	console = Console::NewL(_L("OCSP Response Resign Utility"), TSize(KDefaultConsWidth,KDefaultConsHeight));
+	CleanupStack::PushL(console);
+
+	CResign* resign = CResign::NewLC();
+	// Next stage
+	resign->ProcessCommandLineL();
+	
+	CleanupStack::PopAndDestroy(resign);
+	CleanupStack::PopAndDestroy(console);
+	__UHEAP_MARKEND;
+	}
+
+
+// Entry point
+GLDEF_C TInt E32Main()
+    {
+	__UHEAP_MARK;
+
+	CTrapCleanup* cleanup=CTrapCleanup::New();
+
+	TRAPD(error, RunConsoleL()); 
+
+	__ASSERT_ALWAYS(!error, User::Panic(_L("TOCSP\\RESIGN ERROR"), error));
+
+	delete cleanup;
+
+	__UHEAP_MARKEND;
+
+	return KErrNone;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/resign/resign.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,364 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// App for resigning OCSP responses.
+// 
+//
+
+#include <e32cons.h>
+#include <f32file.h>
+#include <asn1dec.h>
+#include <asn1enc.h>
+#include <x509cert.h>
+#include <signed.h>
+#include <bigint.h>
+#include <asymmetric.h>
+#include <hash.h>
+#include <bacline.h>
+
+#include "resign.h"
+
+// CertTool command line parameters
+_LIT(KResign, "-resign");
+_LIT(KResignShort, "-r");
+
+_LIT(KCreate, "-create");
+_LIT(KCreateShort, "-c");
+
+_LIT(KExtractResponse, "-e");
+_LIT(KExtractResponseShort, "-extract");
+
+CResign* CResign::NewLC()
+	{
+	CResign* resign = new(ELeave) CResign();
+	CleanupStack::PushL(resign);
+	resign->ConstructL();
+	return resign;
+	}
+	
+CResign* CResign::NewL()
+	{
+	CResign* resign = CResign::NewLC();
+	CleanupStack::Pop(resign);
+	return resign;
+	}
+		
+CResign::CResign()
+	{}
+	
+void CResign::ConstructL()
+	{
+	User::LeaveIfError(iFs.Connect());
+	}
+
+CResign::~CResign()
+	{
+	delete iArguments;
+	iFs.Close();
+	}
+
+void CResign::ResignL(const TPtrC8& aSignedData,
+			 TPtr8& aSignature,
+			 RInteger& aModulus,
+			 const RInteger& /*aPublicExponent*/,
+			 RInteger& aPrivateExponent)
+	{
+	__UHEAP_MARK;
+	// Build message digest
+	CSHA1* hash = CSHA1::NewL();
+	CleanupStack::PushL(hash);
+	TPtrC8 digest = hash->Final(aSignedData);
+
+	// Build ASN1 encoding of digestAlgId and digest..
+	CASN1EncSequence* encAll = CASN1EncSequence::NewLC();
+
+	// Build AlgID encoder (for SHA1)
+	CASN1EncSequence* encAlgId = CASN1EncSequence::NewLC();
+
+	CASN1EncObjectIdentifier* encObjId = CASN1EncObjectIdentifier::NewLC(KSHA1);
+	encAlgId->AddChildL(encObjId);
+	CleanupStack::Pop(); // encObjId, now owned by endAlgId
+
+	CASN1EncNull* encNull = CASN1EncNull::NewLC();
+	encAlgId->AddChildL(encNull);
+	CleanupStack::Pop(); // encNull, now owned by endAlgId
+
+	encAll->AddChildL(encAlgId);
+	CleanupStack::Pop(); // endAlgId, now owned by encAll
+
+	CASN1EncOctetString* encDigest = CASN1EncOctetString::NewLC(digest);
+	encAll->AddChildL(encDigest);
+	CleanupStack::Pop(); // encDigest, now owned by encAll
+
+	HBufC8* digestInfo = HBufC8::NewMaxLC(encAll->LengthDER());
+	TUint pos = 0;
+	TPtr8 digestInfoPtr = digestInfo->Des();
+	encAll->WriteDERL(digestInfoPtr, pos);
+
+	__UHEAP_MARK;
+
+	CRSAPrivateKeyStandard* rsaPriv = CRSAPrivateKeyStandard::NewLC(aModulus, aPrivateExponent);
+
+	CRSAPKCS1v15Signer* signer = CRSAPKCS1v15Signer::NewLC(*rsaPriv);
+	
+	const CRSASignature* signature = signer->SignL(digestInfoPtr);
+	
+	HBufC8* theSignature = signature->S().BufferLC();
+	aSignature.Copy(*theSignature);
+	
+	CleanupStack::PopAndDestroy(4, rsaPriv);
+
+	__UHEAP_MARKEND;
+
+	CleanupStack::PopAndDestroy(3, hash);
+	
+	__UHEAP_MARKEND;
+	}
+
+void CResign::DecodeDataL(TDes8& aResponse, const TDesC8& aKey)
+	{
+	__UHEAP_MARK;
+	TASN1DecSequence seqDec;
+	TInt pos = 0;
+
+	// Get the signed data and signature portions of the response
+	CArrayPtr<TASN1DecGeneric>* ocspResponseSeq = seqDec.DecodeDERLC(aResponse, pos, 2, 2);
+	TPtrC8 responseBytes = ocspResponseSeq->At(1)->GetContentDER();
+	CleanupStack::PopAndDestroy(ocspResponseSeq);
+
+	pos = 0;
+	CArrayPtr<TASN1DecGeneric>* responseBytesSeq = seqDec.DecodeDERLC(responseBytes, pos, 2, 2);
+	TPtrC8 basicOCSPResponse = responseBytesSeq->At(1)->GetContentDER();
+	CleanupStack::PopAndDestroy(responseBytesSeq);
+
+	pos = 0;
+	CArrayPtr<TASN1DecGeneric>* basicOCSPResponseSeq = seqDec.DecodeDERLC(basicOCSPResponse, pos, 3, 4);
+	TPtrC8 responseData = basicOCSPResponseSeq->At(0)->Encoding();
+	TPtrC8 signatureAlgorithm = basicOCSPResponseSeq->At(1)->Encoding();
+	TPtrC8 signature = basicOCSPResponseSeq->At(2)->GetContentDER();
+	CleanupStack::PopAndDestroy(basicOCSPResponseSeq);
+
+	// Check that it's RSA with SHA1
+	CX509SigningAlgorithmIdentifier* algId = CX509SigningAlgorithmIdentifier::NewLC(signatureAlgorithm);
+	if (algId->DigestAlgorithm().Algorithm() != ESHA1
+		|| algId->AsymmetricAlgorithm().Algorithm() != ERSA)
+		{
+		User::Leave(KErrNotSupported);
+		}
+	CleanupStack::PopAndDestroy(algId);
+
+	// Get the modulus and private key portions of the key - only RSA supported
+
+	// ASN1 .key files have 9 parts: version, modulus, public exponent, private exponent,
+	// prime 1, prime2, exponent 1, exponent 2, coefficient
+	// This is defined in PKCS1 (RFC 2313), the RSAPrivateKey ASN1 data structure
+	pos = 0;
+	CArrayPtr<TASN1DecGeneric>* keySeq = seqDec.DecodeDERLC(aKey, pos, 9, 9);
+	TASN1DecInteger decInt;
+
+	RInteger modulus = decInt.DecodeDERLongL(*keySeq->At(1));
+	CleanupStack::PushL(modulus);
+
+	RInteger publicExponent = decInt.DecodeDERLongL(*keySeq->At(2));
+	CleanupStack::PushL(publicExponent);
+
+	RInteger privateExponent = decInt.DecodeDERLongL(*keySeq->At(3));
+	CleanupStack::PushL(privateExponent);
+
+	// Cast constness off the signature - and skip the 'number of unused bits' octet
+	TPtr8 sigEdit(CONST_CAST(TUint8*, signature.Ptr() + 1), signature.Length() - 1, signature.Length() - 1);
+
+	// Pass data on for re-signing
+	ResignL(responseData, sigEdit, modulus, publicExponent, privateExponent);
+
+	CleanupStack::PopAndDestroy(3, &modulus); // The RIntegers
+	CleanupStack::PopAndDestroy(keySeq);
+	__UHEAP_MARKEND;
+	}
+
+void CResign::ProcessCommandLineL()
+    {
+	iArguments = CCommandLineArguments::NewL();
+	
+	if(iArguments->Count() > 1)
+		{	
+		TCommand command = ENone; 
+		
+		TPtrC args = iArguments->Arg(1);
+		if ((args.Compare(KResign)==0) || (args.Compare(KResignShort)==0))
+			{
+			command = EResign;
+			}	
+		if ((args.Compare(KCreate)==0) || (args.Compare(KCreateShort)==0))
+			{
+			command = ECreate;
+			}
+		if ((args.Compare(KExtractResponse)==0) || (args.Compare(KExtractResponseShort)==0))
+			{
+			command = EExtract;
+			}
+		
+		if(command != ENone)
+			{
+			HandleCommandL(command);
+			}
+		}
+    }
+
+void CResign::HandleCommandL(TCommand aCommand)
+	{
+	switch(aCommand)
+		{
+		case EResign:
+			ResignFilesL();
+			break;
+			
+		case ECreate:
+			CreateDatFileL();
+			break;
+		
+		case EExtract:
+			ExtractResponseL();
+			break;
+		}
+	}
+
+void CResign::ResignFilesL()
+	{
+	__UHEAP_MARK;
+	
+	TPtrC responseFile(iArguments->Arg(2));
+	TPtrC keyFile(iArguments->Arg(3));
+	
+	// Load the key
+	RFile file;
+	User::LeaveIfError(file.Open(iFs, keyFile, EFileRead | EFileShareAny));
+	CleanupClosePushL(file);
+	
+	TInt keySize;
+	User::LeaveIfError(file.Size(keySize));
+	HBufC8* keyBuf = HBufC8::NewLC(keySize);
+	TPtr8 key = keyBuf->Des();
+
+	User::LeaveIfError(file.Read(key));
+	
+	// Open the logged response file
+
+	RFileReadStream readStream;
+	User::LeaveIfError(readStream.Open(iFs, responseFile, EFileRead | EFileShareAny));
+	CleanupClosePushL(readStream);
+	MStreamBuf* readBuf = readStream.Source();
+
+	RFileWriteStream writeStream;
+	User::LeaveIfError(writeStream.Open(iFs, responseFile, EFileWrite | EFileShareAny));
+	CleanupClosePushL(writeStream);
+	MStreamBuf* writeBuf = writeStream.Sink();
+
+	TInt totalResponses = readStream.ReadUint32L();
+
+	for (TInt i = 0 ; i < totalResponses ; ++i)
+		{
+		TInt responseSize = readStream.ReadUint32L();
+		TStreamPos pos = readBuf->TellL(MStreamBuf::ERead);
+
+		HBufC8* responseBuf = HBufC8::NewLC(responseSize);
+
+		TPtr8 response = responseBuf->Des();
+		readStream.ReadL(response);
+
+		// resigning response
+		DecodeDataL(response, key);
+
+		writeBuf->SeekL(MStreamBuf::EWrite, pos);
+		writeStream.WriteL(response);
+
+		CleanupStack::PopAndDestroy(responseBuf);
+		}
+	
+	CleanupStack::PopAndDestroy(4,&file); // close writeStream, readStream, keyBuf and file
+	
+	__UHEAP_MARKEND;
+	}
+
+void CResign::CreateDatFileL()
+	{
+	__UHEAP_MARK;
+	
+	
+	// this path will fail if the directories are not already present.
+	_LIT(KDatFile,"c:\\system\\tocsp\\responses\\response.dat");
+	RFileWriteStream writeStream;
+	User::LeaveIfError(writeStream.Replace(iFs, KDatFile, EFileWrite | EFileShareAny));
+	CleanupClosePushL(writeStream);
+	
+	TInt fileCount = iArguments->Count(); 
+	
+	// total no of responses in this dat file
+	writeStream.WriteInt32L(fileCount-2);
+	RFile file;
+	for(TInt i=2;i<fileCount;i++)
+		{
+		TPtrC responseFile(iArguments->Arg(i));
+		// Load the response file
+		User::LeaveIfError(file.Open(iFs, responseFile, EFileRead | EFileShareAny));
+		CleanupClosePushL(file);
+		
+		TInt respSize = 0;
+		User::LeaveIfError(file.Size(respSize));
+		HBufC8* respBuf = HBufC8::NewLC(respSize);
+		TPtr8 resp = respBuf->Des();
+		User::LeaveIfError(file.Read(resp));
+		
+		writeStream.WriteInt32L(respSize);
+		writeStream.WriteL(resp);
+		
+		CleanupStack::PopAndDestroy(2,&file); // respBuf and file
+		}
+	
+	CleanupStack::PopAndDestroy(&writeStream);
+	
+	__UHEAP_MARKEND;
+	}
+
+void CResign::ExtractResponseL()
+	{
+	__UHEAP_MARK;
+	
+	TPtrC responseFile(iArguments->Arg(2));
+	
+	// Load the response file
+	RFileReadStream respFile;
+	User::LeaveIfError(respFile.Open(iFs, responseFile, EFileRead | EFileShareAny));
+	CleanupClosePushL(respFile);
+	
+	// reading the transaction value.
+	respFile.ReadInt32L();
+	TInt respSize = respFile.ReadInt32L();
+	
+	HBufC8* respBuf = HBufC8::NewLC(respSize);
+	TPtr8 resp = respBuf->Des();
+
+	respFile.ReadL(resp, respSize);
+	
+	// this path will fail if the directories are not already present.
+	_LIT(KDerFile,"c:\\system\\tocsp\\responses\\response.der");
+	RFileWriteStream writeStream;
+	User::LeaveIfError(writeStream.Replace(iFs, KDerFile, EFileWrite | EFileShareAny));
+	CleanupClosePushL(writeStream);
+	writeStream.WriteL(resp);
+	
+	CleanupStack::PopAndDestroy(3,&respFile); // writeStream, respBuf and respFile
+	
+	__UHEAP_MARKEND;
+
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/resign/resign.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,65 @@
+// Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Tool for generating test response files to be used for testing ocsp module.
+// 
+//
+
+/**
+ @file 
+ @internalComponent
+*/
+
+#ifndef __RESIGN_H
+#define __RESIGN_H
+
+class CCommandLineArguments;
+
+class CResign : public CBase
+	{
+	
+	enum TCommand
+		{
+		ENone,
+		EResign,
+		ECreate,
+		EExtract,
+		};
+
+	public:
+		static CResign* NewLC();
+		static CResign* NewL();
+		virtual ~CResign();
+		
+		void ProcessCommandLineL();
+		
+	protected:
+		CResign();
+	
+	private:
+		void ConstructL();
+		void ResignL( const TPtrC8& aSignedData,	 TPtr8& aSignature,
+				 	  RInteger& aModulus, const RInteger& /*aPublicExponent*/,
+				 	  RInteger& aPrivateExponent);
+		void DecodeDataL(TDes8& aResponse, const TDesC8& aKey);
+		void ResignFilesL();
+		void HandleCommandL(TCommand aCommand);
+		void CreateDatFileL();
+		void ExtractResponseL();
+		
+	private:
+		CCommandLineArguments* iArguments;
+		RFs iFs;
+	};
+	
+#endif //__RESIGN_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/resign/resign.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+/**
+@file
+
+@SYMPurpose resign.exe Resign the OCSP response 
+*/
+
+TARGET		resign.exe
+TARGETTYPE	exe
+
+UID 0x10000079 0x1000AF92
+VENDORID 0x70000001
+
+SOURCEPATH	.
+
+SOURCE 		main.cpp
+SOURCE 		resign.cpp
+USERINCLUDE	.
+
+MW_LAYER_SYSTEMINCLUDE_SYMBIAN
+
+LIBRARY	euser.lib efsrv.lib asn1.lib x509.lib estor.lib hash.lib crypto.lib
+LIBRARY cryptography.lib bafl.lib
+SMPSAFE
Binary file pkiutilities/ocsp/test/responses/Error_00_Single_R5.rsp has changed
Binary file pkiutilities/ocsp/test/responses/Error_01_Double_R5.rsp has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/responses/README.TXT	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,66 @@
+This directory contains pre-computed OCSP responses which are used by the input
+scripts for TOCSP.  Most have been hand-edited to contain particular errors, and
+in some cases then re-signed using the 'resign' utility.
+
+(* signifies resigning was used)
+
+The following are used in the Error.txt input script:
+
+response.000     Original response, upon which other non-trivial responses are based
+response.001     'malformedRequest'
+response.002     'internalError'
+response.003     'tryLater'
+response.004     ..invalid responseStatus
+response.005     'sigRequired'
+response.006     'unauthorised'
+response.007     ..invalid responseStatus
+response.008     ..invalid responseStatus (-ve)
+response.009     invalid RSA signature
+response.010     corrupt RSA signature data (#unused bits not 0)
+response.011*    invalid hashAlgorithm in CertId
+response.012*    corrupt issuerNameHash in CertId
+response.013*    corrupt issuerKeyHash in CertId
+response.014*    corrupt serialNumber in CertId
+response.015     hash algorithm specified in signature doesn't match that
+                  used (which is specified before the signature)
+                  - produced using a modified version of resign.exe
+response.016     Invalid response type (outside signed data portion)
+response.017*    Inserted 'version' field with value v1 (shouldn't be there since this is
+                  the default value, and defaults are skipped in DER)
+response.018*    As 017, but with unrecognised version value '1'.
+response.019*    producedAt before thisUpdate
+response.020*    Added nextUpdate field - one month after thisUpdate
+response.021*    From 020, set producedAt > nextUpdate
+response.022*    From 020, set thisUpdate > nextUpdate (producedAt < nextUpdate)
+response.023*    From 020, set thisUpdate > nextUpdate (producedAt between the two)
+response.024*    From 020, set thisUpdate > nextUpdate (producedAt > thisUpdate)
+response.025*    Issuer name corrupted (doesn't match signing cert subject field)
+response.026-030 Corrupt length fields (* on 29)
+response.031-035 Corrupt tag fields (* on 32, 34)
+
+The following are used in XCert.txt:
+
+response.n1      Testing Nonce on, incorrect value / unexpected nonce received
+response.n2      Testing Nonce on, response with missing nonce
+
+The following are used in XCert-local.txt, in addition to those used in XCert.txt:
+
+XCert_00_Good_RSA_XCert.rsp
+XCert_01_Revoked_RSA_XCert.rsp
+XCert_02_Suspended_RSA_XCert.rsp
+XCert_03_Unknown_RSA_XCert.rsp
+XCert_04_Good_DSA_XCert.rsp
+XCert_05_Revoked_DSA_XCert.rsp
+XCert_06_Suspended_DSA_XCert.rsp
+XCert_07_Unknown_DSA_XCert.rsp
+XCert_08_All_RSA_XCert.rsp
+XCert_09_All_DSA_XCert.rsp
+XCert_10_Expired_Subject_and_Issuer.rsp
+XCert_11_Expired_Signing.rsp
+XCert_12_Expired_Subject.rsp
+XCert_13_Unspecified_Date.rsp
+XCert_14_Expired_subject_valid_time.rsp
+XCert_15_Expired_unspecified.rsp
+XCert_16_Expired_specified.rsp
+XCert_20_Nonce_Off.rsp
+XCert_22_BadSig_DSA_XCert.rsp
Binary file pkiutilities/ocsp/test/responses/XCert_00_Good_RSA_XCert.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_01_Revoked_RSA_XCert.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_02_Suspended_RSA_XCert.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_03_Unknown_RSA_XCert.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_04_Good_DSA_XCert.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_05_Revoked_DSA_XCert.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_06_Suspended_DSA_XCert.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_07_Unknown_DSA_XCert.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_08_All_RSA_XCert.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_09_All_DSA_XCert.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_10_Expired_Subject_and_Issuer.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_11_Expired_Signing.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_12_Expired_Subject.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_14_Expired_subject_valid_time.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_15_Expired_unspecified.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_16_ThisUpdateTooEarly.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_20_Nonce_Off.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_22_BadSig_DSA_XCert.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_23_ResultCombination1.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_24_ResultCombination2.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_25_ResultCombination3.rsp has changed
Binary file pkiutilities/ocsp/test/responses/XCert_26_ResultCombination4.rsp has changed
Binary file pkiutilities/ocsp/test/responses/ca_1ext_usage_not_ocspsigning_resp.dat has changed
Binary file pkiutilities/ocsp/test/responses/ca_2ext_usage_not_ocspsigning_resp.dat has changed
Binary file pkiutilities/ocsp/test/responses/ca_2ext_usage_ocspsigning_bad_name_resp.dat has changed
Binary file pkiutilities/ocsp/test/responses/ca_2ext_usage_ocspsigning_bad_sign_resp.dat has changed
Binary file pkiutilities/ocsp/test/responses/ca_2ext_usage_ocspsigning_resp.dat has changed
Binary file pkiutilities/ocsp/test/responses/ca_delg_wrong_key.dat has changed
Binary file pkiutilities/ocsp/test/responses/ca_direct_good_wrong_key.dat has changed
Binary file pkiutilities/ocsp/test/responses/ca_direct_multi_cert_inc_right.dat has changed
Binary file pkiutilities/ocsp/test/responses/ca_direct_multi_cert_no_right.dat has changed
Binary file pkiutilities/ocsp/test/responses/ca_direct_revoked.dat has changed
Binary file pkiutilities/ocsp/test/responses/ca_direct_wrong_cert.dat has changed
Binary file pkiutilities/ocsp/test/responses/ca_direct_wrong_resp_name.dat has changed
Binary file pkiutilities/ocsp/test/responses/ca_no_ext_usage_resp.dat has changed
Binary file pkiutilities/ocsp/test/responses/multi_cert_resp.dat has changed
Binary file pkiutilities/ocsp/test/responses/multiple_response.dat has changed
Binary file pkiutilities/ocsp/test/responses/no_cert_resp.dat has changed
Binary file pkiutilities/ocsp/test/responses/no_certresp_signedby_delegate.dat has changed
Binary file pkiutilities/ocsp/test/responses/openssl/no_aia_no_ocspext.dat has changed
Binary file pkiutilities/ocsp/test/responses/openssl/response01.dat has changed
Binary file pkiutilities/ocsp/test/responses/openssl/response02.dat has changed
Binary file pkiutilities/ocsp/test/responses/openssl/response03.dat has changed
Binary file pkiutilities/ocsp/test/responses/openssl/response04.dat has changed
Binary file pkiutilities/ocsp/test/responses/openssl/response05.dat has changed
Binary file pkiutilities/ocsp/test/responses/openssl/response06.dat has changed
Binary file pkiutilities/ocsp/test/responses/openssl/response07.dat has changed
Binary file pkiutilities/ocsp/test/responses/openssl/response08.dat has changed
Binary file pkiutilities/ocsp/test/responses/openssl/response09.dat has changed
Binary file pkiutilities/ocsp/test/responses/openssl/response10.dat has changed
Binary file pkiutilities/ocsp/test/responses/openssl/response11.dat has changed
Binary file pkiutilities/ocsp/test/responses/openssl/response12.dat has changed
Binary file pkiutilities/ocsp/test/responses/response.000 has changed
Binary file pkiutilities/ocsp/test/responses/response.001 has changed
Binary file pkiutilities/ocsp/test/responses/response.002 has changed
Binary file pkiutilities/ocsp/test/responses/response.003 has changed
Binary file pkiutilities/ocsp/test/responses/response.004 has changed
Binary file pkiutilities/ocsp/test/responses/response.005 has changed
Binary file pkiutilities/ocsp/test/responses/response.006 has changed
Binary file pkiutilities/ocsp/test/responses/response.007 has changed
Binary file pkiutilities/ocsp/test/responses/response.008 has changed
Binary file pkiutilities/ocsp/test/responses/response.009 has changed
Binary file pkiutilities/ocsp/test/responses/response.010 has changed
Binary file pkiutilities/ocsp/test/responses/response.011 has changed
Binary file pkiutilities/ocsp/test/responses/response.012 has changed
Binary file pkiutilities/ocsp/test/responses/response.013 has changed
Binary file pkiutilities/ocsp/test/responses/response.014 has changed
Binary file pkiutilities/ocsp/test/responses/response.015 has changed
Binary file pkiutilities/ocsp/test/responses/response.016 has changed
Binary file pkiutilities/ocsp/test/responses/response.018 has changed
Binary file pkiutilities/ocsp/test/responses/response.019 has changed
Binary file pkiutilities/ocsp/test/responses/response.020 has changed
Binary file pkiutilities/ocsp/test/responses/response.021 has changed
Binary file pkiutilities/ocsp/test/responses/response.022 has changed
Binary file pkiutilities/ocsp/test/responses/response.023 has changed
Binary file pkiutilities/ocsp/test/responses/response.024 has changed
Binary file pkiutilities/ocsp/test/responses/response.025 has changed
Binary file pkiutilities/ocsp/test/responses/response.026 has changed
Binary file pkiutilities/ocsp/test/responses/response.027 has changed
Binary file pkiutilities/ocsp/test/responses/response.028 has changed
Binary file pkiutilities/ocsp/test/responses/response.029 has changed
Binary file pkiutilities/ocsp/test/responses/response.030 has changed
Binary file pkiutilities/ocsp/test/responses/response.031 has changed
Binary file pkiutilities/ocsp/test/responses/response.032 has changed
Binary file pkiutilities/ocsp/test/responses/response.033 has changed
Binary file pkiutilities/ocsp/test/responses/response.034 has changed
Binary file pkiutilities/ocsp/test/responses/response.035 has changed
Binary file pkiutilities/ocsp/test/responses/response.n1 has changed
Binary file pkiutilities/ocsp/test/responses/response.n2 has changed
Binary file pkiutilities/ocsp/test/responses/vs_explicit_version.dat has changed
Binary file pkiutilities/ocsp/test/responses/wrong_ca_cert_resp.dat has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/result.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,130 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Class to handle the acumulation of pass/fail data on the tests
+// 
+//
+
+#include "result.h"
+#include "logger.h"
+
+CTOCSPResult* CTOCSPResult::NewLC()
+	{
+	CTOCSPResult* self = NewL();
+	CleanupStack::PushL(self);
+	return self;
+	}
+
+
+CTOCSPResult* CTOCSPResult::NewL()
+	{
+	CTOCSPResult* self = new (ELeave) CTOCSPResult;
+	return self;
+	}
+
+
+CTOCSPResult::~CTOCSPResult()
+	{
+	iNames.ResetAndDestroy();
+	iResults.Close();
+	}
+
+
+// Call this when you're starting a new test
+void CTOCSPResult::NewTestL(const TDesC& aName)
+	{
+	CheckL();
+
+	HBufC* name = aName.AllocLC();
+	User::LeaveIfError(iNames.Append(name));
+	CleanupStack::Pop(name);
+
+	iTotal++;
+	}
+
+
+// Then call this to say if it passed
+void CTOCSPResult::ResultL(const TBool aResult)
+	{
+	User::LeaveIfError(iResults.Append(aResult));
+
+	if (aResult)
+		{
+		iPassed++;
+		}
+	else
+		{
+		iFailed++;
+		}
+
+	CheckL();
+	}
+
+
+void CTOCSPResult::CheckL() const
+	{
+	if (iTotal != iPassed + iFailed
+		|| iTotal != iNames.Count()
+		|| iTotal != iResults.Count())
+		{
+		User::Leave(KErrCorrupt);
+		}
+	}
+
+
+void CTOCSPResult::LogSummaryL(CTOCSPLogger& aLog)
+	{
+	// Allow one less test result than test started,
+	// assume this meanswe crashed out of last test
+	if (iTotal == (iPassed + iFailed + 1))
+		{
+		User::LeaveIfError(iResults.Append(EFalse));
+		++iFailed;
+		}
+
+	CheckL();
+
+	aLog.LogL(_L("Run: "));
+	aLog.LogL(iTotal);
+	aLog.LogL(_L("\nPassed: "));
+	aLog.LogL(iPassed);
+
+	aLog.LogL(_L("\n"));
+	aLog.LogL(iFailed);
+	aLog.LogL(_L(" tests failed out of "));
+	aLog.LogL(iTotal);
+	aLog.LogL(_L("\n"));
+
+	aLog.LogL(_L("Failed tests: "));
+	TInt tally = 0;
+	for (TInt i = 0; i < iTotal; ++i)
+		{
+		if (!iResults[i])
+			{
+			aLog.LogL(*iNames[i]);
+			aLog.LogL(_L(" ("));
+			aLog.LogL(i);
+			aLog.LogL(_L(")"));
+			
+			if (++tally < iFailed)
+				{
+				aLog.LogL(_L(", "));
+				}
+			else
+				{
+				aLog.LogL(_L("\n"));
+				}
+			}
+		}
+	aLog.LogL(_L("\r\n</pre></body></html>\r\n"));	
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/result.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,58 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Class to handle the acumulation of pass/fail data on the tests
+// 
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+
+#ifndef __TOCSP_RESULT_H__
+#define __TOCSP_RESULT_H__
+
+#include "e32base.h"
+
+class CTOCSPLogger;
+
+class CTOCSPResult : public CBase
+	{
+public:
+	static CTOCSPResult* NewLC();
+	static CTOCSPResult* NewL();
+	~CTOCSPResult();
+
+	// Call this when you're starting a new test
+	void NewTestL(const TDesC& aName);
+
+	// Then call this to say if it passed
+	void ResultL(const TBool aResult);
+
+	// Print text report on conclusions
+	void LogSummaryL(CTOCSPLogger& aLog);
+
+private:
+	void CheckL() const;
+
+private:
+	RPointerArray<HBufC> iNames;
+	RArray<TBool> iResults;
+
+	TInt iTotal;
+	TInt iPassed;
+	TInt iFailed;
+	};
+
+#endif // __TOCSP_RESULT_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/script.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,191 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Reads lines from script using idle tick for each.  Parse into tokens, pass to command object.
+// 
+//
+
+#include "script.h"
+#include "command.h"
+
+#include <e32cons.h>
+#include <unifiedcertstore.h>
+
+CTOCSPScript* CTOCSPScript::NewLC(CTOCSPLogger& aLog,
+								  CTOCSPResult& aResult, 
+								  const TDesC& aInputFileName,
+								  TInt aTransaction)
+	{
+	CTOCSPScript* self = new (ELeave) CTOCSPScript(aLog);
+	CleanupStack::PushL(self);
+	self->ConstructL(aInputFileName, aResult, aTransaction);
+	return self;
+	}
+
+
+CTOCSPScript* CTOCSPScript::NewL(CTOCSPLogger& aLog,
+								 CTOCSPResult& aResult, 
+								 const TDesC& aInputFileName,
+								 TInt aTransaction)
+	{
+	CTOCSPScript* self = NewLC(aLog, aResult, aInputFileName, aTransaction);
+	CleanupStack::Pop(self);
+	return self;
+	}
+//********************************************************************
+CTOCSPScript* CTOCSPScript::NewL(CTOCSPLogger& aLog,
+								 CTOCSPResult& aResult, 
+								 TInt aTransaction)
+	{
+	CTOCSPScript* self = NewLC(aLog, aResult, aTransaction);
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+CTOCSPScript* CTOCSPScript::NewLC(CTOCSPLogger& aLog,
+								  CTOCSPResult& aResult, 
+								  TInt aTransaction)
+	{
+	CTOCSPScript* self = new (ELeave) CTOCSPScript(aLog);
+	CleanupStack::PushL(self);
+	self->ConstructL(aResult, aTransaction);
+	return self;
+	}
+
+void CTOCSPScript::ConstructL(CTOCSPResult& aResult, TInt aTransaction)
+	{
+	CActiveScheduler::Add(this);
+
+	iCommand = CTOCSPCommand::NewL(iLog, aResult, aTransaction);
+	
+	}
+
+//*********************************************************************
+
+CTOCSPScript::CTOCSPScript(CTOCSPLogger& aLog) :
+	CActive(EPriorityNormal),
+	iLog(aLog)
+	{
+	}
+
+
+void CTOCSPScript::ConstructL(const TDesC& aInputFileName, CTOCSPResult& aResult, TInt aTransaction)
+	{
+	CActiveScheduler::Add(this);
+
+	iCommand = CTOCSPCommand::NewL(iLog, aResult, aTransaction);
+
+	User::LeaveIfError(iFs.Connect());
+	TInt err = iFile.Open(iFs, aInputFileName, EFileRead | EFileShareAny);
+	if (err != KErrNone)
+		{
+		iLog.LogL(_L("Error while opening "));
+		iLog.LogL(aInputFileName);
+		iLog.NewLineL();
+		User::Leave(err);
+		}
+	iLineReader.Set(iFile);
+	}
+
+
+CTOCSPScript::~CTOCSPScript()
+	{
+	Cancel();
+	iFile.Close();
+	iFs.Close();
+
+	delete iCommand;
+	}
+
+
+void CTOCSPScript::RunTestL(TRequestStatus& aStatus)
+	{
+	iClientRequestStatus = &aStatus;
+	aStatus = KRequestPending;
+	ReadLineL();
+	}
+
+
+TInt CTOCSPScript::TransactionCount()
+    {
+    return iCommand->CurrentTransaction();
+    }
+
+
+void CTOCSPScript::RunL()
+	{
+	User::LeaveIfError(iStatus.Int());
+	ReadLineL();
+	}
+
+
+void CTOCSPScript::DoCancel()
+	{
+    iCommand->Cancel();
+	}
+
+
+TInt CTOCSPScript::RunError(TInt aError)
+    {
+    User::RequestComplete(iClientRequestStatus, aError);
+    return KErrNone;
+    }
+
+
+
+// void CTOCSPScript::ReadLineL()f-
+//reads in from the TDes  
+void CTOCSPScript::ReadLineL()
+	{
+	TInt error = iLineReader.Read(iLine);
+
+    if (error == KErrNone)
+        {
+		++iLinesProcessed;
+        TBool carryOn = iCommand->ProcessCommand(iLine, iStatus);
+
+        if (carryOn)
+			{
+			SetActive();
+			}
+		else
+            {
+			User::RequestComplete(iClientRequestStatus, KErrNone);
+            }
+        }
+    else if (error == KErrEof)
+        {
+		User::RequestComplete(iClientRequestStatus, KErrNone);
+        }
+    else
+        {
+		User::Leave(error);
+		}
+	}
+
+
+void CTOCSPScript::SetVerbose(TBool aVerbose)
+	{
+	iCommand->SetVerbose(aVerbose);
+	}
+
+
+TInt CTOCSPScript::LinesProcessed() const
+	{
+	return iLinesProcessed;
+	}
+
+const TDesC& CTOCSPScript::LastLine() const
+	{
+	return iLine;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/script.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,121 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Declare CTOCSPScript.  This opens a file, starts a scheduler and runs a CIdle object.
+// Each tick takes a line from the file, parses it into tokens and gives these to 
+// the command processor.
+// 
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+
+#ifndef __TOCSP_SCRIPT_H__
+#define __TOCSP_SCRIPT_H__
+
+#include <e32base.h>
+#include <f32file.h>
+
+#include "logger.h"
+#include "TEFparser.h"
+#include "main.h"
+
+class CTOCSPCommand;
+class CTOCSPResult;
+
+// At most this many chars per line in input file, thanks.
+const TInt KMaxInputFileLineLength = 256;
+
+/**
+ * This class provides a convenient interface to the test script.
+ */
+class CTOCSPScript : public CActive
+	{
+public:
+	/**
+	 * This function creates a new CTOCSPScript instance and pushes it on the
+	 * cleanup stack.
+	 * @param aLog the logger which writes the log into the log file and the cosole.
+	 * @param aResult pass/fail result data on the tests
+	 * @param aInputFileName The name of the test script file we want to access.
+	 * @return A new instance of CTOCSPScript.
+	 */
+	static CTOCSPScript* NewLC(CTOCSPLogger& aLog, 
+							   CTOCSPResult& aResult, 
+							   const TDesC& aInputFileName,
+							   TInt aTransaction = 0);
+
+	static CTOCSPScript* NewL(CTOCSPLogger& aLog, 
+							  CTOCSPResult& aResult, 
+							  const TDesC& aInputFileName,
+							  TInt aTransaction = 0);
+//   script file parser
+//***********************************************************
+	static CTOCSPScript* NewL(CTOCSPLogger& aLog, 
+							  CTOCSPResult& aResult,
+							  TInt aTransaction = 0);
+	
+	static CTOCSPScript* NewLC(CTOCSPLogger& aLog, 
+							   CTOCSPResult& aResult,
+							   TInt aTransaction = 0);
+//***********************************************************
+
+	
+	~CTOCSPScript();
+
+	void RunTestL(TRequestStatus& aStatus);
+
+    // Get the number of transactions performed
+    TInt TransactionCount();
+
+	/** Set whether to print informational messages. */
+	void SetVerbose(TBool aVerbose);	
+
+	/** Get the number of lines we have processed. */
+	TInt LinesProcessed() const;
+
+	/** Get the last line processed. */
+	const TDesC& LastLine() const;
+
+	void RunL();
+	void DoCancel();
+    TInt RunError(TInt aError);
+
+private:
+	CTOCSPScript(CTOCSPLogger& aLog);
+	void ConstructL(const TDesC& aInputFileName, CTOCSPResult& aResult, TInt aTransaction);
+	
+	void ConstructL(CTOCSPResult& aResult, TInt aTransaction);
+
+	void ReadLineL();
+	
+private:
+	CTOCSPLogger& iLog;
+	
+	CTOCSPCommand* iCommand;
+
+	TInt iError; // error code to return to client
+
+	// File server stuff
+	RFs iFs;
+	RFile iFile;
+	TFileText iLineReader;
+	TInt iLinesProcessed;
+	TBuf<KMaxInputFileLineLength> iLine;
+	TRequestStatus* iClientRequestStatus;
+	TInt iStartPos;
+	};
+
+#endif
Binary file pkiutilities/ocsp/test/scripts/2002b28b-new.txt has changed
Binary file pkiutilities/ocsp/test/scripts/CertCo.txt has changed
Binary file pkiutilities/ocsp/test/scripts/DefaultPolicy.ini has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/scripts/DefaultPolicy.script	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,72 @@
+//
+// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+//!  This tests the default OCSP policy
+//!  This tests a certificate with a AIA URL and
+//!  and a certificate with no AIA URL when there is 
+//!  no default URI
+//!  The expected result is the first outcome is ok 
+//!  and the second is "No server result unknown" 
+
+START_TESTCASE                SEC-TOCSP-DEFAULTPOLICY-0001
+//! @SYMTestCaseID            SEC-TOCSP-DEFAULTPOLICY-0001
+RUN_TEST_STEP                 DefaultPolicy.ini   SEC-TOCSP-DEFAULTPOLICY-0001-0001
+END_TESTCASE                  SEC-TOCSP-DEFAULTPOLICY-0001
+
+//!  **************************Test for CheckCertsWithAIAOnly ******************************
+
+//!  Generate Response for missing URI is enabled for all these test cases
+
+
+START_TESTCASE                SEC-TOCSP-DEFAULTPOLICY-0002
+//! @SYMTestCaseID            SEC-TOCSP-DEFAULTPOLICY-0002
+RUN_TEST_STEP                 DefaultPolicy.ini   SEC-TOCSP-DEFAULTPOLICY-0002-0001
+END_TESTCASE                  SEC-TOCSP-DEFAULTPOLICY-0002
+
+START_TESTCASE                SEC-TOCSP-DEFAULTPOLICY-0003
+//! @SYMTestCaseID            SEC-TOCSP-DEFAULTPOLICY-0003
+RUN_TEST_STEP                 DefaultPolicy.ini   SEC-TOCSP-DEFAULTPOLICY-0003-0001
+END_TESTCASE                  SEC-TOCSP-DEFAULTPOLICY-0003
+
+START_TESTCASE                SEC-TOCSP-DEFAULTPOLICY-0004
+//! @SYMTestCaseID            SEC-TOCSP-DEFAULTPOLICY-0004
+RUN_TEST_STEP                 DefaultPolicy.ini   SEC-TOCSP-DEFAULTPOLICY-0004-0001
+END_TESTCASE                  SEC-TOCSP-DEFAULTPOLICY-0004
+
+START_TESTCASE                SEC-TOCSP-DEFAULTPOLICY-0005
+//! @SYMTestCaseID            SEC-TOCSP-DEFAULTPOLICY-0005
+RUN_TEST_STEP                 DefaultPolicy.ini   SEC-TOCSP-DEFAULTPOLICY-0005-0001
+END_TESTCASE                  SEC-TOCSP-DEFAULTPOLICY-0005
+
+START_TESTCASE                SEC-TOCSP-DEFAULTPOLICY-0006
+//! @SYMTestCaseID            SEC-TOCSP-DEFAULTPOLICY-0006
+RUN_TEST_STEP                 DefaultPolicy.ini   SEC-TOCSP-DEFAULTPOLICY-0006-0001
+END_TESTCASE                  SEC-TOCSP-DEFAULTPOLICY-0006
+
+START_TESTCASE                SEC-TOCSP-DEFAULTPOLICY-0007
+//! @SYMTestCaseID            SEC-TOCSP-DEFAULTPOLICY-0007
+RUN_TEST_STEP                 DefaultPolicy.ini   SEC-TOCSP-DEFAULTPOLICY-0007-0001
+END_TESTCASE                  SEC-TOCSP-DEFAULTPOLICY-0007
+
+START_TESTCASE                SEC-TOCSP-DEFAULTPOLICY-0008
+//! @SYMTestCaseID            SEC-TOCSP-DEFAULTPOLICY-0008
+RUN_TEST_STEP                 DefaultPolicy.ini   SEC-TOCSP-DEFAULTPOLICY-0008-0001
+END_TESTCASE                  SEC-TOCSP-DEFAULTPOLICY-0008
+
+START_TESTCASE                SEC-TOCSP-DEFAULTPOLICY-0009
+//! @SYMTestCaseID            SEC-TOCSP-DEFAULTPOLICY-0009
+RUN_TEST_STEP                 DefaultPolicy.ini   SEC-TOCSP-DEFAULTPOLICY-0009-0001
+END_TESTCASE                  SEC-TOCSP-DEFAULTPOLICY-0009
\ No newline at end of file
Binary file pkiutilities/ocsp/test/scripts/Error.ini has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/scripts/Error.script	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,356 @@
+//
+// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+//! ****************************************************************************
+//! Input for TOCSP - Script-based test harness for OCSP
+//! See \Certman\TOCSP\Commands.cpp for description of commands
+//! This file must be in UNICODE
+//! ****************************************************************************
+
+//! This script features error tests, against pre-computed logged responses.
+
+//! *******  BEGIN OCSP ERROR TESTS  ***********
+
+
+
+START_TESTCASE                SEC-TOCSP-ERROR-0001
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0001
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0001
+END_TESTCASE                  SEC-TOCSP-ERROR-0001
+
+
+START_TESTCASE                SEC-TOCSP-ERROR-0002
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0002
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0002
+END_TESTCASE                  SEC-TOCSP-ERROR-0002
+
+
+START_TESTCASE                SEC-TOCSP-ERROR-0003
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0003
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0003
+END_TESTCASE                  SEC-TOCSP-ERROR-0003
+
+
+START_TESTCASE                SEC-TOCSP-ERROR-0004
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0004
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0004
+END_TESTCASE                  SEC-TOCSP-ERROR-0004
+
+
+START_TESTCASE                SEC-TOCSP-ERROR-0005
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0005
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0005
+END_TESTCASE                  SEC-TOCSP-ERROR-0005
+
+START_TESTCASE                SEC-TOCSP-ERROR-0006
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0006
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0006
+END_TESTCASE                  SEC-TOCSP-ERROR-0006
+
+START_TESTCASE                SEC-TOCSP-ERROR-0007
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0007
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0007
+END_TESTCASE                  SEC-TOCSP-ERROR-0007
+
+START_TESTCASE                SEC-TOCSP-ERROR-0008
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0008
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0008
+END_TESTCASE                  SEC-TOCSP-ERROR-0008
+
+START_TESTCASE                SEC-TOCSP-ERROR-0009
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0009
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0009
+END_TESTCASE                  SEC-TOCSP-ERROR-0009
+
+START_TESTCASE                SEC-TOCSP-ERROR-0010
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0010
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0010
+END_TESTCASE                  SEC-TOCSP-ERROR-0010
+
+START_TESTCASE                SEC-TOCSP-ERROR-0011
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0011
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0011
+END_TESTCASE                  SEC-TOCSP-ERROR-0011
+
+START_TESTCASE                SEC-TOCSP-ERROR-0012
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0012
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0012
+END_TESTCASE                  SEC-TOCSP-ERROR-0012
+
+START_TESTCASE                SEC-TOCSP-ERROR-0013
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0013
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0013
+END_TESTCASE                  SEC-TOCSP-ERROR-0013
+
+START_TESTCASE                SEC-TOCSP-ERROR-0014
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0014
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0014
+END_TESTCASE                  SEC-TOCSP-ERROR-0014
+
+START_TESTCASE                SEC-TOCSP-ERROR-0015
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0015
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0015
+END_TESTCASE                  SEC-TOCSP-ERROR-0015
+
+START_TESTCASE                SEC-TOCSP-ERROR-0016
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0016
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0016
+END_TESTCASE                  SEC-TOCSP-ERROR-0016
+
+START_TESTCASE                SEC-TOCSP-ERROR-0017
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0017
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0017
+END_TESTCASE                  SEC-TOCSP-ERROR-0017
+
+START_TESTCASE                SEC-TOCSP-ERROR-0018
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0018
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0018
+END_TESTCASE                  SEC-TOCSP-ERROR-0018
+
+START_TESTCASE                SEC-TOCSP-ERROR-0019
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0019
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0019
+END_TESTCASE                  SEC-TOCSP-ERROR-0019
+
+START_TESTCASE                SEC-TOCSP-ERROR-0020
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0020
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0020
+END_TESTCASE                  SEC-TOCSP-ERROR-0020
+
+START_TESTCASE                SEC-TOCSP-ERROR-0021
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0021
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0021
+END_TESTCASE                  SEC-TOCSP-ERROR-0021
+
+START_TESTCASE                SEC-TOCSP-ERROR-0022
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0022
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0022
+END_TESTCASE                  SEC-TOCSP-ERROR-0022
+
+START_TESTCASE                SEC-TOCSP-ERROR-0023
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0023
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0023
+END_TESTCASE                  SEC-TOCSP-ERROR-0023
+
+START_TESTCASE                SEC-TOCSP-ERROR-0024
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0024
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0024
+END_TESTCASE                  SEC-TOCSP-ERROR-0024
+
+START_TESTCASE                SEC-TOCSP-ERROR-0025
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0025
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0025
+END_TESTCASE                  SEC-TOCSP-ERROR-0025
+
+START_TESTCASE                SEC-TOCSP-ERROR-0026
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0026
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0026
+END_TESTCASE                  SEC-TOCSP-ERROR-0026
+
+START_TESTCASE                SEC-TOCSP-ERROR-0027
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0027
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0027
+END_TESTCASE                  SEC-TOCSP-ERROR-0027
+
+START_TESTCASE                SEC-TOCSP-ERROR-0028
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0028
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0028
+END_TESTCASE                  SEC-TOCSP-ERROR-0028
+
+START_TESTCASE                SEC-TOCSP-ERROR-0029
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0029
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0029
+END_TESTCASE                  SEC-TOCSP-ERROR-0029
+
+START_TESTCASE                SEC-TOCSP-ERROR-0030
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0030
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0030
+END_TESTCASE                  SEC-TOCSP-ERROR-0030
+
+START_TESTCASE                SEC-TOCSP-ERROR-0031
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0031
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0031
+END_TESTCASE                  SEC-TOCSP-ERROR-0031
+
+START_TESTCASE                SEC-TOCSP-ERROR-0032
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0032
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0032
+END_TESTCASE                  SEC-TOCSP-ERROR-0032
+
+START_TESTCASE                SEC-TOCSP-ERROR-0033
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0033
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0033
+END_TESTCASE                  SEC-TOCSP-ERROR-0033
+
+START_TESTCASE                SEC-TOCSP-ERROR-0034
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0034
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0034
+END_TESTCASE                  SEC-TOCSP-ERROR-0034
+
+START_TESTCASE                SEC-TOCSP-ERROR-0035
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0035
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0035
+END_TESTCASE                  SEC-TOCSP-ERROR-0035
+
+START_TESTCASE                SEC-TOCSP-ERROR-0036
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0036
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0036
+END_TESTCASE                  SEC-TOCSP-ERROR-0036
+
+START_TESTCASE                SEC-TOCSP-ERROR-0037
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0037
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0037
+END_TESTCASE                  SEC-TOCSP-ERROR-0037
+
+START_TESTCASE                SEC-TOCSP-ERROR-0038
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0038
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0038
+END_TESTCASE                  SEC-TOCSP-ERROR-0038
+
+START_TESTCASE                SEC-TOCSP-ERROR-0039
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0039
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0039
+END_TESTCASE                  SEC-TOCSP-ERROR-0039
+
+START_TESTCASE                SEC-TOCSP-ERROR-0040
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0040
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0040
+END_TESTCASE                  SEC-TOCSP-ERROR-0040
+
+START_TESTCASE                SEC-TOCSP-ERROR-0041
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0041
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0041
+END_TESTCASE                  SEC-TOCSP-ERROR-0041
+
+START_TESTCASE                SEC-TOCSP-ERROR-0042
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0042
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0042
+END_TESTCASE                  SEC-TOCSP-ERROR-0042
+
+START_TESTCASE                SEC-TOCSP-ERROR-0043
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0043
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0043
+END_TESTCASE                  SEC-TOCSP-ERROR-0043	
+
+START_TESTCASE                SEC-TOCSP-ERROR-0044
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0044
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0044
+END_TESTCASE                  SEC-TOCSP-ERROR-0044
+
+START_TESTCASE                SEC-TOCSP-ERROR-0045
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0045
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0045
+END_TESTCASE                  SEC-TOCSP-ERROR-0045
+
+START_TESTCASE                SEC-TOCSP-ERROR-0046
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0046
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0046
+END_TESTCASE                  SEC-TOCSP-ERROR-0046
+
+START_TESTCASE                SEC-TOCSP-ERROR-0047
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0047
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0047
+END_TESTCASE                  SEC-TOCSP-ERROR-0047
+
+START_TESTCASE                SEC-TOCSP-ERROR-0048
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0048
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0048
+END_TESTCASE                  SEC-TOCSP-ERROR-0048
+
+START_TESTCASE                SEC-TOCSP-ERROR-0049	
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0049
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0049
+END_TESTCASE                  SEC-TOCSP-ERROR-0049
+
+START_TESTCASE                SEC-TOCSP-ERROR-0050
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0050
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0050
+END_TESTCASE                  SEC-TOCSP-ERROR-0050
+
+START_TESTCASE                SEC-TOCSP-ERROR-0051
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0051
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0051
+END_TESTCASE                  SEC-TOCSP-ERROR-0051
+
+START_TESTCASE                SEC-TOCSP-ERROR-0052
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0052
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0052
+END_TESTCASE                  SEC-TOCSP-ERROR-0052
+
+START_TESTCASE                SEC-TOCSP-ERROR-0053
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0053
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0053
+END_TESTCASE                  SEC-TOCSP-ERROR-0053
+
+START_TESTCASE                SEC-TOCSP-ERROR-0054
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0054
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0054
+END_TESTCASE                  SEC-TOCSP-ERROR-0054
+
+START_TESTCASE                SEC-TOCSP-ERROR-0055
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0055
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0055
+END_TESTCASE                  SEC-TOCSP-ERROR-0055
+
+START_TESTCASE                SEC-TOCSP-ERROR-0056
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0056
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0056
+END_TESTCASE                  SEC-TOCSP-ERROR-0056
+
+START_TESTCASE                SEC-TOCSP-ERROR-0057
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0057
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0057
+END_TESTCASE                  SEC-TOCSP-ERROR-0057
+
+START_TESTCASE                SEC-TOCSP-ERROR-0058
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0058
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0058
+END_TESTCASE                  SEC-TOCSP-ERROR-0058
+
+START_TESTCASE                SEC-TOCSP-ERROR-0059
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0059
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0059
+END_TESTCASE                  SEC-TOCSP-ERROR-0059
+
+START_TESTCASE                SEC-TOCSP-ERROR-0060
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0060
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0060
+END_TESTCASE                  SEC-TOCSP-ERROR-0060
+
+START_TESTCASE                SEC-TOCSP-ERROR-0061
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0061
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0061
+END_TESTCASE                  SEC-TOCSP-ERROR-0061
+
+START_TESTCASE                SEC-TOCSP-ERROR-0062
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0062
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0062
+END_TESTCASE                  SEC-TOCSP-ERROR-0062
+
+START_TESTCASE                SEC-TOCSP-ERROR-0063
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0063
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0063
+END_TESTCASE                  SEC-TOCSP-ERROR-0063
+
+START_TESTCASE                SEC-TOCSP-ERROR-0064
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0064
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0064
+END_TESTCASE                  SEC-TOCSP-ERROR-0064
+
+START_TESTCASE                SEC-TOCSP-ERROR-0065
+//! @SYMTestCaseID            SEC-TOCSP-ERROR-0065
+RUN_TEST_STEP                 Error.ini   SEC-TOCSP-ERROR-0001-0065
+END_TESTCASE                  SEC-TOCSP-ERROR-0065
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/scripts/NewPolicy.script	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,79 @@
+//
+// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+//!  This tests the NEW OCSP policy that contains the following settings
+//!  
+//!  GenerateResponseForMissingUri = false
+//!  	This tests a certificate with a AIA URL and
+//!  	and a certificate with no AIA URL when there is 
+//!  	no default URI
+//!  	The expected result is the first outcome is ok and 
+//!  	the second certificate is ignored
+//! 
+//!  EnableHttpGETMethod = true
+//!  	This tests that the HTTP GET method is used for communicating
+//!  	with the OCSP responder
+
+
+START_TESTCASE                SEC-TOCSP-NEWPOLICY-0001
+//! @SYMTestCaseID            SEC-TOCSP-NEWPOLICY-0001
+RUN_TEST_STEP                 NewPolicyTEF.ini   SEC-TOCSP-NEWPOLICY-0001-0001
+END_TESTCASE                  SEC-TOCSP-NEWPOLICY-0001
+
+START_TESTCASE                SEC-TOCSP-NEWPOLICY-0002
+//! @SYMTestCaseID            SEC-TOCSP-NEWPOLICY-0002
+RUN_TEST_STEP                 NewPolicyTEF.ini   SEC-TOCSP-NEWPOLICY-0002-0001
+END_TESTCASE                  SEC-TOCSP-NEWPOLICY-0002
+
+START_TESTCASE                SEC-TOCSP-NEWPOLICY-0003
+//! @SYMTestCaseID            SEC-TOCSP-NEWPOLICY-0003
+RUN_TEST_STEP                 NewPolicyTEF.ini   SEC-TOCSP-NEWPOLICY-0003-0001
+END_TESTCASE                  SEC-TOCSP-NEWPOLICY-0003
+
+START_TESTCASE                SEC-TOCSP-NEWPOLICY-0004
+//! @SYMTestCaseID            SEC-TOCSP-NEWPOLICY-0004
+RUN_TEST_STEP                 NewPolicyTEF.ini   SEC-TOCSP-NEWPOLICY-0004-0001
+END_TESTCASE                  SEC-TOCSP-NEWPOLICY-0004
+
+START_TESTCASE                SEC-TOCSP-NEWPOLICY-0005
+//! @SYMTestCaseID            SEC-TOCSP-NEWPOLICY-0005
+RUN_TEST_STEP                 NewPolicyTEF.ini   SEC-TOCSP-NEWPOLICY-0005-0001
+END_TESTCASE                  SEC-TOCSP-NEWPOLICY-0005
+
+START_TESTCASE                SEC-TOCSP-NEWPOLICY-0006
+//! @SYMTestCaseID            SEC-TOCSP-NEWPOLICY-0006
+RUN_TEST_STEP                 NewPolicyTEF.ini   SEC-TOCSP-NEWPOLICY-0006-0001
+END_TESTCASE                  SEC-TOCSP-NEWPOLICY-0006
+
+START_TESTCASE                SEC-TOCSP-NEWPOLICY-0007
+//! @SYMTestCaseID            SEC-TOCSP-NEWPOLICY-0007
+RUN_TEST_STEP                 NewPolicyTEF.ini   SEC-TOCSP-NEWPOLICY-0007-0001
+END_TESTCASE                  SEC-TOCSP-NEWPOLICY-0007
+
+START_TESTCASE                SEC-TOCSP-NEWPOLICY-0008
+//! @SYMTestCaseID            SEC-TOCSP-NEWPOLICY-0008
+RUN_TEST_STEP                 NewPolicyTEF.ini   SEC-TOCSP-NEWPOLICY-0008-0001
+END_TESTCASE                  SEC-TOCSP-NEWPOLICY-0008
+
+START_TESTCASE                SEC-TOCSP-NEWPOLICY-0009
+//! @SYMTestCaseID            SEC-TOCSP-NEWPOLICY-0009
+RUN_TEST_STEP                 NewPolicyTEF.ini   SEC-TOCSP-NEWPOLICY-0009-0001
+END_TESTCASE                  SEC-TOCSP-NEWPOLICY-0009
+
+START_TESTCASE                SEC-TOCSP-NEWPOLICY-0010
+//! @SYMTestCaseID            SEC-TOCSP-NEWPOLICY-0010
+RUN_TEST_STEP                 NewPolicyTEF.ini   SEC-TOCSP-NEWPOLICY-0010-0001
+END_TESTCASE                  SEC-TOCSP-NEWPOLICY-0010
\ No newline at end of file
Binary file pkiutilities/ocsp/test/scripts/NewPolicyTEF.ini has changed
Binary file pkiutilities/ocsp/test/scripts/OpenSSL-local.ini has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/scripts/OpenSSL-local.script	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,86 @@
+//
+// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+//!  OpenSSL.txt
+//! 
+//!  Local OCSP tests using logged requests and responses from OpenSSL server
+
+//!  CA1 standard tests
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-LOCAL-0001
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-LOCAL-0001
+RUN_TEST_STEP                 OPENSSL-local.ini   SEC-TOCSP-OPENSSL-LOCAL-0001
+END_TESTCASE                  SEC-TOCSP-OPENSSL-LOCAL-0001
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-LOCAL-0002
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-LOCAL-0002
+RUN_TEST_STEP                 OPENSSL-local.ini   SEC-TOCSP-OPENSSL-LOCAL-0002
+END_TESTCASE                  SEC-TOCSP-OPENSSL-LOCAL-0002
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-LOCAL-0003
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-LOCAL-0003
+RUN_TEST_STEP                 OPENSSL-local.ini   SEC-TOCSP-OPENSSL-LOCAL-0003
+END_TESTCASE                  SEC-TOCSP-OPENSSL-LOCAL-0003
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-LOCAL-0004
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-LOCAL-0004
+RUN_TEST_STEP                 OPENSSL-local.ini   SEC-TOCSP-OPENSSL-LOCAL-0004
+END_TESTCASE                  SEC-TOCSP-OPENSSL-LOCAL-0004
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-LOCAL-0005
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-LOCAL-0005
+RUN_TEST_STEP                 OPENSSL-local.ini   SEC-TOCSP-OPENSSL-LOCAL-0005
+END_TESTCASE                  SEC-TOCSP-OPENSSL-LOCAL-0005
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-LOCAL-0006
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-LOCAL-0006
+RUN_TEST_STEP                 OPENSSL-local.ini   SEC-TOCSP-OPENSSL-LOCAL-0006
+END_TESTCASE                  SEC-TOCSP-OPENSSL-LOCAL-0006
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-LOCAL-0007
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-LOCAL-0007
+RUN_TEST_STEP                 OPENSSL-local.ini   SEC-TOCSP-OPENSSL-LOCAL-0007
+END_TESTCASE                  SEC-TOCSP-OPENSSL-LOCAL-0007
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-LOCAL-0008
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-LOCAL-0008
+RUN_TEST_STEP                 OPENSSL-local.ini   SEC-TOCSP-OPENSSL-LOCAL-0008
+END_TESTCASE                  SEC-TOCSP-OPENSSL-LOCAL-0008
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-LOCAL-0009
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-LOCAL-0009
+RUN_TEST_STEP                 OPENSSL-local.ini   SEC-TOCSP-OPENSSL-LOCAL-0009
+END_TESTCASE                  SEC-TOCSP-OPENSSL-LOCAL-0009
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-LOCAL-0010
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-LOCAL-0010
+RUN_TEST_STEP                 OPENSSL-local.ini   SEC-TOCSP-OPENSSL-LOCAL-0010
+END_TESTCASE                  SEC-TOCSP-OPENSSL-LOCAL-0010
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-LOCAL-0011
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-LOCAL-0011
+RUN_TEST_STEP                 OPENSSL-local.ini   SEC-TOCSP-OPENSSL-LOCAL-0011
+END_TESTCASE                  SEC-TOCSP-OPENSSL-LOCAL-0011
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-LOCAL-0012
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-LOCAL-0012
+RUN_TEST_STEP                 OPENSSL-local.ini   SEC-TOCSP-OPENSSL-LOCAL-0012
+END_TESTCASE                  SEC-TOCSP-OPENSSL-LOCAL-0012
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-LOCAL-0013
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-LOCAL-0013
+RUN_TEST_STEP                 OPENSSL-local.ini   SEC-TOCSP-OPENSSL-LOCAL-0013
+END_TESTCASE                  SEC-TOCSP-OPENSSL-LOCAL-0013
\ No newline at end of file
Binary file pkiutilities/ocsp/test/scripts/OpenSSL-logging.txt has changed
Binary file pkiutilities/ocsp/test/scripts/SmartTrust.txt has changed
Binary file pkiutilities/ocsp/test/scripts/Valicert.txt has changed
Binary file pkiutilities/ocsp/test/scripts/XCert-local.ini has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/scripts/XCert-local.script	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,244 @@
+//
+// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+//!  ****************************************************************************
+//!  Input for TOCSP - Script-based test harness for OCSP
+//!  See \Certman\TOCSP\Commands.cpp for description of commands
+//!  This file must be in UNICODE
+//!  ****************************************************************************
+
+//!  This script tests against the internal Symbian OCSP server running
+//!  XCert software
+//!  There were two original XCert CAs used - Root1 (RSA) and Root2 (DSA)
+//!  Now a third is also use - Root5 (RSA)
+//!  On XCert, the OCSP response signing certs are also RSA and DSA respectively.
+
+//!  As we're using logged responses we set the validation  time explicitly in
+//!  each test.  For cases when the validation time necessarily doesn't agree
+//!  with the time the response was produced, we turn of max status age checking.
+
+//!  ********** BEGIN XCERT SERVER TESTS **************
+
+//!  ********** Testing 4 basic Root5 certs against XCert server ***********
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0001
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0001
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0001
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0001
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0002
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0002
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0002
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0002
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0003
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0003
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0003
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0003
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0004
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0004
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0004
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0004
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0005
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0005
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0005
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0005
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0006
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0006
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0006
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0006
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0007
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0007
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0007
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0007
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0008
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0008
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0008
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0008
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0009
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0009
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0009
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0009
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0010
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0010
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0010
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0010
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0011
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0011
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0011
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0011
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0012
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0012
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0012
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0012
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0013
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0013
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0013
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0013
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0014
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0014
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0014
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0014
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0015
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0015
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0015
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0015
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0016
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0016
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0016
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0016
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0017
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0017
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0017
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0017
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0018
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0018
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0018
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0018
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0019
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0019
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0019
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0019
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0020
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0020
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0020
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0020
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0021
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0021
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0021
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0021
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0022
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0022
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0022
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0022
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0023
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0023
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0023
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0023
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0024
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0024
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0024
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0024
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0025
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0025
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0025
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0025
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0026
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0026
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0026
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0026
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0027
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0027
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0027
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0027
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0028
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0028
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0028
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0028
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0029
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0029
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0029
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0029
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0030
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0030
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0030
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0030
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0031
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0031
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0031
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0031
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0032
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0032
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0032
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0032
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0033
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0033
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0033
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0033
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0034
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0034
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0034
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0034
+
+
+START_TESTCASE                SEC-TOCSP-XCERT-LOCAL-0035
+//! @SYMTestCaseID            SEC-TOCSP-XCERT-LOCAL-0035
+RUN_TEST_STEP                 XCert-local.ini   SEC-TOCSP-XCERT-LOCAL-0035
+END_TESTCASE                  SEC-TOCSP-XCERT-LOCAL-0035
Binary file pkiutilities/ocsp/test/scripts/XCert-logging.txt has changed
Binary file pkiutilities/ocsp/test/scripts/XCert-oom.ini has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/scripts/XCert-oom.script	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,46 @@
+//
+// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+//!  ****************************************************************************
+//!  Input for TOCSP - Script-based test harness for OCSP
+//!  See \Certman\TOCSP\Commands.cpp for description of commands
+//!  This file must be in UNICODE
+//!  ****************************************************************************
+
+//!  This script is for OOM testing - it contains a few of the tests in XCert-local.txt
+
+//!  ********** BEGIN XCERT SERVER TESTS **************
+
+
+START_TESTCASE                SEC-TOCSP-XCERTOOM-0001
+//! @SYMTestCaseID            SEC-TOCSP-XCERTOOM-0001
+RUN_TEST_STEP                 XCert-oom.ini   SEC-TOCSP-XCERTOOM-0001-0001
+END_TESTCASE                  SEC-TOCSP-XCERTOOM-0001
+
+START_TESTCASE                SEC-TOCSP-XCERTOOM-0002
+//! @SYMTestCaseID            SEC-TOCSP-XCERTOOM-0002
+RUN_TEST_STEP                 XCert-oom.ini   SEC-TOCSP-XCERTOOM-0002-0001
+END_TESTCASE                  SEC-TOCSP-XCERTOOM-0002
+
+START_TESTCASE                SEC-TOCSP-XCERTOOM-0003
+//! @SYMTestCaseID            SEC-TOCSP-XCERTOOM-0003
+RUN_TEST_STEP                 XCert-oom.ini   SEC-TOCSP-XCERTOOM-0003-0001
+END_TESTCASE                  SEC-TOCSP-XCERTOOM-0003
+
+START_TESTCASE                SEC-TOCSP-XCERTOOM-0004
+//! @SYMTestCaseID            SEC-TOCSP-XCERTOOM-0004
+RUN_TEST_STEP                 XCert-oom.ini   SEC-TOCSP-XCERTOOM-0004-0001
+END_TESTCASE                  SEC-TOCSP-XCERTOOM-0004
\ No newline at end of file
Binary file pkiutilities/ocsp/test/scripts/XCert.txt has changed
Binary file pkiutilities/ocsp/test/scripts/error-logging.txt has changed
Binary file pkiutilities/ocsp/test/scripts/httpinterface.ini has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/scripts/httpinterface.script	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,163 @@
+//
+// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+//!  ****************************************************************************
+//!  Input for TOCSP - Script-based test harness for OCSP
+//!  See \Certman\TOCSP\Commands.cpp for description of commands
+//!  This file must be in UNICODE
+//!  ****************************************************************************
+
+//!  This script tests against the internal Symbian OCSP server running
+//!  openssl. 
+//!  Transport errors are injected using the test HTTP filter. The test code communicates
+//!  the script settings (FILTERPARAMS) to the filter. The parameters to FILTERPARAMS command are:
+//!  numDelayResp countDropResp countCorruptHTTPDataHeader countCorruptHTTPDataBodySizeLarge countCorruptHTTPDataBodySizeSmall countCorruptOCSPData countInternalErrorResp countTryLaterResp
+//!  where:
+//!  	numDelayResp - Delays response by specified number of milliseconds
+//!  	countDropResp - Drops specified number of responses
+//!  	countCorruptHTTPDataHeader - Corrupts specified number of responses (content-type in header is corrupted)
+//!  	countCorruptHTTPDataBodySizeLarge - Corrupts specified number of responses (body is of larger size than expected)
+//!  	countCorruptHTTPDataBodySizeSmall - Corrupts specified number of responses (body is of smaller size than expected)
+//!  	countCorruptOCSPData - Corrupts specified number of responses (OCSPResponse data is corrupted)
+//!  	countInternalErrorResp - Returns an "internalError" response for specified number of requests
+//!  	countTryLaterResp - Returns a "tryLater" response for specified number of requests
+//!  	countSigValidateFailure - Causes a signature validation failure by corrupting the Responder ID
+
+
+//!  These tests are added to test the new transport requi//! ents
+//!  Security/CertMan/xxx.xxx.001
+//!  Security/CertMan/xxx.xxx.002
+//!  Security/CertMan/xxx.xxx.003
+//! 
+//!  NOTE: These test support only one certificate request per test case. 
+//!  Meaning multiple REQUESTCERT commands are NOT supported within one START and END.
+//!  
+//!  One CA is used - Root5 (RSA)
+//!  The OCSP response signing certs are also RSA and DSA respectively.
+
+
+//!  ********** BEGIN Transport Tests **************
+
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-0001
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-0001
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-0001-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-0001
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-0002
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-0002
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-0002-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-0002
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-0003
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-0003
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-0003-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-0003
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-0004
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-0004
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-0004-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-0004
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-0005
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-0005
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-0005-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-0005
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-0006
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-0006
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-0006-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-0006
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-0007
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-0007
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-0007-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-0007
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-0008
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-0008
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-0008-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-0008
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-0009
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-0009
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-0009-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-0009
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-00010
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-00010
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-00010-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-00010
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-00011
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-00011
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-00011-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-00011
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-00012
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-00012
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-00012-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-00012
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-00013
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-00013
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-00013-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-00013
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-00014
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-00014
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-00014-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-00014
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-00015
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-00015
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-00015-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-00015
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-00016
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-00016
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-00016-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-00016
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-00017
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-00017
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-00017-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-00017
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-00018
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-00018
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-00018-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-00018
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-00019
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-00019
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-00019-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-00019
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-00020
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-00020
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-00020-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-00020
+
+START_TESTCASE                SEC-TOCSP-HTTPINTERFACE-00021
+//! @SYMTestCaseID            SEC-TOCSP-HTTPINTERFACE-00021
+RUN_TEST_STEP                 httpinterface.ini   SEC-TOCSP-HTTPINTERFACE-00021-0001
+END_TESTCASE                  SEC-TOCSP-HTTPINTERFACE-00021
+
+
+
+
+
Binary file pkiutilities/ocsp/test/scripts/openssl-ocspsupport-oom.txt has changed
Binary file pkiutilities/ocsp/test/scripts/openssl-ocspsupport.txt has changed
Binary file pkiutilities/ocsp/test/scripts/openssl.ini has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/scripts/openssl.script	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,523 @@
+//
+// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+//!  ****************************************************************************
+//!  Input for TOCSP - Script-based test harness for OCSP
+//!  See \Certman\TOCSP\Commands.cpp for description of commands
+//!  This file must be in UNICODE
+//!  ****************************************************************************
+
+//!  This script tests against the internal Symbian OCSP server running
+//!  openssl
+//!  There were three CAs used - Root1 (RSA), Root2 (DSA) and Root5 (RSA)
+//!  The OCSP response signing certs are also RSA and DSA respectively.
+
+//!  ********** BEGIN OpenSSL SERVER TESTS **************
+
+//!  ********** Testing 4 basic Root5 certs against OpenSSL server ***********
+
+
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0001
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0001
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0001
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0001
+
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0002
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0002
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0002
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0002
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0003
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0003
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0003
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0003
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0004
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0004
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0004
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0004
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0005
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0005
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0005
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0005
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0006
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0006
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0006
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0006
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0007
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0007
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0007
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0007
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0008
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0008
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0008
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0008
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0009
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0009
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0009
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0009
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0010
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0010
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0010
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0010
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0011
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0011
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0011
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0011
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0012
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0012
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0012
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0012
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0013
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0013
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0013
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0013
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0014
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0014
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0014
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0014
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0015
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0015
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0015
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0015
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0016
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0016
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0016
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0016
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0017
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0017
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0017
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0017
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0018
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0018
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0018
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0018
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0019
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0019
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0019
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0019
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0020
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0020
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0020
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0020
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0021
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0021
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0021
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0021
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0022
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0022
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0022
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0022
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0023
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0023
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0023
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0023
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0024
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0024
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0024
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0024
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0025
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0025
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0025
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0025
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0026
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0026
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0026
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0026
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0027
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0027
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0027
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0027
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0028
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0028
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0028
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0028
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0029
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0029
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0029
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0029
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0030
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0030
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0030
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0030
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0031
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0031
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0031
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0031
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0032
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0032
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0032
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0032
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0033
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0033
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0033
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0033
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0034
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0034
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0034
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0034
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0035
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0035
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0035
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0035
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0036
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0036
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0036
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0036
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0037
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0037
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0037
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0037
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0038
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0038
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0038
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0038
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0039
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0039
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0039
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0039
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0040
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0040
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0040
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0040
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0041
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0041
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0041
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0041
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0042
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0042
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0042
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0042
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0043
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0043
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0043
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0043
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0044
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0044
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0044
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0044
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0045
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0045
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0045
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0045
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0046
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0046
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0046
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0046
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0047
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0047
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0047
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0047
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0048
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0048
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0048
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0048
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0049
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0049
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0049
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0049
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0050
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0050
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0050
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0050
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0051
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0051
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0051
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0051
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0052
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0052
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0052
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0052
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0053
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0053
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0053
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0053
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0054
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0054
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0054
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0054
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0055
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0055
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0055
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0055
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0056
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0056
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0056
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0056
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0057
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0057
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0057
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0057
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0058
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0058
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0058
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0058
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0059
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0059
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0059
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0059
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0060
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0060
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0060
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0060
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0061
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0061
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0061
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0061
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0062
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0062
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0062
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0062
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0063
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0063
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0063
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0063
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0064
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0064
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0064
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0064
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0065
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0065
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0065
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0065
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0066
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0066
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0066
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0066
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0067
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0067
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0067
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0067
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0068
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0068
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0068
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0068
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0069
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0069
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0069
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0069
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0070
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0070
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0070
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0070
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0071
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0071
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0071
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0071
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0072
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0072
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0072
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0072
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0073
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0073
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0073
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0073
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0074
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0074
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0074
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0074
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0075
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0075
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0075
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0075
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0076
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0076
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0076
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0076
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0077
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0077
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0077
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0077
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0078
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0078
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0078
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0078
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0079
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0079
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0079
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0079
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0080
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0080
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0080
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0080
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0081
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0081
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0081
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0081
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0082
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0082
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0082
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0082
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0083
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0083
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0083
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0083
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0084
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0084
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0084
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0084
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0085
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0085
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0085
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0085
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0086
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0086
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0086
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0086
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0087
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0087
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0087
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0087
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0088
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0088
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0088
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0088
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0089
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0089
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0089
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0089
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0090
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0090
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0090
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0090
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0091
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0091
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0091
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0091
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0092
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0092
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0092
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0092
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0093
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0093
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0093
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0093
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0094
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0094
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0094
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0094
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0095
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0095
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0095
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0095
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0096
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0096
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0096
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0096
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0097
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0097
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0097
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0097
+
+START_TESTCASE                SEC-TOCSP-OPENSSL-0098
+//! @SYMTestCaseID            SEC-TOCSP-OPENSSL-0098
+RUN_TEST_STEP                 OPENSSL.ini   SEC-TOCSP-OPENSSL-0098
+END_TESTCASE                  SEC-TOCSP-OPENSSL-0098
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/scripts/setupOcspPolicy.bat	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,49 @@
+@rem
+@rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+@rem All rights reserved.
+@rem This component and the accompanying materials are made available
+@rem under the terms of "Eclipse Public License v1.0"
+@rem which accompanies this distribution, and is available
+@rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+@rem
+@rem Initial Contributors:
+@rem Nokia Corporation - initial contribution.
+@rem
+@rem Contributors:
+@rem
+@rem Description:
+@rem
+
+@ECHO Off
+REM 
+
+REM Copies the OCSP repository specified in %1 to the correct place
+REM Called with the the repository file as the only argument
+
+set NAME=%1
+set FILE=\epoc32\winscw\c\system\tocsp\scripts\%1
+
+echo Installing OCSP repository from %FILE%
+
+
+IF %NAME% == 2002b28b-new.txt GOTO NEWREPOSITORY
+
+IF %NAME% == 2002b28b.txt GOTO OLDREPOSITORY
+
+:NEWREPOSITORY
+copy \epoc32\release\winscw\udeb\z\private\10202be9\2002b28b.txt \epoc32\release\winscw\udeb\z\private\10202be9\2002b28b-old.txt
+copy %FILE% \epoc32\release\winscw\udeb\z\private\10202be9\2002b28b.txt
+GOTO END
+
+
+
+:OLDREPOSITORY
+copy \epoc32\release\winscw\udeb\z\private\10202be9\2002b28b-old.txt \epoc32\release\winscw\udeb\z\private\10202be9\2002b28b.txt
+del \epoc32\release\winscw\udeb\z\private\10202be9\2002b28b-old.txt
+
+
+
+:END
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/scripts/setupOcspPolicy_urel.bat	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,50 @@
+@rem
+@rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+@rem All rights reserved.
+@rem This component and the accompanying materials are made available
+@rem under the terms of "Eclipse Public License v1.0"
+@rem which accompanies this distribution, and is available
+@rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+@rem
+@rem Initial Contributors:
+@rem Nokia Corporation - initial contribution.
+@rem
+@rem Contributors:
+@rem
+@rem Description:
+@rem
+
+@ECHO Off
+REM 
+
+REM Copies the OCSP repository specified in %1 to the correct place
+REM Called with the the repository file as the only argument
+
+set NAME=%1
+
+set FILE=\epoc32\winscw\c\system\tocsp\scripts\%1
+
+echo Installing OCSP repository from %FILE%
+
+IF %NAME% == donothing GOTO END
+
+IF %NAME% == 2002b28b-new.txt GOTO NEWREPOSITORY
+
+IF %NAME% == 2002b28b.txt GOTO OLDREPOSITORY
+
+
+:NEWREPOSITORY
+copy \epoc32\release\winscw\urel\z\private\10202be9\2002b28b.txt \epoc32\release\winscw\urel\z\private\10202be9\2002b28b-old.txt
+copy %FILE% \epoc32\release\winscw\urel\z\private\10202be9\2002B28B.txt
+GOTO END
+
+:OLDREPOSITORY
+copy \epoc32\release\winscw\urel\z\private\10202be9\2002b28b-old.txt \epoc32\release\winscw\urel\z\private\10202be9\2002b28b.txt
+del \epoc32\release\winscw\urel\z\private\10202be9\2002b28b-old.txt
+
+
+
+:END
+cd \epoc32\winscw\c\twtlscert\scripts\batchfiles
+perl certstorePlugins disable_all
+perl certstorePlugins enable filecertstore.dll
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/server/OpenSSL/README	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,14 @@
+OpenSSL OCSP Server
+===================
+
+The files in this directory relate to running the OpenSSL OCSP server.  They
+were used to generate the OpenSSL test data, and are mainly provided for
+reference purposes.  An installation of cygwin is required to run the scripts.
+The version of OpenSSL used was 0.9.7.
+
+Files:
+
+openssl.config			Config file for openssl ca operations
+generateCerts.sh		A script to generate the certs used
+runOCSPResponder.sh 	A script to run several OCSP responders in the sequence
+						expected by the logging script OpenSSL-logging.txt
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/server/OpenSSL/generateCerts.sh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,90 @@
+#!/bin/sh
+
+# Generate certs for testing OCSP against OpenSSL implementation
+#
+# There are two CAs:
+#   ca1 signs a responder cert which signs responses
+#   ca2 signs responses with its ca cert
+
+# Trash existing data
+rm -rf ca1 ca2 certs tmp
+mkdir ca1 ca2 certs tmp 
+
+# ca1 ##########################################################################
+
+# RSA keys, CA signed responder cert signed responses
+
+# Create ca files
+touch ca1/index.txt
+echo "01" > ca1/serial
+mkdir ca1/private
+mkdir ca1/certs
+
+# Generate root cert
+openssl req -x509 -newkey rsa:1024 -keyout ca1/private/cakey.pem -out ca1/cacert.pem -subj "/O=Symbian/CN=CA Root Cert" -days 3650 -nodes 
+openssl x509 -in ca1/cacert.pem -outform DER -out certs/ca1-root.der
+
+# Generate ocsp responder cert 
+openssl req -newkey rsa:1024 -keyout ca1/private/reskey.pem -out tmp/req.pem -subj "/O=Symbian/CN=CA OCSP Responder" -days 3650 -nodes
+openssl ca -config openssl.config -name ca1 -in tmp/req.pem -batch -days 3650
+openssl x509 -in ca1/certs/01.pem -outform DER -out certs/ca1-responder.der
+
+# Generate entity cert 1
+openssl req -newkey rsa:1024 -keyout tmp/key.pem -out tmp/req.pem -subj "/O=Symbian/CN=Entity Cert 1 (Good)" -days 3650 -nodes
+openssl ca -config openssl.config -name ca1 -in tmp/req.pem -batch -days 3650
+openssl x509 -in ca1/certs/02.pem -outform DER -out certs/ca1-entity1.der
+
+# Generate entity cert 2 and revoke it
+openssl req -newkey rsa:1024 -keyout tmp/key.pem -out tmp/req.pem -subj "/O=Symbian/CN=Entity Cert 2 (Revoked)" -days 3650 -nodes
+openssl ca -config openssl.config -name ca1 -in tmp/req.pem -batch -days 3650
+openssl x509 -in ca1/certs/03.pem -outform DER -out certs/ca1-entity2.der
+openssl ca -config openssl.config -name ca1 -revoke ca1/certs/03.pem -crl_reason keyCompromise
+
+# Generate entity cert 3 and then remove it from the ca
+openssl req -newkey rsa:1024 -keyout tmp/key.pem -out tmp/req.pem -subj "/O=Symbian/CN=Entity Cert 3 (Unknown)" -days 3650 -nodes
+openssl ca -config openssl.config -name ca1 -in tmp/req.pem -batch -days 3650
+openssl x509 -in ca1/certs/04.pem -outform DER -out certs/ca1-entity3.der
+mv ca1/index.txt tmp
+head -3 tmp/index.txt > ca1/index.txt
+rm ca1/certs/04.pem
+
+# ca2 ##########################################################################
+
+# DSA keys, CA cert signs responses
+
+# Create ca files
+touch ca2/index.txt
+echo "01" > ca2/serial
+mkdir ca2/private
+mkdir ca2/certs
+
+# Generate root cert
+openssl req -x509 -newkey rsa:1024 -keyout ca2/private/cakey.pem -out ca2/cacert.pem -subj "/O=Symbian/CN=CA Root Cert" -days 3650 -nodes 
+openssl x509 -in ca2/cacert.pem -outform DER -out certs/ca2-root.der
+
+# Generate entity cert 1
+openssl req -newkey rsa:1024 -keyout tmp/key.pem -out tmp/req.pem -subj "/O=Symbian/CN=Entity Cert 1 (Good)" -days 3650 -nodes
+openssl ca -config openssl.config -name ca2 -in tmp/req.pem -batch -days 3650
+openssl x509 -in ca2/certs/01.pem -outform DER -out certs/ca2-entity1.der
+
+# Generate entity cert 2 and revoke it
+openssl req -newkey rsa:1024 -keyout tmp/key.pem -out tmp/req.pem -subj "/O=Symbian/CN=Entity Cert 2 (Revoked)" -days 3650 -nodes
+openssl ca -config openssl.config -name ca2 -in tmp/req.pem -batch -days 3650
+openssl x509 -in ca2/certs/02.pem -outform DER -out certs/ca2-entity2.der
+openssl ca -config openssl.config -name ca2 -revoke ca2/certs/02.pem -crl_reason keyCompromise
+
+# Generate entity cert 3 and then remove it from the ca
+openssl req -newkey rsa:1024 -keyout tmp/key.pem -out tmp/req.pem -subj "/O=Symbian/CN=Entity Cert 3 (Unknown)" -days 3650 -nodes
+openssl ca -config openssl.config -name ca2 -in tmp/req.pem -batch -days 3650
+openssl x509 -in ca2/certs/03.pem -outform DER -out certs/ca2-entity3.der
+mv ca2/index.txt tmp
+head -2 tmp/index.txt > ca2/index.txt
+rm ca2/certs/03.pem
+
+# To use DSA instead of RSA, first generate DSA parameters:
+#   openssl dsaparam -out tmp/dsaparam.pem 1024
+# And use this in the newkey options
+#   openssl req -x509 -newkey dsa:tmp/dsaparam.pem ...
+
+# Tidy
+rm -rf tmp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/server/OpenSSL/openssl.config	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,56 @@
+# openssl.config
+#
+# Config file for OpenSSL CA
+
+[ ca ]
+
+default_ca      = ca_default            # The default ca section
+
+[ ca1 ]
+
+dir            = ./ca1
+database       = $dir/index.txt         # index file.
+new_certs_dir  = $dir/certs             # new certs dir
+
+certificate    = $dir/cacert.pem        # The CA cert
+serial         = $dir/serial            # serial no file
+private_key    = $dir/private/cakey.pem # CA private key
+RANDFILE       = $dir/private/.rand     # random number file
+
+default_days   = 365                    # how long to certify for
+default_crl_days= 30                    # how long before next CRL
+default_md     = md5                    # md to use
+
+policy         = ca_policy              # our policy
+email_in_dn    = no                     # Don't add the email into cert DN
+
+nameopt        = default_ca             # Subject name display option
+certopt        = default_ca             # Certificate display option
+copy_extensions = none                  # Don't copy extensions from request
+
+[ ca2 ]
+
+dir            = ./ca2
+database       = $dir/index.txt         # index file.
+new_certs_dir  = $dir/certs             # new certs dir
+
+certificate    = $dir/cacert.pem        # The CA cert
+serial         = $dir/serial            # serial no file
+private_key    = $dir/private/cakey.pem # CA private key
+RANDFILE       = $dir/private/.rand     # random number file
+
+default_days   = 365                    # how long to certify for
+default_crl_days= 30                    # how long before next CRL
+default_md     = md5                    # md to use
+
+policy         = ca_policy              # our policy
+email_in_dn    = no                     # Don't add the email into cert DN
+
+nameopt        = default_ca             # Subject name display option
+certopt        = default_ca             # Certificate display option
+copy_extensions = none                  # Don't copy extensions from request
+
+[ ca_policy ]
+
+organizationName       = supplied
+commonName             = supplied
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/server/OpenSSL/runOCSPResponder.sh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,21 @@
+#!/bin/sh
+
+# Run OpenSSL OCSP responder
+
+# CA1, normal, 5 responses
+openssl ocsp -index ca1/index.txt -CA ca1/cacert.pem -rsigner ca1/certs/01.pem -rkey ca1/private/reskey.pem -port 100 -nrequest 5
+
+# CA2, normal, 5 responses
+openssl ocsp -index ca2/index.txt -CA ca2/cacert.pem -rsigner ca2/cacert.pem -rkey ca2/private/cakey.pem -port 100 -nrequest 5
+
+# CA1, no certs in response, 1 response
+openssl ocsp -index ca1/index.txt -CA ca1/cacert.pem -rsigner ca1/certs/01.pem -rkey ca1/private/reskey.pem -port 100 -resp_no_certs -nrequest 1
+
+# CA2, no certs in response, 1 response
+openssl ocsp -index ca2/index.txt -CA ca2/cacert.pem -rsigner ca2/cacert.pem -rkey ca2/private/cakey.pem -port 100 -resp_no_certs -nrequest 1
+
+# CA1, responder cert idenified by id, 1 response
+openssl ocsp -index ca1/index.txt -CA ca1/cacert.pem -rsigner ca1/certs/01.pem -rkey ca1/private/reskey.pem -port 100 -resp_key_id -nrequest 1
+
+# CA2, responder cert idenified by id, 1 response
+openssl ocsp -index ca2/index.txt -CA ca2/cacert.pem -rsigner ca2/cacert.pem -rkey ca2/private/cakey.pem -port 100 -resp_key_id -nrequest 1
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/t_input.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,216 @@
+/*
+* Copyright (c) 1998-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef __T_INPUT_H__
+#define __T_INPUT_H__
+
+#include <e32cons.h>
+#include <f32file.h>
+#include <e32std.h>
+
+/**
+ * This class provides useful functions to read and parse the input file.
+ */
+class Input
+	{
+public: // static functions no object required
+	/*
+	Parses the parameters aBuf to find the section of the script within parameters aStart and aEnd
+	NB use these if you want just want to use the result temporarily, because it just points
+	to the result in aBuf
+
+	Parameters
+	const TDesC& aBuf	[IN] - Buffer to search
+	const TDesC& aStart	[IN] - Start tag t be searched for
+	const TDesC& aEnd   [IN] - (Optional)End tag t be searched for (Optional, if not supplied function will default aStart with a / i.e. if aStart <tag> aEnd will be </tag>
+	TInt& aPos			[IN/OUT]- (Optional)Position in buffer to start searching, this will be updated with the position after the search (Optional) default zero 
+	TInt& aError		[OUT]- (Optional)Returns negative number if start tag cannot be found (Optional)
+
+	Returns
+	TPtrC		- Returns a TPtr to the position in the buffer between the start and end tags
+	*/
+	// base functions for parsing tokens in scripts, but better to use functions below
+	IMPORT_C static TPtrC8 ParseElement(const TDesC8& aBuf, const TDesC8& aStart);
+	IMPORT_C static TPtrC8 ParseElement(const TDesC8& aBuf, const TDesC8& aStart, const TDesC8& aEnd);
+	IMPORT_C static TPtrC8 ParseElement(const TDesC8& aBuf, const TDesC8& aStart, const TDesC8& aEnd, TInt& aPos);
+	IMPORT_C static TPtrC8 ParseElement(const TDesC8& aBuf, const TDesC8& aStart, const TDesC8& aEnd, TInt& aPos, TInt& aError);
+	IMPORT_C static TPtrC16 ParseElement(const TDesC16& aBuf, const TDesC16& aStart, const TDesC16& aEnd);
+	IMPORT_C static TPtrC16 ParseElement(const TDesC16& aBuf, const TDesC16& aStart, const TDesC16& aEnd, TInt& aPos);
+	IMPORT_C static TPtrC16 ParseElement(const TDesC16& aBuf, const TDesC16& aStart, const TDesC16& aEnd, TInt& aPos, TInt& aError);
+	IMPORT_C static TPtrC ParseElement(const TDesC& aBuf, const TDesC& aStart);
+	IMPORT_C static TPtrC ParseElement(const TDesC& aBuf, const TDesC& aStart, TInt& aPos);
+	IMPORT_C static TPtrC ParseElement(const TDesC& aBuf,  const TDesC& aStart, TInt& aPos, TInt& aError);
+	/**
+	 * Reads the between the start and end tags assuming the data is in ASCII
+	 * hex format.  Returns an HBufC8* which is a binary representation of that
+	 * ASCII hex.  (ie a string of length 6 becomes a string of length 3)
+	 */
+	IMPORT_C static HBufC8* ParseElementHexL(const TDesC8& aBuf, const TDesC8& aStart);
+	/**
+	 * Returns ETrue if the the value was "True" or "ETrue" and returns EFalse
+	 * if the value was "False" or "EFalse" (case insensitive comparisons all
+	 * round).  Leaves if none of the above is true 
+	 */
+	IMPORT_C static TBool ParseElementBoolL(const TDesC8& aBuf, const TDesC8& aStart);
+	/**
+	 * Parses the parameters aBuf to find the section of the script within
+	 * parameters aStart and aEnd, and parses the contants as an integer.  Both
+	 * decimal ('123') and hex ('0x7b') format strings are supported.
+	 *
+	 * @param aBuf		[IN] - Buffer to search
+	 * @param aStart	[IN] - Start tag t be searched for
+	 * @param aEnd   	[IN] - (Optional)End tag t be searched for (Optional, if not supplied function will default aStart with a / i.e. if aStart <tag> aEnd will be </tag>
+	 * @param aPos		[IN/OUT]- (Optional)Position in buffer to start searching, this will be updated with the position after the search (Optional) default zero 
+	 * @param aError	[OUT]- (Optional)Returns negative number if start tag cannot be found (Optional)
+	 *
+	 * @return The parsed integer value, or zero.
+	 */
+	IMPORT_C static TUint ParseIntElement(const TDesC8& aBuf, const TDesC8& aStart, const TDesC8& aEnd);
+	IMPORT_C static TUint ParseIntElement(const TDesC8& aBuf, const TDesC8& aStart, const TDesC8& aEnd, TInt& aPos);
+	IMPORT_C static TUint ParseIntElement(const TDesC8& aBuf, const TDesC8& aStart, const TDesC8& aEnd, TInt& aPos, TInt& aError);
+	IMPORT_C static TUint ParseIntElement(const TDesC16& aBuf, const TDesC16& aStart, const TDesC16& aEnd);
+	IMPORT_C static TUint ParseIntElement(const TDesC16& aBuf, const TDesC16& aStart, const TDesC16& aEnd, TInt& aPos);
+	IMPORT_C static TUint ParseIntElement(const TDesC16& aBuf, const TDesC16& aStart, const TDesC16& aEnd, TInt& aPos, TInt& aError);
+	IMPORT_C static TUint ParseIntElement(const TDesC& aBuf, const TDesC& aStart);
+	IMPORT_C static TUint ParseIntElement(const TDesC& aBuf, const TDesC& aStart, TInt& aPos);
+	IMPORT_C static TUint ParseIntElement(const TDesC& aBuf,  const TDesC& aStart, TInt& aPos, TInt& aError);
+	/*
+	Searches the list of standard error codes (e32err.h 0 to -46) finding the matching error code for the string 
+
+	Parameters
+	const TDesC& aResult  	[IN] - Error code string to be searched from
+	TInt &aError 	 		[OUT] - Matching error code if found
+
+	Returns
+	TBool			- True if error code was found, False if it was not
+	*/
+	IMPORT_C static TBool GetExpectedResultL(const TDesC& aResult /*in*/, TInt &aError /*out*/);
+	/*
+	Searches the list of standard error codes (e32err.h 0 to -46) finding the matching text representaion of the error code
+
+	Parameters
+	 TInt &aError 	 	[IN] - Error code to return the string of
+	HBufC*& aResult   	[OUT] -Reference to a pointer, pointing to the error string of the matching error code (Dont forget to free it)
+
+	Returns
+	TBool			- True if error code was found, False if it was not
+	*/
+	IMPORT_C static TBool GetExpectedResultL(const TInt &aError /*in*/, HBufC*& aResult /*out*/);
+	/*
+	Parses the parameters aBuf to find the section of the script within parameters aStart and aEnd, 
+	then allocs the required memory and places a copy of this section in aMember
+	use these if you want the result copied into a new area of memory to use, for example when
+	stored a member data
+
+	Parameters
+	HBufC*& aMember		[OUT] - Reference to a pointer that will point to a copy of the section of aBuf 
+	const TDesC& aBuf	[IN] - Buffer to search
+	const TDesC& aStart	[IN] - Start tag t be searched for
+	const TDesC& aEnd   [IN] - (Optional) End tag t be searched for (, if not supplied function will default aStart with a / i.e. if aStart <tag> aEnd will be </tag>
+	TInt& aPos			[IN/OUT]- (Optional) Position in buffer to start searching, this will be updated with the position after the search (Optional) default zero 
+	TInt& aError		[OUT]- (Optional) Returns negative number if start tag cannot be found (Optional)
+
+	Returns
+	TPtrC		- Returns a TPtr to the position in the buffer between the start and 
+	end tags
+	*/
+	IMPORT_C static void ParseElementL(HBufC*& aMember, const TDesC& aBuf, 
+		const TDesC& aStart);
+	IMPORT_C static void ParseElementL(HBufC8*& aMember, const TDesC& aBuf, 
+		const TDesC& aStart);
+	IMPORT_C static void ParseElementL(HBufC*& aMember, const TDesC& aBuf,
+		const TDesC& aStart, TInt& aPos);
+	IMPORT_C static void ParseElementL(HBufC8*& aMember, const TDesC& aBuf,
+		const TDesC& aStart, TInt& aPos);
+	IMPORT_C static void ParseElementL(HBufC*& aMember, const TDesC& aBuf,  
+		const TDesC& aStart, TInt& aPos, TInt& aError);
+	IMPORT_C static void ParseElementL(HBufC8*& aMember, const TDesC& aBuf,  
+		const TDesC& aStart, TInt& aPos, TInt& aError);
+	/*
+	Reads an entire file into memory into a HBuf8
+
+	Parameters
+	const TDesC& aFilename 	[IN] - Name of file to read
+	const TDesC& aPath		[IN] - (Optional) Path of file, if aPath is missing the path is taken from aFilename
+	RFs &aFs				[IN] - Reference to the file system handle class
+
+	Returns
+	HBufC8*		-  Pointer to the 8 bit file data
+	*/
+	IMPORT_C static HBufC8* ReadFileL(const TDesC& aFilename, RFs& aFs);
+	IMPORT_C static HBufC8* ReadFileL(const TDesC& aFilename, const TDesC& aPath, RFs& aFs);
+	IMPORT_C static HBufC8* ReadFileLC(const TDesC& aFilename, RFs& aFs);
+	IMPORT_C static HBufC8* ReadFileLC(const TDesC& aFilename, const TDesC& aPath, RFs& aFS);
+	/*
+	Reads a ascii hex file into a binary HBufC i.e. a file containing "FFAA11" will be converted into a 3 byte buffer
+
+	Parameters
+	const TDesC& aFilename 	[IN] - Name of file including path to read
+	RFs &aFs			[IN] - Reference to the file system handle class
+
+	Returns
+	HBufC8*		-  Pointer to the 8 bit file data
+	*/
+	IMPORT_C static HBufC8* ReadHexFileLC(const TDesC& aFilename, RFs& aFs);
+	/**
+	 * This function reads an entire Unicode file and returns it as an HBufC.
+	 * This function only works for Unicode builds of EPOC.
+	 */
+	IMPORT_C static HBufC* ReadFile16LC(const TDesC& aFilename, RFs& aFS);
+	/*
+	Parses the parameters aBuf to find multiple sections of the script within parameters aStart and aEnd, then adds them to the aElements list
+	For instance, if the aBuf argument is <StartTag>abc<EndTag><StartTag>xyz<EndTag>,  then aElements will contain 2 elements: abc and xyz.
+
+	const TDesC& aBuf	[IN] - Buffer to search
+	const TDesC& aStart	[IN] - Start tag to be searched for
+	const TDesC& aEnd   [IN]- End tag t be searched for
+	RPointerArray<HBufC>& aElements [OUT] - Array of sections found
+	TInt& aPos		[IN/OUT]- Position in buffer to start searching, this will be updated with the position after the search
+
+	Returns
+	None
+	 */
+	IMPORT_C static void ParseElementListL(const TDesC& aBuf, const TDesC& aStart, const TDesC& aEnd, 
+		RPointerArray<HBufC>& aElements, TInt& aPos);
+
+	
+	/**
+	 * Parse a string containg a capability name.
+	 * @leave KErrArgument If the string is not a recognised capability name.
+	 */
+	IMPORT_C static TCapability ParseCapabilityNameL(const TDesC8& aName);
+	
+	/**
+	 * Parse a section of script file describing a capability set.
+	 * 
+	 * The script contains zero or more capabilities contained in <capability>
+	 * tags.
+	 */
+	IMPORT_C static void ParseCapabilitySetL(const TDesC8& aIn, TCapabilitySet& aOut);
+
+	/**
+	 * Parse a section of script file describing a security policy.
+	 * 
+	 * The script contains zero or more capabilities contained in <capability>
+	 * tags.
+	 */
+	IMPORT_C static void ParseSecurityPolicyL(const TDesC8& aIn, TSecurityPolicy& aOut);
+	
+	};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/t_output.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,116 @@
+/*
+* Copyright (c) 1998-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef __T_OUTPUT_H__
+#define __T_OUTPUT_H__
+
+#include <f32file.h>
+#include <e32base.h>
+#include <e32std.h>
+#include <e32cons.h>
+
+/**
+ * Astract base class for classes that provide logging of test output.
+ *
+ * 
+ */
+class Output : public CBase
+	{
+public:
+	// Public interface
+	IMPORT_C void writeString(const TDesC& aString);
+	IMPORT_C void writeString(const TDesC8& aString);
+	IMPORT_C void write(TRefByValue<const TDesC16> aFmt, ...);
+	IMPORT_C void writeSpaces(TInt aSpaces); 
+	IMPORT_C void writeNewLine(); 
+	IMPORT_C void writeNum(TInt aNum); 
+	IMPORT_C void writeHex(TInt aHex);
+	IMPORT_C void writeError(TInt aError);
+	IMPORT_C void writeOctetString(const TDesC8& aString);
+	IMPORT_C void writeOctetStringL(const TDesC8& aString);
+	IMPORT_C void writeBoolL(TBool aBool);
+	IMPORT_C void writeCapabilityL(TCapability aCap);
+	IMPORT_C void writeCapabilitySetL(const TCapabilitySet& aCap);
+	IMPORT_C void writeSecurityPolicyL(const TSecurityPolicy& aPolicy);
+
+protected:
+	// Implemented by subclasses
+	virtual void DoWriteL(const TDesC& aString) = 0;
+
+private:
+	void FixNewlinesAndWriteL(const TDesC& aString);
+	};
+
+/**
+ * Implementation of Output that throws away its output.
+ */
+class NullOutput : public Output
+	{
+public:
+	IMPORT_C NullOutput();
+	virtual void DoWriteL(const TDesC& aString);
+	};
+
+/**
+ * Implementation of Output that writes its output to a file.
+ * 
+ * There used to be a comment here "Writes narrow on WINS, wide on target".
+ * This was not true because the implementation always wrote strings in 8 bits
+ * regardless - resulting in log files containing a mixture of 8 and 16 bit
+ * data.  Now this always writes as 8 bit - if this is a problem it can be
+ * changed easily enough.
+ */
+class FileOutput : public Output
+	{
+public:
+	IMPORT_C FileOutput(RFile& aFile);
+	virtual void DoWriteL(const TDesC& aString); 
+private:
+	RFile iFile;
+	};
+
+/**
+ * Implementation of Output that prints the output to a console.
+ */
+class ConsoleOutput : public Output
+	{
+public:
+	IMPORT_C ConsoleOutput(CConsoleBase& aConsole);
+	virtual void DoWriteL(const TDesC& aString); 
+private:
+	CConsoleBase& iConsole;
+	};
+
+/**
+ * Implementation of Output that writes to multiple other Output objects (a bit
+ * like the unix tee command).  Use to log output to console and to file.
+ */
+
+class COutputTee : public Output
+	{
+public:
+	COutputTee();
+	~COutputTee();
+	/// Add a new child object - takes ownership
+	void AddChildL(Output* aChild);
+	virtual void DoWriteL(const TDesC& aString); 
+private:
+	RPointerArray<Output> iChildren;
+	};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/tcertutils.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,241 @@
+// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// tcertuils.h
+// 
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+
+
+#ifndef __TCERTUTILS_H__
+#define __TCERTUTILS_H__
+
+#include <e32base.h>
+#include <x509cert.h>
+#include <unifiedcertstore.h>
+#include <pkixcertchain.h>
+#include "t_output.h"
+
+/**
+CCertUtils provides various functions often used in tests.
+This class has changed because the functions are asynchronous now. 
+The function are no longer static as we need an instance to serve as
+an active object.
+*/
+class CCertUtils : public CActive
+	{
+public:
+	/**
+	 * This enumeration enumerates all the states used for the
+	 * RunL function.
+	 */
+	enum TState
+		{
+		EAddCACerts,
+
+		EAddCert,
+		EAddCACertGetCAEntry,
+		EAddCACertSetApplications,
+		EAddCACertSetTrust,
+		EAddCACertFinished,
+
+		ERemoveCertsGetCACerts,
+		ERemoveCertsCACertsRetrieved,
+		ERemoveCertsRemoveCACerts,
+		ERemoveCertsGetUserCerts,
+		ERemoveCertsUserCertsRetrieved,
+		ERemoveCertsRemoveUserCerts,
+		ERemoveCertsFinished
+		};	
+	
+public:
+	IMPORT_C static CCertUtils* NewL(RFs& aFs);
+	IMPORT_C static CCertUtils* NewLC(RFs& aFs);
+	/**
+	The destructor destroys all the members of CCertUtils but only destroys
+	iStoreManager if the CCertStoreManager instance was created by this CCertUtils
+	instance. It doesn't destroy it if it was passed as an argument in the 
+	constructor.
+	*/
+	IMPORT_C virtual ~CCertUtils();
+
+
+	/**
+	Certificate handling functions
+	*/
+	IMPORT_C void AddCertL(const TDesC& aLabel, 
+							TCertificateFormat aFormat,
+							TCertificateOwnerType aCertificateOwnerType, 
+							TInt aTrustedUsage, 
+							const TDesC& aCertificatePath, 
+							const TDesC& aCertificateFileName, 
+							TRequestStatus& aStatus);
+							
+	IMPORT_C void AddCert(const TDesC& aLabel, 
+							TCertificateFormat aFormat,
+							TCertificateOwnerType aCertificateOwnerType, 
+							TInt aTrustedUsage, 
+							const TDesC& aCertificatePath, 
+							const TDesC& aCertificateFileName, 
+							CUnifiedCertStore& aUnifiedCertStore, 
+							TRequestStatus& aStatus);
+						
+	IMPORT_C void AddCACertsL(const CDesCArray& aRoots, 
+							const CDesCArray& aLabels,
+							TCertificateFormat aFormat, 
+							TInt aTrustedUsage, 
+							const TDesC& aPath, 
+							TRequestStatus& aStatus);
+							
+	IMPORT_C void AddCACertsL(const CDesCArray& aRoots, 
+							const CDesCArray& aLabels,
+							TCertificateFormat aFormat, 
+							TInt aTrustedUsage, 
+							const TDesC& aPath, 
+							CUnifiedCertStore& aUnifiedCertStore, 
+							TRequestStatus& aStatus);
+							
+	IMPORT_C void RemoveCertsL(TRequestStatus& aStatus);
+	IMPORT_C void RemoveCertsL(CUnifiedCertStore& aUnifiedCertStore, 
+							TRequestStatus& aStatus);
+
+	IMPORT_C static CCertificate* CertFromFileLC(const TDesC& aFilename, 
+							const TDesC& aPathname, 
+							RFs& aFs, 
+							TCertificateFormat aFormat);
+							
+	IMPORT_C static CCertificate* CertFromFileL(const TDesC& aFilename,
+							const TDesC& aPathname, 
+							RFs& aFs, 
+							TCertificateFormat aFormat);
+							
+	IMPORT_C static void WriteError(TValidationError aError, Output& aOut);
+	IMPORT_C static TPtrC MapError(TValidationError aError);
+	IMPORT_C static TValidationError MapError(const TDesC& aError);
+	IMPORT_C static TPtrC ParseElement(const TDesC& aBuf, const TDesC& aStart, const TDesC& aEnd, TInt& aPos, TInt& aError);
+
+	IMPORT_C HBufC* DiagnosticLC() const;
+	IMPORT_C void AddApplicationL(const TDesC& aName, TUid aUid) const;
+	IMPORT_C void RemoveApplicationL(TUid aUid) const;
+
+private:
+	/**
+	This constructor constructs a CCertUtils instance without initializing
+	iStoreManager. A store manager will be created if one is needed and
+	will be destroyed by the destructor.
+	@param aFs A file server session. The file server session must have opened.
+	*/
+	CCertUtils(RFs& aFs);
+	void ConstructL();
+
+	//Virtual from CActive
+	void RunL();
+	void DoCancel();
+    TInt RunError(TInt aError);
+
+
+private:
+	// The following functions handle the different RunL states
+	void HandleEAddCACertsL();
+
+	void HandleEAddCACertL();
+	void HandleEAddCACertGetCAEntry();
+	void HandleEAddCACertSetApplicationsL();
+	void HandleEAddCACertSetTrust();
+	void HandleEAddCACertFinishedL();
+	
+	void HandleERemoveCertsGetCACerts();
+	void HandleERemoveCertsCACertsRetrieved();
+	void HandleERemoveCertsRemoveCACerts();
+	void HandleERemoveCertsGetUserCerts();
+	void HandleERemoveCertsUserCertsRetrieved();
+	void HandleERemoveCertsRemoveUserCerts();
+	void HandleERemoveCertsFinished();
+
+
+private:
+	/**
+	File Server Sessioin
+	*/
+	RFs& iFs;
+
+	/**
+	The state used to know what RunL should do
+	*/
+	TState iState;
+	
+	/**
+	The store managers will be used for certificate store operations,
+	*/
+	CUnifiedCertStore* iUnifiedCertStore;
+	CUnifiedCertStore* iCreatedUnifiedCertStore;
+	
+	/**
+	These members are used to store the arguments of the functions
+	because most of the things are handled in a RunL.
+	*/
+	const CDesCArray* iRoots;					// Used by AddCertsL
+	const CDesCArray* iLabels;					// Used by AddCertsL
+	TCertificateFormat iFormat;
+	TInt iTrustedUsage;							// Used by AddCertsL, AddCert
+	RArray<TUid> iTrusters;						// Used by AddCertsL, AddCert
+	const TDesC* iPath;							// Used by AddCertsL, AddCert
+	TRequestStatus* iOriginalRequestStatus;		// Used by AddCertsL, AddCert
+	TInt iIndex;								// Used by AddCertsL to know 
+												// which certificate to add next
+												// Used by RemoveCerts
+	CCertUtils* iSecondCertUtils;				// Used by AddCertsL to add each individual
+												// certificate
+	const TDesC* iLabel;						// Used by AddCert
+	TCertificateOwnerType iCertificateOwnerType;
+	const TDesC* iCertificateFileName;			// Used by AddCert 
+	CCertificate* iCertificate;					// Used by AddCACert
+	MCTWritableCertStore *iStore;				// Used by AddCACert
+	TPtrC8 iEncoding;							// Used by AddCACert
+
+	HBufC* iCertData;
+	HBufC* iLabelData;
+
+	/**
+	This is a filter used by the GetCACerts function. We use the filter constructed
+	by the constructor with no argument, the filter doesn't filter anything.
+	*/
+	CCertAttributeFilter* iCAFilter;				// Used by RemoveCerts
+	RMPointerArray<CCTCertInfo> iCACertStoreEntries;	// Used by RemoveCerts
+	
+	/**
+	This is a filter used by the GetUserCerts function. We use the filter constructed
+	by the constructot with no argument, the filter doesn't filter anything.
+	*/
+	CCertAttributeFilter* iUserFilter;			// Used by RemoveCerts
+	RMPointerArray<CCTCertInfo> iUserCertStoreEntries; // Used by RemoveCerts
+
+public:
+	/**
+	A diagnostic variable for when an error occurs. It stores the state at which
+	the error occurred.
+	*/
+	TState iDiagnosticState;
+	
+	/** 
+	A diagnostic variable for when an error occurs. It is an info message set
+	to whatever is relevant for the error.
+	*/
+	TBuf<400> iDiagnosticMessage;
+	};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/testfilterparameters.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,42 @@
+// Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// This file contains the UID and key ids of Publish and Subscribe flags used for IPC between the test code and the test http filter
+// 
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+
+#ifndef __TESTFILTERPARAMETERS_H__
+#define __TESTFILTERPARAMETERS_H__
+
+#include <e32def.h>
+
+// UID used to reference the P&S flags
+const TInt KFilterParametersCategoryUID							= 0x1000A405;
+
+// Keys for the various parameters
+const TInt KFilterParameterNumDelayResp							=  1; // Delay by n milliseconds
+const TInt KFilterParameterCountDropResp 						=  2; // Drop n requests/responses
+const TInt KFilterParameterCountCorruptHTTPDataHeader 			=  3; // Corrupt HTTP data
+const TInt KFilterParameterCountCorruptHTTPDataBodySizeLarge	=  4; // Corrupt HTTP data
+const TInt KFilterParameterCountCorruptHTTPDataBodySizeSmall 	=  5; // Corrupt HTTP data
+const TInt KFilterParameterCountCorruptOCSPData 				=  6; // Corrupt OCSP data
+const TInt KFilterParameterCountInternalErrorResp 				=  7; // Respond with internalError
+const TInt KFilterParameterCountTryLaterResp 					=  8; // Respond with tryLater
+const TInt KFilterParameterCountSigValidateFailure 				=  9; // Cause signature validation failure
+
+#endif // __TESTFILTERPARAMETERS_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/tocsp.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,51 @@
+// Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// tocsp.exe Implementation of Online Certification Status Protocol
+// 
+//
+
+/**
+ @file
+*/
+
+TARGET		tocsp.exe
+TARGETTYPE	exe
+
+UID 0x10000079 0x1000A405
+VENDORID 0x70000001
+
+SOURCEPATH	.
+
+//WriteDeviceData is needed so that we can set the certificate apps
+CAPABILITY AllFiles NetworkServices WriteDeviceData
+
+SOURCE 		main.cpp panic.cpp script.cpp command.cpp engine.cpp TEFparser.cpp
+SOURCE		transport.cpp comms.cpp logger.cpp result.cpp
+SOURCE		requestlogger.cpp
+
+USERINCLUDE ../
+USERINCLUDE ../
+
+MW_LAYER_SYSTEMINCLUDE_SYMBIAN
+
+LIBRARY ocsp.lib 
+LIBRARY	euser.lib efsrv.lib c32.lib estor.lib
+LIBRARY x509.lib
+LIBRARY crypto.lib
+LIBRARY tcertcommon.lib certstore.lib t_testhandler2.lib
+LIBRARY http.lib inetprotutil.lib bafl.lib secutil.lib httputils.lib esock.lib
+LIBRARY ocsptransport.lib sectcbutil.lib
+
+LIBRARY ocspsupportclient.lib
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/tocsphttpfilter/A0004F14.rls	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,17 @@
+// Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+rls_string STRING_theInfo1 "TOCSPHTTPFilter"
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/tocsphttpfilter/A0004F14.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,43 @@
+// Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Registration data for user agent filter interface implementation
+// 
+//
+
+
+#include "A0004F14.rls"
+#include "ecom/registryinfo.rh"
+RESOURCE REGISTRY_INFO theInfo
+	{
+	dll_uid = 0xA0004F14;
+	interfaces=
+		{
+		INTERFACE_INFO
+			{
+			interface_uid = 0x20010FEA;
+			implementations =
+				{
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x20010FEB;
+					version_no = 1;
+					display_name = STRING_theInfo1;
+					default_data = "HTTP/-TOCSPHEADER";
+					opaque_data = "";
+					}
+				};
+			}
+		};
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/tocsphttpfilter/ocsphttpfilter.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,410 @@
+// Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+#include "ocsphttpfilter.h"
+#include <e32cmn.h>
+#include <e32std.h>
+#include <e32property.h>
+#include <http/rhttptransaction.h>
+#include <http/rhttpheaders.h>
+#include <http/thttphdrval.h>
+#include <httpstringconstants.h>
+#include "testfilterparameters.h"
+
+// Filter name used to register the filter
+_LIT8(KFilterName,"tocsphttpfilter");
+
+// Filter log file read by the test code
+_LIT(KFilterLogFileName, "\\tocsphttpfilter.log");
+
+// HTTPMethod StartTimeInMicroseconds
+_LIT8(KFilterLogFormat1, "%S %Ld");
+// StopTimeInMicroseconds
+_LIT8(KFilterLogFormat2, " %Ld\n"); 
+
+// Canned responses
+_LIT8(KCannedResponseInteralError, "\x30\x03\x0a\x01\x02");
+_LIT8(KCannedResponseTryLater, "\x30\x03\x0a\x01\x03");
+_LIT8(KCannedResponseCorruptOCSPData, "\x30\x03\x0a\x01\xf0");
+
+// A non-existent ocsp responder. Redirect requests to this
+// responder to simulate a missing response
+_LIT8(KNonExistentServer, "http://42.042.042.042:0420/");
+
+// HTTP response header for content-type (canned corrupted)
+_LIT8(KOCSPContentTypeResponseCorrupted, "application/ocsp-reponse");
+
+// Byte offset (+1) of Responder ID field of OCSPResponse
+const TInt KOCSPResponderIDOffset = 42;
+
+const TInt KTimeMilliToMicro = 1000;
+
+COCSPHTTPFilter::COCSPHTTPFilter()
+		: iLogLineCompleted(ETrue)
+	{
+	}
+
+CEComFilter* COCSPHTTPFilter::InstallFilterL(TAny* aSession)
+	{
+	RHTTPSession* session = reinterpret_cast<RHTTPSession*>(aSession);
+	COCSPHTTPFilter* filter = new (ELeave) COCSPHTTPFilter();
+	CleanupStack::PushL(filter);
+	filter->ConstructL(*session);
+	CleanupStack::Pop(filter);
+	return filter;
+	}
+
+void COCSPHTTPFilter::ConstructL(const RHTTPSession& aSession)
+	{
+	iStringPool = aSession.StringPool();
+	iFilterName = iStringPool.OpenFStringL(KFilterName);
+	// Register the filter for submit events
+	aSession.FilterCollection().AddFilterL(*this, THTTPEvent::EAnyTransactionEvent, MHTTPFilter::EClientFilters, iFilterName);
+	User::LeaveIfError(iFs.Connect());
+	User::LeaveIfError(iLogFile.Replace(iFs, KFilterLogFileName, EFileShareAny|EFileWrite));
+	}
+
+COCSPHTTPFilter::~COCSPHTTPFilter()
+	{
+	iFilterName.Close();
+	iLogFile.Close();
+	iFs.Close();
+	delete iCustomDataSupplier;
+	}
+
+void COCSPHTTPFilter::MHFLoad(RHTTPSession, THTTPFilterHandle)
+	{
+	++iLoadCount;
+	}
+
+void COCSPHTTPFilter::MHFUnload(RHTTPSession /*aSession*/, THTTPFilterHandle)
+	{
+	if (--iLoadCount)
+		return;
+
+	delete this;
+	}
+
+void COCSPHTTPFilter::MHFRunL(RHTTPTransaction aTransaction,
+									const THTTPEvent& aEvent)
+	{
+	// Read test parameters
+	TInt countDropResp, numDelayResp;
+	TInt countCorruptHTTPDataHeader, countCorruptHTTPDataBodySizeLarge, countCorruptHTTPDataBodySizeSmall;
+	TInt countCorruptOCSPData;
+	TInt countInternalErrorResp, countTryLaterResp;
+	TInt countSigValidateFailure;
+	ReadTestParameters(numDelayResp, countDropResp,
+			countCorruptHTTPDataHeader, countCorruptHTTPDataBodySizeLarge, countCorruptHTTPDataBodySizeSmall,
+			countCorruptOCSPData,
+			countInternalErrorResp, countTryLaterResp, 
+			countSigValidateFailure);
+
+	switch (aEvent.iStatus)
+		{
+	case THTTPEvent::ESubmit:
+		// Start of the HTTP transaction
+		iDataSupplied = EFalse;
+		iLogLineCompleted = EFalse;
+		LogTransactionStartL(aTransaction);
+		
+		if (countDropResp > 0)
+			{
+			// Drop the request
+			--countDropResp;
+			TUriParser8 uri;
+			uri.Parse(KNonExistentServer);
+			aTransaction.Request().SetURIL(uri);
+			}
+		break;
+	case THTTPEvent::EGotResponseHeaders:
+		{
+		RHTTPResponse response = aTransaction.Response();
+		RHTTPHeaders headers = response.GetHeaderCollection();
+		RStringPool stringPool = aTransaction.Session().StringPool();
+
+		// Modify http body size if we plan to modify the body (response data) later
+		if (countInternalErrorResp > 0 || countTryLaterResp > 0 || countCorruptOCSPData > 0) // Common code since size is same for all canned responses
+			{
+			// Create the data supplier
+			delete iCustomDataSupplier;
+			iCustomDataSupplier = NULL;
+			TPtrC8 ptr(KCannedResponseInteralError);
+			RStringF contentLengthString = stringPool.StringF(HTTP::EContentLength, RHTTPSession::GetTable());
+			if (countTryLaterResp > 0)
+				{
+				ptr.Set(KCannedResponseTryLater);
+				}
+			else if (countCorruptOCSPData > 0)
+				{
+				ptr.Set(KCannedResponseCorruptOCSPData);
+				}
+			iCustomDataSupplier = new (ELeave) TCustomDataSupplier(ptr, aTransaction);
+			THTTPHdrVal contentLengthVal;
+			TInt size = iCustomDataSupplier->OverallDataSize();
+			contentLengthVal.SetInt(size);
+			headers.RemoveFieldPart(contentLengthString, 0);
+			headers.SetFieldL(contentLengthString, contentLengthVal);
+			}
+		// Create and keep a data supplier if we plan to corrupt the data leading to a signature validation failure
+		if (countSigValidateFailure > 0)
+			{
+			// Create the data supplier
+			delete iCustomDataSupplier;
+			iCustomDataSupplier = NULL;
+			TPtrC8 ptr(KNullDesC8);
+			iCustomDataSupplier = new (ELeave) TCustomDataSupplier(ptr, aTransaction);
+			}
+		if (countCorruptHTTPDataHeader > 0)
+			{
+			// Corrupt the header
+			RStringF ocspResponse = stringPool.OpenFStringL(KOCSPContentTypeResponseCorrupted);
+			CleanupClosePushL(ocspResponse); 
+			RStringF contentTypeString = stringPool.StringF(HTTP::EContentType, RHTTPSession::GetTable());
+			THTTPHdrVal contentTypeVal;
+			contentTypeVal.SetStrF(ocspResponse);
+			headers.RemoveFieldPart(contentTypeString, 0);
+			headers.SetFieldL(contentTypeString, contentTypeVal);
+			CleanupStack::PopAndDestroy(&ocspResponse);
+			--countCorruptHTTPDataHeader;
+			}
+		if (countCorruptHTTPDataBodySizeLarge > 0 || countCorruptHTTPDataBodySizeSmall > 0)
+			{
+			// Corrupt the body size recorded in the header
+			RStringF contentLengthString = stringPool.StringF(HTTP::EContentLength, RHTTPSession::GetTable());
+			THTTPHdrVal contentLengthVal;
+			TInt err = headers.GetField(contentLengthString, 0, contentLengthVal);
+			if ((err == KErrNone) && (contentLengthVal.Type() == THTTPHdrVal::KTIntVal))
+				{
+				TInt bodySize = contentLengthVal.Int();
+				if (countCorruptHTTPDataBodySizeLarge > 0)
+					{
+					--bodySize;
+					--countCorruptHTTPDataBodySizeLarge;
+					}
+				else
+					{
+					++bodySize;
+					--countCorruptHTTPDataBodySizeSmall;
+					}
+				contentLengthVal.SetInt(bodySize);
+				headers.RemoveFieldPart(contentLengthString, 0);
+				headers.SetFieldL(contentLengthString, contentLengthVal);
+				}
+			}
+		}
+		break;
+	case THTTPEvent::EGotResponseBodyData:
+		if (iCustomDataSupplier && (countInternalErrorResp > 0 || countTryLaterResp > 0 || countCorruptOCSPData > 0 || countSigValidateFailure > 0))
+			{
+			aTransaction.Response().RemoveBody();
+			aTransaction.Response().SetBody(*iCustomDataSupplier);
+			// Make sure state machine goes on
+			aTransaction.Response().SetStatusCode(THTTPEvent::EResponseComplete);
+			}
+		break;
+	case THTTPEvent::ESucceeded:
+	case THTTPEvent::EFailed:
+		// Delay response (numDelayResp is in milliseconds)
+		if (numDelayResp > 0)
+			{
+			User::After(numDelayResp * KTimeMilliToMicro);
+			}
+	// Deliberate fall through case
+	case THTTPEvent::ECancel:
+		if (!iLogLineCompleted)
+			{
+			// End of the HTTP transaction
+			iLogLineCompleted = ETrue;
+			LogTransactionEndL(aTransaction);
+			}
+		// Since EGotResponseBodyData event can happen more than once per transaction ensure to decrement
+		// counters only once
+		if (!iDataSupplied)
+			{
+			if (countInternalErrorResp > 0)
+				{
+				--countInternalErrorResp;
+				}
+			if (countTryLaterResp > 0)
+				{
+				--countTryLaterResp;
+				}
+			if (countCorruptOCSPData > 0)
+				{
+				--countCorruptOCSPData;
+				}
+			if (countSigValidateFailure > 0)
+				{
+				--countSigValidateFailure;
+				}
+			iDataSupplied = ETrue;
+			}
+		break;
+	default:
+		break;
+		}
+
+	// Write the parameters back to keep them persistent between retries
+	WriteTestParameters(countDropResp, 
+			countCorruptHTTPDataHeader, countCorruptHTTPDataBodySizeLarge, countCorruptHTTPDataBodySizeSmall, 
+			countCorruptOCSPData, 
+			countInternalErrorResp, countTryLaterResp,
+			countSigValidateFailure);
+	}
+
+TInt COCSPHTTPFilter::MHFRunError(TInt /*aError*/,
+										RHTTPTransaction aTransaction,
+										const THTTPEvent& /*aEvent*/)
+	{
+	// If anything left, we've run out of memory or something
+	// similarly catastrophic has gone wrong.
+	aTransaction.Fail();
+	return KErrNone;
+	}
+
+// Logs the transaction method used and the current (start) time
+void COCSPHTTPFilter::LogTransactionStartL(const RHTTPTransaction& aTransaction)
+	{
+	// Get the transaction method being used (GET/POST) and log it
+	RHTTPRequest request = aTransaction.Request();
+	RStringF method = request.Method();
+	TTime time;
+	time.HomeTime();
+	TInt64 intTime = time.Int64();
+	RBuf8 logText;
+	logText.CreateL(255);
+	CleanupClosePushL(logText);
+	logText.Format(KFilterLogFormat1, &method.DesC(), intTime);
+	User::LeaveIfError(iLogFile.Write(logText));
+	CleanupStack::PopAndDestroy(&logText);
+	}
+
+// Logs the current (end) time
+void COCSPHTTPFilter::LogTransactionEndL(const RHTTPTransaction& /*aTransaction*/)
+	{
+	TTime time;
+	time.HomeTime();
+	TInt64 intTime = time.Int64();
+	RBuf8 logText;
+	logText.CreateL(255);
+	CleanupClosePushL(logText);
+	logText.Format(KFilterLogFormat2, intTime);
+	User::LeaveIfError(iLogFile.Write(logText));
+	CleanupStack::PopAndDestroy(&logText);
+	}
+
+// Read test parameters using Publish & Subscribe method
+void COCSPHTTPFilter::ReadTestParameters(TInt& aNumDelayResp, TInt& aCountDropResp,
+		TInt& aCountCorruptHTTPDataHeader, TInt& aCountCorruptHTTPDataBodySizeLarge, TInt& aCountCorruptHTTPDataBodySizeSmall,
+		TInt& aCountCorruptOCSPData, 
+		TInt& aCountInternalErrorResp, TInt& aCountTryLaterResp,
+		TInt& aCountSigValidateFailure)
+	{
+	// Set default values which will be used if P&S doesn't exist
+	aNumDelayResp = aCountDropResp = 
+	aCountCorruptHTTPDataHeader = aCountCorruptHTTPDataBodySizeLarge = aCountCorruptHTTPDataBodySizeSmall = 
+		aCountCorruptOCSPData = 
+		aCountInternalErrorResp = aCountTryLaterResp = 
+		aCountSigValidateFailure = 0;
+
+	TUid categoryUid = TUid::Uid(KFilterParametersCategoryUID);
+	RProperty::Get(categoryUid, KFilterParameterNumDelayResp, aNumDelayResp);
+	RProperty::Get(categoryUid, KFilterParameterCountDropResp, aCountDropResp);
+	RProperty::Get(categoryUid, KFilterParameterCountCorruptHTTPDataHeader, aCountCorruptHTTPDataHeader);
+	RProperty::Get(categoryUid, KFilterParameterCountCorruptHTTPDataBodySizeLarge, aCountCorruptHTTPDataBodySizeLarge);
+	RProperty::Get(categoryUid, KFilterParameterCountCorruptHTTPDataBodySizeSmall, aCountCorruptHTTPDataBodySizeSmall);
+	RProperty::Get(categoryUid, KFilterParameterCountCorruptOCSPData, aCountCorruptOCSPData);
+	RProperty::Get(categoryUid, KFilterParameterCountInternalErrorResp, aCountInternalErrorResp);
+	RProperty::Get(categoryUid, KFilterParameterCountTryLaterResp, aCountTryLaterResp);
+	RProperty::Get(categoryUid, KFilterParameterCountSigValidateFailure, aCountSigValidateFailure);
+	}
+
+// To maintain persistence between retry attempts store the updated counts back
+void COCSPHTTPFilter::WriteTestParameters(TInt aCountDropResp,
+		TInt aCountCorruptHTTPDataHeader, TInt aCountCorruptHTTPDataBodySizeLarge, TInt aCountCorruptHTTPDataBodySizeSmall,
+		TInt aCountCorruptOCSPData, 
+		TInt aCountInternalErrorResp, TInt aCountTryLaterResp,
+		TInt aCountSigValidateFailure)
+	{
+	TUid categoryUid = TUid::Uid(KFilterParametersCategoryUID);
+	RProperty::Set(categoryUid, KFilterParameterCountDropResp, aCountDropResp);
+	RProperty::Set(categoryUid, KFilterParameterCountCorruptHTTPDataHeader, aCountCorruptHTTPDataHeader);
+	RProperty::Set(categoryUid, KFilterParameterCountCorruptHTTPDataBodySizeLarge, aCountCorruptHTTPDataBodySizeLarge);
+	RProperty::Set(categoryUid, KFilterParameterCountCorruptHTTPDataBodySizeSmall, aCountCorruptHTTPDataBodySizeSmall);
+	RProperty::Set(categoryUid, KFilterParameterCountCorruptOCSPData, aCountCorruptOCSPData);
+	RProperty::Set(categoryUid, KFilterParameterCountInternalErrorResp, aCountInternalErrorResp);
+	RProperty::Set(categoryUid, KFilterParameterCountTryLaterResp, aCountTryLaterResp);
+	RProperty::Set(categoryUid, KFilterParameterCountSigValidateFailure, aCountSigValidateFailure);
+	}
+
+TCustomDataSupplier::TCustomDataSupplier(TPtrC8& aData, RHTTPTransaction& aTransaction)
+	{
+	iData.Set(aData);
+	iTransaction = &aTransaction;
+	iDataSupplied = EFalse;
+	iOriginalSupplier = aTransaction.Response().Body();
+	}
+
+// Methods from MHTTPDataSupplier
+TBool TCustomDataSupplier::GetNextDataPart(TPtrC8& aDataPart)
+	{
+	// Check if we need to simulate a signature validation failure
+	if (iData == KNullDesC8)
+		{
+		// Get the original data
+		iOriginalSupplier->GetNextDataPart(aDataPart);
+		iCorruptData.Create(aDataPart);
+		// Corrupt it (byte is part of ResponderID field)
+		--iCorruptData[KOCSPResponderIDOffset];
+		// Send it along
+		aDataPart.Set(iCorruptData);
+		}
+	else
+		{
+		// Consume the original data and pass back canned response
+		iOriginalSupplier->GetNextDataPart(aDataPart);
+		if (!iDataSupplied)
+			{
+			aDataPart.Set(iData);
+			iDataSupplied = ETrue;
+			}
+		else
+			{
+			// no data
+			aDataPart.Set(KNullDesC8);
+			}
+		}
+	return ETrue;
+	}
+
+void TCustomDataSupplier::ReleaseData()
+	{
+	iCorruptData.Close();
+	// Call original method to ensure it does it's work to let the state machine go on
+	iOriginalSupplier->ReleaseData();
+	// We are done supplying canned response so restore original supplier
+	iTransaction->Response().SetBody(*iOriginalSupplier);
+	}
+
+TInt TCustomDataSupplier::OverallDataSize()
+	{
+	return iData.Length();
+	}
+
+TInt TCustomDataSupplier::Reset()
+	{
+	return KErrNotSupported;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/tocsphttpfilter/ocsphttpfilter.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,115 @@
+// Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+/**
+ @file
+ @internalComponent
+*/
+
+#ifndef __OCSPHTTPFILTER_H__
+#define __OCSPHTTPFILTER_H__
+
+#include <http/mhttpfilter.h>
+#include <http/rhttpsession.h>
+#include <http/cecomfilter.h>
+#include <http.h>
+
+// Forward declarations
+class TCustomDataSupplier;
+
+/**
+ * An http filter which logs the requests sent to the responder
+ * @see MHTTPFilter
+ */
+class COCSPHTTPFilter : public CEComFilter, public MHTTPFilter
+	{
+public:
+	/** Installs the user-agent filter
+		@param  aSession the session to install the filter into.
+		@return Pointer to the newly installed plugin
+	*/
+	static CEComFilter* InstallFilterL(TAny* aSession);
+	~COCSPHTTPFilter();
+
+	// Methods from MHTTPFilterBase
+	virtual void MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent);
+	virtual TInt MHFRunError(TInt aError, RHTTPTransaction aTransaction,
+							 const THTTPEvent& aEvent);
+
+	// Methods from MHTTPFilter
+	virtual void MHFUnload(RHTTPSession aSession, THTTPFilterHandle aHandle);
+	virtual void MHFLoad(RHTTPSession aSession, THTTPFilterHandle aHandle);
+
+protected:
+	COCSPHTTPFilter();
+	void ConstructL(const RHTTPSession& aSession);
+
+	// Log the transaction
+	void LogTransactionStartL(const RHTTPTransaction& aTransaction);
+	void LogTransactionEndL(const RHTTPTransaction& aTransaction);
+
+	// Read test parameters using Publish & Subscribe method
+	void ReadTestParameters(TInt& aNumDelayResp, TInt& aCountDropResp,
+			TInt& aCountCorruptHTTPDataHeader, TInt& aCountCorruptHTTPDataBodySizeLarge, TInt& aCountCorruptHTTPDataBodySizeSmall,
+			TInt& aCountCorruptOCSPData, 
+			TInt& aCountInternalErrorResp, TInt& aCountTryLaterResp,
+			TInt& aCountSigValidateFailure);
+
+	// To maintain persistence between retry attempts store the updated counts back
+	void WriteTestParameters(TInt aCountDropResp,
+			TInt aCountCorruptHTTPDataHeader, TInt aCountCorruptHTTPDataBodySizeLarge, TInt aCountCorruptHTTPDataBodySizeSmall,
+			TInt aCountCorruptOCSPData, 
+			TInt aCountInternalErrorResp, TInt aCountTryLaterResp,
+			TInt aCountSigValidateFailure);
+
+protected:
+ 	RStringF     	iFilterName; // name of this filter (appears in filter lists)
+	TInt         	iLoadCount;  // reference count - unloads filter when reaches 0
+	RStringPool		iStringPool; // for the filter name
+	RFs			 	iFs;
+	RFile 		 	iLogFile;
+	TBool		 	iLogLineCompleted; // To prevent double logging of end time
+	TBool		 	iDataSupplied;
+
+	// HTTP custom data supplier for returning canned responses
+	TCustomDataSupplier* iCustomDataSupplier;
+	};
+
+/**
+ * Custom HTTP body data supplier to send back canned responses
+ * @see MHTTPDataSupplier
+ */
+class TCustomDataSupplier : public MHTTPDataSupplier
+	{
+public:
+	TCustomDataSupplier(TPtrC8& aData, RHTTPTransaction& aTransaction);
+
+public:
+	// Methods from MHTTPDataSupplier
+	TBool GetNextDataPart(TPtrC8& aDataPart);
+	void ReleaseData();
+	TInt OverallDataSize();
+	TInt Reset();
+
+private:
+	TBool iDataSupplied;
+	RHTTPTransaction* iTransaction;
+	MHTTPDataSupplier* iOriginalSupplier;
+	TPtrC8 iData;
+	RBuf8 iCorruptData;
+	};
+
+#endif //__OCSPHTTPFILTER_H__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/tocsphttpfilter/ocsphttpfiltermain.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,30 @@
+// Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+
+#include <e32std.h>
+#include <ecom/implementationproxy.h>
+#include "ocsphttpfilter.h"
+
+const TImplementationProxy KImplementationTable[] =
+	{
+		IMPLEMENTATION_PROXY_ENTRY(0x20010FEB, COCSPHTTPFilter::InstallFilterL)
+	};
+
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+	{
+	aTableCount = sizeof(KImplementationTable) / sizeof(TImplementationProxy);
+	return KImplementationTable;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/tocsphttpfilter/tocsphttpfilter.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,47 @@
+// Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// ocsphttpfilter.mmp
+// DESRIPTION:
+// Test HTTP filter used for testing OCSP transport module
+// ocsphttpfilter.dll Test HTTP filter used for testing OCSP transport module
+// 
+//
+
+/**
+ @file
+*/
+
+target tocsphttpfilter.dll
+CAPABILITY    All -Tcb
+targettype plugin
+
+// ECom Recognition UID followed by Unique 3rd UID
+UID 0x10009D8D 0xA0004F14
+VENDORID 0x70000001
+
+SOURCEPATH	.
+
+SOURCE ocsphttpfilter.cpp
+SOURCE ocsphttpfiltermain.cpp
+
+USERINCLUDE .
+USERINCLUDE ../
+MW_LAYER_SYSTEMINCLUDE_SYMBIAN
+
+START RESOURCE A0004F14.rss
+TARGET tocsphttpfilter.rsc
+END
+
+LIBRARY euser.lib ecom.lib http.lib bafl.lib efsrv.lib inetprotutil.lib
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/transport.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,139 @@
+// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Test transport object.  May be used in place of the default transport used by
+// the ocsp module.  May later be extended to act as a dummy server producing
+// a variety of test responses.
+// 
+//
+
+#include "transport.h"
+
+#include <f32file.h>
+
+CTOCSPTransport* CTOCSPTransport::NewL(const TDesC& aResponseFile, const TDesC* aRequestFile)
+	{
+	CTOCSPTransport* self = new (ELeave) CTOCSPTransport;
+	CleanupStack::PushL(self);
+	self->ConstructL(aResponseFile, aRequestFile);
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+
+void CTOCSPTransport::ConstructL(const TDesC& aResponseFile, const TDesC* aRequestFile)
+	{
+	User::LeaveIfError(iFs.Connect());
+	User::LeaveIfError(iResponseStream.Open(iFs, aResponseFile, EFileShareReadersOnly));
+	iTransactions = iResponseStream.ReadUint32L();
+
+	if (aRequestFile)
+		{
+		iRequestStream = new (ELeave) RFileReadStream;
+		User::LeaveIfError(iRequestStream->Open(iFs, *aRequestFile, EFileShareReadersOnly));
+		TInt requests = iRequestStream->ReadUint32L();
+		__ASSERT_ALWAYS(requests == iTransactions, User::Leave(KErrCorrupt));	
+		} 		
+	}
+
+
+CTOCSPTransport::~CTOCSPTransport()
+	{
+	iResponseStream.Close();
+	
+	if (iRequestStream)
+		{
+		iRequestStream->Close();
+		delete iRequestStream;
+		}
+	
+	iFs.Close();
+	delete iResponseData;
+	}
+
+
+void CTOCSPTransport::SendRequest(const TDesC8& aURI,
+								  const TDesC8& aRequest, 
+								  const TInt,				// Timeout not used
+								  TRequestStatus& aStatus)
+	{
+	iCallBack = &aStatus;
+	aStatus = KRequestPending;
+
+	TRAPD(error, DoSendRequestL(aURI, aRequest));
+	User::RequestComplete(iCallBack, error);
+	}
+
+
+void CTOCSPTransport::DoSendRequestL(const TDesC8& aURI,
+									 const TDesC8& aRequest)
+	{	
+	__ASSERT_ALWAYS(iIndex++ < iTransactions, User::Leave(TOCSP::ETooManyTransactions));
+
+	CheckRequestL(aURI, aRequest);
+
+	delete iResponseData;
+	iResponseData = NULL;
+
+	iResponseData = ReadDataLC(iResponseStream);
+	CleanupStack::Pop(iResponseData);
+	}
+
+
+void CTOCSPTransport::CheckRequestL(const TDesC8& aURI,
+									const TDesC8& aRequest)
+	{
+	if (!iRequestStream)
+		{
+		return;
+		}
+
+	HBufC8* expectURI = ReadDataLC(*iRequestStream);
+	if (aURI != *expectURI)
+		{
+		User::Leave(TOCSP::EURIMismatch);
+		}
+	CleanupStack::PopAndDestroy(expectURI);
+	
+	HBufC8* expectRequest = ReadDataLC(*iRequestStream);
+	if (aRequest != *expectRequest)
+		{
+		User::Leave(TOCSP::ERequestMismatch);
+		}
+	CleanupStack::PopAndDestroy(expectRequest);
+	}
+
+HBufC8* CTOCSPTransport::ReadDataLC(RFileReadStream& aStream)
+	{
+	TUint32 len = aStream.ReadUint32L();
+	HBufC8* data = HBufC8::NewLC(len);
+	TPtr8 dataDes = data->Des();
+	aStream.ReadL(dataDes, len);
+	return data;
+	}
+
+void CTOCSPTransport::CancelRequest()
+	{
+	// If its not been done already, complete the active object
+	if (iCallBack)
+		{
+		User::RequestComplete(iCallBack, KErrCancel);
+		}
+	}
+
+
+TPtrC8 CTOCSPTransport::GetResponse() const
+	{
+	__ASSERT_ALWAYS(iResponseData, User::Panic(_L("TOCSP"), KErrNotReady));
+	return *iResponseData;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/test/transport.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,80 @@
+// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Test transport object.  May be used in place of the automatically-constructed
+// transport object from OCSP.DLL
+// Allows a file to be specified, the contents of which will be returned as the response.
+// 
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+
+#ifndef __TOCSP_TRANSPORT_H__
+#define __TOCSP_TRANSPORT_H__
+
+#include <e32base.h>
+#include <ocsp.h>
+#include <s32file.h>
+
+#include "ocsprequestandresponse.h"
+namespace TOCSP
+	{
+	// Some test code specific status codes
+	
+	enum TStatus
+		{
+		ETooManyTransactions = 200, // Client made more requests than we had responses for
+		EURIMismatch,				// Request URI didn't match expected
+		ERequestMismatch			// Request data didn't match expectedo		
+		};
+	}
+
+class CTOCSPTransport : public CBase, public MOCSPTransport
+	{
+public:
+
+	/**
+	 * Create a test transport object.
+	 * @param aResponseFile The filename of the response to return.
+	 * @param aRequestFile The name of the request file to compare the request
+	 * data against, or null.
+	 */
+	static CTOCSPTransport* NewL(const TDesC& aResponseFile, const TDesC* aRequestFile);
+
+private:
+	// From MOCSPTransport
+	~CTOCSPTransport();
+	void SendRequest(const TDesC8& aURI, const TDesC8& aRequest, const TInt aTimeout, TRequestStatus& aStatus);
+	void CancelRequest();
+	TPtrC8 GetResponse() const;
+
+private:
+	void DoSendRequestL(const TDesC8& aURI, const TDesC8& aRequest);
+	void CheckRequestL(const TDesC8& aURI, const TDesC8& aRequest);
+	void ConstructL(const TDesC& aResponseFile, const TDesC* aRequestFile);
+	HBufC8* ReadDataLC(RFileReadStream& aStream);
+
+private:
+	RFs				 iFs;
+	RFileReadStream  iResponseStream;
+	RFileReadStream* iRequestStream;
+	TInt			 iTransactions;	
+	TInt			 iIndex;
+	HBufC8*			 iResponseData;
+	TRequestStatus*  iCallBack;
+	};
+
+#endif // __TOCSP_TRANSPORT_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/transport/ocsptransport.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,45 @@
+// Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// ocsptransport.dll Provides implementation of HTTP transport for OCSP
+// 
+//
+
+/**
+ @file
+*/
+
+TARGET        ocsptransport.dll
+TARGETTYPE    DLL
+CAPABILITY All -Tcb
+
+UID    0x1000008d 0x10202142
+VENDORID 0x70000001
+
+DEFFILE ocsptransport_v2.def
+
+MW_LAYER_SYSTEMINCLUDE_SYMBIAN
+
+
+USERINCLUDE 	../inc
+
+SOURCEPATH		.
+SOURCE			panic.cpp
+SOURCE			transportdefault.cpp
+SOURCE			transporthttp.cpp
+
+LIBRARY ocspcommon.lib
+LIBRARY bafl.lib efsrv.lib euser.lib
+LIBRARY inetprotutil.lib http.lib ecom.lib securitymanager.lib
+LIBRARY	secutil.lib httputils.lib esock.lib
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/transport/panic.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// The panic method
+// 
+//
+
+#include "panic.h"
+
+#include <e32std.h>
+
+GLDEF_C void Panic(TInt aPanic)
+	{
+	User::Panic(_L("OCSP"), aPanic);
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/transport/panic.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// The panic method and OCSP panic code declarations 
+// 
+//
+
+/**
+ @file 
+ @internalTechnology
+*/
+ 
+#ifndef __OCSP_PANIC_H__
+#define __OCSP_PANIC_H__
+
+#include <e32def.h>
+
+enum TOCSPPanics
+	{
+	KErrNoCertificates,
+	KErrNoAuthorisationSchemes
+	};
+
+
+GLDEF_C void Panic(TInt aPanic);
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/transport/transportdefault.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,130 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// COCSPTransportDefault.  Looks at the URI and creates appropriate transport
+// object to send the request.
+// 
+//
+
+#include <ocsptransport.h>
+#include "panic.h"
+#include "ocsp.h"
+
+#include <uri8.h>
+
+_LIT8(KHttpString, "http");
+
+EXPORT_C COCSPTransportDefault* COCSPTransportDefault::NewL(TUint32& aIap)
+	{
+	COCSPTransportDefault* self = new (ELeave) COCSPTransportDefault(aIap);
+	return self;
+	}
+
+COCSPTransportDefault::COCSPTransportDefault(TUint32& aIap)
+	: iIap(aIap)
+	{
+	}
+
+COCSPTransportDefault::~COCSPTransportDefault()
+	{
+	delete iTransport;
+	}
+
+void COCSPTransportDefault::SendRequest(const TDesC8& aURI, 
+										const TDesC8& aRequest,
+										const TInt aTimeout,
+									    TRequestStatus& iStatus)
+	{
+	TRAPD(err, CreateTransportL(aURI));
+	if (err)
+		{
+		TRequestStatus* status = &iStatus;
+		User::RequestComplete(status, err);
+		}
+	else
+		{
+		iTransport->SendRequest(aURI, aRequest, aTimeout, iStatus);
+		}
+	}
+
+void COCSPTransportDefault::CancelRequest()
+	{
+	if (iTransport)
+		{
+		iTransport->CancelRequest();
+		}
+	}
+
+TPtrC8 COCSPTransportDefault::GetResponse() const
+	{
+	ASSERT(iTransport);
+	return iTransport->GetResponse();
+	}
+
+COCSPTransportDefault::TTransportScheme COCSPTransportDefault::IdentifySchemeL(const TDesC8& aURI)
+	{
+	TTransportScheme ret = ETransportSchemeNotSupported;
+	
+	TUriParser8 uri;
+	TInt error = uri.Parse(aURI);
+	if (error != KErrNone || !uri.IsPresent(EUriScheme))
+		{
+		return ret;
+		}
+	const TPtrC8 scheme = uri.Extract(EUriScheme);
+			
+	RStringPool stringPool;
+	stringPool.OpenL();
+	CleanupClosePushL(stringPool);
+
+	RStringF schemeF = stringPool.OpenFStringL(scheme);
+	CleanupClosePushL(schemeF);
+	RStringF httpF = stringPool.OpenFStringL(KHttpString);
+	CleanupClosePushL(httpF);
+
+	if (schemeF == httpF)
+		{
+		ret = ETransportSchemeHTTP;
+		}
+
+	CleanupStack::PopAndDestroy(3); // close httpF, schemeF, stringPool
+
+	return ret;
+	}
+
+
+void COCSPTransportDefault::CreateTransportL(const TDesC8& aURI)
+	{
+	TTransportScheme scheme = IdentifySchemeL(aURI);
+
+	if (iTransport && iScheme == scheme)
+		{
+		return; // reuse existing transport
+		}
+
+	delete iTransport;
+	iTransport = NULL;
+	
+	switch (scheme)
+		{
+		case ETransportSchemeHTTP:
+			iTransport = COCSPTransportHttp::NewL(aURI, iIap);
+			break;
+			
+		default:
+			User::Leave(OCSP::KErrInvalidURI);
+			break;
+		}
+
+	iScheme = scheme;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/ocsp/transport/transporthttp.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,558 @@
+// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Implement the transport class for using HTTP GET and POST.
+// Links the OCSP module to the HTTP module.
+// 
+//
+
+#include <http/cecomfilter.h>
+#include <escapeutils.h>
+#include "securitypolicy.h"
+#include "ocsppolicy.h"
+#include "ocsptransport.h"
+#include "panic.h"
+#include <tconvbase64.h>
+#include "callbacktimer.h"
+
+_LIT8(KOCSPContentTypeRequest, "application/ocsp-request");
+_LIT8(KOCSPContentTypeResponse, "application/ocsp-response");
+_LIT8(KSlash, "/");
+
+// Min request size for the use of POST method (else use GET method)
+const TInt KMinReqSizeForHTTPPOST = 255;
+
+const TInt KMillSecsToMicroSecs = 1000;
+
+// Default value of timeout means it's disabled
+const TInt KTimeoutDisabledValue = KTransportDefaultRequestTimeout;
+
+EXPORT_C COCSPTransportHttp* COCSPTransportHttp::NewL(const TDesC8& aUri, TUint32& aIap)
+	{
+	COCSPTransportHttp* self = new (ELeave) COCSPTransportHttp(aIap);
+	CleanupStack::PushL(self);
+	self->ConstructL(aUri);
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+COCSPTransportHttp::COCSPTransportHttp(TUint32& aIap)
+	: CActive(CActive::EPriorityStandard), iIap(aIap), 
+	  iTimeout(KTimeoutDisabledValue)
+	{
+	CActiveScheduler::Add(this);
+	}
+	
+void COCSPTransportHttp::ConstructL(const TDesC8& aUri)
+	{
+	// Create the timer object
+	iTimer = CCallbackTimer::NewL(*this);
+
+	TUriParser8	uri;
+	uri.Parse(aUri);
+	iHTTPSession.OpenL(uri, iIap, EFalse);
+	
+	// Install the HTTP filter (filter UID is specified in swipolicy.ini file)
+	InstallHttpFilterL();
+	}
+
+COCSPTransportHttp::~COCSPTransportHttp()
+	{
+	Deque();
+	iHTTPTransaction.Close();
+	iHTTPSession.Close();
+
+	delete iUri;
+	delete iRequest;
+	delete iResponseData;
+	delete iTimer;
+	}
+
+// From MOCSPTransport
+void COCSPTransportHttp::SendRequest(const TDesC8& aURI, 
+										 const TDesC8& aRequest,
+										 const TInt aTimeout,
+										 TRequestStatus& aStatus)
+	{
+	iCallBack = &aStatus;
+	aStatus = KRequestPending;
+	iServerFound = ETrue;
+
+	delete iUri;
+	delete iRequest;
+
+	iTimeout = aTimeout;
+	iUri = aURI.Alloc();
+	iRequest = aRequest.Alloc();
+
+	// Check for out of memory
+	if (iUri == NULL || iRequest == NULL)
+		{
+		Complete(KErrNoMemory);
+		}
+
+	// Take action depending on current state
+	if (iState == ETransportConnectingState)
+		{
+		// Establish a connection
+		// Note: Timeout and retries don't apply to this operation
+		iState = ETransportConnectingState;
+		iHTTPSession.StartConnection(iStatus);
+		SetActive();
+		}
+	else
+		{
+		// We've connected already, send the request.
+		iStatus = KRequestPending;
+		TRAPD(err, DoSendRequestL(*iUri, *iRequest));
+		if (err == KErrNone)
+			{
+			// Start the timer (if enabled)
+			if (iTimeout > KTimeoutDisabledValue)
+				{
+				iTimer->After(iTimeout * KMillSecsToMicroSecs);
+				}
+			SetActive();
+			}
+		else
+			{
+			Complete(err);
+			}
+		}
+	}
+
+void COCSPTransportHttp::InstallHttpFilterL()
+	{
+	// Install filters (if any)
+	Swi::RSecPolHandle secPol;
+	secPol.OpenLC();
+	TUint32 filterId = secPol().OcspHttpHeaderFilter();
+	if (filterId != 0)
+		{
+		TUid headerFilterUid = {filterId};
+		CEComFilter::InstallFilterL(iHTTPSession.HTTPSession(), headerFilterUid);
+		}
+	CleanupStack::PopAndDestroy(&secPol);
+	}
+
+void COCSPTransportHttp::DoSendRequestL(const TDesC8& aURI, 
+											const TDesC8& aRequest)
+	{
+	delete iResponseData;
+	iResponseData = NULL;
+	iOCSPRequest.Set(aRequest);
+
+	// Close previous transaction, if any
+	iHTTPTransaction.Close();
+
+	// If the size of the DER encoded request is less than 255 bytes use the GET method (if enabled)
+	// else use the POST method
+	RBuf8 url8;
+	CleanupClosePushL(url8);
+	TInt reqSize = aRequest.Length();
+
+	COcspPolicy* ocspPolicy = COcspPolicy::NewL();
+	TBool useHTTPGETMethod = ocspPolicy->IsHttpGETMethodEnabled();
+
+	delete ocspPolicy;
+
+	if (useHTTPGETMethod && reqSize < KMinReqSizeForHTTPPOST)
+		{
+		// Set the OCSP request as part of the url after Base64 and URL encoding
+		
+		TBase64 base64;
+  		
+		TInt destLen = ((iOCSPRequest.Length() - 1 ) / 3 + 1) * 4;
+ 		HBufC8* encodedBuf = HBufC8::NewMaxLC(destLen); // to get the decoded string
+   		TPtr8 encodedPtr = encodedBuf->Des();
+ 		
+ 		base64.Encode(iOCSPRequest, encodedPtr);
+		 				
+ 		HBufC8* escEncodedReq = EscapeUtils::EscapeEncodeL(encodedPtr, EscapeUtils::EEscapeUrlEncoded);
+
+		CleanupStack::PushL(escEncodedReq);
+		url8.CreateL(aURI, aURI.Length() + KSlash().Length() + escEncodedReq->Length());
+		// Append a slash only if it's already not present
+		if ((aURI.Length() > 0) && (aURI.Right(1) != KSlash))
+			{
+			url8.Append(KSlash);
+			}
+		url8.Append(*escEncodedReq);
+		CleanupStack::PopAndDestroy(2, encodedBuf);
+
+		if (iURI.Parse(url8))
+			{
+			User::Leave(OCSP::KErrInvalidURI);
+			}
+
+		// Create HTTP transaction, method = GET (default)
+		iHTTPTransaction = iHTTPSession().OpenTransactionL(iURI, *this);
+
+		// Add the appropriate Http headers
+		AddHttpHeadersL();
+		}
+	else
+		{
+		// Use the passed in URL as is
+		if (iURI.Parse(aURI))
+			{
+			User::Leave(OCSP::KErrInvalidURI);
+			}
+
+		// Create HTTP transaction, method = POST
+		RStringPool stringPool = iHTTPSession().StringPool();
+		iHTTPTransaction = iHTTPSession().OpenTransactionL(iURI, *this, stringPool.StringF(HTTP::EPOST,RHTTPSession::GetTable()));
+
+		// Add the appropriate Http headers
+		AddHttpHeadersL();
+
+		// Setup the data supplier
+		iHTTPTransaction.Request().SetBody(*this);
+		}
+
+	// Finally submit the transaction
+	iHTTPTransaction.SubmitL();
+	CleanupStack::PopAndDestroy(&url8);
+	}
+
+void COCSPTransportHttp::AddHttpHeadersL()
+	{
+	// Get request + it's headers
+	RStringPool stringPool = iHTTPSession().StringPool();
+	RHTTPRequest request = iHTTPTransaction.Request();
+	RHTTPHeaders headers = request.GetHeaderCollection();
+
+	// Host header: done by HTTP module
+	// Content-Length header: done by HTTP module
+
+	// Connection:close header:
+	headers.SetFieldL(stringPool.StringF(HTTP::EConnection, RHTTPSession::GetTable()), stringPool.StringF(HTTP::EClose, RHTTPSession::GetTable()));
+
+	// Content-Type header:
+	RStringF ocspRequest = stringPool.OpenFStringL(KOCSPContentTypeRequest);
+	CleanupClosePushL(ocspRequest);
+	THTTPHdrVal contentTypeVal(ocspRequest);
+	headers.SetFieldL(stringPool.StringF(HTTP::EContentType,RHTTPSession::GetTable()), contentTypeVal);
+	CleanupStack::PopAndDestroy(&ocspRequest);
+	}
+
+// From MOCSPTransport
+void COCSPTransportHttp::CancelRequest()
+	{
+	Cancel();
+	}
+
+
+// From MOCSPTransport
+TPtrC8 COCSPTransportHttp::GetResponse() const
+	{
+	__ASSERT_ALWAYS(iResponseData, Panic(KErrNotReady));
+
+	return iResponseData->Des();
+	}
+
+
+// From MHTTPDataSupplier
+TBool COCSPTransportHttp::GetNextDataPart(TPtrC8& aDataPart)
+	{
+	aDataPart.Set(iOCSPRequest);
+	return ETrue;  // This is the last chunk
+	}
+
+
+// From MHTTPDataSupplier
+void COCSPTransportHttp::ReleaseData()
+	{
+	// Nothing to do - from the OCSP side, ownership of the outgoing data is sorted already
+	}
+
+
+// From MHTTPDataSupplier
+TInt COCSPTransportHttp::OverallDataSize()
+	{
+	return iOCSPRequest.Length();
+	}
+
+
+// From MHTTPDataSupplier
+TInt COCSPTransportHttp::Reset()
+	{
+	return KErrNotSupported;
+	}
+
+// From MHTTPTransactionCallback
+void COCSPTransportHttp::MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent)
+	{
+	__ASSERT_ALWAYS(aTransaction == iHTTPTransaction, Panic(KErrArgument));
+
+	// Either ESucceeded or EFailed *will* happen
+	switch (aEvent.iStatus)
+		{
+		case THTTPEvent::EGotResponseHeaders:
+			ProcessHeadersL();
+			break;
+		case THTTPEvent::EGotResponseBodyData:
+			ProcessDataL();
+			break;
+		case THTTPEvent::EResponseComplete:
+			CheckDataCompleteL();
+			break;
+		case THTTPEvent::EFailed:
+			{
+			// Stop the timer
+			iTimer->Cancel();
+			TRequestStatus* reqstatus = &iStatus;
+			if (iServerFound)
+				{
+				User::RequestComplete(reqstatus, OCSP::KErrTransportFailure);
+				}
+			else
+				{
+				User::RequestComplete(reqstatus, OCSP::KErrServerNotFound);
+				}
+			}
+			break;
+		case THTTPEvent::ESucceeded:
+			{
+			// Stop the timer
+			iTimer->Cancel();
+			CheckDataCompleteL();
+			SetIAPL();
+			TRequestStatus* status = &iStatus;
+			User::RequestComplete(status, KErrNone);
+			}
+			break;
+		case KErrTimedOut:
+			// HTTP timed out - this really means it couldn't find the server mentioned in the url
+			// Remember this error so we pass it up correctly when we receive "THTTPEvent::EFailed" event
+			iServerFound = EFalse;
+			break;
+		default:
+			// Some other event (or error).
+			// Do nothing - HTTP module will cause EFailed or ESucceeded to occur
+			break;
+		}
+	}
+	
+void COCSPTransportHttp::SetIAPL()
+	{
+	const RStringPool strPool = iHTTPSession().StringPool();
+	RHTTPConnectionInfo connectionInfo = iHTTPSession().ConnectionInfo();
+	THTTPHdrVal hdrVal;
+	if (connectionInfo.Property(strPool.StringF(HTTP::EHttpSocketConnection, RHTTPSession::GetTable()),
+			hdrVal)) 
+		{
+		RConnection* connection =  reinterpret_cast<RConnection*>(hdrVal.Int());
+		_LIT(KIapId, "IAP\\Id");
+		User::LeaveIfError(connection->GetIntSetting(KIapId, iIap));
+		}	
+	}
+
+
+// From MHTTPTransactionCallback
+TInt COCSPTransportHttp::MHFRunError(TInt aError, RHTTPTransaction aTransaction, const THTTPEvent& /*aEvent*/)
+	{
+	__ASSERT_ALWAYS(aTransaction == iHTTPTransaction, Panic(KErrArgument));
+
+	// Process error (otherwise, we get a panic)
+	AbortTransaction(aError);
+	return KErrNone;
+	}
+
+// Methods from MCallbackTimer
+void COCSPTransportHttp::TimerRun(TInt aError)
+	{
+	if (aError == KErrNone)
+		{
+		// Handle the timeout
+		iHTTPTransaction.Cancel();
+		TRequestStatus* status = &iStatus;
+		User::RequestComplete(status, OCSP::KErrTransportTimeout);
+		}
+	else
+		{
+		// Propagate the error upward
+		TRequestStatus* status = &iStatus;
+		User::RequestComplete(status, aError);
+		}
+	}
+
+// The headers have been received - check them out
+void COCSPTransportHttp::ProcessHeadersL()
+	{
+	RHTTPResponse response = iHTTPTransaction.Response();
+	RHTTPHeaders headers = response.GetHeaderCollection();
+	RStringPool stringPool = iHTTPSession().StringPool();
+
+	// Check content type
+	RStringF ocspResponse = stringPool.OpenFStringL(KOCSPContentTypeResponse);
+	CleanupClosePushL(ocspResponse);
+	RStringF contentTypeString = stringPool.StringF(HTTP::EContentType,RHTTPSession::GetTable());
+	THTTPHdrVal contentTypeVal;
+	TInt error = headers.GetField(contentTypeString, 0, contentTypeVal);
+	if (error != KErrNone 
+		|| contentTypeVal.Type() != THTTPHdrVal::KStrFVal
+		|| contentTypeVal.StrF() != ocspResponse)
+		{
+		User::Leave(OCSP::KErrTransportFailure);
+		}
+	CleanupStack::PopAndDestroy(); // close ocspResponse
+
+	// Check content length - make descriptor ready to recieve data
+	RStringF contentLengthString = stringPool.StringF(HTTP::EContentLength,RHTTPSession::GetTable());
+	THTTPHdrVal contentLengthVal;
+	error = headers.GetField(contentLengthString, 0, contentLengthVal);
+	if (error == KErrNone
+		&& contentLengthVal.Type() == THTTPHdrVal::KTIntVal)
+		{
+		// Make descriptor ready to receive response data
+		__ASSERT_ALWAYS(iResponseData == NULL, Panic(KErrAlreadyExists));
+		iResponseLength = contentLengthVal.Int();
+		iResponseData = HBufC8::NewL(iResponseLength);
+		}
+	else
+		{
+		// No Contents-Length field in headers, or wrong data type
+		User::Leave(OCSP::KErrTransportFailure);
+		}
+	}
+
+void COCSPTransportHttp::ProcessDataL()
+	{
+	if (iResponseData)
+		{
+		// Some data has come in - copy it into our descriptor
+		MHTTPDataSupplier* body = iHTTPTransaction.Response().Body();
+		if (!body)
+			{
+			User::Leave(OCSP::KErrTransportFailure);
+			}
+
+		TPtrC8 dataChunk;
+		TBool finished = body->GetNextDataPart(dataChunk);
+		if (iResponseLength - iResponseData->Length() >= dataChunk.Length())
+			{
+			iResponseData->Des().Append(dataChunk);			
+			body->ReleaseData();
+			}
+		else
+			{
+			// Data is longer than Contents-Length header said it would be - error
+			body->ReleaseData();
+			User::Leave(OCSP::KErrTransportFailure);
+			}
+
+		if (finished)
+			{
+			CheckDataCompleteL();
+			}
+		}		
+	}
+
+void COCSPTransportHttp::CheckDataCompleteL() const
+	{
+	if (iResponseLength != iResponseData->Length())
+		{
+		User::Leave(OCSP::KErrTransportFailure);
+		}
+	}
+
+void COCSPTransportHttp::Complete(TInt aError)
+	{
+	if (iCallBack)
+		{
+		// If something went wrong, remove the dodgy response data
+		if (aError != KErrNone)
+			{
+			delete iResponseData;
+			iResponseData = NULL;
+			}
+
+		// Sets iCallBack back to NULL, so we can only do this once
+		User::RequestComplete(iCallBack, aError);
+		}
+	}
+
+void COCSPTransportHttp::RunL()
+	{
+	User::LeaveIfError(iStatus.Int());
+	switch(iState)
+		{
+	case ETransportConnectingState:
+		iState = ETransportSendRequestState;
+		iStatus = KRequestPending;
+		DoSendRequestL(*iUri, *iRequest);
+		// Start the timer (if enabled)
+		if (iTimeout > KTimeoutDisabledValue)
+			{
+			iTimer->After(iTimeout * KMillSecsToMicroSecs);
+			}
+		SetActive();
+		break;
+
+	case ETransportSendRequestState:
+		// All OK
+		Complete(KErrNone);
+		break;
+	default:
+		User::Leave(KErrNotSupported);
+		break;
+		};
+	}
+
+TInt COCSPTransportHttp::RunError(TInt aError)
+	{
+	// If we failed in the transport connection state, return a
+	// transport error. Otherwise, just propogate the error recieved.
+	if (iState == ETransportConnectingState)
+		{
+		Complete(OCSP::KErrTransportFailure);
+		}
+	else
+		{
+		Complete(aError);
+		}
+	return KErrNone;
+	}
+
+void COCSPTransportHttp::DoCancel()
+	{
+	AbortTransaction(KErrCancel);
+	Complete(KErrCancel);
+	}
+
+void COCSPTransportHttp::AbortTransaction(TInt aError)
+	{
+	switch(iState)
+		{
+		case ETransportConnectingState:
+		iHTTPSession.CancelStart();
+		break;
+
+		case ETransportSendRequestState:
+		iTimer->Cancel();
+		iHTTPTransaction.Cancel();
+
+		//DEF101099 Fix - In a very rare situation after starting invocation of this DoCancel(), the asynchronous request
+		//is getting completed normally. In that case(iStatus!=KRequestPending) no need call this request complete codes,
+		//otherwise which leads to a "Stray Signal" and ending up in a Panic - E32USER-CBase 46.
+		if(iStatus == KRequestPending)
+			{
+			// Thanks to HTTP not exporting a callback for "DoCancel()" we complete the request here
+			TRequestStatus* status = &iStatus;
+			User::RequestComplete(status, aError);
+			}	
+		break;
+		}
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/rom/CTSecurityDialogs.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,34 @@
+/*
+* Copyright (c) 2003-2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   iby file of the CTSecurityDialogs
+*
+*/
+
+
+
+#ifndef __CTSECURITYDIALOGS_IBY
+#define __CTSECURITYDIALOGS_IBY
+#include <bldvariant.hrh>
+
+#ifdef __JAVA_JSR_177_SECURITY_AND_TRUST_SERVICES
+file=ABI_DIR\BUILD_DIR\CTSecDlgs.dll            SHARED_LIB_DIR\CTSecDlgs.dll
+#endif
+
+file=ABI_DIR\BUILD_DIR\CTSecDialogImpl.dll 	SHARED_LIB_DIR\CTSecDialogImpl.dll
+
+ECOM_PLUGIN(CTSECDLGNOTIFIER.dll, 10008D4F.rsc)
+
+#endif // __CTSECURITYDIALOGS_IBY
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/rom/CTSecurityDialogs_resources.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   iby file of the CTSecurityDialogs resources
+*
+*/
+
+
+
+#ifndef __CTSECURITYDIALOGSRESOURCES_IBY
+#define __CTSECURITYDIALOGSRESOURCES_IBY
+
+data=DATAZ_\RESOURCE_FILES_DIR\CTSECDLGS.RSC  RESOURCE_FILES_DIR\CTSECDLGS.RSC
+
+#endif // __CTSECURITYDIALOGSRESOURCES_IBY
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/rom/CertSaver.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef __CERTSAVER_IBY__
+#define __CERTSAVER_IBY__
+
+file=ABI_DIR\BUILD_DIR\CERTSAVER.exe        PROGRAMS_DIR\CERTSAVER.exe
+
+data=ZSYSTEM\..\PRIVATE\10003A3F\APPS\CERTSAVER_reg.rsc Private\10003a3f\apps\CERTSAVER_reg.rsc
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/rom/CertSaver_resources.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,28 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   IBY file for resources of the CertSaver
+*
+*/
+
+
+
+#ifndef CERTSAVERRESOURCES_IBY
+#define CERTSAVERRESOURCES_IBY
+
+S60_APP_RESOURCE(CertSaver)
+S60_APP_CAPTION(CertSaver)
+
+#endif // CERTSAVERRESOURCES_IBY
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/rom/DevToken.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Image description file for DevToken
+*
+*/
+
+
+
+#ifndef __DEVTOKEN_IBY__
+#define __DEVTOKEN_IBY__
+
+#ifdef RD_CLIENT_CERTIFICATES
+
+#include <bldvariant.hrh>
+
+FILE=ABI_DIR\BUILD_DIR\DevTokenClient.DLL	SHARED_LIB_DIR\DevTokenclient.DLL
+FILE=ABI_DIR\BUILD_DIR\DevTokenServer.exe	SHARED_LIB_DIR\DevTokenServer.exe
+FILE=ABI_DIR\BUILD_DIR\DevTokenShared.DLL	SHARED_LIB_DIR\DevTokenShared.DLL
+
+
+ECOM_PLUGIN( DevCertStore.DLL, 101FB667.rsc )
+ECOM_PLUGIN( DevKeyStore.DLL, 101FB669.rsc )
+ECOM_PLUGIN( DevSrvCertStore.DLL, 101FB66E.rsc )
+
+#endif //RD_CLIENT_CERTIFICATES
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/rom/SecModUI.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   iby file of the Security Module UI DLL
+*
+*/
+
+
+
+#ifndef __SECMODUI_IBY__
+#define __SECMODUI_IBY__
+
+
+#ifdef RD_GS_RENOVATION
+  ECOM_PLUGIN( SecModUI.dll,101F8668.rsc )
+#else
+  file=ABI_DIR\BUILD_DIR\SecModUI.dll        SHARED_LIB_DIR\SecModUI.dll
+#endif // RD_GS_RENOVATION
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/rom/SecModUI_resources.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   iby file of the Security Module UI resources
+*
+*/
+
+
+
+#ifndef __SECMODUI_RESOURCES_IBY__
+#define __SECMODUI_RESOURCES_IBY__
+
+//Resource file(s) for SecModUI DLL
+data=DATAZ_\RESOURCE_FILES_DIR\secmodui.rsc  RESOURCE_FILES_DIR\secmodui.rsc
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/rom/StubSIS.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   iby file of stub SIS files
+*
+*/
+
+
+
+
+#ifndef __STUBSIS_IBY__
+#define __STUBSIS_IBY__
+
+#include <bldvariant.hrh>
+
+data=ZSYSTEM\install\CenRepStub.sis    System\Install\CenRepStub.sis
+
+//data = EPOCROOT##epoc32\release\winscw\urel\z\system\data\swipolicy.ini  System\data\swipolicy.ini
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/rom/certman.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,64 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+#ifndef __CERTMAN_IBY__
+#define __CERTMAN_IBY__
+
+// depends upon lower level crypto libraries
+#include <crypto.iby>
+
+#ifdef __INCLUDE_SW_KEYSTORE__
+#include "filetokens.iby"
+#include "asnpkcs.iby"
+#endif
+
+#include "secutil.iby"
+#include "sectcbutil.iby"
+#include "ocspconfig.iby"
+
+REM Certificate management libraries
+
+file=ABI_DIR\BUILD_DIR\asn1.dll		System\Libs\asn1.dll
+file=ABI_DIR\BUILD_DIR\certstore.dll	System\Libs\CertStore.dll
+file=ABI_DIR\BUILD_DIR\crypto.dll	System\Libs\crypto.dll
+file=ABI_DIR\BUILD_DIR\pkixcert.dll	System\Libs\PKIXCert.dll
+file=ABI_DIR\BUILD_DIR\x500.dll		System\Libs\x500.dll
+file=ABI_DIR\BUILD_DIR\x509.dll		System\Libs\x509.dll
+file=ABI_DIR\BUILD_DIR\wtlscert.dll 	System\Libs\wtlscert.dll
+file=ABI_DIR\BUILD_DIR\ocsp.dll		System\Libs\ocsp.dll
+file=ABI_DIR\BUILD_DIR\ctframework.dll		System\Libs\ctframework.dll
+
+file=ABI_DIR\BUILD_DIR\pkixcertbase.dll	System\Libs\PKIXCertBase.dll
+file=ABI_DIR\BUILD_DIR\ocsptransport.dll		System\Libs\ocsptransport.dll
+file=ABI_DIR\BUILD_DIR\ocspcommon.dll			System\Libs\ocspcommon.dll
+file=ABI_DIR\BUILD_DIR\ctfinder.dll		System\Libs\ctfinder.dll
+file=ABI_DIR\BUILD_DIR\swicertstore.dll	System\Libs\swicertstore.dll
+#ifndef __SECURITY_TEST_ROM__
+ECOM_PLUGIN(swicertstoreplugin.dll, 1020430C.rsc)
+#endif
+
+
+REM Add certificate recogniser 
+ECOM_PLUGIN(reccert.dll, 000047EB.rsc)
+
+//Not needed in S60 currently
+//ECOM_PLUGIN(pkcs8recog.dll, 1020361A.rsc)
+
+//REM Certificate management libraries, extra DLL for Cedar builds
+//file=ABI_DIR\BUILD_DIR\pkcs10.dll	System\Libs\pkcs10.dll
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/rom/certmanui.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+#ifndef __CERTMANUI_IBY__
+#define __CERTMANUI_IBY__
+
+#ifdef RD_GS_RENOVATION
+  ECOM_PLUGIN( CertManUi.dll,10008D3D.rsc )
+#else
+  file=ABI_DIR\BUILD_DIR\CERTMANUI.dll        SHARED_LIB_DIR\CERTMANUI.dll
+#endif // RD_GS_RENOVATION
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/rom/certmanui_resources.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,24 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+#ifndef __CERTMANUI_RESOURCES_IBY__
+#define __CERTMANUI_RESOURCES_IBY__
+
+//Resource file(s) for CERTMANUI application
+data=DATAZ_\RESOURCE_FILES_DIR\certmanui.rsc  RESOURCE_FILES_DIR\certmanui.rsc
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/rom/pkcs12.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   iby file of the PKCS12
+*
+*/
+
+
+
+#ifndef __PKCS12_IBY
+#define __PKCS12_IBY
+#include <bldvariant.hrh>
+
+file=ABI_DIR\BUILD_DIR\crber.dll       SHARED_LIB_DIR\crber.dll	
+file=ABI_DIR\BUILD_DIR\crpkcs12.dll    SHARED_LIB_DIR\crpkcs12.dll
+ECOM_PLUGIN(PKCS12Recognizer.dll, 101F8714.rsc)
+
+#endif  // __PKCS12_IBY
+
+//  End of File  
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/rom/x509certnameparser.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,24 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef __X509CERTNAMEPARSER_IBY__
+#define __X509CERTNAMEPARSER_IBY__
+
+file=ABI_DIR\BUILD_DIR\X509CertNameParser.dll       SHARED_LIB_DIR\X509CertNameParser.dll
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/x509certnameparser/BMARM/X509CERTNAMEPARSERU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	IssuerFullNameL__18X509CertNameParserRC16CX509CertificateRP7HBufC16 @ 1 NONAME R3UNUSED ; X509CertNameParser::IssuerFullNameL(CX509Certificate const &, HBufC16 *&)
+	PrimaryAndSecondaryNameL__18X509CertNameParserRC16CX509CertificateRP7HBufC16T2RC7TDesC16 @ 2 NONAME ; X509CertNameParser::PrimaryAndSecondaryNameL(CX509Certificate const &, HBufC16 *&, HBufC16 *&, TDesC16 const &)
+	SubjectFullNameL__18X509CertNameParserRC16CX509CertificateRP7HBufC16RC7TDesC16 @ 3 NONAME R3UNUSED ; X509CertNameParser::SubjectFullNameL(CX509Certificate const &, HBufC16 *&, TDesC16 const &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/x509certnameparser/BWINS/X509CERTNAMEPARSERU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	?IssuerFullNameL@X509CertNameParser@@SAHABVCX509Certificate@@AAPAVHBufC16@@@Z @ 1 NONAME ; public: static int __cdecl X509CertNameParser::IssuerFullNameL(class CX509Certificate const &,class HBufC16 * &)
+	?PrimaryAndSecondaryNameL@X509CertNameParser@@SAHABVCX509Certificate@@AAPAVHBufC16@@1ABVTDesC16@@@Z @ 2 NONAME ; public: static int __cdecl X509CertNameParser::PrimaryAndSecondaryNameL(class CX509Certificate const &,class HBufC16 * &,class HBufC16 * &,class TDesC16 const &)
+	?SubjectFullNameL@X509CertNameParser@@SAHABVCX509Certificate@@AAPAVHBufC16@@ABVTDesC16@@@Z @ 3 NONAME ; public: static int __cdecl X509CertNameParser::SubjectFullNameL(class CX509Certificate const &,class HBufC16 * &,class TDesC16 const &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/x509certnameparser/BWINSCW/X509CERTNAMEPARSERU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	?IssuerFullNameL@X509CertNameParser@@SAHABVCX509Certificate@@AAPAVHBufC16@@@Z @ 1 NONAME ; int X509CertNameParser::IssuerFullNameL(class CX509Certificate const &, class HBufC16 * &)
+	?PrimaryAndSecondaryNameL@X509CertNameParser@@SAHABVCX509Certificate@@AAPAVHBufC16@@1ABVTDesC16@@@Z @ 2 NONAME ; int X509CertNameParser::PrimaryAndSecondaryNameL(class CX509Certificate const &, class HBufC16 * &, class HBufC16 * &, class TDesC16 const &)
+	?SubjectFullNameL@X509CertNameParser@@SAHABVCX509Certificate@@AAPAVHBufC16@@ABVTDesC16@@@Z @ 3 NONAME ; int X509CertNameParser::SubjectFullNameL(class CX509Certificate const &, class HBufC16 * &, class TDesC16 const &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/x509certnameparser/EABI/X509CertNameParserU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	_ZN18X509CertNameParser15IssuerFullNameLERK16CX509CertificateRP7HBufC16 @ 1 NONAME
+	_ZN18X509CertNameParser16SubjectFullNameLERK16CX509CertificateRP7HBufC16RK7TDesC16 @ 2 NONAME
+	_ZN18X509CertNameParser24PrimaryAndSecondaryNameLERK16CX509CertificateRP7HBufC16S5_RK7TDesC16 @ 3 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/x509certnameparser/group/X509CertNameParser.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is project specification file for the X509CertNameParser.
+*               The X509CertNameParser is an algorithm for collecting certificate
+*               information.
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          X509CertNameParser.dll
+TARGETTYPE      dll
+UID             0x1000008d 0x101F857E
+SOURCEPATH      ../src
+SOURCE          ../src/X509CertNameParser.cpp
+USERINCLUDE     . ../inc
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY     euser.lib
+LIBRARY			X500.lib
+LIBRARY			X509.lib
+LIBRARY			bafl.lib
+LIBRARY			InetProtUtil.lib
+
+LANG			SC
+
+CAPABILITY		CAP_GENERAL_DLL
+VENDORID        VID_DEFAULT
+
+#if defined(ARMCC)
+deffile ../EABI/ 
+#elif defined( WINSCW )
+deffile ../BWINSCW/ 
+#elif defined( WINS )
+deffile ../BWINS/ 
+#else
+deffile ../BMARM/ 
+#endif
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/x509certnameparser/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This file provides the information required for
+*               building the whole of a X509 Certificate Name Parser
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT -ARMI
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+../group/X509CertNameParser.mmp
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkiutilities/x509certnameparser/src/X509CertNameParser.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,583 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Extracts relevant certificate information to be shown to user.
+*
+*/
+
+
+// INCLUDE FILES
+#include "X509CertNameParser.h"
+#include <x509cert.h>       //X509Certificate
+#include <x500dn.h>         // CX500DistinguishedName
+#include <pkixcertchain.h>  // OIDS for the extensions
+#include <escapeutils.h>    // for escape decoding
+
+// CONSTANTS
+_LIT (KX509CertParserSpace, " ");
+
+// Max length of array in case of PrimaryAndSecondaryNameL.
+const TInt KX509CNPPrimAndSecondNameLengh( 3 ); 
+
+// ============================ MEMBER FUNCTIONS =============================== 
+                                                                                                                                                               
+// -----------------------------------------------------------------------------
+// X509CertNameParser::PrimaryAndSecondaryNameL
+//
+// -----------------------------------------------------------------------------
+EXPORT_C TInt X509CertNameParser::PrimaryAndSecondaryNameL( 
+                                      const CX509Certificate& aCertificate,
+                                      HBufC*& aPrimaryName, 
+                                      HBufC*& aSecondaryName,
+                                      const TDesC& aLabel)
+    {
+    // Get subjectname
+    const CX500DistinguishedName& dName = aCertificate.SubjectName();
+    // Get subject alternative name
+    const CX509CertExtension* extension = 
+        aCertificate.Extension( KSubjectAltName );
+
+    CDesCArrayFlat* nameArray = new( ELeave ) CDesCArrayFlat(3);
+    CleanupStack::PushL( nameArray );
+    // Append label to array
+    nameArray->AppendL( aLabel );
+    
+    // Get PrimaryName and SecondaryName to nameArray if they exists.
+    GetNamePartsL( dName, extension, *nameArray, EX509CNPPrimAndSecond );
+    
+    // Make sure that these are NULL
+    aPrimaryName = NULL;
+    aSecondaryName = NULL;
+
+    switch ( nameArray->MdcaCount() )
+        {
+        case 1: //Neither PrimaryName nor SecondaryName found
+            {
+            aPrimaryName = HBufC::NewLC( KNullDesC.iTypeLength );
+            *aPrimaryName = KNullDesC;
+            aSecondaryName = HBufC::NewLC( KNullDesC.iTypeLength );
+            *aSecondaryName = KNullDesC;
+            break;
+            }
+        case 2: // Only PrimaryName found
+            {
+            aPrimaryName = HBufC::NewLC(( *nameArray)[1].Length() );
+            *aPrimaryName = ( *nameArray )[1];
+            aSecondaryName = HBufC::NewLC( KNullDesC.iTypeLength );
+            *aSecondaryName = KNullDesC;
+            break;
+            }
+        case 3: // Both found
+            {
+            aPrimaryName = HBufC::NewLC(( *nameArray)[1].Length() );
+            *aPrimaryName = ( *nameArray )[1];
+            aSecondaryName = HBufC::NewLC( ( *nameArray )[2].Length() );
+            *aSecondaryName = ( *nameArray )[2];
+            break;
+            }
+        default: // Something went wrong.
+            {
+            aPrimaryName = HBufC::NewLC( KNullDesC.iTypeLength );
+            *aPrimaryName = KNullDesC;
+            aSecondaryName = HBufC::NewLC( KNullDesC.iTypeLength );
+            *aSecondaryName = KNullDesC;
+            break;
+            }
+        }
+
+    if ( aSecondaryName )
+        {
+        CleanupStack::Pop( aSecondaryName ); // aSecondaryName
+        }
+    if ( aPrimaryName )
+        {
+        CleanupStack::Pop( aPrimaryName ); // aPrimaryName
+        }
+    CleanupStack::PopAndDestroy( nameArray ); //  nameArray
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// X509CertNameParser::SubjectFullNameL
+// 
+// -----------------------------------------------------------------------------
+
+EXPORT_C TInt X509CertNameParser::SubjectFullNameL(
+                                      const CX509Certificate& aCertificate,
+                                      HBufC*& aSubjectName,
+									  const TDesC& aLabel )
+    {
+    // Get subjectname
+    const CX500DistinguishedName& dName = aCertificate.SubjectName();
+    // Get subject alternative name
+    const CX509CertExtension* extension = 
+        aCertificate.Extension( KSubjectAltName );
+    
+    return GetFullNameL( dName, extension, aSubjectName, aLabel );
+    }
+
+// -----------------------------------------------------------------------------
+// X509CertNameParser::IssuerFullNameL
+//  
+// -----------------------------------------------------------------------------
+                                                                                
+EXPORT_C TInt X509CertNameParser::IssuerFullNameL( 
+                                      const CX509Certificate& aCertificate,
+                                      HBufC*& aIssuerName )
+    {
+    // Get issuerName
+    const CX500DistinguishedName& dName = aCertificate.IssuerName();
+    // Get issuer alternative name
+    const CX509CertExtension* extension = 
+        aCertificate.Extension( KIssuerAltName );
+
+    return GetFullNameL( dName, extension, aIssuerName );
+    }
+
+// -----------------------------------------------------------------------------
+// X509CertNameParser::GetFullNameL
+// 
+// -----------------------------------------------------------------------------
+TInt X509CertNameParser::GetFullNameL( 
+                              const CX500DistinguishedName& aDN, 
+                              const CX509CertExtension* aExtension,
+                              HBufC*& aName,
+                              const TDesC& aLabel )
+    {
+    CDesCArrayFlat* nameArray = new( ELeave ) CDesCArrayFlat(3);
+    CleanupStack::PushL( nameArray );
+    // Add label to array. It is used for comparing.
+    nameArray->AppendL( aLabel );
+
+    // Collect name parts to array
+    GetNamePartsL( aDN, aExtension, *nameArray, EX509CNPFullName);
+    
+    // Count length of the aName.
+    TInt length = 0;
+    TInt i = 1; // Pass label
+    for ( ; i < nameArray->MdcaCount(); i++ )
+        { 
+        length += (*nameArray)[i].Length();
+        length += KX509CNPComma.iTypeLength;
+        }
+    
+    // Add elements of the array to aName.
+    // First element is label, so it is passed.
+    aName = HBufC::NewLC( length );
+    for ( i = 1; i < nameArray->MdcaCount(); i++ )
+        {
+        if ( i != 1 )
+            {
+            aName->Des().Append( KX509CNPComma );
+            }
+        aName->Des().Append( (*nameArray)[i] );   
+        }
+
+    CleanupStack::Pop( aName ); 
+    CleanupStack::PopAndDestroy( nameArray ); 
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// X509CertNameParser::GetNamePartsL
+// 
+// -----------------------------------------------------------------------------
+
+TInt X509CertNameParser::GetNamePartsL( 
+                             const CX500DistinguishedName& aDN, 
+                             const CX509CertExtension* aExtension, 
+                             CDesCArray& aNameArray, 
+                             TX509CNPNameType aNameType)
+    {
+    const CX509AltNameExt* altNameExt = NULL;
+    
+    if (aExtension)
+        {
+        altNameExt = CX509AltNameExt::NewLC( aExtension->Data() ); 
+        }
+
+    TBool notFound = ETrue; 
+    
+    // In case of PrimaryAndSecondaryName loop goes through name elements
+    // until two of them is found.
+    // In case of FullNames loop goes through all supported name element and
+    // adds founded names to array.
+    for( TInt round = 1; notFound; round++ )
+        {
+        switch( round )
+            {
+            case EDNCommonName:
+                {
+                GetDNPartL( aDN, KX520CommonName, aNameArray );
+                break;
+                }
+            case ECritAltRFC822Name:
+                {
+                if (aExtension && aExtension->Critical())
+                    {
+                    GetAltNamePartL( *altNameExt, EX509RFC822Name, aNameArray );
+                    }
+                break;
+                }
+            case EDNOrganizationName:
+                {
+                GetDNPartL( aDN, KX520OrganizationName, aNameArray);    
+                break;  
+                }
+            case EDNOrganizationalUnitName:
+                {
+                if ( aNameType == EX509CNPPrimAndSecond )
+                    {
+                    GetDNPartL( aDN, KX520OrganizationalUnitName, aNameArray);    
+                    }
+                else
+                    {
+                    GetDNPartAllL( aDN, KX520OrganizationalUnitName, aNameArray);    
+                    }
+                break;
+                }
+            case ECritAltURI:
+                {
+                if (aExtension && aExtension->Critical())
+                    {
+                    GetAltNamePartL( *altNameExt, EX509URI, aNameArray );
+                    }
+                break;
+                }
+            case ECritAltDNSName:
+                {
+                if (aExtension && aExtension->Critical())
+                    {
+                    GetAltNamePartL( *altNameExt, EX509DNSName, aNameArray);
+                    }
+                break;
+                }
+            case ECritAltDirectoryName:
+                {
+                if (aExtension && aExtension->Critical())
+                    {
+                    GetAltNamePartL( *altNameExt, EX509DirectoryName, 
+                                     aNameArray );                                   
+                    }
+                break;
+                }
+            case ECritAltIPAddress:
+                {
+                if (aExtension && aExtension->Critical())
+                    {
+                    GetAltNamePartL( *altNameExt, EX509IPAddress, 
+                                     aNameArray );                                   
+                    }
+                break;
+                } 
+            case EAltRFC822Name:
+                {
+                if (aExtension)
+                    {
+                    GetAltNamePartL( *altNameExt, EX509RFC822Name, 
+                                      aNameArray );
+                    }
+                break;
+                }
+            case EAltURI:
+                {
+                if ( aExtension )
+                    {
+                    GetAltNamePartL( *altNameExt, EX509URI, aNameArray );
+                    }
+                break;
+                }
+            case EAltDNSName:
+                {
+                if ( aExtension )
+                    {
+                    GetAltNamePartL( *altNameExt, EX509DNSName, aNameArray );
+                    }  
+                break;
+                }
+            case EDNCountryName:
+                {
+                GetDNPartL( aDN, KX520CountryName, aNameArray );
+                break;
+                }
+            case EDNStateOrProvinceName:
+                {
+                GetDNPartL( aDN, KX520StateOrProvinceName, aNameArray );
+                break;
+                }
+            case EDNLocalityName:
+                {
+                GetDNPartL( aDN, KX520LocalityName, aNameArray );
+                break;
+                }
+            case EAltDirectoryName:
+                {
+                if ( aExtension )
+                    {
+                    GetAltNamePartL( *altNameExt, EX509DirectoryName, 
+                                     aNameArray );
+                    }
+                break;
+                }
+            case EAltIPAddress:
+                {
+                if ( aExtension )
+                    {
+                    GetAltNamePartL( *altNameExt, EX509IPAddress, 
+                                     aNameArray );                                   
+                    }
+                break;
+                }    
+            default:
+                {
+                // All the names are gone through.
+                notFound = EFalse;
+                break;
+                }
+            } // switch
+
+        if ( notFound ) 
+            {
+            // If caller is PrimaryAndSecondaryNameL and PrimaryName and
+            // SecondaryName have found then end loop.
+            if ( aNameType == EX509CNPPrimAndSecond &&  
+               ( aNameArray.MdcaCount() >= KX509CNPPrimAndSecondNameLengh ) )
+                {
+                notFound = EFalse;    
+                } // if
+            } // if 
+        } // for
+    
+    if ( aExtension )
+        {
+        CleanupStack::PopAndDestroy(); // altNameExt
+        }
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// X509CertNameParser::GetDNPartAllL
+// 
+// -----------------------------------------------------------------------------
+
+void X509CertNameParser::GetDNPartAllL(
+                             const CX500DistinguishedName& aDN, 
+                             const TDesC& aSubPartOID, 
+                             CDesCArray& aNameArray )
+    {
+    HBufC* buf = NULL;
+    // Count of the name parts of the DN
+    TInt count = aDN.Count();
+
+    // This goes through all the nameparts of the DN and appends all the
+    // parts, that OID is aSubPartOID, to the array.
+	for ( TInt i = 0; i < count; i++ )
+		{
+		const CX520AttributeTypeAndValue& ava = aDN.Element( i );
+		if ( ava.Type() == aSubPartOID )
+			{
+			TRAPD( error, buf = ava.ValueL() );
+            HandleErrorL( error );
+            
+            if ( buf )
+                {
+                CleanupStack::PushL( buf );
+                CompareAndAddNameL( *buf, aNameArray );
+                CleanupStack::PopAndDestroy( buf ); // buf
+                buf = NULL; 
+                } // if 
+            } // if
+        } // for
+    }
+
+// -----------------------------------------------------------------------------
+// X509CertNameParser::GetDNPartL
+// 
+// -----------------------------------------------------------------------------
+
+void X509CertNameParser::GetDNPartL( 
+                             const CX500DistinguishedName& aDN, 
+                             const TDesC& aSubPartOID, 
+                             CDesCArray& aNameArray )
+    {
+    HBufC* buf = NULL;
+    // Extract one DN part
+    TRAPD( error, buf = aDN.ExtractFieldL( aSubPartOID ) );
+    HandleErrorL( error );
+
+    // Add to array
+    if ( buf )
+        {
+        CleanupStack::PushL( buf );
+        CompareAndAddNameL( *buf, aNameArray );
+        CleanupStack::PopAndDestroy( buf );  // buf
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// X509CertNameParser::GetAltNamePartL
+// 
+// -----------------------------------------------------------------------------
+
+void X509CertNameParser::GetAltNamePartL( 
+                             const CX509AltNameExt& aAltName, 
+                             const TGNType& aSubPartType, 
+                             CDesCArray& aNameArray )
+    {
+    // Get all parts of the alternative name to the array
+    const CArrayPtrFlat<CX509GeneralName>& subParts = aAltName.AltName();
+    TInt count = subParts.Count();
+    CX509DomainName* domainName = NULL;
+    TInt error = KErrNone;  
+
+    // This goes through all the nameparts of the DN and appends all the
+    // parts, that OID is aSubPartOID, to the array.
+    for (TInt i = 0; count > i; i++)
+        {
+        if ( subParts[i]->Tag() == aSubPartType )
+            {
+            TPtrC8 data = subParts[i]->Data(); 
+            switch ( aSubPartType )
+                {
+                case EX509RFC822Name:
+                    {
+                    TRAP( error, domainName = CX509RFC822Name::NewL( data ) );
+                    CleanupStack::PushL( domainName );
+                    AddAltNameToArrayL( error, domainName, aNameArray );
+                    CleanupStack::PopAndDestroy( domainName );     
+                    break;
+                    }
+                case EX509DNSName:
+                case EX509DirectoryName:
+                    {
+                    TRAP( error, domainName = CX509DNSName::NewL( data ) );
+                    CleanupStack::PushL( domainName );
+                    AddAltNameToArrayL( error, domainName, aNameArray );
+                    CleanupStack::PopAndDestroy( domainName );
+                    break;
+                    }
+                case EX509URI:
+                    {
+                    CX509IPBasedURI* uri = NULL;
+                    HBufC* decodedUri = NULL;
+                    TRAP( error, uri = CX509IPBasedURI::NewL( data ) );
+                    
+                    if ( error == KErrNone )
+                        {
+                        CleanupStack::PushL( uri );
+                        TRAP( error, decodedUri = EscapeUtils::
+                            EscapeDecodeL( uri->Name() ) );
+                        CleanupStack::PopAndDestroy(); //uri
+                        }
+                    
+                    HandleErrorL( error );
+                    if ( error == KErrNone )
+                        {
+                        CleanupStack::PushL( decodedUri );
+                        CompareAndAddNameL( *decodedUri, aNameArray );
+                        CleanupStack::PopAndDestroy(); // decodedUri
+                        }
+                    break;
+                    }
+                case EX509IPAddress:
+                    {
+                    // Not supported
+                    break;
+                    }
+                default:
+                    {
+                    break;
+                    }
+                } // switch
+            } // if 
+        } // for
+    }
+
+// -----------------------------------------------------------------------------
+// X509CertNameParser::AddAltNameToArrayL
+// 
+// -----------------------------------------------------------------------------
+
+TInt X509CertNameParser::AddAltNameToArrayL( 
+                            TInt aError, 
+                            CX509DomainName* aDomainName, 
+                            CDesCArray& aNameArray )
+    {
+    TInt error = HandleErrorL( aError );
+    
+    if ( error == KErrNone )
+        {
+        const TPtrC name = aDomainName->Name();
+        CompareAndAddNameL( name, aNameArray );
+        }
+
+    return error;
+    }
+
+// -----------------------------------------------------------------------------
+// X509CertNameParser::AddToBufLD
+// 
+// -----------------------------------------------------------------------------
+
+void X509CertNameParser::AddToBufLD( const TDesC& aName, HBufC*& aBuf )
+    {
+    if (!aBuf)
+        {
+        aBuf = HBufC::NewL( aName.Length() );
+        aBuf->Des().Append( aName );
+        }
+    else
+        {
+        HBufC* helpBuf = HBufC::NewL( aName.Length() + aBuf->Length() + 1);
+        helpBuf->Des().Append( *aBuf );
+        helpBuf->Des().Append( KX509CertParserSpace );
+        helpBuf->Des().Append( aName );
+        CleanupStack::PopAndDestroy( aBuf ); // aBuf
+        aBuf = helpBuf;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// X509CertNameParser::CompareAndAddNameL
+// 
+// -----------------------------------------------------------------------------
+
+void X509CertNameParser::CompareAndAddNameL( const TDesC& aProposal, 
+                                             CDesCArray& aNameArray )
+    {
+    TInt pos = 0; // This is needed only for calling Find().
+    // Append to array, if aProposal don't already exist in the array.
+    if ( aNameArray.Find( aProposal, pos, ECmpNormal ) )
+        {
+        aNameArray.AppendL( aProposal );
+        }
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// X509CertNameParser::HandleErrorL
+// 
+// -----------------------------------------------------------------------------
+
+TInt X509CertNameParser::HandleErrorL( TInt aError )
+    {    
+    if ( !( aError == KErrNone || aError == KErrArgument || aError == KErrNotSupported ) )
+        {
+        User::Leave( aError );
+        }       
+    return aError;
+    }
+    
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/CenRep/RemoteLockPrivateCRKeys.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Private CenRep keys header file
+*
+*/
+
+
+#ifndef REMOTELOCKPRIVATECRKEYS_H
+#define REMOTELOCKPRIVATECRKEYS_H
+
+const TUid KCRUidRemoteLock = {0x101FB654};
+
+const TUint32 KRLLockCode = 0x00000001;
+const TUint32 KRLLockCode2 = 0x00000002;
+const TUint32 KRLEnable = 0x00000003;
+
+#endif      // REMOTELOCKPRIVATECRKEYS_H
+
Binary file remotelock/CenRep/keys_remotelock.xls has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/Data/RemoteLock.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource definitions for Remotelock
+*
+*/
+
+CHARACTER_SET UTF8 
+//  RESOURCE IDENTIFIER
+
+//  NAME RLOC
+
+//  INCLUDES
+#include <remotelock.loc>
+
+//  CONSTANTS  
+
+//  MACROS  
+
+//  RESOURCE DEFINITIONS 
+STRUCT TBUF
+    {
+    BUF buf; // non-zero terminated text string
+    }
+
+RESOURCE TBUF R_RLOC_TI_EVERYTHING_LOCKED {buf = qtn_rloc_ti_everything_locked; }
+RESOURCE TBUF R_RLOC_TI_PHONE_LOCKED {buf = qtn_rloc_ti_phone_locked; }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/Group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file for RemoteLock
+*
+*/
+
+#ifdef RD_REMOTELOCK
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+//Configuration tool migration
+../conf/remotelock.confml            MW_LAYER_CONFML(remotelock.confml)
+../conf/remotelock_101FB654.crml 	   MW_LAYER_CRML(remotelock_101FB654.crml)
+
+../loc/remotelock.loc MW_LAYER_LOC_EXPORT_PATH(remotelock.loc)
+
+../Rom/RemoteLock.iby CORE_MW_LAYER_IBY_EXPORT_PATH( RemoteLock.iby )
+../Rom/RemoteLockResources.iby LANGUAGE_MW_LAYER_IBY_EXPORT_PATH( RemoteLockResources.iby )
+
+PRJ_MMPFILES
+../RemotelockSettings/Group/RemoteLockSettings.mmp
+../RemoteLockEngine/Group/RemoteLockEngine.mmp
+#endif //RD_RMOTELOCK
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/Inc/RemoteLockTrace.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Print debug log 
+*
+*/
+
+
+#ifndef	REMOTELOCKTRACE_H
+#define	REMOTELOCKTRACE_H
+
+#include <e32base.h>
+
+//#define RL_TRACE
+
+#ifdef RL_TRACE
+#include <e32svr.h>
+#define RL_TRACE_PRINT( aText ) { RDebug::Print( _L(aText) ); }
+#define RL_TRACE_PRINT_NUM( aText, aNum ) \
+		{ RDebug::Print( _L(aText), aNum ); }
+#else
+#define RL_TRACE_PRINT( aText )
+#define RL_TRACE_PRINT_NUM( aText, aNum ) 
+#endif
+
+#endif	
+//EOF
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/RemoteLockEngine/Group/RemoteLockEngine.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file for RemoteLock
+*
+*/
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET              RLock.exe
+TARGETTYPE          exe
+UID                 0x00000000 0x101FB653
+
+VENDORID            VID_DEFAULT
+CAPABILITY          CAP_APPLICATION DiskAdmin
+
+USERINCLUDE         ../Inc
+USERINCLUDE         ../../Inc
+APP_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH          ../Src
+SOURCE              RemoteLock.cpp
+SOURCE              RLLockObserver.cpp
+
+
+START RESOURCE      ../../Data/RemoteLock.rss
+HEADER
+TARGETPATH          APP_RESOURCE_DIR
+LANGUAGE_IDS
+END
+
+LIBRARY             euser.lib 
+LIBRARY             msgs.lib 
+LIBRARY             RLockSettings.lib
+LIBRARY             efsrv.lib       
+LIBRARY             smcm.lib
+LIBRARY             gsmu.lib 
+LIBRARY             bafl.lib 
+LIBRARY             platformEnv.lib
+LIBRARY             charconv.lib
+LIBRARY             centralrepository.lib
+LIBRARY             CenRepNotifHandler.lib
+LIBRARY             CommonEngine.lib
+
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/RemoteLockEngine/Inc/RLLockObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,111 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  The header file of unlocking event observer
+*
+*/
+
+
+#ifndef     RLLOCKOBSERVER_H
+#define     RLLOCKOBSERVER_H
+
+#include    <e32base.h>
+#include    <e32property.h>
+
+// CONSTANTS 
+
+// MACROS 
+
+// FORWARD DECLARATIONS 
+class MRLLockObserverHandler;
+
+// LOCAL FUNCTION PROTOTYPES 
+
+// MEMBER FUNCTIONS 
+
+
+// CLASS DECLARATION
+/**
+* Observe the unlocking event
+*
+* @since S60 3.2
+*/
+class CRLLockObserver: public CActive
+    {
+    public:
+       /**
+        * Two-Phased constructor
+        *
+        * @since S60 3.2
+        * @param aHandler Client implemented observer handler that will be
+        *                 called when phone are unlocked. 
+        * @return
+        */
+        static CRLLockObserver* NewL( MRLLockObserverHandler* aHandler );
+    
+        ~CRLLockObserver();    
+    
+    private:
+    
+        /**
+        * Starts asynchronic listening 
+        * KCoreAppUIsAutolockStatus/
+        * KPSUidAutolockStatusValue event
+        *
+        * @Since S60 3.2
+        * @return KErrNone: if no errors
+        *         KErrInUse: if already listening
+        */
+        TInt Start();            
+    
+    private: 
+
+        CRLLockObserver( MRLLockObserverHandler* aHandler );
+        
+        void ConstructL();
+        
+    private: // from CActive
+         
+        void RunL();
+    
+        void DoCancel();
+        
+    private: // data
+    
+        RProperty                iProperty;
+        MRLLockObserverHandler*  iHandler; //not owned
+    };
+
+// CLASS DECLARATION
+
+/**
+* Abstract interface class declares a callback function for 
+* remotelock observer to call when the phone is unlocked. User
+* derives his class from this and implements HandleUnlockEvent().
+*
+* @since S60 3.2
+*/
+class MRLLockObserverHandler 
+    {
+    public:
+    
+    /**
+    * The function is called when the phone is unlocked.
+    *
+    * @since S60 3.2
+    */
+    virtual void HandleUnlockEvent() = 0;
+    };
+
+#endif //RLLOCKOBSERVER_H
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/RemoteLockEngine/Inc/RemoteLock.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,340 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  The main header file of RemoteLock Engine
+*
+*/
+
+
+
+#ifndef REMOTELOCK_H
+#define REMOTELOCK_H
+
+// INCLUDE FILES 
+#include <msvapi.h>
+#include <RemoteLockSettings.h>
+#include <cenrepnotifyhandler.h>   
+#include <centralrepository.h>
+#include "RLLockObserver.h"
+
+// CONSTANTS 
+
+// MACROS 
+
+// FORWARD DECLARATIONS 
+class CClientMtmRegistry;
+
+// LOCAL FUNCTION PROTOTYPES 
+LOCAL_C TInt ThreadStartL();
+
+// MEMBER FUNCTIONS 
+
+// CLASS DECLARATION
+/**
+* Main class for remote lock program
+* 
+* @lib 
+* @since S60 3.2
+*/
+class CRemoteLock : public CTimer,
+                    public MMsvSessionObserver,
+                    public MRemoteLockSettingsHandler,
+                    public MRLLockObserverHandler,
+                    public MCenRepNotifyHandlerCallback
+    {
+    public:
+        /**
+        * Two-Phased constructor
+        */
+        static CRemoteLock* NewL();  
+        
+        /**
+        * Destructor.
+        */ 
+        virtual ~CRemoteLock();   
+         
+        // from base class MMsvSessionObserver 
+
+        /**
+        * From MMsvSessionObserver 
+        * Session observer 
+        *
+        * @param aEvent EMsvEntriesCreated when new sms arrives, 
+        *  EMsvServerReady while MSV server is ready,
+        *  EMsvServerFailedToStart while server is failed to start
+        *  EMsvCloseSession while session is closed
+        *  EMsvServerTerminated while server is terminated.
+        * @param aArg1 A CMsvEntrySelection of the new entries. 
+        * @param aArg2 The TMsvId of the parent entry 
+        * @param aArg3 Event type-specific argument value 
+        * @return
+        */
+        void HandleSessionEventL( 
+            TMsvSessionEvent aEvent, 
+            TAny* aArg1, 
+            TAny* aArg2, 
+            TAny* aArg3  );
+       
+        /**
+        * Remote Lock Settings notify handler called
+        * when remote lock settings are changed by client.
+        *
+        * @param 
+        * @return
+        */
+        void HandleRemoteLockNotifyL();
+        
+        
+    public: // from MRLLockObserverHandler
+        
+        void HandleUnlockEvent(); 
+
+    private:
+    
+        CRemoteLock();
+
+        void ConstructL();  
+        
+        /**
+        * Handles remote lock message.
+        *
+        * @param aEntry Message entry to be handled. 
+        * @return       
+        */
+        void HandleMessageL( CMsvEntry* aEntry );
+        
+        /**
+        * Compares lock code from SMS against correct lock code. 
+        * If the lock code is correct, lock the phone.
+        *
+        * @param
+        * @return ETrue when remotelock is correct.
+        *         EFalse remotelock is not correct.
+        */
+        TBool VerifyAndLockL();
+
+        /**
+        * Check the remote lock settings.
+        *
+        * @param
+        * @return
+        */
+        void CheckSettingsL();
+
+        /**
+        * Check whether memory card is locked or not.
+        *
+        * @param  aDriveInfo Drive information
+        * @return ETrue if memory card is locked, 
+        *         EFalse if memory card isn't locked.
+        */
+        TBool IsMemoryCardLocked( const TDriveInfo& aDriveInfo ) const;
+        
+        /**
+        * Check whether memory card has password or not.
+        *
+        * @param  aDriveInfo Drive information
+        * @return ETrue if memory card has password, 
+        *         EFalse if memory card doesn't have password.
+        */
+        TBool HasMemoryCardPassword( const TDriveInfo& aDriveInfo ) const;
+        
+        /**
+        * Check whether memory card is present or not.
+        *
+        * @param  aDriveInfo Drive information
+        * @return ETrue memory card is in the phone, 
+        *         EFalse memory card is not in the phone.
+        */
+        TBool IsMemoryCardPresent( const TDriveInfo& aDriveInfo ) const;
+        
+        /**
+        * Sets the password to memory card, if the memory card is mounted into the phone
+        * and memory card doesn't have password or not locked
+        *
+        * @param  aClear if ETrue, then remove the password
+        * @return ETrue if memory card is locked or password removed,
+        *         EFalse memory card is not locked.  
+        */
+        TBool SetMemoryCardPasswdL( const TBool aClear ); 
+
+        /**
+        * Converts memory card password format
+        *
+        * @param aPassword Password that needs to be converted
+        *        aClear if ETrue, then remove the password
+        * @return
+        */
+        void ConvertMemoryCardPassword( TMediaPassword& aPassword, const TBool aClear );
+         
+        /**
+        * Initialize a new reply message when phone is on lock status.
+        *
+        * @param
+        * @return ETrue if initialize is succeed,
+        *         EFalse inistialize is failed.
+        */
+        TBool InitialSendMessageL();
+
+        /**
+        * Creates a new message server entry and set up default values.
+        *
+        * @param
+        * @return TMsvId a Id of operational progress entry.
+        */
+        TMsvId CreateNewMessageL();
+                
+        /**
+        * Set up current message entry.
+        *
+        * @param aEntryId Entry Id of message.
+        * @return
+        */
+        void SetEntryL( TMsvId aEntryId );
+                
+        /**
+        * Moves an entry to another parent entry.
+        *
+        * @param aEntryId Entry Id of target.
+        * @return TMsvId a message entry
+        */
+        TMsvId MoveMessageEntryL( TMsvId aTarget );
+        
+        /**
+        * Reply SMS when the terminal or memory card is successfully locked.
+        *
+        * @param aRecipientAddress the phone number which is used to send Lock
+        *                          sms
+        * @return ETrue if message is successfully sent,
+        *         EFalse message is not sent.  
+        */
+        TBool SendMessageL( const TDesC& aRecipientAddress );
+        
+        /**
+        * Schedules the message to be immediately sent through the message server.
+        *
+        * @param aSelection A point contains TMsvId
+        * @return       
+        */
+        void SetScheduledSendingStateL( CMsvEntrySelection* aSelection );
+        
+        /**
+        * Try to re-connect message server every 10 seconds after 
+        * it is shut down or terminated.
+        *
+        * @param 
+        * @return       
+        */
+        void RunL();
+        
+        /**
+        * Checks if there are any unicode characters in the message
+        *
+        * @param TDesC& a reference to a string to be checked
+        * @return TBool indicates whether we have unicode chars or not
+        */
+        TBool NeedsToBeSentAsUnicodeL( const TDesC& aInputString ) const;
+        
+        /**
+        * Active the device lock to lock the phone
+        */
+        TBool ActivateDeviceLock();
+
+        
+        /**
+        * Get the current profile 
+        *
+        * @param    aProfile profile id
+        * @return   ETrue if succeeded
+        *           EFalse otherwise
+        */
+        TBool GetProfile( TInt& aProfile );
+        
+        /**
+        * Setup Profile notifier
+        *
+        * @param aNotifyEnable enable or disable notifier
+        * @return    ETrue
+        *            EFalse
+        */
+        TBool ProfileNotifyL( const TBool aNotifyEnable ); 
+        
+        
+        /**
+        * Call back function of Central Repository
+        * from MCenRepNotifyHandlerCallback
+        */
+        void HandleNotifyGeneric( TUint32 aId );
+
+        
+        /**
+        * Do Sets the password to memory card, if the memory card is mounted into the phone
+        * and memory card doesn't have password or not locked
+        *
+        * @param  aClear if ETrue, then remove the password
+        * @return ETrue if memory card is locked or password removed,
+        *         EFalse memory card is not locked.  
+        */
+        TBool DoSetMemoryCardPasswdL( TBool aClear );
+        
+    private: // Data       
+        // Remote lock code from SMS.
+        HBufC* iRemoteLockCode;
+        
+        // memory card password buffer having the same
+        // content with iRemoteLockCode buffer 
+        HBufC* iMemoryCardPasswd;
+        
+        // Correct remote lock code digest.
+        HBufC* iStoredCode;
+        
+        // Correct remote lock code digest (spaces trimmed).
+        HBufC* iStoredTrimmedCode;
+
+        // If remote lock is enabled or not.
+        TBool iIsEnabled; 
+        
+        // The lock state of memory card
+        TBool iStateMemoryCard;
+        
+        CRemoteLockSettings* iRemoteLockSetting;       
+
+        CMsvSession* iMsvSession;        
+
+        CBaseMtm* iClientMtmForSending;       
+
+        CClientMtmRegistry* iMtmReg;  
+        
+        //Indicate if the phone is locked by remote lock
+        TBool iLockedByRL;   
+        
+        //Indicate if the memory card is locked by remote lock
+        TBool iMemoryCardLockedByRL;
+        
+        //Device lock observer 
+        CRLLockObserver* iObserver;
+        
+        CRepository*  iProfileSession;
+        
+        CCenRepNotifyHandler*  iProfileNotifyHandler;  
+        
+        //Boolean used to indicate whether we have subscribed profile 
+        //changes in CenRep or not, default value is EFalse; 
+        TBool iSubscribeProfile;
+        
+        //Current profile
+        TInt iCurrentProfile;
+             
+    };        
+
+#endif 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/RemoteLockEngine/Src/RLLockObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,137 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of Unlocking event observer
+*
+*/
+
+#include    <PSVariables.h>
+#include    <coreapplicationuisdomainpskeys.h>
+#include    "RLLockObserver.h"	
+#include    "RemoteLockTrace.h"
+
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CRLLockObserver::NewL()
+// Constructs a new entry with given values.
+// ----------------------------------------------------------
+//
+CRLLockObserver* CRLLockObserver::NewL( MRLLockObserverHandler* aHandler )
+    {
+    CRLLockObserver* self = new (ELeave) CRLLockObserver( aHandler );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+//
+// ----------------------------------------------------------
+// CRLLockObserver::CRLLockObserver()
+// Destructor
+// ----------------------------------------------------------
+//
+CRLLockObserver::~CRLLockObserver()
+    {
+    Cancel();
+    }
+//
+// ----------------------------------------------------------
+// CRLLockObserver::Start()
+// Starts listening KCoreAppUIsAutolockStatus/
+// KPSUidAutolockStatusValue event 
+// ----------------------------------------------------------
+//
+TInt CRLLockObserver::Start()
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] CLockObserver::Start() "); 
+    
+    if (IsActive())
+        {
+        return KErrInUse;
+        }   
+        
+    iStatus = KRequestPending;
+    
+    #ifndef RD_STARTUP_CHANGE   
+    iProperty.Attach( KUidSystemCategory, KPSUidAutolockStatusValue ); 
+    #else //RD_STARTUP_CHANGE
+    iProperty.Attach( KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus ); 
+    #endif //RD_STARTUP_CHANGE    
+    iProperty.Subscribe(iStatus);
+    
+    SetActive();
+    return KErrNone;
+    }
+//
+// ----------------------------------------------------------
+// CRLLockObserver::CRLLockObserver()
+// C++ constructor
+// ----------------------------------------------------------
+// 
+CRLLockObserver::CRLLockObserver( MRLLockObserverHandler* aHandler ) 
+    : CActive(0), iHandler( aHandler )
+    {                            
+    }
+//
+// ----------------------------------------------------------
+// CRLLockObserver::ConstructL()
+// ----------------------------------------------------------
+// 
+void CRLLockObserver::ConstructL()
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] CLockObserver::ConstructL() ");
+    // Add this active object to the scheduler.
+    CActiveScheduler::Add(this);
+    //Start listenning
+    Start();
+    }
+//
+// ----------------------------------------------------------
+// CRLLockObserver::RunL()
+// Called when device (autolock) is activated from menu.
+// ----------------------------------------------------------
+// 
+void CRLLockObserver::RunL()
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] CLockObserver::RunL() ");
+
+    TInt autolockState;
+    iProperty.Get( autolockState );
+    
+    #ifndef RD_STARTUP_CHANGE
+    if (autolockState == EPSAutolockOff )
+    #else //RD_STARTUP_CHANGE
+    if (autolockState == EAutolockOff )
+    #endif //RD_STARTUP_CHANGE
+        {
+        RL_TRACE_PRINT(" [ rl.exe ] CLockObserver::RunL remove Memory card Password ");
+        iHandler->HandleUnlockEvent();
+        } 
+    Start();
+    }
+//
+// ----------------------------------------------------------
+// CRLLockObserver::DoCancel()
+// Cancels event listening
+// ----------------------------------------------------------
+// 
+void CRLLockObserver::DoCancel()
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] CLockObserver::DoCancel() ");
+    iProperty.Cancel();
+    }
+    
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/RemoteLockEngine/Src/RemoteLock.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1519 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of RemoteLock Engine
+*
+*/
+
+
+// INCLUDE FILES 
+#include <smscmds.h>
+#include <smutset.h>
+#include <smuthdr.h>
+#include <e32property.h>
+#include <PSVariables.h>
+#include <mtclreg.h> //CClientMtmRegistry
+#include <smsclnt.h> //CSmsClientMtm
+#include <txtrich.h>
+#include <bautils.h> //file system utilities
+#include <remotelock.rsg>
+#ifdef RD_MULTIPLE_DRIVE 
+#include <driveinfo.h>
+#else
+#include <pathinfo.h> 
+#endif //RD_MULTIPLE_DRIVE 
+#include <coreapplicationuisdomainpskeys.h>
+#include <charconv.h>
+#include <ProfileEngineSDKCRKeys.h>
+#include <Profile.hrh>
+#include <stringresourcereader.h> //CStringResourceReader
+#include "RemoteLockTrace.h"
+#include "RemoteLock.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+_LIT( KRLockResourceFileName ,"z:\\Resource\\apps\\Remotelock.RSC" );
+
+//Interval of reconnecting to the message server 
+const TInt KRLockTimerInterval( 10000000 ); 
+const TInt KRLockMaxMemoryCardPasswdLength( 8 );
+const TInt KBufLengthInUnicodeCheck = 200;
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ---------------------------------------------------------------------------
+// E32Main()
+// ---------------------------------------------------------------------------
+//
+GLDEF_C TInt E32Main() 
+    {    
+    __UHEAP_MARK;
+    if ( User::TrapHandler() != NULL )
+        {
+        User::SetTrapHandler( NULL );
+        }
+        
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+    if ( !cleanup )
+        {
+        return KErrNone;
+        }
+
+    TRAPD( err, ThreadStartL() );
+    ( void ) err;
+    
+    delete cleanup;
+    __UHEAP_MARKEND;
+
+    return err;    
+    }
+
+
+// ---------------------------------------------------------------------------
+// ThreadStartL()
+// ---------------------------------------------------------------------------
+//
+LOCAL_C TInt ThreadStartL()
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] Inside ThreadStartL() "); 
+    CActiveScheduler *threadScheduler = new CActiveScheduler;
+    
+    CleanupStack::PushL( threadScheduler );
+    
+    CActiveScheduler::Install( threadScheduler );
+    
+    RL_TRACE_PRINT(" [ rl.exe ] Create remotelock object "); 
+
+    CRemoteLock* remoteLock = CRemoteLock::NewL();
+    
+    RL_TRACE_PRINT(" [ rl.exe ] Creation of Remotelock is done" );
+    
+    CleanupStack::PushL( remoteLock );
+        
+    RL_TRACE_PRINT(" Doing Rendezvous..."); 
+    // Initialisation complete, now signal the client
+    RProcess::Rendezvous(KErrNone);            
+
+    CActiveScheduler::Start();
+    
+    CleanupStack::PopAndDestroy( 2 );
+    
+    return KErrNone;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::NewL
+// Two-Phased constructor.
+// ---------------------------------------------------------------------------
+//
+CRemoteLock* CRemoteLock::NewL()
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] NewL()");
+    
+    CRemoteLock* self = new ( ELeave ) CRemoteLock;
+    
+    CleanupStack::PushL( self );
+    
+    self->ConstructL();  
+    
+    CleanupStack::Pop();
+    
+    RL_TRACE_PRINT(" [ rl.exe ] exit NewL() ");
+    
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+CRemoteLock::~CRemoteLock()
+    {
+    Cancel();
+    delete iRemoteLockSetting;
+    delete iRemoteLockCode;
+    delete iMemoryCardPasswd;
+    delete iStoredCode;
+    delete iStoredTrimmedCode;
+    delete iClientMtmForSending;
+    delete iMtmReg;
+    delete iMsvSession;
+    delete iObserver;
+    
+    if ( iProfileNotifyHandler ) 
+        {
+      iProfileNotifyHandler->StopListening();
+      delete iProfileNotifyHandler;
+        }
+    delete iProfileSession; 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::HandleSessionEventL
+//
+// Called by message server when new event occures.
+// ---------------------------------------------------------------------------
+//
+void CRemoteLock::HandleSessionEventL( 
+    TMsvSessionEvent aEvent, 
+    TAny* aArg1, 
+    TAny* aArg2, 
+    TAny* /*aArg3*/  )
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] HandleSessionEventL() ");  
+    switch ( aEvent )
+        {            
+        // A new entry has been created in the message server
+        case EMsvEntriesCreated: 
+            {
+            RL_TRACE_PRINT(" [ rl.exe ] HandleSessionEventL() 1");  
+            if ( !iIsEnabled )
+                {
+                // Do nothing if remote lock is disabled
+                return;
+                }
+            
+            if ( *( static_cast<TMsvId*>( aArg2 ) ) != 
+                KMsvGlobalInBoxIndexEntryId )
+                {
+                // Doing nothing if not to inbox
+                return;
+                }
+
+            CMsvEntrySelection* entries =
+                static_cast<CMsvEntrySelection*>( aArg1 );
+
+            for ( TInt i = 0; i < entries->Count(); i++ )
+                {
+                TMsvEntry entryInfo;
+                TMsvId serviceId;
+                iMsvSession->GetEntry( entries->At( i ), serviceId, entryInfo );
+
+                if ( entryInfo.iMtm != KUidMsgTypeSMS || 
+                    entryInfo.iDescription.Length() > KRLockMaxLockCodeLength || 
+                    entryInfo.iDescription.Length() == 0)
+                    {
+                    // Doing nothing if not a SMS, or length not appropriate.
+                    return;
+                    }
+
+                // For performance reasons, lets first compare the content of 
+                // the SMS (taken from the TMsvEntry, containing no extra 
+                // spaces) against the saved digest of a trimmed remote lock 
+                // code. This way unnecessary access to CMsvEntry is avoided 
+                // if these two do not match.
+                
+                
+                if ( iRemoteLockSetting->CompareLockCodesL( 
+                    entryInfo.iDescription, *iStoredTrimmedCode ) )
+                    {
+                    CMsvEntry* entry = 
+                        iMsvSession->GetEntryL( entries->At( i ) );
+                
+                    // The CMsvEntry object must be deleted by the client
+                    // when it is no longer required. 
+                    CleanupStack::PushL( entry );
+
+                    TRAPD( error, HandleMessageL( entry ) );
+
+                    CleanupStack::PopAndDestroy( 1 ); // entry
+                    
+                    delete iRemoteLockCode;
+                    iRemoteLockCode = NULL;
+                    
+                    User::LeaveIfError( error );
+                    } // if
+                } // for
+            break;
+            } // case
+      
+        // When message server is closed and server terminated
+        case EMsvCloseSession:
+        case EMsvServerFailedToStart:
+        case EMsvServerTerminated:
+            {
+            RL_TRACE_PRINT(" [ rl.exe ] HandleSessionEventL() 2");  
+            // When server is terminated remote lock will
+            // try to reconnect it in every 10 seconds.
+            After( KRLockTimerInterval );
+            break;
+            }
+
+        default:
+            break;
+        }
+    RL_TRACE_PRINT(" [ rl.exe ] exit HandleSessionEventL() ");
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::HandleRemoteLockNotifyL
+// Function is called when remote lock setting is changed by client
+// ---------------------------------------------------------------------------
+//
+void CRemoteLock::HandleRemoteLockNotifyL()
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] HandleNotify() ");
+    CheckSettingsL();
+    RL_TRACE_PRINT(" [ rl.exe ] exit HandleNotify() ")
+    }
+    
+    
+// ---------------------------------------------------------------------------
+// CRemoteLock::CRemoteLock
+// default constructor
+// ---------------------------------------------------------------------------
+CRemoteLock::CRemoteLock() : CTimer( CActive::EPriorityStandard )
+    {
+    iRemoteLockCode = NULL;
+    iMemoryCardPasswd = NULL;
+    iStoredCode = NULL;
+    iStoredTrimmedCode = NULL;
+    iClientMtmForSending = NULL;
+    iMtmReg = NULL;
+    iRemoteLockSetting = NULL;
+    iMsvSession = NULL;
+    iIsEnabled = EFalse;
+    iLockedByRL = EFalse; 
+    iMemoryCardLockedByRL = EFalse;
+    iSubscribeProfile = EFalse;
+    iProfileSession = NULL;
+    iObserver = NULL;
+    iProfileNotifyHandler = NULL;   
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::ConstructL
+// Symbian 2nd phase constructor can leave.
+// ---------------------------------------------------------------------------
+//
+void CRemoteLock::ConstructL()
+    {    
+    RL_TRACE_PRINT(" [ Rl.exe ] ConstructL()"); 
+    
+    CTimer::ConstructL();
+    
+    iRemoteLockSetting = CRemoteLockSettings::NewL( this ); 
+     
+    iRemoteLockSetting->RemoteLockNotifyL( ETrue );
+    
+    CheckSettingsL(); 
+    // Add active object into active scheduler
+    CActiveScheduler::Add( this );
+        
+    
+    
+    RL_TRACE_PRINT(" [ rl.exe ] exit ConstructL() ");
+    }
+    
+    
+// ---------------------------------------------------------------------------
+// CRemoteLock::HandleMessageL()
+//
+// Handles the message: checks if it really is remote lock message, and acts
+// accordingly.
+// ---------------------------------------------------------------------------
+//
+void CRemoteLock::HandleMessageL( CMsvEntry* aEntry )
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] HandleMessageL() ");
+    delete iRemoteLockCode;
+    iRemoteLockCode = NULL;
+    TMsvEntry entryInfo = aEntry->Entry();
+    if ( !iMtmReg )
+        {
+        iMtmReg = CClientMtmRegistry::NewL( *iMsvSession );
+        }
+
+    // Loops 100 times to ensure the clientMtm is correctly created
+    CBaseMtm* clientMtm = NULL;
+    TInt error = 0;
+    TInt i;
+    for ( i = 0; i < 100; i++ )
+        {
+        TRAP( error, clientMtm = iMtmReg->NewMtmL( entryInfo.iMtm ));
+        if ( error == KErrNone )
+            {
+            break;
+            }
+        } 
+   
+    RL_TRACE_PRINT_NUM("[rl.exe] HandleMessageL() error after NewMTmL = %d", error );
+
+    User::LeaveIfError( error );
+    CleanupStack::PushL( clientMtm );        
+
+    clientMtm->SwitchCurrentEntryL( entryInfo.Id() );
+
+    RL_TRACE_PRINT(" [ rl.exe ] HandleMessageL() after switch Current EntryL");
+   
+    CSmsClientMtm* smsClientMTM = STATIC_CAST( CSmsClientMtm*, clientMtm );
+    
+    // Change from 100 to 20. When the message storage is memory card. 
+    // LoadMessageL() function return -21 when loading the message.
+    // It might be caused by slow operation, so we add 0.05 seconds pending 
+    // in each loop.
+    // @ check why loading operation is slow!
+    for ( i = 0; i < 20; i++ )
+        {   
+        RL_TRACE_PRINT_NUM("[rl.exe] HandleMessageL() error load message1 = %d", error );
+        
+        // Loops 100 times to ensure the LoadMessageL() succeedes
+        TRAP( error, smsClientMTM->LoadMessageL() );
+        
+        RL_TRACE_PRINT_NUM("[rl.exe] HandleMessageL() error load message2 = %d", error );
+        
+        if ( error == KErrNone )
+            {
+            break;
+            }
+        
+        const TInt KDelay = 50000; // 0.05s
+        User::After( KDelay );
+        }
+    
+    RL_TRACE_PRINT_NUM("[rl.exe] HandleMessageL() error after LoadMessageL = %d", error );
+    
+    User::LeaveIfError( error );        
+
+    CRichText& mtmBody = smsClientMTM->Body();                            
+    
+    // Let's then use the real content of the SMS (taken from 
+    // the message body) and compare that against the 
+    // saved digest of a complete (not trimmed) remote lock 
+    // code. This ensures that remote locking happens only
+    // if the SMS is exactly the same as what the user has 
+    // specified.
+    iRemoteLockCode = HBufC::NewL( mtmBody.DocumentLength() );
+
+    TPtr smsTextPtr = iRemoteLockCode->Des();
+    smsTextPtr.Copy( mtmBody.Read( 0, mtmBody.DocumentLength() ) );
+    
+    
+    // The following code is to get the current state
+    // of manuallock. If manuallock state is off, that means
+    // the owner has unlocked the phone or the phone has
+    // never been locked by both remote lock and auto lock.
+    RL_TRACE_PRINT(" [ rl.exe ] HandleMessageL() Pub&Sub Get autoLState");    
+    TInt autoLState;
+    RProperty property;
+    
+    #ifndef RD_STARTUP_CHANGE    
+    User::LeaveIfError( property.Attach( KUidSystemCategory, KPSUidAutolockStatusValue ));
+    #else
+    User::LeaveIfError( property.Attach( KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus ));
+    #endif //RD_STARTUP_CHANGE
+    property.Get( autoLState );
+    
+    #ifndef RD_STARTUP_CHANGE
+    if ( autoLState == EPSAutolockOff ) 
+    #else
+    if ( autoLState == EAutolockOff ) 
+    #endif //RD_STARTUP_CHANGE      
+      {  
+      //Assign iLockedByRL to EFalse to indicate that
+      //the phone is not locked by Remote lock, the 
+      //reply SMS should be sent if correct remote lock
+      //code is received.
+      iLockedByRL = EFalse;
+      }
+    
+    property.Close();
+    
+    // If the phone receives correct lock code, the phone
+    // will be locked eventhough it may have been locked by
+    // auto lock.
+  
+    if ( VerifyAndLockL() ) 
+        {
+        RL_TRACE_PRINT(" [ rl.exe ] HandleMessageL() After VerifyAndLockL() ");
+        // Sets remote lock sms as read
+        entryInfo.SetVisible( ETrue );
+        entryInfo.SetUnread( EFalse );
+        entryInfo.SetNew( EFalse );
+        entryInfo.SetInPreparation( EFalse );
+        entryInfo.SetReadOnly( ETrue );
+        aEntry->ChangeL( entryInfo );
+        
+        
+        // Locks MemoryCard drive.
+        iStateMemoryCard = SetMemoryCardPasswdL( EFalse );
+
+        if ( iClientMtmForSending )
+            {
+            // Previous reply sending is still in progress, let's not start 
+            // sending new one.
+            User::Leave( KErrNone );
+            } 
+        
+        // The value of iLockedByRL is checked before sending SMS
+        // to make sure if the phone has been locked by remote 
+        // lock. By doing this, it is able to avoid the threat where 
+        // malware tries to use remote lock to keep on sending SMS.
+        
+        
+        if ( !iLockedByRL )
+            { 
+            RL_TRACE_PRINT(" [ rl.exe ] HandleMessageL() Send re-SMS ");
+            // Replies sms
+            iLockedByRL = ETrue;
+            CSmsHeader& header = smsClientMTM->SmsHeader();
+            HBufC* recipientAddress = header.FromAddress().AllocLC();
+
+            TBool initialSendMessage = EFalse;
+            TRAP( error, initialSendMessage = InitialSendMessageL() );
+            if ( error != KErrNone )
+                {
+                delete iClientMtmForSending;
+                iClientMtmForSending = NULL;
+                User::Leave( error );
+                }
+                
+            RL_TRACE_PRINT(" [ rl.exe ] HandleMessageL() Check recipientaddresslenght ");
+            if ( recipientAddress->Length() > 0 && initialSendMessage )
+                {
+                RL_TRACE_PRINT(" [ rl.exe ] HandleMessageL() before call sendMEssage ");
+                TRAP( error, SendMessageL( *recipientAddress ) );
+                if ( error != KErrNone )
+                    {
+                    RL_TRACE_PRINT(" [ rl.exe ] HandleMessageL() error occurs ");
+                    delete iClientMtmForSending;
+                    iClientMtmForSending = NULL;
+                    User::Leave( error );
+                    }
+                }
+            delete iClientMtmForSending;
+            iClientMtmForSending = NULL;
+
+            CleanupStack::PopAndDestroy( 1 ); // recipientAddress
+            }
+        CleanupStack::PopAndDestroy( 1 ); // clientMtm    
+        }
+    else
+        {
+        CleanupStack::PopAndDestroy( 1 ); // clientMtm
+        }
+    RL_TRACE_PRINT(" [ rl.exe ] exit HandleMessageL() ");
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::VerifyAndLockL()
+//
+// Compares if the remote lock received in SMS is correct.
+// If correct, locks the terminal.
+// ---------------------------------------------------------------------------
+//
+TBool CRemoteLock::VerifyAndLockL()
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] VerifyAndLockL() ");
+    
+    User::LeaveIfNull( iRemoteLockCode );
+    User::LeaveIfNull( iStoredCode );
+
+    if ( iRemoteLockSetting->CompareLockCodesL( 
+        *iRemoteLockCode, *iStoredCode ) )
+        {        
+        return ActivateDeviceLock();
+        }
+    RL_TRACE_PRINT(" [ rl.exe ] exit VerifyAndLockL() ");
+    return EFalse;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::ActivateDeviceLock()
+// Activate the device lock to lock the phone
+// ---------------------------------------------------------------------------
+// 
+TBool CRemoteLock::ActivateDeviceLock()
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] ActivateDeviceLock() ");
+       
+    RProperty property;
+        
+    TInt err = 0;
+       
+    #ifndef RD_STARTUP_CHANGE
+    err = property.Attach( KUidSystemCategory, 
+                               KPSUidAutolockStatusValue );
+    #else
+    err = property.Attach( KPSUidCoreApplicationUIs, 
+                               KCoreAppUIsAutolockStatus );
+    #endif 
+    if ( err != KErrNone )
+        {
+        return EFalse;
+        }
+
+    #ifndef RD_STARTUP_CHANGE
+    property.Set( EPSRemoteLocked );
+    #else
+    property.Set( ERemoteLocked );
+    #endif //RD_STARTUP_CHANGE 
+ 
+    property.Close();
+    RL_TRACE_PRINT(" [ rl.exe ] exit ActivateDeviceLock() ");
+    return ETrue;
+    }
+
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::CheckSettingsL
+// Checks remote lock setting.
+// ---------------------------------------------------------------------------
+//
+void CRemoteLock::CheckSettingsL()
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] CheckSettingsL () "); 
+    iRemoteLockSetting->GetEnabled( iIsEnabled );
+    
+    delete iStoredCode;
+    iStoredCode = NULL;
+    iStoredCode = HBufC::NewL( KRLockStoredLockCodeLength );
+    TPtr storedCodePtr = iStoredCode->Des();
+    
+    delete iStoredTrimmedCode;
+    iStoredTrimmedCode = NULL;
+    iStoredTrimmedCode = HBufC::NewL( KRLockStoredLockCodeLength );
+    TPtr storedTrimmedCodePtr = iStoredTrimmedCode->Des();
+    
+    iRemoteLockSetting->GetLockCode( storedCodePtr, storedTrimmedCodePtr );
+        
+    if ( iIsEnabled )
+        {
+        RL_TRACE_PRINT(" [ rl.exe ] CheckSettingsL() enable "); 
+       
+        if ( !iMsvSession )
+            {
+            TRAPD( error, iMsvSession = CMsvSession::OpenAsyncL( *this ) );
+        
+            RL_TRACE_PRINT_NUM(" [ rl.exe ] CheckSettingsL() openasyncL %d ", error );
+        
+            if ( error != KErrNone )
+                {
+                After( KRLockTimerInterval );
+                }  
+            }
+
+       if ( !iProfileSession )
+           {
+           RL_TRACE_PRINT(" [ rl.exe ] CheckSettingsL() create session "); 
+           iProfileSession = CRepository::NewL( KCRUidProfileEngine ); 
+           }
+       if ( !iObserver )
+           {
+           iObserver =  CRLLockObserver::NewL( this );      
+           } 
+       if( !iSubscribeProfile )
+           {
+           ProfileNotifyL( ETrue );
+           iSubscribeProfile = ETrue; 
+           }   
+        }
+    else
+        {
+        RL_TRACE_PRINT(" [ rl.exe ] CheckSettingsL() disable "); 
+        
+        delete iClientMtmForSending;
+        iClientMtmForSending = NULL;
+        delete iMtmReg;
+        iMtmReg = NULL;
+        delete iMsvSession;
+        iMsvSession = NULL;
+        
+        RL_TRACE_PRINT(" [ rl.exe ] CheckSettingsL() delete iMsvSession ");
+        
+        if ( iSubscribeProfile )
+            {
+            if ( !iProfileSession )
+                {
+                RL_TRACE_PRINT(" [ rl.exe ] CheckSettingsL() create session "); 
+                iProfileSession = CRepository::NewL( KCRUidProfileEngine ); 
+                }
+            ProfileNotifyL( EFalse );
+            delete iProfileSession;
+            iProfileSession = NULL;
+            delete iObserver;
+            iObserver = NULL; 
+            iSubscribeProfile = EFalse;
+            }  
+        }   
+    
+    RL_TRACE_PRINT(" [ rl.exe ] exit CheckSettingsL() ");
+    }
+    
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::IsMemoryCardLocked
+// Check MemoryCard whether it is locked or not.
+// ---------------------------------------------------------------------------
+//
+TBool CRemoteLock::IsMemoryCardLocked( const TDriveInfo& aDriveInfo ) const
+    {
+    return aDriveInfo.iMediaAtt&( KMediaAttLocked );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::HasMemoryCardPassword
+// Check MemoryCard whether it has password.
+// ---------------------------------------------------------------------------
+//
+TBool CRemoteLock::HasMemoryCardPassword( const TDriveInfo& aDriveInfo ) const
+    {
+    return aDriveInfo.iMediaAtt&( KMediaAttHasPassword );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::IsMemoryCardPresent
+// Check MemoryCard whether it is mounted into the phone and it supports locking.
+// ---------------------------------------------------------------------------
+//
+TBool CRemoteLock::IsMemoryCardPresent( const TDriveInfo& aDriveInfo ) const
+    {
+    return aDriveInfo.iDriveAtt&( KDriveAttRemovable ) && 
+        aDriveInfo.iMediaAtt&( KMediaAttLockable );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::SetMemoryCardPasswdL
+// Sets/remove the password to MemoryCard.
+// ---------------------------------------------------------------------------
+//
+TBool CRemoteLock::SetMemoryCardPasswdL( const TBool aClear )
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] SetMemoryCardPasswdL() ");
+    if ( aClear )
+        {
+        if ( iMemoryCardLockedByRL && iLockedByRL )
+            {
+            //remove the password
+            if ( DoSetMemoryCardPasswdL( ETrue ) )
+                {
+                iMemoryCardLockedByRL = EFalse;
+                RL_TRACE_PRINT(" [ rl.exe ] exit SetMemoryCardPasswdL() ");    
+                return ETrue;   
+                }
+            else
+                {
+                //Only try to remove password once no matter success or not 
+                iMemoryCardLockedByRL = EFalse; 
+              }    
+             
+            }       
+        }
+    else
+        {
+        if ( iMemoryCardLockedByRL )
+            {
+            //the memory card is locked already by rlock, 
+            //just return ETrue;
+            return ETrue;
+            }
+        
+        if ( !iRemoteLockCode || iRemoteLockCode->Length() == 0 )
+            {
+            return EFalse;
+            }
+        //Change the password
+        if ( DoSetMemoryCardPasswdL( EFalse ) )
+            {
+            iMemoryCardLockedByRL = ETrue;
+            RL_TRACE_PRINT(" [ rl.exe ] exit SetMemoryCardPasswdL() ");    
+            return ETrue; 
+            }
+           
+        }
+    RL_TRACE_PRINT(" [ rl.exe ] exit SetMemoryCardPasswdL() ");    
+    return EFalse;
+    }   
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::DoSetMemoryCardPasswdL
+// Do Sets/remove the password to MemoryCard.
+// ---------------------------------------------------------------------------
+//
+TBool CRemoteLock::DoSetMemoryCardPasswdL( TBool aClear )
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] DoSetMemoryCardPasswdL() ");
+    RFs fsMemoryCard;
+    TInt err = fsMemoryCard.Connect();
+    if ( err != KErrNone )
+        {
+        RL_TRACE_PRINT(" [ rl.exe ] DoSetMemoryCardPasswdL() error");
+        return EFalse;
+        }
+         
+#ifdef RD_MULTIPLE_DRIVE 
+
+   // Get the removeable user visible drives
+   TDriveList driveList;
+   TInt driveCount;
+   
+   //Get all removeable drive, both physically and logically
+   User::LeaveIfError( DriveInfo::GetUserVisibleDrives(
+       fsMemoryCard, driveList, driveCount, KDriveAttRemovable ) );   
+   RL_TRACE_PRINT_NUM(" [ rl.exe ] DoSetMemoryCardPasswdL() driveCount = %d ", driveCount );
+ 
+   //boolen to indicate at least one operation(clear/add password) 
+   // in the loop is ok.
+   TBool OperationSucceed = EFalse;
+  
+   RArray<TInt> arrayMemoryCardIndex;
+  
+   TInt max( driveList.Length() );
+   
+   for ( TInt i = 0; i < max; i++ )
+       {
+       if ( driveList[ i ] )
+          {
+          TUint status;	
+          DriveInfo::GetDriveStatus( fsMemoryCard, i, status );	
+          //To make sure the drive is physically removeable not logically removeable	
+          if( status & DriveInfo::EDriveRemovable )	
+              {
+              //append all physical removable memory card index into this array	
+              arrayMemoryCardIndex.Append(i); 
+              RL_TRACE_PRINT_NUM(" [ rl.exe ] DoSetMemoryCardPasswdL() physically removable drive %d", i );
+		          }
+		      else
+		          {
+		          RL_TRACE_PRINT_NUM(" [ rl.exe ] DoSetMemoryCardPasswdL() logically removable drive %d", i );
+		          }    
+		      }    
+       }
+      
+   //Lock/Unblock all physical removeable memory card
+   for ( TInt i = 0; i < arrayMemoryCardIndex.Count(); i++ )
+       {
+       TDriveInfo driveInfoT;
+       TInt driveIndex = arrayMemoryCardIndex[i];
+       RL_TRACE_PRINT_NUM(" [ rl.exe ] DoSetMemoryCardPasswdL() driveIndex %d", driveIndex );	
+       fsMemoryCard.Drive( driveInfoT, driveIndex );
+    
+       if ( IsMemoryCardPresent( driveInfoT ) ) 
+          {
+          	RL_TRACE_PRINT(" [ rl.exe ] Memory card is present");
+          if ( aClear )
+              {
+              RL_TRACE_PRINT(" [ rl.exe ] DoSetMemoryCardPasswdL() Remove password");	
+              if ( HasMemoryCardPassword( driveInfoT ) || IsMemoryCardLocked( driveInfoT ) ) 
+                  { 
+                  TMediaPassword memoryCardPassword; 
+              
+                  // Converts MemoryCardpassword
+                  ConvertMemoryCardPassword( memoryCardPassword, ETrue  );
+              
+                  err = fsMemoryCard.ClearPassword( driveIndex, memoryCardPassword );
+              
+                  if ( err == KErrNone )
+                      {
+                  	  OperationSucceed = ETrue;
+                      }
+              
+                  RL_TRACE_PRINT_NUM(" [ rl.exe ] exit DoSetMemoryCardPasswdL() password for index %d is cleaned", driveIndex);
+                  //Go for next
+                  }
+              else
+                  {
+                  //Go for next
+                  }      
+               }
+            else
+               {
+               RL_TRACE_PRINT(" [ rl.exe ] DoSetMemoryCardPasswdL() Set password");
+               if ( !HasMemoryCardPassword( driveInfoT ) && !IsMemoryCardLocked( driveInfoT ) )
+                   { 
+                   TMediaPassword memoryCardPassword;
+                
+                   TMediaPassword nullMemoryCardPassword;
+                
+                   // Converts MemoryCardpassword
+                   ConvertMemoryCardPassword( memoryCardPassword, EFalse );
+                
+                   // Locks MemoryCard drive
+                   err = fsMemoryCard.LockDrive( driveIndex, nullMemoryCardPassword, memoryCardPassword, ETrue );        
+                
+                   if ( err == KErrNone )
+                      {
+                  	  OperationSucceed = ETrue;
+                      }
+                
+                   RL_TRACE_PRINT_NUM(" [ rl.exe ] DoSetMemoryCardPasswdL() password for index %d is set", driveIndex);
+                   
+                   //Go for next
+                   }
+                else
+                   {
+                   //go for next
+                   }   
+               }
+            } //if ( IsMemoryCardPresent( driveInfoT ) ) 
+         } //for
+    
+     
+     if ( aClear )
+         {
+     	   delete iMemoryCardPasswd; 
+         iMemoryCardPasswd = NULL; 
+         fsMemoryCard.Close(); 
+         
+         return OperationSucceed ? ETrue : EFalse;
+         }
+     else 
+        {
+
+        delete iMemoryCardPasswd;
+        iMemoryCardPasswd = NULL; 
+        iMemoryCardPasswd = iRemoteLockCode->AllocL();
+        fsMemoryCard.Close();	
+        
+        return OperationSucceed ? ETrue : EFalse;
+        }       
+#else
+    
+    TInt i = 0;
+    TParsePtrC folder( PathInfo::MemoryCardRootPath() );
+    fsMemoryCard.CharToDrive( folder.Drive()[ 0 ], i );
+      
+    TDriveInfo driveInfoT;
+    fsMemoryCard.Drive( driveInfoT, i );
+    
+    if ( IsMemoryCardPresent( driveInfoT ) ) 
+      {
+      if ( aClear )
+          {
+          if ( HasMemoryCardPassword( driveInfoT ) || IsMemoryCardLocked( driveInfoT ) ) 
+              { 
+              TMediaPassword memoryCardPassword; 
+              // Converts MemoryCardpassword
+              ConvertMemoryCardPassword( memoryCardPassword, ETrue  );
+              err = fsMemoryCard.ClearPassword( i, memoryCardPassword );
+              
+              if( err == KErrNone )
+                  {
+                  delete iMemoryCardPasswd; 
+                  iMemoryCardPasswd = NULL; 
+                  }
+              fsMemoryCard.Close(); 
+              RL_TRACE_PRINT(" [ rl.exe ] exit DoSetMemoryCardPasswdL() clear");
+              return ( err == KErrNone );
+              }
+          else
+              {
+              fsMemoryCard.Close();  
+              return ETrue;
+              }      
+           }
+        else
+           {
+           if ( !HasMemoryCardPassword( driveInfoT ) && !IsMemoryCardLocked( driveInfoT ) )
+                { 
+                TMediaPassword memoryCardPassword;
+                TMediaPassword nullMemoryCardPassword;
+                // Converts MemoryCardpassword
+                ConvertMemoryCardPassword( memoryCardPassword, EFalse );
+                // Locks MemoryCard drive
+                err = fsMemoryCard.LockDrive( i, nullMemoryCardPassword, memoryCardPassword, ETrue );        
+                if ( err == KErrNone )
+                    {
+                    if ( iMemoryCardPasswd )
+                          {
+                          delete iMemoryCardPasswd;
+                          iMemoryCardPasswd = NULL; 
+                          }
+                     iMemoryCardPasswd = iRemoteLockCode->AllocL();
+                     }
+          
+                fsMemoryCard.Close();
+                RL_TRACE_PRINT(" [ rl.exe ] exit DoSetMemoryCardPasswdL() change");
+                return ( err == KErrNone );  
+                }
+            else
+                {
+                fsMemoryCard.Close();  
+                return EFalse;
+                }   
+            }
+        }    
+    fsMemoryCard.Close();
+    return EFalse;  
+    
+#endif //RD_MULTIPLE_DRIVE       
+    }
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::ConvertMemoryCardPasswordL
+// Converts MemoryCardPassword to acceptable format.
+// ---------------------------------------------------------------------------
+//
+void CRemoteLock::ConvertMemoryCardPassword( TMediaPassword& aPassword, const TBool aClear ) 
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] ConvertMemoryCardPassword() ");
+    
+    TBuf16 < KMaxMediaPassword / 2 > memoryCardPassword; 
+    // Takes left most 8 digits of lockcode as
+    // the password of MemoryCard.
+    RL_TRACE_PRINT(" [ rl.exe ] ConvertMemoryCardPassword() 1");
+    
+    if ( aClear )
+        {
+        if ( iMemoryCardPasswd )
+           {
+           memoryCardPassword.Copy( iMemoryCardPasswd->Left( KRLockMaxMemoryCardPasswdLength ) );
+           }
+        }
+     else
+        {
+        if ( iRemoteLockCode )
+            {
+            memoryCardPassword.Copy( iRemoteLockCode->Left( KRLockMaxMemoryCardPasswdLength ) );
+            }
+        } 
+  
+    // Fills the descriptor's data area with binary zeroes, i.e. 0x00, 
+    // replacing any existing data.
+    RL_TRACE_PRINT(" [ rl.exe ] ConvertMemoryCardPassword() 2");
+    aPassword.FillZ( KMaxMediaPassword ); 
+
+    aPassword.Zero();
+    // Sets the length of the data to zero.
+    // Copies data into this descriptor replacing any existing data. 
+    // The length of this descriptor is set to reflect the new data
+    RL_TRACE_PRINT(" [ rl.exe ] ConvertMemoryCardPassword() 3");
+    aPassword.Copy( reinterpret_cast<TUint8 *>
+        ( &memoryCardPassword[ 0 ] ), memoryCardPassword.Length() * 2 );
+        
+    RL_TRACE_PRINT(" [ rl.exe ] ConvertMemoryCardPassword() over ");    
+    }
+  
+  
+// ---------------------------------------------------------------------------
+// CRemoteLock::InitialSendMessageL
+// Reply SMS when the terminal is successfully locked.
+// ---------------------------------------------------------------------------
+//
+TBool CRemoteLock::InitialSendMessageL()
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] InitialSendMessageL() ");
+    
+    RProperty property;
+    
+    TInt err = 0;
+     
+    #ifndef RD_STARTUP_CHANGE        
+    err = property.Attach( KUidSystemCategory, KPSUidAutolockStatusValue );              
+    #else
+    err = property.Attach( KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus );
+    #endif
+    
+    if ( err != KErrNone )
+        {
+      return EFalse;
+        }
+    
+    TInt state = 0;
+    
+    CleanupClosePushL( property );
+    
+    err = property.Get( state );
+    if ( err != KErrNone )
+        {
+      CleanupStack::PopAndDestroy( 1 );
+        return EFalse;
+        }
+         
+    #ifndef RD_STARTUP_CHANGE
+    if ( state  == EPSRemoteLocked )
+    #else
+    if ( state == ERemoteLocked )
+    #endif // RD_STARTUP_CHANGE 
+      {
+      // message server entry id
+      TMsvId msvId = NULL;
+      // Set up a new message
+      msvId = CreateNewMessageL();
+      //Set the new message to be the current entry
+      SetEntryL( msvId );
+      CleanupStack::PopAndDestroy( 1 ); // property
+      RL_TRACE_PRINT(" [ rl.exe ] exit InitialSendMessageL() ETrue "); 
+      return ETrue; 
+      }
+    CleanupStack::PopAndDestroy( 1 ); // property   
+    RL_TRACE_PRINT(" [ rl.exe ] exit InitialSendMessageL() "); 
+    return EFalse;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::CreateNewMessageL()
+// Creates a new message server entry and set up default values.
+// Return values:      TMsvId (the id of created entry)
+// ---------------------------------------------------------------------------
+//
+TMsvId CRemoteLock::CreateNewMessageL()
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] CreateNewMessageL() ");
+    TMsvEntry newEntry;
+    // The type of message is SMS
+    newEntry.iMtm = KUidMsgTypeSMS;
+    // The type of the entry: message
+    newEntry.iType = KUidMsvMessageEntry;                    
+    newEntry.iServiceId = KMsvLocalServiceIndexEntryId;
+    // Set the date of the entry to home time
+    newEntry.iDate.UniversalTime();                           
+    newEntry.SetInPreparation( ETrue );                      
+
+    CMsvEntry* entry = CMsvEntry::NewL( *iMsvSession, 
+        KMsvDraftEntryIdValue, TMsvSelectionOrdering() );
+    CleanupStack::PushL( entry );
+    CMsvOperationWait* wait = CMsvOperationWait::NewLC();
+    wait->Start();    
+
+    // Asynchronously create a new entry.    
+    CMsvOperation* oper = entry->CreateL( newEntry, wait->iStatus );
+    CleanupStack::PushL( oper );
+
+    CActiveScheduler::Start();
+
+    // Keep track of the progress of the create operation.
+    TMsvLocalOperationProgress progress = 
+        McliUtils::GetLocalProgressL( *oper );
+    User::LeaveIfError( progress.iError );
+
+    // Set entry context to the created one
+    // operation progress contains the ID of the created entry
+    entry->SetEntryL( progress.iId ); 
+
+    CleanupStack::PopAndDestroy( 3 );
+    RL_TRACE_PRINT(" [ rl.exe ] CreateNewMessageL() end ");
+    return progress.iId;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::SetEntryL(TMsvId aEntryId)
+// Set up current message entry.
+// Note: It can be useful to remember the original entry id for 
+//       error handling.
+// ---------------------------------------------------------------------------
+//
+void CRemoteLock::SetEntryL( TMsvId aEntryId )
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] SetEntryL() ");
+    // Get the server entry from our session
+    CMsvEntry* entry = iMsvSession->GetEntryL( aEntryId );
+    CleanupStack::PushL( entry );
+    delete iClientMtmForSending;
+    iClientMtmForSending = NULL;
+    
+    TInt error;
+    TInt i;
+    for ( i = 0; i < 100; i++ )
+        {
+        TRAP( error, 
+            iClientMtmForSending = iMtmReg->NewMtmL( entry->Entry().iMtm ) );
+        if ( error == KErrNone )
+            {
+             RL_TRACE_PRINT(" [ rl.exe ] SetEntryL() iClientMtmForSending ");
+            break;
+            }
+        } 
+
+    User::LeaveIfError( error );
+    iClientMtmForSending->SetCurrentEntryL( entry );
+
+    CleanupStack::Pop( 1 ); // entry
+    RL_TRACE_PRINT(" [ rl.exe ] exit SetEntryL() ");
+    entry = NULL;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::MoveMessageEntryL(TMsvId aTarget) const
+// Moves an entry to another parent.
+// Return values:      TMsvId of the moved message
+// ---------------------------------------------------------------------------
+//
+TMsvId CRemoteLock::MoveMessageEntryL( TMsvId aTarget )
+    {
+    User::LeaveIfNull( iClientMtmForSending );
+    TMsvEntry msvEntry( ( iClientMtmForSending->Entry() ).Entry() );
+    TMsvId id = msvEntry.Id();
+
+    if ( msvEntry.Parent() != aTarget )
+        {
+        TMsvSelectionOrdering sort;
+        sort.SetShowInvisibleEntries( ETrue );    
+        // Take a handle to the parent entry
+        CMsvEntry* parentEntry = 
+            CMsvEntry::NewL( 
+            iClientMtmForSending->Session(), msvEntry.Parent(), sort );
+
+        CleanupStack::PushL( parentEntry );
+    
+        // Move original from the parent to the new location
+        CMsvOperationWait* wait = CMsvOperationWait::NewLC();
+        wait->Start();
+    
+        CMsvOperation* op = 
+                parentEntry->MoveL( msvEntry.Id(), aTarget, wait->iStatus );
+
+        CleanupStack::PushL( op );
+        CActiveScheduler::Start();     
+        TMsvLocalOperationProgress prog=McliUtils::GetLocalProgressL( *op );
+        User::LeaveIfError(prog.iError);
+    
+        id = prog.iId; 
+        CleanupStack::PopAndDestroy( 3 ); // op, wait, parentEntry
+        }
+    return id;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::SendMessageL
+// Reply SMS when the terminal is successfully locked.
+// Return values:      ETrue or EFalse
+// ---------------------------------------------------------------------------
+//
+TBool CRemoteLock::SendMessageL( const TDesC& aRecipientAddress )
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] SendMessageL() ");
+    
+    User::LeaveIfNull( iClientMtmForSending );
+    
+    RL_TRACE_PRINT(" [ rl.exe ] SendMessageL() 1 ");
+    
+    TMsvEntry msvEntry = ( iClientMtmForSending->Entry() ).Entry();
+
+    // We get the message body from Mtm and insert a bodytext
+    CRichText& mtmBody = iClientMtmForSending->Body();
+    mtmBody.Reset();
+    
+    TFileName fileName; 
+    fileName = KRLockResourceFileName;
+
+    // Use CStringResourceReader instead of StringLoader
+    // StringLoader is meant for applications in app framework   
+    CStringResourceReader* resourceReader = CStringResourceReader::NewLC( fileName );
+
+    RL_TRACE_PRINT(" [ rl.exe ] SendMessageL() 3");
+    
+    HBufC* retBuf = NULL;
+
+    if ( iStateMemoryCard )
+        {
+        RL_TRACE_PRINT(" [ rl.exe ] SendMessageL() memory card locked");
+        // When memory card is locked.
+        TPtrC buf;
+        buf.Set( resourceReader->ReadResourceString(R_RLOC_TI_EVERYTHING_LOCKED) );
+        retBuf = buf.AllocLC();
+        }
+    else
+        {
+        RL_TRACE_PRINT(" [ rl.exe ] SendMessageL() only phone locked ");
+        TPtrC buf;
+        buf.Set( resourceReader->ReadResourceString(R_RLOC_TI_PHONE_LOCKED) );
+        retBuf = buf.AllocLC();
+        }
+    mtmBody.InsertL( 0, *retBuf );
+    msvEntry.iDescription.Set( *retBuf );
+     
+    // Set aRecipientAddress into the Details of the entry
+    msvEntry.iDetails.Set( aRecipientAddress );  
+    msvEntry.SetInPreparation( EFalse );         
+    
+    // Set the sending state (immediately)
+    msvEntry.SetSendingState( KMsvSendStateWaiting );                         
+    msvEntry.iDate.UniversalTime();   
+    // To handle the sms specifics we start using SmsMtm
+    CSmsClientMtm* smsMtm = STATIC_CAST( CSmsClientMtm*, 
+                                         iClientMtmForSending );
+    smsMtm->RestoreServiceAndSettingsL();
+
+    // SMS MTM encapsulation of an SMS message.
+    CSmsHeader& header = smsMtm->SmsHeader();
+    CSmsSettings* sendOptions = CSmsSettings::NewL();
+    CleanupStack::PushL( sendOptions );
+    // Reset existing settings
+    sendOptions->CopyL( smsMtm->ServiceSettings() ); 
+    // Set unicode if needed
+    if ( NeedsToBeSentAsUnicodeL( retBuf->Des() ))
+        {
+        sendOptions->SetCharacterSet( TSmsDataCodingScheme::ESmsAlphabetUCS2 );
+        }
+    // Set send options to be delivered immediately
+    sendOptions->SetDelivery( ESmsDeliveryImmediately );      
+    header.SetSmsSettingsL( *sendOptions );
+    
+    // let's check if there's sc address
+    if (header.Message().ServiceCenterAddress().Length() == 0)
+        {
+        // no, there isn't. Use the default SC number. 
+        CSmsSettings* serviceSettings = NULL;
+        serviceSettings = &( smsMtm->ServiceSettings() );
+        
+        RL_TRACE_PRINT(" [ rl.exe ] SendMessageL() Get SC number ");    
+        if ( serviceSettings->ServiceCenterCount() )
+            {
+            //Set sc address to default.
+            CSmsServiceCenter& sc = serviceSettings->GetServiceCenter(
+                serviceSettings->DefaultServiceCenter() );
+            header.Message().SetServiceCenterAddressL( sc.Address() );
+            }
+        }
+    
+    // Add recipient to the list.
+    smsMtm->AddAddresseeL( aRecipientAddress, msvEntry.iDetails );
+
+    CMsvEntry& entry = iClientMtmForSending->Entry();
+    entry.ChangeL( msvEntry );                
+    smsMtm->SaveMessageL();                 
+
+    // Move message to outbox
+    TMsvId movedId;
+    TInt err;
+    for ( TInt i = 0; i < 100; i++ )
+        {
+        TRAP( err, movedId = MoveMessageEntryL( 
+                                 KMsvGlobalOutBoxIndexEntryId ));  
+        if ( err == KErrNone )
+            break;
+        }
+    RL_TRACE_PRINT(" [ rl.exe ] SendMessageL() put created message in outbox ");
+    User::LeaveIfError( err );
+    // We must create an entry selection for message copies 
+    CMsvEntrySelection* selection = new ( ELeave ) CMsvEntrySelection;
+    CleanupStack::PushL( selection );
+    selection->AppendL( movedId );        
+    // schedule the sending with the active scheduler
+    SetScheduledSendingStateL( selection );   
+    CleanupStack::PopAndDestroy( 4 ); // resourceReader,retbuf,sendOptions,selection 
+    RL_TRACE_PRINT(" [ rl.exe ] Exit SendMessageL() ");
+    return ETrue; 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::SetScheduledSendingStateL
+// Schedules the message to be sent through the etel server.
+// Return values:      none
+// ---------------------------------------------------------------------------
+//
+void CRemoteLock::SetScheduledSendingStateL( CMsvEntrySelection* aSelection )
+    {
+    User::LeaveIfNull( iClientMtmForSending );
+    // Add entry to task scheduler
+    TBuf8<1> dummyParams;
+    CMsvOperationWait* waiter = CMsvOperationWait::NewLC();
+    waiter->Start();
+
+    // invoking async schedule copy command on our mtm
+    CMsvOperation* op= iClientMtmForSending->InvokeAsyncFunctionL(
+            ESmsMtmCommandScheduleCopy,
+            *aSelection,
+            dummyParams,
+            waiter->iStatus );
+
+    CleanupStack::PushL( op );
+    CActiveScheduler::Start();
+
+    CleanupStack::PopAndDestroy( 2 ); // op, wait 
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::RunL
+// Reconnect msg server after it is shut down
+// Return values:      none
+// ---------------------------------------------------------------------------
+//
+void CRemoteLock::RunL()
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] RunL() ");
+    delete iClientMtmForSending;
+    iClientMtmForSending = NULL;
+    delete iMtmReg;
+    iMtmReg = NULL;
+    delete iMsvSession;
+    iMsvSession = NULL;
+
+    TRAPD( error, iMsvSession = CMsvSession::OpenAsyncL( *this ) );
+
+    if ( error != KErrNone )
+        {
+        After( KRLockTimerInterval );
+        }
+    RL_TRACE_PRINT(" [ rl.exe ] Exit RunL() ");    
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::NeedsToBeSentAsUnicodeL
+// Check if needs to be sent as unicode
+// Return value ETrue or EFalse
+// ---------------------------------------------------------------------------
+//
+TBool CRemoteLock::NeedsToBeSentAsUnicodeL( const TDesC& aInputString ) const
+    {
+    TBool needsToBeSentAsUnicode = EFalse;
+    CCnvCharacterSetConverter* const
+        characterSetConverter = CCnvCharacterSetConverter::NewLC();
+    
+    RFs fsSession;
+    TInt err = fsSession.Connect();
+    User::LeaveIfError( err );
+    CleanupClosePushL( fsSession ); 
+    const TUint KSmsEdSmsStrictPluginID = 0x101F85CD;
+    characterSetConverter->PrepareToConvertToOrFromL(
+        KSmsEdSmsStrictPluginID,
+        fsSession);
+
+    characterSetConverter->SetDowngradeForExoticLineTerminatingCharacters(
+        CCnvCharacterSetConverter::EDowngradeExoticLineTerminatingCharactersToJustLineFeed );
+   
+    for (TPtrC remainderOfInputString( aInputString ); remainderOfInputString.Length()>0 ; )
+        {
+        TBuf8<KBufLengthInUnicodeCheck> notUsed;
+        TInt numberOfUnconvertibleCharacters = 0;
+        const TInt returnValue = 
+            characterSetConverter->ConvertFromUnicode( 
+                notUsed,
+                remainderOfInputString, 
+                numberOfUnconvertibleCharacters );
+        if (( returnValue < 0 ) || ( numberOfUnconvertibleCharacters > 0 )) 
+            // if there was an error in trying to do the conversion, or if there was an
+            // unconvertible character (e.g. a Chinese character)
+            {
+            needsToBeSentAsUnicode = ETrue;
+            break;
+            }
+        
+        remainderOfInputString.Set( remainderOfInputString.Right( returnValue ));
+        }
+    CleanupStack::PopAndDestroy( 2 );
+    return needsToBeSentAsUnicode;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CRemoteLock::HandleUnlockEvent()
+// Callback function for unlocking event observer
+// ---------------------------------------------------------------------------
+void CRemoteLock::HandleUnlockEvent()
+    { 
+    TRAPD( err, SetMemoryCardPasswdL( ETrue ) );
+    err = err;
+    iLockedByRL = EFalse;
+    }   
+
+// -----------------------------------------------------------------------------
+// CRemoteLock::ProfileNotifyL
+// Setup Profile notifier
+// Returns:   ETrue if everything is OK
+//            EFalse otherwise
+// -----------------------------------------------------------------------------
+//
+TBool CRemoteLock::ProfileNotifyL( 
+    const TBool aNotifyEnable ) 
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] ProfileNotifyL() ");
+    
+    if ( !iProfileNotifyHandler )
+        {
+        RL_TRACE_PRINT(" [ rl.exe ] ProfileNotifyL() create notify handler");
+        iProfileNotifyHandler = CCenRepNotifyHandler::NewL( *this, *iProfileSession ); 
+        }
+    
+    if ( aNotifyEnable )
+        {
+        
+        TInt err = iProfileSession->Get( KProEngActiveProfile, iCurrentProfile );
+        User::LeaveIfError( err );
+        RL_TRACE_PRINT(" [ rl.exe ] ProfileNotifyL() startlisten");
+        iProfileNotifyHandler->StartListeningL();  
+        }
+    else
+        {
+        RL_TRACE_PRINT(" [ rl.exe ] ProfileNotifyL() stop listen ");
+        iProfileNotifyHandler->StopListening();
+        
+        delete iProfileNotifyHandler;
+        iProfileNotifyHandler = NULL;
+        }
+    RL_TRACE_PRINT(" [ rl.exe ] exit ProfileNotifyL() ");
+    return ETrue;
+    }
+    
+// -----------------------------------------------------------------------------
+// CRemoteLock::GetProfile
+// Get the current Profile
+// Returns:   ETrue if everything is OK
+//            EFalse otherwise
+// -----------------------------------------------------------------------------
+//
+TBool CRemoteLock::GetProfile( TInt& aProfile )
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] GetProfile() ");
+    TInt err;
+    err = iProfileSession->Get( KProEngActiveProfile, aProfile );
+    RL_TRACE_PRINT(" [ rl.exe ] exit GetProfile() ");
+    return ( err == KErrNone );
+    }    
+
+
+// -----------------------------------------------------------------------------
+// CRemoteLock::HandleNotifyGeneric
+// Remote lock Notify handler 
+//
+// -----------------------------------------------------------------------------
+//
+void CRemoteLock::HandleNotifyGeneric(
+    TUint32 /*aId*/ ) 
+    {
+    RL_TRACE_PRINT(" [ rl.exe ] HandleNotifyGeneric() "); 
+    
+    TInt profile = 0; 
+    GetProfile( profile ); 
+    
+    if ( ( profile == EProfileOffLineId ) && ( iIsEnabled  ) && ( iCurrentProfile != EProfileOffLineId )) 
+        {
+        ActivateDeviceLock();  
+        }
+        
+    iCurrentProfile = profile;
+    RL_TRACE_PRINT(" [ rl.exe ] exit HandleNotifyGeneric() ");
+    }
+    
+//EOF  
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/RemotelockSettings/BWINS/RLockSettingsU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,12 @@
+EXPORTS
+	??1CRemoteLockSettings@@UAE@XZ @ 1 NONAME ; CRemoteLockSettings::~CRemoteLockSettings(void)
+	?CompareLockCodesL@CRemoteLockSettings@@QBEHABVTDesC16@@0@Z @ 2 NONAME ; int CRemoteLockSettings::CompareLockCodesL(class TDesC16 const &, class TDesC16 const &) const
+	?GetEnabled@CRemoteLockSettings@@QBEHAAH@Z @ 3 NONAME ; int CRemoteLockSettings::GetEnabled(int &) const
+	?GetLockCode@CRemoteLockSettings@@QBEHAAVTDes16@@0@Z @ 4 NONAME ; int CRemoteLockSettings::GetLockCode(class TDes16 &, class TDes16 &) const
+	?GetLockCode@CRemoteLockSettings@@QBEHAAVTDes16@@@Z @ 5 NONAME ; int CRemoteLockSettings::GetLockCode(class TDes16 &) const
+	?NewL@CRemoteLockSettings@@SAPAV1@PAVMRemoteLockSettingsHandler@@@Z @ 6 NONAME ; class CRemoteLockSettings * CRemoteLockSettings::NewL(class MRemoteLockSettingsHandler *)
+	?NewLC@CRemoteLockSettings@@SAPAV1@PAVMRemoteLockSettingsHandler@@@Z @ 7 NONAME ; class CRemoteLockSettings * CRemoteLockSettings::NewLC(class MRemoteLockSettingsHandler *)
+	?RemoteLockNotifyL@CRemoteLockSettings@@QAEHH@Z @ 8 NONAME ; int CRemoteLockSettings::RemoteLockNotifyL(int)
+	?SetDisabled@CRemoteLockSettings@@QAEHXZ @ 9 NONAME ; int CRemoteLockSettings::SetDisabled(void)
+	?SetEnabledL@CRemoteLockSettings@@QAEHABVTDesC16@@@Z @ 10 NONAME ; int CRemoteLockSettings::SetEnabledL(class TDesC16 const &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/RemotelockSettings/EABI/RLockSettingsU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,16 @@
+EXPORTS
+	_ZN19CRemoteLockSettings11SetDisabledEv @ 1 NONAME
+	_ZN19CRemoteLockSettings11SetEnabledLERK7TDesC16 @ 2 NONAME
+	_ZN19CRemoteLockSettings17RemoteLockNotifyLEi @ 3 NONAME
+	_ZN19CRemoteLockSettings4NewLEP26MRemoteLockSettingsHandler @ 4 NONAME
+	_ZN19CRemoteLockSettings5NewLCEP26MRemoteLockSettingsHandler @ 5 NONAME
+	_ZN19CRemoteLockSettingsD0Ev @ 6 NONAME
+	_ZN19CRemoteLockSettingsD1Ev @ 7 NONAME
+	_ZN19CRemoteLockSettingsD2Ev @ 8 NONAME
+	_ZNK19CRemoteLockSettings10GetEnabledERi @ 9 NONAME
+	_ZNK19CRemoteLockSettings11GetLockCodeER6TDes16 @ 10 NONAME
+	_ZNK19CRemoteLockSettings11GetLockCodeER6TDes16S1_ @ 11 NONAME
+	_ZNK19CRemoteLockSettings17CompareLockCodesLERK7TDesC16S2_ @ 12 NONAME
+	_ZTI19CRemoteLockSettings @ 13 NONAME ; #<TI>#
+	_ZTV19CRemoteLockSettings @ 14 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/RemotelockSettings/Group/RemoteLockSettings.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,40 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file for RemoteLockSettings
+*
+*/
+
+
+#include <platform_paths.hrh>
+TARGET              RLockSettings.dll
+TARGETTYPE          dll
+UID                 0x1000008d  0x101FB654
+
+VENDORID            VID_DEFAULT
+CAPABILITY          CAP_CLIENT_DLL
+
+USERINCLUDE         ../../CenRep
+USERINCLUDE         ../../Inc
+MW_LAYER_SYSTEMINCLUDE  
+
+SOURCEPATH          ../Src
+SOURCE              RemoteLockSettings.cpp
+
+LIBRARY             centralrepository.lib
+LIBRARY             CenRepNotifHandler.lib
+LIBRARY             euser.lib 
+LIBRARY             commonengine.lib
+LIBRARY             hash.lib
+
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/RemotelockSettings/Src/RemoteLockSettings.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,403 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of RemoteLock Settings API
+*
+*/
+
+
+
+// INCLUDE FILES 
+#include <RemoteLockSettings.h>
+#include <hash.h>
+#include <centralrepository.h>
+#include "RemoteLockPrivateCRKeys.h"
+#include "RemoteLockTrace.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+_LIT( KRLockLeadingHexZero, "0" );
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+// -----------------------------------------------------------------------------
+// CRemoteLockSettings::NewL
+// Two-Phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CRemoteLockSettings* CRemoteLockSettings::NewL( 
+    MRemoteLockSettingsHandler* aHandler )
+    {
+    RL_TRACE_PRINT(" [ rlsetting.dll ] NewL() ");
+    
+    CRemoteLockSettings* self = CRemoteLockSettings::NewLC( aHandler );
+         
+    CleanupStack::Pop( self );
+    RL_TRACE_PRINT(" [ rlsetting.dll ] exit NewL() ");
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CRemoteLockSettings::NewLC
+// Two-Phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CRemoteLockSettings* CRemoteLockSettings::NewLC( 
+    MRemoteLockSettingsHandler* aHandler )
+    {
+    
+    CRemoteLockSettings* self = new ( ELeave ) CRemoteLockSettings( aHandler );
+    
+    CleanupStack::PushL( self );
+    
+    self->ConstructL();
+    return self;
+    }
+
+
+// ----------------------------------------------------------------------------
+// Destructor
+// ----------------------------------------------------------------------------
+EXPORT_C CRemoteLockSettings::~CRemoteLockSettings()
+    {
+    if ( iNotifyHandler )
+        {
+        iNotifyHandler->StopListening();
+        delete iNotifyHandler;
+        }
+
+    delete iSession;
+    }
+
+
+// ----------------------------------------------------------------------
+// CRemoteLockSettings::GetLockCode
+// Gets remote lock code
+// Returns: ETrue
+//          EFalse  
+// ----------------------------------------------------------------------
+//
+EXPORT_C TBool CRemoteLockSettings::GetLockCode( TDes& aLockCode ) const                                               
+    {
+    RL_TRACE_PRINT(" [ rlsetting.dll ] Getlockcode() ");
+    TInt err = iSession->Get( KRLLockCode, aLockCode ); 
+    RL_TRACE_PRINT(" [ rlsetting.dll ] exit Getlockcode() ");   
+    return ( err == KErrNone );
+    }
+
+
+// ----------------------------------------------------------------------
+// CRemoteLockSettings::GetLockCode
+// Gets remote lock code and trimmed remote lock code
+// Returns: ETrue
+//          EFalse  
+// ----------------------------------------------------------------------
+//
+EXPORT_C TBool CRemoteLockSettings::GetLockCode( 
+    TDes& aLockCode, 
+    TDes& aLockCodeTrimmed ) const 
+    {
+    RL_TRACE_PRINT(" [ rlsetting.dll ] Getlockcode() ");
+    TInt err = iSession->Get( KRLLockCode, aLockCode );    
+    
+    if ( err != KErrNone )
+        {
+        return EFalse;
+        }
+    
+    err = iSession->Get( KRLLockCode2, aLockCodeTrimmed );
+    
+    if ( err == KErrNone )
+        {
+        RL_TRACE_PRINT(" [ rlsetting.dll ] exit Getlockcode() noError");
+        return ETrue;
+        }
+    else
+        {
+        RL_TRACE_PRINT(" [ rlsetting.dll ] exit Getlockcode() Error");
+        return EFalse;
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CRemoteLockSettings::SetEnabled
+// Enables and sets remote lock code
+// Returns   ETrue
+//           EFalse  
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TBool CRemoteLockSettings::SetEnabledL( const TDesC& aLockCode )
+    {
+    RL_TRACE_PRINT(" [ rlsetting.dll ] SetEnabledL() ");
+    if ( aLockCode.Length() > KRLockMaxLockCodeLength )
+       {
+       return EFalse;
+       }  
+       
+    // Creates MD5 object.
+    CMD5* hash = CMD5::NewL();
+    CleanupStack::PushL( hash );
+
+    TBuf<KRLockMaxLockCodeLength> tempBuf;
+    tempBuf = aLockCode;
+       
+    HBufC8* hashBuf = HBufC8::NewLC( KRLockMaxLockCodeLength * 2 );        
+    TPtr8 tempPtr = hashBuf->Des();
+    tempPtr.Copy( tempBuf );
+       
+    // Calculate the digest.
+    TPtrC8 hashPtr = hash->Hash( *hashBuf );
+    HBufC* storeBuf = HBufC::NewLC( hash->HashSize());     
+    storeBuf->Des().Copy( hashPtr );
+
+       // Convert digest into hexadecimal representation
+    HBufC* hexStoreBuf = HBufC::NewLC( storeBuf->Length() * 2);
+    TBuf<2> singleHex;
+    TInt i = 0;
+    for ( i = 0; i < storeBuf->Length(); i++ )
+        {
+        singleHex.Num( storeBuf->Des()[i], EHex );
+        if ( singleHex.Length() == 1 )
+            hexStoreBuf->Des().Append( KRLockLeadingHexZero );
+        hexStoreBuf->Des().Append( singleHex );
+        }
+       
+    // Saves the digest into repository file.
+    TInt err = 0;
+    err = iSession->Set( KRLLockCode, *hexStoreBuf );
+       
+    if ( err != KErrNone )
+        {
+        CleanupStack::PopAndDestroy( 4 ); 
+        return EFalse;
+        }
+        
+     // Then process the trimmed password the same way.
+    tempBuf.TrimAll();
+    tempPtr.Copy( tempBuf );
+    // Calculate the digest.
+    hash->Reset();
+    TPtrC8 hashPtr1 = hash->Hash( *hashBuf );
+    storeBuf->Des().Copy( hashPtr1 );
+    // Convert digest into hexadecimal representation
+    hexStoreBuf->Des().Zero();
+    for ( i = 0; i < storeBuf->Length(); i++ )
+        {
+        singleHex.Num( storeBuf->Des()[i], EHex );
+        if ( singleHex.Length() == 1 )
+            hexStoreBuf->Des().Append( KRLockLeadingHexZero );
+        hexStoreBuf->Des().Append( singleHex );
+        }
+        
+    // Saves the digest into ini file.
+    err = iSession->Set( KRLLockCode2, *hexStoreBuf );
+        
+    if ( err != KErrNone )
+        {
+        RL_TRACE_PRINT(" [ rlsetting.dll ] SetenabledL() exit Error ");
+        CleanupStack::PopAndDestroy( 4 );
+        return EFalse;
+        }
+    
+    err = iSession->Set( KRLEnable, 1 );
+        
+    if ( err != KErrNone )
+        {
+        RL_TRACE_PRINT(" [ rlsetting.dll ] SetenabledL() exit Error ");
+        CleanupStack::PopAndDestroy( 4 );
+        return EFalse;
+        }
+    RL_TRACE_PRINT(" [ rlsetting.dll ] SetenabledL() exit no Error ");
+    CleanupStack::PopAndDestroy( 4 );//MD5, 3 Heap buffer
+    return ETrue;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CRemoteLockSettings::SetDisabled
+// Disables remote lock
+// Returns   ETrue
+//           EFalse  
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TBool CRemoteLockSettings::SetDisabled()
+    {
+    RL_TRACE_PRINT(" [ rlsetting.dll ] SetDisabled() ");
+    TInt err;
+    err = iSession->Set( KRLEnable, 0 );
+    RL_TRACE_PRINT(" [ rlsetting.dll ] exit SetDisabled() ");
+    return ( err == KErrNone );
+    }
+
+// -----------------------------------------------------------------------------
+// CRemoteLockSettings::GetEnabled
+// Returns whether remote lock is enabled or disabled
+// Returns    ETrue
+//            EFalse  
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TBool CRemoteLockSettings::GetEnabled( TBool& aEnable ) const
+    {
+    RL_TRACE_PRINT(" [ rlsetting.dll ] GetEnabled() ");  
+    TInt err;
+    err = iSession->Get( KRLEnable, aEnable );
+    RL_TRACE_PRINT(" [ rlsetting.dll ] Exit GetEnabled() ");
+    return ( err == KErrNone );
+    }
+    
+   
+// -----------------------------------------------------------------------------
+// CRemoteLockSettings::CompareLockCodes
+// Compares the given remote lock code to the stored one.
+// Returns   ETrue
+//           EFalse  
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TBool CRemoteLockSettings::CompareLockCodesL( 
+    const TDesC& aLockCode, 
+    const TDesC& aCorrectLockCode ) const
+    {
+    RL_TRACE_PRINT(" [ rlsetting.dll ] CompareLockCodesL() ");
+    if ( aLockCode.Length() > KRLockMaxLockCodeLength || 
+        aCorrectLockCode.Length() > KRLockStoredLockCodeLength )
+        {
+        RL_TRACE_PRINT(" [ rlsetting.dll ] exit CompareLockCodeL() lockcode length is illegal ");
+        return EFalse;
+        }
+
+    // Creates MD5 object.
+    CMD5* hash = CMD5::NewL();
+    CleanupStack::PushL( hash );
+
+    HBufC8* hashBuf = HBufC8::NewLC( KRLockMaxLockCodeLength * 2 );
+    TPtr8 tempPtr = hashBuf->Des();
+    tempPtr.Copy( aLockCode );
+
+    // Hashes data.
+    TPtrC8 hashPtr = hash->Hash( *hashBuf );
+
+    HBufC* lockCode = HBufC::NewLC( hash->HashSize() );
+
+    // Copies hashPtr to lockCode.
+    lockCode->Des().Copy( hashPtr );
+
+    // Convert digest into hexadecimal representation
+    HBufC* hexLockCode = HBufC::NewLC( lockCode->Length() * 2);
+    TBuf<2> singleHex;
+    for ( TInt i = 0; i < lockCode->Length(); i++ )
+        {
+        singleHex.Num( lockCode->Des()[i], EHex );
+        if ( singleHex.Length() == 1 )
+            hexLockCode->Des().Append( KRLockLeadingHexZero );
+        hexLockCode->Des().Append( singleHex );
+        }
+
+    RL_TRACE_PRINT(" [ rlsetting.dll ] CompareLockCodeL() compare ");
+    if ( hexLockCode->Compare( aCorrectLockCode ) == 0 )
+        {
+        // When two hash results matches each other.
+        RL_TRACE_PRINT(" [ rlsetting.dll ] ComparelockcodeL() match ");
+        CleanupStack::PopAndDestroy( 4 );
+        return ETrue;
+        }
+    else
+        {
+        RL_TRACE_PRINT(" [ rlsetting.dll ] CompareLockCodeL() dismatch ");
+        CleanupStack::PopAndDestroy( 4 );
+        return EFalse;
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CRemoteLockSettings::RemoteLockNotifyL
+// Setup RemoteLock notifier
+// Returns:   ETrue
+//            EFalse
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TBool CRemoteLockSettings::RemoteLockNotifyL( 
+    const TBool aNotifyEnable ) 
+    {
+    RL_TRACE_PRINT(" [ rlsetting.dll ] RemotelockNotifyL() ");
+    if ( !iNotifyHandler )
+        {
+        iNotifyHandler = CCenRepNotifyHandler::NewL( *this, *iSession ); 
+        }
+
+    if ( aNotifyEnable )
+        {
+        iNotifyHandler->StartListeningL();  
+        }
+    else
+        {
+        iNotifyHandler->StopListening();
+        }
+    RL_TRACE_PRINT(" [ rlsetting.dll ] exit RemotelockNotifyL() ");
+    return ETrue;
+    }
+
+// ----------------------------------------------------------------------------
+// CRemoteLockSettings::CRemoteLockSettings
+// default constructor
+// ----------------------------------------------------------------------------
+CRemoteLockSettings::CRemoteLockSettings( MRemoteLockSettingsHandler* aHandler ) 
+    {    
+    iHandler = aHandler;
+    } 
+    
+      
+// -----------------------------------------------------------------------------
+// CRemoteLockSettings::ConstructL
+// Symbian 2nd phase constructor can leave
+//------------------------------------------------------------------------------
+//
+void CRemoteLockSettings::ConstructL()
+    {
+    RL_TRACE_PRINT(" [ rlsetting.dll ] ConstructL() ");  
+    iSession = CRepository::NewL( KCRUidRemoteLock ); 
+    RL_TRACE_PRINT(" [ rlsetting.dll ] exit ConstructL() ");
+    }
+    
+
+// -----------------------------------------------------------------------------
+// CRemoteLockSettings::HandleNotifyGeneric
+// Notify handler
+//
+// -----------------------------------------------------------------------------
+//
+void CRemoteLockSettings::HandleNotifyGeneric( 
+    TUint32 /*aId*/ ) 
+    {
+    RL_TRACE_PRINT(" [ rlsetting.dll ] HandleNotifyGeneric() ");
+    TRAPD( error, iHandler->HandleRemoteLockNotifyL() );
+    error = error;
+    RL_TRACE_PRINT(" [ rlsetting.dll ] exit HandleNotifyGeneric() ");
+    }
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/Rom/RemoteLock.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,31 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Image description file for RemoteLock
+*
+*/
+
+
+#ifndef REMOTELOCK_IBY
+#define REMOTELOCK_IBY
+
+#ifdef RD_REMOTELOCK
+//Remotelock
+file=ABI_DIR\BUILD_DIR\RLockSettings.dll                       SHARED_LIB_DIR\RLockSettings.dll
+#ifdef __REMOTE_LOCK
+file=ABI_DIR\BUILD_DIR\RLock.exe                               PROGRAMS_DIR\RLock.exe
+#endif
+#endif //RD_REMOTELOCK
+#endif //REMOTELOCK_IBY
+//  End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/Rom/RemoteLockResources.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource description file for RemoteLock
+*
+*/
+
+
+#ifndef REMOTELOCKRESOURCES_IBY
+#define REMOTELOCKRESOURCES_IBY
+#ifdef RD_REMOTELOCK
+//Remotelock resources
+#ifdef __REMOTE_LOCK
+data=DATAZ_\APP_RESOURCE_DIR\Remotelock.rsc                    APP_RESOURCE_DIR\Remotelock.rsc
+#endif
+#endif //RD_REMOTELOCK
+#endif 
+//  End of File
+
+
Binary file remotelock/conf/remotelock.confml has changed
Binary file remotelock/conf/remotelock_101FB654.crml has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/remotelock/loc/remotelock.loc	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2002-2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Localisation of Remotelock
+*
+*/
+
+
+// LOCALISATION STRINGS:
+
+//d: Text indicating succesfull phone and MMC remote lock.
+//d: When device is locked using remote lock SMS, information of this
+//d: is sent back as a SMS to the sender. The content of this reply-SMS
+//d: depends whether MMC was also locked or not.
+//d: Do not use line feeds ("\n"). Do not exceed length of an SMS (160).
+//l: 
+//w: 
+#define qtn_rloc_ti_everything_locked "Mobile phone and memory card are locked. Remote lock message is used as a memory card password."
+
+//d: Text indicating succesfull phone remote lock.
+//d: When device is locked using remote lock SMS, information of this
+//d: is sent back as a SMS to the sender. The content of this reply-SMS
+//d: depends whether MMC was also locked or not.
+//d: Do not use line feeds ("\n"). Do not exceed length of an SMS (160).
+//l:
+//w: 
+#define qtn_rloc_ti_phone_locked "Mobile phone is locked"
+
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/cms_api.metaxml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,18 @@
+<?xml version="1.0" ?>
+<api id="2bf6e1e7f9bcc57ca0928c14fd9cd158" dataversion="1.0">
+  <name>CMS API</name>
+  <description>Provides Cryptographic Message Syntax(CMS) services</description>
+  <type>c++</type>
+  <subsystem>CMS</subsystem>
+  <libs>
+    <lib name="cms.lib" />
+  </libs>
+  <release category="domain"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>yes</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+:                CMS API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/MCMSModule.h     MW_LAYER_PLATFORM_EXPORT_PATH(MCMSModule.h)
+../inc/CCMSX509Validity.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSX509Validity.h)
+../inc/CCMSX509AttributeCertificate.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSX509AttributeCertificate.h)
+../inc/CCMSSignerInfo.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSSignerInfo.h)
+../inc/CCMSX509GeneralNames.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSX509GeneralNames.h)
+../inc/CCMSAuthenticatedData.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSAuthenticatedData.h)
+../inc/CCMSOriginatorPublicKey.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSOriginatorPublicKey.h)
+../inc/CCMSRecipientInfo.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSRecipientInfo.h)
+../inc/CCMSOriginatorInfo.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSOriginatorInfo.h)
+../inc/CCMSKeyAgreeRecipientInfo.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSKeyAgreeRecipientInfo.h)
+../inc/CCMSX509GeneralName.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSX509GeneralName.h)
+../inc/CCMSX509AttributeCertificateInfo.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSX509AttributeCertificateInfo.h)
+../inc/CCMSX509SubjectPublicKeyInfo.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSX509SubjectPublicKeyInfo.h)
+../inc/CCMSAttribute.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSAttribute.h)
+../inc/CCMSX509Certificate.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSX509Certificate.h)
+../inc/CCMSX509Signed.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSX509Signed.h)
+../inc/CCMSX509CertificateList.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSX509CertificateList.h)
+../inc/CCMSKeyTransRecipientInfo.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSKeyTransRecipientInfo.h)
+../inc/CCMSKeyIdentifier.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSKeyIdentifier.h)
+../inc/CCMSEncapsulatedContentInfo.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSEncapsulatedContentInfo.h)
+../inc/CCMSX509IssuerSerial.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSX509IssuerSerial.h)
+../inc/CCMSContentInfo.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSContentInfo.h)
+../inc/CCMSSequence.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSSequence.h)
+../inc/CCMSRecipientEncryptedKey.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSRecipientEncryptedKey.h)
+../inc/CCMSX509AlgorithmIdentifier.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSX509AlgorithmIdentifier.h)
+../inc/CCMSIssuerAndSerialNumber.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSIssuerAndSerialNumber.h)
+../inc/CCMSKEKRecipientInfo.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSKEKRecipientInfo.h)
+../inc/CCMSCertificateChoices.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSCertificateChoices.h)
+../inc/CCMSSignedData.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSSignedData.h)
+../inc/CCMSOriginatorIdentifierOrKey.h     MW_LAYER_PLATFORM_EXPORT_PATH(CCMSOriginatorIdentifierOrKey.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSAttribute.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,196 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef CCMSAttribute_H
+#define CCMSAttribute_H
+
+//  INCLUDES
+#include "CCMSSequence.h"
+#include <badesca.h>
+
+// FORWARD DECLARATIONS
+// Extension
+class MCMSAttributeExtension;
+
+
+// CLASS DECLARATION
+/**
+*  Attribute type module
+*
+*  ASN.1 Definition:
+*  Attribute ::= SEQUENCE {
+*  		attrType OBJECT IDENTIFIER,
+*  		attrValues SET OF AttributeValue }
+*
+*  AttributeValue ::= ANY
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSAttribute : public CCMSSequence
+    {
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        * NOTE: Encrypt will leave with KErrBadDescriptor if
+        * valid Attribute Type has not setted.
+        */
+        IMPORT_C static CCMSAttribute* NewLC();
+
+	   /**
+        * Two-phased constructor.
+        * NOTE: Encrypt will leave with KErrBadDescriptor if
+        * valid Attribute Type has not setted.
+        */
+        IMPORT_C static CCMSAttribute* NewL();
+		
+		/**
+        * Two-phased constructor.
+        * Takes copy of the both type and values.
+        * @param aAttributeType	The attribute type in desc e.g.
+        *						content type = "1.2.840.113549.1.9.3".
+        * @param aAttriteValues	Set of attribute values. Each attribute must be
+        *						already encoded since they are added as is.
+        */
+        IMPORT_C static CCMSAttribute* NewL( const TDesC& aAttributeType,
+										     const CDesC8Array& aAttributeValues );
+
+        /**
+        * Two-phased constructor.
+        * Takes copy of the both type and values.
+		* Leaves newly created instance in CleanupStack
+        * @param aAttributeType	The attribute type in desc e.g.
+        *						content type = "1.2.840.113549.1.9.3".
+        * @param aAttriteValues	Set of attribute values. Each attribute must be
+        *						already encoded since they are added as is.
+        */
+        IMPORT_C static CCMSAttribute* NewLC( const TDesC& aAttributeType,
+											  const CDesC8Array& aAttributeValues );
+
+		/**
+        * Two-phased constructor.
+        * Same as above although takes only one value
+        * @param aAttributeType	The attribute type in desc e.g.
+        *						content type = "1.2.840.113549.1.9.3".
+        * @param aAttriteValue	Single attribute value. Attribute must be
+        *						already encoded since it is added as is.
+        */
+        IMPORT_C static CCMSAttribute* NewL( const TDesC& aAttributeType,
+											 const TDesC8& aAttributeValue );
+
+		/**
+        * Two-phased constructor.
+        * Same as above although takes only one value
+		* Leaves newly created instance in CleanupStack
+        * @param aAttributeType	The attribute type in desc e.g.
+        *						content type = "1.2.840.113549.1.9.3".
+        * @param aAttriteValue	Single attribute value. Attribute must be
+        *						already encoded since it is added as is.
+        */
+        IMPORT_C static CCMSAttribute* NewLC( const TDesC& aAttributeType,
+											  const TDesC8& aAttributeValue );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSAttribute();
+
+    public: // New functions
+
+        /**
+		* Getter for attribute type
+		* @since 2,8
+		* @return Attribute type in TDesC reference
+		*/
+		IMPORT_C const TDesC& AttributeType() const;
+
+        /**
+        * Getter for attribute values
+        * @since 2.8
+        * @return Attribute values in CDesC8ArrayFlat reference
+        */
+		IMPORT_C const CDesC8Array& AttributeValues() const;
+
+		/**
+        * Setter for attribute type, takes copy
+        * @since 2.8
+        * @param aAttributeType	Attribute type to be set as TDesC.
+        */
+		IMPORT_C void SetAttributeTypeL( const TDesC& aAttributeType );
+
+        /**
+        * Setter for attribute values
+        * @since 2,8
+        * @param aSerialNumber Array of attribute values
+        */
+		IMPORT_C void SetAttributeValuesL( const CDesC8Array& aAttributeValues );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL();
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL( const TDesC& aAttributeType,
+								  const CDesC8Array& aAttributeValues );
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL( const TDesC& aAttributeType,
+								  const TDesC8& aAttributeValue );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSAttribute();
+
+    private:    // Data
+        // Attribute Type, owned
+        HBufC* iAttributeType;
+        // Attribute values, owned
+		CDesC8ArrayFlat* iAttributeValues;
+
+		// Reserved for extensions
+		MCMSAttributeExtension* iReserved;
+    };
+
+#endif      // CCMSAttribute_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSAuthenticatedData.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,331 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  CMS AuthenticatedData type
+*
+*/
+
+
+
+#ifndef CCMSAuthenticatedData_H
+#define CCMSAuthenticatedData_H
+
+//  INCLUDES
+#include "CCMSSequence.h"
+#include "CCMSEncapsulatedContentInfo.h"
+#include "CCMSX509AlgorithmIdentifier.h"
+#include <badesca.h>
+
+// FORWARD DECLARATIONS
+// Extension
+
+class MCMSAuthenticatedDataExtension;
+class CCMSOriginatorInfo;
+class CCMSRecipientInfo;
+class CCMSAttribute;
+class CCMSCertificateChoices;
+class CCMSX509CertificateList;
+
+// CLASS DECLARATION
+/**
+*  AuthenticatedData type module
+*
+*  ASN.1 Definition:
+*
+*     AuthenticatedData ::= SEQUENCE {
+*        version CMSVersion,
+*        originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
+*        recipientInfos RecipientInfos,
+*        macAlgorithm MessageAuthenticationCodeAlgorithm,
+*        digestAlgorithm [1] DigestAlgorithmIdentifier OPTIONAL,
+*        encapContentInfo EncapsulatedContentInfo,
+*        authenticatedAttributes [2] IMPLICIT AuthAttributes OPTIONAL,
+*        mac MessageAuthenticationCode,
+*        unauthenticatedAttributes [3] IMPLICIT UnauthAttributes OPTIONAL }
+*
+*     AuthAttributes ::= SET SIZE (1..MAX) OF Attribute
+*     UnauthAttributes ::= SET SIZE (1..MAX) OF Attribute
+* 
+*     RecipientInfos ::= SET OF RecipientInfo
+*
+*     MessageAuthenticationCode ::= OCTET STRING
+* 
+*     MessageAuthenticationCodeAlgorithm ::= AlgorithmIdentifier
+*     DigestAlgorithmIdentifier ::= AlgorithmIdentifier
+*
+*  @lib cms.lib
+*  @since 3.0
+*/
+class CCMSAuthenticatedData : public CCMSSequence
+    {
+    private:
+        /**
+         * Container for the actual data
+         */
+        NONSHARABLE_CLASS( CAuthenticatedDataData ) : public CBase
+            {
+            public: // destructor
+                ~CAuthenticatedDataData();
+
+            public: // data
+                // version
+                TInt iVersion;
+
+                // originatorInfo, owned
+                CCMSOriginatorInfo* iOriginatorInfo;
+                
+                // recipientInfos, owned
+                CArrayPtr< CCMSRecipientInfo >* iRecipientInfos;
+
+                // macAlgorithm, owned
+                CCMSX509AlgorithmIdentifier* iMacAlgorithm;
+
+                // digestAlgorithm, owned
+                CCMSX509AlgorithmIdentifier* iDigestAlgorithm;
+
+                // encapContentInfo, owned
+                CCMSEncapsulatedContentInfo* iEncapContentInfo;
+
+                // authenticatedAttributes, owned
+                CArrayPtr< CCMSAttribute >* iAuthenticatedAttributes;
+
+                // mac, owned
+                HBufC8* iMac;
+
+                // unauthenticatedAttributes, owned
+                CArrayPtr< CCMSAttribute >* iUnauthenticatedAttributes;
+                
+            };
+        
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        * NOTE: Encrypt will leave with KErrArgument if
+        * valid parameters are not set.
+        */
+        IMPORT_C static CCMSAuthenticatedData* NewLC();
+
+        /**
+        * Two-phased constructor.
+        * Takes ownership of all parameters, except aMac which is copied.
+        * Leaves newly created instance in CleanupStack
+        */
+        IMPORT_C static CCMSAuthenticatedData* NewLC(
+			CArrayPtr< CCMSRecipientInfo >* aRecipientInfos,
+            CCMSX509AlgorithmIdentifier* aMacAlgorithm,
+        	CCMSEncapsulatedContentInfo* aEncapContentInfo,
+        	const TDesC8& aMac );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSAuthenticatedData();
+
+    public: // New functions
+        /**
+         * Getter for version
+         * @since 3.0
+         * @return CMSVersion
+         */
+        IMPORT_C TInt Version() const;
+
+        /**
+         * Getter for originatorInfo
+         * @since 3.0
+         * @return OriginatorInfo or NULL
+         */
+        IMPORT_C const CCMSOriginatorInfo* OriginatorInfo() const;
+        
+        /**
+         * Getter for recipientInfos.
+         * @since 3.0
+         * @return array of RecipientInfos
+         */
+        IMPORT_C const CArrayPtr< CCMSRecipientInfo >& RecipientInfos() const;
+
+        /**
+         * Getter for macAlgorithm. 
+         * @since 3.0
+         * @return MessageAuthenticationCodeAlgorithm
+         */
+        IMPORT_C const CCMSX509AlgorithmIdentifier& MacAlgorithm() const;
+
+        /**
+         * Getter for digestAlgorithm
+         * @since 3.0
+         * @return DigestAlgorithmIdentifier or NULL
+         */
+        IMPORT_C const CCMSX509AlgorithmIdentifier* DigestAlgorithm() const;
+
+        /**
+         * Getter for encapContentInfo
+         * @since 3.0
+         * @return EncapsulatedContentInfo
+         */
+        IMPORT_C const CCMSEncapsulatedContentInfo& EncapContentInfo() const;
+
+        /**
+         * Getter for authenticatedAttributes
+         * @since 3.0
+         * @return array of Attributes or NULL
+         */
+        IMPORT_C const CArrayPtr< CCMSAttribute >*
+        AuthenticatedAttributes() const;
+
+        /**
+         * Getter for mac
+         * @since 3.0
+         * @return MessageAuthenticationCode
+         */
+        IMPORT_C const TDesC8& Mac() const;
+
+        /**
+         * Getter for unauthenticatedAttributes
+         * @since 3.0
+         * @return  array of Attributes or NULL
+         */
+        IMPORT_C const CArrayPtr< CCMSAttribute >*
+        UnauthenticatedAttributes() const;
+
+        /**
+         * Setter for version. Default value is 0.
+         * @since 3.0
+         * @param aVersion CMSVersion value
+         */
+        IMPORT_C void SetVersion( TInt aVersion );
+        
+        /**
+         * Setter for originatorInfo. Takes ownership.
+         * @since 3.0
+         * @param aOriginatorInfo OriginatorInfo
+         */
+        IMPORT_C void SetOriginatorInfoL(
+            CCMSOriginatorInfo* aOriginatorInfo );
+
+        /**
+         * Setter for recipientInfos. Takes ownership. 
+         * @since 3.0
+         * @param aRecipientInfos array of RecipientInfos. There must
+         * be at least one element in the array, otherwise thois
+         * method will leave with KErrArgument
+         */
+        IMPORT_C void SetRecipientInfosL(
+            CArrayPtr< CCMSRecipientInfo >* aRecipientInfos );
+
+        /**
+         * Setter for macAlgorithm. Takes ownership.
+         * @since 3.0
+         * @param aMacAlgorithm MessageAuthenticationCodeAlgorithm. If
+         * this parameter is null, this method leaves with KErrArgument.
+         */
+        IMPORT_C void SetMacAlgorithmL(
+            CCMSX509AlgorithmIdentifier* aMacAlgorithm );
+
+        /**
+         * Setter for digestAlgorithm. Takes ownership.
+         * @since 3.0
+         * @param aDigestAlgorithm DigestAlgorithmIdentifier
+         */
+        IMPORT_C void SetDigestAlgorithmL(
+            CCMSX509AlgorithmIdentifier* aDigestAlgorithm );
+
+
+        /**
+         * Setter for encapContentInfo. Takes ownership.
+         * @since 3.0
+         * @param aEncapContentInfo EncapsulatedContentInfo. If this
+         * parameter is NULL, this method will leave with KErrArgument.
+         */
+        IMPORT_C void SetEncapContentInfoL(
+            CCMSEncapsulatedContentInfo* aEncapContentInfo );
+
+        /**
+         * Setter for authenticatedAttributes. Takes ownership.
+         * @since 3.0
+         * @param aAuthenticatedAttributes array of attributes.
+         */
+        IMPORT_C void SetAuthenticatedAttributesL(
+            CArrayPtr< CCMSAttribute >* aAuthenticatedAttributes );
+
+        /**
+         * Setter for mac. Creates a copy.
+         * @since 3.0
+         * @param aMac MessageAuthenticationCode
+         */
+        IMPORT_C void SetMacL( const TDesC8& aMac );
+
+        /**
+         * Setter for unauthenticatedAttributes. Takes ownership.
+         * @since 3.0
+         * @param aUnuthenticatedAttributes array of attributes.
+         */
+        IMPORT_C void SetUnauthenticatedAttributesL(
+            CArrayPtr< CCMSAttribute >* aUnauthenticatedAttributes );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL();
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+			CArrayPtr< CCMSRecipientInfo >* aRecipientInfos,
+            CCMSX509AlgorithmIdentifier* aMacAlgorithm,
+        	CCMSEncapsulatedContentInfo* aEncapContentInfo,
+        	const TDesC8& aMac );
+        
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSAuthenticatedData();
+
+    private: // New functions
+
+        /**
+         * Decodes an attribute sequence.
+         */
+        CArrayPtrFlat< CCMSAttribute >* DecodeAttributesL(
+            TASN1DecGeneric* aAttributesDec );
+        
+    private:    // Data
+        // Contains the actual data, ownedw
+        CAuthenticatedDataData* iData;
+
+        // Reserved for extensions
+        MCMSAuthenticatedDataExtension* iReserved;
+        
+    };
+
+#endif      // CCMSAuthenticatedData_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSCertificateChoices.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,191 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef CCMSCertificateChoices_H
+#define CCMSCertificateChoices_H
+
+// INCLUDES
+#include <e32base.h>
+#include <asn1cons.h>
+#include "MCMSModule.h"
+
+// FORWARD DECLARATIONS
+class CCMSX509Certificate;
+class CCMSX509AttributeCertificate;
+
+// CONSTANTS
+const TTagType KCMSAttrCertTag = 1;
+
+// CLASS DECLARATION
+/**
+*  CertificateChoices type module
+*
+*  ASN.1 definition:
+*       CertificateChoices ::= CHOICE {
+*         certificate Certificate,                 -- See X.509
+*         extendedCertificate [0] IMPLICIT ExtendedCertificate,
+*                                                  -- Obsolete
+*         attrCert [1] IMPLICIT AttributeCertificate }
+*                                                  -- See X.509 and X9.57
+* 
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSCertificateChoices : public CBase, public MCMSModule
+    {
+
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSCertificateChoices* NewL();
+
+		/**
+        * Two-phased constructor. Leaves a copy in cleanup stack.
+        */
+        IMPORT_C static CCMSCertificateChoices* NewLC();
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aCertificate X.509 Certificate
+        */
+        IMPORT_C static CCMSCertificateChoices* NewL(
+            const CCMSX509Certificate& aCertificate );
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        * Leaves a copy in cleanup stack.
+        *
+        * @param aCertificate X.509 Certificate
+        */
+        IMPORT_C static CCMSCertificateChoices* NewLC(
+            const CCMSX509Certificate& aCertificate );
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aSubjectKeyIdentifier X.509 subjectKeyIdentifier
+        */
+        IMPORT_C static CCMSCertificateChoices* NewL(
+            const CCMSX509AttributeCertificate& aAttrCert );
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        * Leaves a copy in cleanup stack.
+        *
+        * @param aSubjectKeyIdentifier X.509 subjectKeyIdentifier
+        */
+        IMPORT_C static CCMSCertificateChoices* NewLC(
+            const CCMSX509AttributeCertificate& aAttrCert );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSCertificateChoices();
+
+    public: // New functions
+
+        /**
+        * Getter for certificate.
+        * @since 2.8
+        * @return Certificate or NULL
+        */
+		IMPORT_C const CCMSX509Certificate* Certificate() const;
+
+        /**
+        * Getter for attrCert.
+        * @since 2.8
+        * @return attrCert or NULL
+        */
+		IMPORT_C const CCMSX509AttributeCertificate* AttrCert() const;
+
+		/**
+        * Setter for Certificate. Create a copy of the parameters.
+        * @since 2.8
+        * @param aCertificate X.509 Certificate
+        */
+		IMPORT_C void SetCertificateL(
+            const CCMSX509Certificate& aCertificate );
+
+		/**
+        * Setter for attrCert. Create a copy of the parameters.
+        * @since 2.8
+        * @param aAttrCert X.509 AttributeCertificate
+        */
+		IMPORT_C void SetAttrCertL(
+            const CCMSX509AttributeCertificate& aAttrCert );
+
+
+    public: // Functions from base classes
+
+        /**
+        * From MCMSModule
+        * @since 2.8
+        * @param aResult Allocates and sets result in this variable
+        * @return ?description
+        */
+        void EncodeL( HBufC8*& aResult ) const;
+        
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSX509Certificate& aCertificate );
+
+        /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSX509AttributeCertificate& aAttrCert );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSCertificateChoices();
+
+    private:    // Data
+
+        // certificate value
+        CCMSX509Certificate* iCertificate;
+
+        // attrCert value
+        CCMSX509AttributeCertificate* iAttrCert;
+        
+    };
+
+#endif      // CCMSCertificateChoices_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSContentInfo.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,154 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef CCMSContentInfo_H
+#define CCMSContentInfo_H
+
+//  INCLUDES
+#include "CCMSSequence.h"
+
+// FORWARD DECLARATIONS
+// Extension
+class MCMSContentInfoExtension;
+
+// CLASS DECLARATION
+/**
+*  ContentInfo module
+*
+*  ASN.1 Definition:
+*  ContentInfo ::= SEQUENCE {
+*       contentType ContentType,
+*       content [0] EXPLICIT ANY DEFINED BY contentType }
+*
+*  ContentType ::= OBJECT IDENTIFIER
+*
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSContentInfo : public CCMSSequence
+    {
+    public:  // Destructor
+        
+		/**
+        * Two-phased constructor. Leaves the created object in cleanup stack.
+        */
+        IMPORT_C static CCMSContentInfo* NewLC();
+
+        /**
+        * Two-phased constructor.
+        * Takes copy of the both contetn type and content. Leaves the
+        * created object in cleanup stack.
+        * @param aAttributeType	The attribute type in desc e.g.
+        *						content type = "1.2.840.113549.1.7.1" (ID-Data).
+        * @param aContent		Content of this ContentInfo.
+        */
+        IMPORT_C static CCMSContentInfo* NewLC( const TDesC& aContentType,
+                                                const TDesC8& aContent );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSContentInfo();
+
+    public: // New functions
+
+        /**
+		* Getter for content type
+		* @since 2,8
+		* @return Content type in TDesC reference
+		*/
+		IMPORT_C const TDesC& ContentType() const;
+
+
+		/**
+        * Setter for content type, takes copy
+        * @since 2.8
+        * @param aContentType	Content type to be set as TDesC.
+        */
+		IMPORT_C void SetContentTypeL( const TDesC& aAttributeType );
+
+        /**
+        * Getter for content
+        * @since 3.0
+        * @return Content in TDesC8 reference
+        */
+		IMPORT_C const TDesC8& Content() const;
+
+        /**
+        * Setter for content, takes copy
+        * @since 3.0
+        * @param aContent Content to be set
+        */
+		IMPORT_C void SetContentL( const TDesC8& aContent );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+        
+    protected:  // New functions
+
+		/**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL();
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL( const TDesC& aContentType );
+
+        /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL( const TDesC& aContentType,
+                                  const TDesC8& aContent );
+        
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSContentInfo();
+
+    protected:    // Data
+        // Content Type, owned
+        HBufC* iContentType;
+
+        // Content, owned.
+        HBufC8* iContent;
+
+        // Reserved for extensions
+        MCMSContentInfoExtension* iReserved;
+    };
+
+#endif      // CCMSContentInfo_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSEncapsulatedContentInfo.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,143 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef CCMSEncapsulatedContentInfo_H
+#define CCMSEncapsulatedContentInfo_H
+
+//  INCLUDES
+#include "CCMSContentInfo.h"
+
+// FORWARD DECLARATIONS
+// Extension
+class MCMSEncapsulatedContentInfoExtension;
+
+
+// CLASS DECLARATION
+/**
+*  EncapsulatedContentInfo module
+*
+*  ASN.1 Definition:
+*  EncapsulatedContentInfo ::= SEQUENCE {
+*       eContentType ContentType,
+*       eContent [0] EXPLICIT OCTET STRING OPTIONAL }
+*
+*  ContentType ::= OBJECT IDENTIFIER
+*
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSEncapsulatedContentInfo : public CCMSContentInfo
+    {
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSEncapsulatedContentInfo* NewL();
+
+		/**
+        * Two-phased constructor. Leaves the created object in cleanup stack.
+        */
+        IMPORT_C static CCMSEncapsulatedContentInfo* NewLC();
+
+        /**
+        * Two-phased constructor.
+        * Takes copy of the both contetn type and content.
+        * @param aAttributeType	The attribute type in desc e.g.
+        *						content type = "1.2.840.113549.1.7.1" (ID-Data).
+        * @param aContent		Content of this ContentInfo. Can be also NULL
+        */
+        IMPORT_C static CCMSEncapsulatedContentInfo* NewL( const TDesC& aContentType,
+											  				const TDesC8* aContent );
+
+        /**
+        * Two-phased constructor.
+        * Takes copy of the both contetn type and content. Leaves the
+        * created object in cleanup stack.
+        * @param aAttributeType	The attribute type in desc e.g.
+        *						content type = "1.2.840.113549.1.7.1" (ID-Data).
+        * @param aContent		Content of this ContentInfo. Can be also NULL
+        */
+        IMPORT_C static CCMSEncapsulatedContentInfo* NewLC( const TDesC& aContentType,
+											  				const TDesC8* aContent );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSEncapsulatedContentInfo();
+
+    public: // New functions
+
+        /**
+        * Getter for content
+        * @since 2.8
+        * @return Content in TDesC8 reference
+        */
+		IMPORT_C const TDesC8* Content() const;
+
+        /**
+        * Setter for content, takes copy
+        * @since 2,8
+        * @param aContent Content to be set, can be NULL
+        */
+		IMPORT_C void SetContentL( const TDesC8* aContent );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL();
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL( const TDesC& aContentType,
+								  const TDesC8* aContent );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSEncapsulatedContentInfo();
+
+    private:    // Data
+
+		// Reserved for extensions
+		MCMSEncapsulatedContentInfoExtension* iReserved;
+    };
+
+#endif      // CCMSEncapsulatedContentInfo_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSIssuerAndSerialNumber.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,137 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef CCMSIssuerAndSerialNumber_H
+#define CCMSIssuerAndSerialNumber_H
+
+//  INCLUDES
+#include "CCMSSequence.h"
+
+// FORWARD DECLARATIONS
+class CX500DistinguishedName;
+
+// Extension
+class MCMSIssuerAndSerialNumberExtension;
+
+
+// CLASS DECLARATION
+/**
+*  IssuerAndSerialNumber type module
+*
+*  ASN.1 definition:
+*  IssuerAndSerialNumber ::= SEQUENCE {
+* 		issuer Name,
+*  		serialNumber CertificateSerialNumber }
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSIssuerAndSerialNumber : public CCMSSequence
+    {
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSIssuerAndSerialNumber* NewL();
+
+        /**
+        * Two-phased constructor.
+        * Does not take ownership of the issuer name
+        * @param aBinaryData	The encoded binary representation of issuer name.
+        * @param aSerialNumber	Serial number.
+        */
+        IMPORT_C static CCMSIssuerAndSerialNumber* NewL(
+											const CX500DistinguishedName& aIssuerName,
+        								    const TDesC8& aSerialNumber );
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSIssuerAndSerialNumber();
+
+    public: // New functions
+        /**
+        * Getter for issuer name
+        * @since 2.8
+        * @return Issuer name in CX500DistinguishedName reference
+        */
+		IMPORT_C const CX500DistinguishedName& IssuerName() const;
+
+        /**
+        * Getter for serial number
+        * @since 2,8
+        * @return Serial number
+        */
+		IMPORT_C const TDesC8& SerialNumber() const;
+
+		/**
+        * Setter for issuer name, takes copy of issuer name
+        * @since 2.8
+        * @param aBinaryData	Issuer name in CX500DistinguishedName.
+        */
+		IMPORT_C void SetIssuerNameL( const CX500DistinguishedName& aIssuerName );
+
+        /**
+        * Setter for serial number
+        * @since 2,8
+        * @param aSerialNumber Serial number to be set
+        */
+		IMPORT_C void SetSerialNumberL( const TDesC8& aSerialNumber );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL( const CX500DistinguishedName& aBinaryData,
+								  const TDesC8& aSerialNumber );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSIssuerAndSerialNumber();
+
+    private:    // Data
+        // Issuer name, owned
+        CX500DistinguishedName* iIssuerName;
+        // Serial number, owned
+		HBufC8* iSerialNumber;
+
+		// Reserved for extensions
+		MCMSIssuerAndSerialNumberExtension* iReserved;
+    };
+
+#endif      // CCMSIssuerAndSerialNumber_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSKEKRecipientInfo.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,156 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+#ifndef CCMSKEKRecipientInfo_H
+#define CCMSKEKRecipientInfo_H
+
+#include "CCMSRecipientInfo.h"
+
+// FORWARD DECLARATION
+class CCMSKeyIdentifier;
+
+// CONSTANTS
+const TInt KCMSKEKRecipientInfoVersion = 4;
+const TTagType KCMSKEKRecipientInfoTag = 2;
+
+// CLASS DECLARATION
+/**
+*  KEKRecipientInfo type module
+*
+*  ASN.1 definition:
+*    KEKRecipientInfo ::= SEQUENCE {
+*        version CMSVersion,  -- always set to 4
+*        kekid KEKIdentifier,
+*        keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
+*        encryptedKey EncryptedKey }
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSKEKRecipientInfo : public CCMSRecipientInfo
+    {
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor. Leaves the object in cleanup stack.
+        */
+        IMPORT_C static CCMSKEKRecipientInfo* NewLC();
+
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSKEKRecipientInfo* NewL();
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aKekid KEKIdentifier
+        * @param aKeyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier
+        * @param aEncryptedKey EncryptedKey value
+        */
+        IMPORT_C static CCMSKEKRecipientInfo* NewL(
+            const CCMSKeyIdentifier& aKekid,
+            const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+            const TDesC8& aEncryptedKey );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSKEKRecipientInfo();
+
+    public: // New functions
+        /**
+        * Getter for EncryptedKey
+        * @since 2.8
+        * @return EncryptedKey
+        */
+		IMPORT_C const TDesC8& EncryptedKey() const;
+
+        /**
+        * Getter for KEKIdentifier
+        * @since 2,8
+        * @return KEKIdentifier
+        */
+		IMPORT_C const CCMSKeyIdentifier& Kekid() const;
+
+		/**
+        * Setter for EncryptedKey. Creates a copy of the parameters.
+        * @since 2.8
+        * @param aEncryptedKey EncryptedKey value.
+        */
+		IMPORT_C void SetEncryptedKeyL(
+            const TDesC8& aEncryptedKey );
+
+		/**
+        * Setter for KEKIdentifier
+        * @since 2.8
+        * @param aKekid KEKIdentifier
+        */
+		IMPORT_C void SetKekidL(
+            const CCMSKeyIdentifier& aKekid );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+        
+        /**
+         * From CCMSRecipientInfo
+         * @since 2.8
+         * @return Returns ASN1 encoder with explicit tag 1 and leaves
+         * it in CleanupStack.
+         */
+        CASN1EncBase* TaggedEncoderLC() const;
+        
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSKeyIdentifier& aKekid,
+            const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+            const TDesC8& aEncryptedKey );
+
+        /**
+        * C++ constructor.
+        */
+        IMPORT_C CCMSKEKRecipientInfo( );
+
+    private:    // Data
+        // EncryptedKey, owned
+        TDesC8* iEncryptedKey;
+        // KEKIdentifier, owned
+        CCMSKeyIdentifier* iKekid;
+
+    };
+
+#endif      // CCMSKEKRecipientInfo_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSKeyAgreeRecipientInfo.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,221 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  CMS KeyAgreeRecipientInfo type
+*
+*/
+
+
+
+#ifndef CCMSKeyAgreeRecipientInfo_H
+#define CCMSKeyAgreeRecipientInfo_H
+
+// INCLUDES
+#include "CCMSRecipientInfo.h"
+
+// FORWARD DECLARATION
+class CCMSOriginatorIdentifierOrKey;
+class CCMSRecipientEncryptedKey;
+
+//Extension
+class MCMSKeyAgreeRecipientInfo;
+
+// CONSTANTS
+const TInt KCMSKeyAgreeRecipientInfoVersion = 3;
+const TTagType KCMSKeyAgreeRecipientInfoTag = 1;
+
+// CLASS DECLARATION
+/**
+*  KeyAgreeRecipientInfo type module
+*
+*  ASN.1 definition:
+*    KeyAgreeRecipientInfo ::= SEQUENCE {
+*        version CMSVersion,  -- always set to 3
+*        originator [0] EXPLICIT OriginatorIdentifierOrKey,
+*        ukm [1] EXPLICIT UserKeyingMaterial OPTIONAL,
+*        keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
+*        recipientEncryptedKeys RecipientEncryptedKeys }
+*
+*    RecipientEncryptedKeys ::= SEQUENCE OF RecipientEncryptedKey
+*
+*    UserKeyingMaterial ::= OCTET STRING
+*
+*  @lib cms.lib
+*  @since 3.0
+*/
+class CCMSKeyAgreeRecipientInfo : public CCMSRecipientInfo
+    {
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor. Leaves the object in cleanup stack.
+        */
+        IMPORT_C static CCMSKeyAgreeRecipientInfo* NewLC();
+
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSKeyAgreeRecipientInfo* NewL();
+        
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        * @param aOriginator OriginatorIdentifierOrKey value
+        * @param aKeyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier value
+        * @param aRecipientEncryptedKeys RecipientEncryptedKeys value
+        */
+        IMPORT_C static CCMSKeyAgreeRecipientInfo* NewL(
+            const CCMSOriginatorIdentifierOrKey& aOriginator,
+            const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+            const CArrayPtr< CCMSRecipientEncryptedKey >& aRecipientEncryptedKeys );
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        * @param aOriginator OriginatorIdentifierOrKey value
+        * @param aUkm UserKeyingMaterial value
+        * @param aKeyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier value
+        * @param aRecipientEncryptedKeys RecipientEncryptedKeys value
+        */
+        IMPORT_C static CCMSKeyAgreeRecipientInfo* NewL(
+            const CCMSOriginatorIdentifierOrKey& aOriginator,
+            const TDesC8& aUkm,
+            const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+            const CArrayPtr< CCMSRecipientEncryptedKey >& aRecipientEncryptedKeys );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSKeyAgreeRecipientInfo();
+
+    public: // New functions
+
+        /**
+        * Getter for Originator
+        * @since 3.0
+        * @return OriginatorIdentifierOrKey
+        */
+		IMPORT_C const CCMSOriginatorIdentifierOrKey& Originator() const;
+
+        /**
+        * Getter for RecipientEncryptedKeys
+        * @since 3.0
+        * @return array of RecipientEncryptedKeys
+        */
+		IMPORT_C const CArrayPtr< CCMSRecipientEncryptedKey >&
+        RecipientEncryptedKeys() const;
+
+        /**
+        * Getter for UserKeyingMaterial. Ownership is not transferred.
+        * @since 2,8
+        * @return UserKeyingMaterial or NULL
+        */
+		IMPORT_C const TDesC8* UserKeyingMaterial() const;
+
+		/**
+        * Setter for Originator. Creates a copy of the parameters.
+        * @since 3.0
+        * @param aOriginator OriginatorIdentifierOrKey
+        */
+		IMPORT_C void SetOriginatorL(
+            const CCMSOriginatorIdentifierOrKey& aOriginator );
+
+        /**
+        * Setter for RecipientEncryptedKeys. Creates a copy of the parameters.
+        * @since 3.0
+        * @param aRecipientEncryptedKeys Array of RecipientEncryptedKeys
+        */
+		IMPORT_C void SetRecipientEncryptedKeysL(
+            const CArrayPtr< CCMSRecipientEncryptedKey >& aRecipientEncryptedKeys );
+
+		/**
+        * Setter for UserKeyingMaterial. Creates a copy of the parameters.
+        * @since 3.0
+        * @param aUkm UserKeyingMaterial
+        */
+		IMPORT_C void SetUserKeyingMaterialL(
+            const TDesC8& aUkm );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+        /**
+         * From CCMSRecipientInfo
+         * @since 3.0
+         * @return Returns ASN1 encoder with explicit tag 1 and leaves
+         * it in CleanupStack.
+         */
+        CASN1EncBase* TaggedEncoderLC() const;
+         
+          
+        
+    protected:  // New functions
+
+        /**
+         * Protected constructor to allow derivation
+         */
+        IMPORT_C void ConstructL( );
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSOriginatorIdentifierOrKey& aOriginator,
+            const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+            const CArrayPtr< CCMSRecipientEncryptedKey >& aRecipientEncryptedKeys );
+
+       /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSOriginatorIdentifierOrKey& aOriginator,
+            const TDesC8& aUkm,
+            const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+            const CArrayPtr< CCMSRecipientEncryptedKey >& aRecipientEncryptedKeys );
+
+        /**
+        * C++ constructor.
+        */
+        IMPORT_C CCMSKeyAgreeRecipientInfo( );
+
+    private:    // Data
+        // originator, owned
+        CCMSOriginatorIdentifierOrKey* iOriginator;
+
+        // keyEncryptionAlgorithm, owned
+        CCMSX509AlgorithmIdentifier* iKeyEncryptionAlgorithm;
+
+        // recipientEncryptedKeys, owned
+        CArrayPtr< CCMSRecipientEncryptedKey >* iRecipientEncryptedKeys;
+
+        // UserKeyingMaterial, owned
+        TDesC8* iUserKeyingMaterial;
+
+        // Reserved for extensions
+        MCMSKeyAgreeRecipientInfo* iReserved;
+        
+    };
+
+#endif      // CCMSKeyAgreeRecipientInfo_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSKeyIdentifier.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,182 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  CMS KeyIdentifier type
+*
+*/
+
+
+
+#ifndef CCMSKeyIdentifier_H
+#define CCMSKeyIdentifier_H
+
+#include "CCMSSequence.h"
+
+// FORWARD DECLARATIONS
+// Extension
+class MCMSKeyIdentifierExtension;
+
+// CLASS DECLARATION
+/**
+*  This module handles two ASN.1 types, RecipientKeyIdentifier and
+*  KEKIdentifier.
+*
+*  ASN.1 definitions:
+*    RecipientKeyIdentifier ::= SEQUENCE {
+*        subjectKeyIdentifier SubjectKeyIdentifier,
+*        date GeneralizedTime OPTIONAL,
+*        other OtherKeyAttribute OPTIONAL }
+*
+*    SubjectKeyIdentifier ::= OCTET STRING
+*
+*    KEKIdentifier ::= SEQUENCE {
+*        keyIdentifier OCTET STRING,
+*        date GeneralizedTime OPTIONAL,
+*        other OtherKeyAttribute OPTIONAL }
+*
+*  @lib cms.lib
+*  @since 3.0
+*/
+class CCMSKeyIdentifier : public CCMSSequence
+    {
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSKeyIdentifier* NewL();
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aKeyIdentifier identifies the recipient's
+        * certificate or the the key-encryption key that was
+        * previously distributed to the sender and one or more recipients.
+        */
+        IMPORT_C static CCMSKeyIdentifier* NewL(
+            const TDesC8& aKeyIdentifier );
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aKeyIdentifier identifies the recipient's
+        * certificate or the the key-encryption key that was
+        * previously distributed to the sender and one or more recipients.
+        * @param aDate specifies which of the
+        * recipient's previously distributed UKMs was used by the
+        * sender. In case of KEKIdentifier, specifies a single
+        * key-encryption key from a set.
+        */
+        IMPORT_C static CCMSKeyIdentifier* NewL(
+            const TDesC8& aKeyIdentifier,
+            const TTime& aDate );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSKeyIdentifier();
+
+    public: // New functions
+        /**
+        * Getter for KeyIdentifier
+        * @since 3.0
+        * @return KeyIdentifier
+        */
+		IMPORT_C const TDesC8& KeyIdentifier() const;
+
+        /**
+        * Getter for Date. Ownership is not transferred.
+        * @since 2,8
+        * @return Date. Ownership is not transferred.
+        */
+		IMPORT_C const TTime* Date() const;
+
+		/**
+        * Setter for KeyIdentifier. Creates a copy of the parameters.
+        * @since 3.0
+        * @param aKeyIdentifier KeyIdentifier value.
+        */
+		IMPORT_C void SetKeyIdentifierL(
+            const TDesC8& aKeyIdentifier );
+
+        /**
+        * Setter for Date. Creates a copy of the parameters.
+        * @since 3.0
+        * @param aDate Date value
+        */
+		IMPORT_C void SetDateL( const TTime& aDate );
+
+        /**
+         * Decoder method with implicit tag checking.
+         * @since 3.0
+         * @param aRawData raw-data to be parsed in this instance
+         * @param aImplicitTag tag to be checked
+         */
+        void DecodeImplicitTagL( const TDesC8& aRawData,
+                                 const TTagType aImplicitTag );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL( const TDesC8& aKeyIdentifier );
+
+       /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL( const TDesC8& aKeyIdentifier,
+                                  const TTime& aDate );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSKeyIdentifier();
+
+    private: // New Methods
+
+        /**
+         * Decodes internal data from a array of ASN.1 decoders
+         * @param aItems items to internalize
+         */
+        void DecodeArrayL( CArrayPtr< TASN1DecGeneric >* aItems );
+
+    private:    // Data
+        // KeyIdentifier, owned
+        TDesC8* iKeyIdentifier;
+        // Date, owned
+		TTime* iDate;
+
+        // Reserved for extensions
+        MCMSKeyIdentifierExtension* iReserved;
+        
+    };
+
+#endif      // CCMSKeyIdentifier_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSKeyTransRecipientInfo.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,217 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef CCMSKeyTransRecipientInfo_H
+#define CCMSKeyTransRecipientInfo_H
+
+#include "CCMSRecipientInfo.h"
+
+// FORWARD DECLARATION
+class CCMSIssuerAndSerialNumber;
+
+// CONSTANTS
+const TInt KCMSKeyTransRecipientInfoIssuerAndSerialNumberVersion = 0;
+const TInt KCMSKeyTransRecipientInfoSubjectKeyIdentifierVersion = 2;
+
+// CLASS DECLARATION
+/**
+*  KeyTransRecipientInfo type module
+*
+*  ASN.1 definition:
+*    KeyTransRecipientInfo ::= SEQUENCE {
+*        version CMSVersion,  -- always set to 0 or 2
+*        rid RecipientIdentifier,
+*        keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
+*        encryptedKey EncryptedKey }
+*
+*    RecipientIdentifier ::= CHOICE {
+*        issuerAndSerialNumber IssuerAndSerialNumber,
+*        subjectKeyIdentifier [0] SubjectKeyIdentifier }
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSKeyTransRecipientInfo : public CCMSRecipientInfo
+    {
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor. Leaves the object in cleanup stack.
+        */
+        IMPORT_C static CCMSKeyTransRecipientInfo* NewLC();
+
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSKeyTransRecipientInfo* NewL();
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aIssuerAndSerialNumber rid (RecipientIdentifier) value
+        * @param aKeyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier
+        * @param aEncryptedKey EncryptedKey value
+        */
+        IMPORT_C static CCMSKeyTransRecipientInfo* NewL(
+            const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber,
+            const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+            const TDesC8& aEncryptedKey );
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        * Leaves the object in cleanup stack.
+        *
+        * @param aSubjectKeyIdentifier rid (RecipientIdentifier) value
+        * @param aKeyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier
+        * @param aEncryptedKey EncryptedKey value
+        */
+        IMPORT_C static CCMSKeyTransRecipientInfo* NewLC(
+            const TDesC8& aSubjectKeyIdentifier,
+            const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+            const TDesC8& aEncryptedKey );
+        
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aSubjectKeyIdentifier rid (RecipientIdentifier) value
+        * @param aKeyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier
+        * @param aEncryptedKey EncryptedKey value
+        */
+        IMPORT_C static CCMSKeyTransRecipientInfo* NewL(
+            const TDesC8& aSubjectKeyIdentifier,
+            const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+            const TDesC8& aEncryptedKey );
+
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSKeyTransRecipientInfo();
+
+    public: // New functions
+        /**
+        * Getter for EncryptedKey
+        * @since 2.8
+        * @return EncryptedKey
+        */
+		IMPORT_C const TDesC8& EncryptedKey() const;
+
+        /**
+        * Getter for IssuerAndSerialNumber. Ownership is not transferred.
+        * @since 2,8
+        * @return IssuerAndSerialNumber or NULL if rid is not
+        * IssuerAndSerialNumber
+        */
+		IMPORT_C const CCMSIssuerAndSerialNumber* IssuerAndSerialNumber() const;
+
+        /**
+        * Getter for subjectKeyIdentifier. Ownership is not transferred.
+        * @since 2,8
+        * @return subjectKeyIdentifier or NULL if rid is not
+        * subjectKeyIdentifier.
+        */
+		IMPORT_C const TDesC8* SubjectKeyIdentifier() const;
+
+		/**
+        * Setter for EncryptedKey. Creates a copy of the parameters.
+        * @since 2.8
+        * @param aEncryptedKey EncryptedKey value.
+        */
+		IMPORT_C void SetEncryptedKeyL(
+            const TDesC8& aEncryptedKey );
+
+		/**
+        * Setter for IssuerAndSerialNumber. Creates a copy of the parameters.
+        * Note that any existing subjectKeyIdentifier value is
+        * deleted. Also version is set to 0.
+        * @since 2.8
+        * @param aIssuerAndSerialNumber IssuerAndSerialNumber value.
+        */
+		IMPORT_C void SetIssuerAndSerialNumberL(
+            const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber );
+
+		/**
+        * Setter for subjectKeyIdentifier. Creates a copy of the parameters.
+        * Note that any existing IssuerAndSerialNumber value is
+        * deleted. Also version is set to 2.
+        * @since 2.8
+        * @param aSubjectKeyIdentifier SubjectKeyIdentifier value.
+        */
+		IMPORT_C void SetSubjectKeyIdentifierL(
+            const TDesC8& aSubjectKeyIdentifier );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+        
+        /**
+         * From CCMSRecipientInfo
+         * @since 2.8
+         * @return Returns ASN1 encoder with explicit tag 1 and leaves
+         * it in CleanupStack.
+         */
+        CASN1EncBase* TaggedEncoderLC() const;
+        
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber,
+            const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+            const TDesC8& aEncryptedKey );
+
+       /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const TDesC8& aSubjectKeyIdentifier,
+            const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm,
+            const TDesC8& aEncryptedKey );
+
+        /**
+        * C++ constructor.
+        */
+        IMPORT_C CCMSKeyTransRecipientInfo( TInt aVersion );
+
+    private:    // Data
+        // EncryptedKey, owned
+        TDesC8* iEncryptedKey;
+        // IssuerAndSerialNumber, owned
+        CCMSIssuerAndSerialNumber* iIssuerAndSerialNumber;
+        // RecipientEncryptedKey, owned
+        TDesC8* iSubjectKeyIdentifier;
+
+    };
+
+#endif      // CCMSKeyTransRecipientInfo_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSOriginatorIdentifierOrKey.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,238 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef CCMSOriginatorIdentifierOrKey_H
+#define CCMSOriginatorIdentifierOrKey_H
+
+// INCLUDES
+#include <e32base.h>
+#include <asn1cons.h>
+#include "MCMSModule.h"
+
+// FORWARD DECLARATIONS
+class CCMSIssuerAndSerialNumber;
+class CCMSOriginatorPublicKey;
+class CASN1EncBase;
+
+// CLASS DECLARATION
+/**
+*  OriginatorIdentifierOrKey type module
+*
+*  ASN.1 definition:
+*  OriginatorIdentifierOrKey ::= CHOICE {
+*        issuerAndSerialNumber IssuerAndSerialNumber,
+*        subjectKeyIdentifier [0] SubjectKeyIdentifier,
+*        originatorKey [1] OriginatorPublicKey }
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSOriginatorIdentifierOrKey : public CBase, public MCMSModule
+    {
+    public: // data types
+        enum TType
+            {
+            ESubjectKeyIdentifier = 0,
+            EOriginatorKey = 1,
+            EIssuerAndSerialNumber
+            };
+
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSOriginatorIdentifierOrKey* NewL();
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aIssuerAndSerialNumber identifies sender's certificate
+        */
+        IMPORT_C static CCMSOriginatorIdentifierOrKey* NewL(
+            const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber );
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aSubjectKeyIdentifier X.509 subjectKeyIdentifier
+        */
+        IMPORT_C static CCMSOriginatorIdentifierOrKey* NewL(
+            const TDesC8& aSubjectKeyIdentifier );
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aOriginatorKey includes algorithm identifier and public key
+        */
+        IMPORT_C static CCMSOriginatorIdentifierOrKey* NewL(
+            const CCMSOriginatorPublicKey& aOriginatorKey );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSOriginatorIdentifierOrKey();
+
+    public: // New functions
+        /**
+         * Getter for the CHOICE type. There is no corresponding
+         * setter method as the type is set implicitly by the member
+         * value setters.
+         * @since 2.8
+         * @return the CHOICE type
+         */
+        IMPORT_C TType Type() const;
+
+        /**
+        * Getter for IssuerAndSerialNumber. Leaves with KErrNotFound
+        * if the type of this CHOICE is not EIssuerAndSerialNumber.
+        * @since 2.8
+        * @return IssuerAndSerialNumber
+        */
+		IMPORT_C const CCMSIssuerAndSerialNumber&
+        IssuerAndSerialNumberL() const;
+
+        /**
+        * Getter for the X.509 subjectKeyIdentifier. Leaves with
+        * KErrNotFound if the type of this CHOICE is not ESubjectKeyIdentifier.
+        * @since 2,8
+        * @return subjectKeyIdentifier
+        */
+		IMPORT_C const TDesC8& SubjectKeyIdentifierL() const;
+
+        /**
+         * Getter for OriginatorKey. Leaves with KErrNotFound if the
+         * type of this CHOICE is not EOriginatorKey.
+         * @since 2,8
+         * @return OriginatorKey
+         */
+        IMPORT_C const CCMSOriginatorPublicKey& OriginatorKeyL() const;
+
+		/**
+        * Setter for IssuerAndSerialNumber. Create a copy of the parameters.
+        * @since 2.8
+        * @param aIssuerAndSerialNumber identifies sender's certificate
+        */
+		IMPORT_C void SetIssuerAndSerialNumberL(
+            const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber );
+
+        /**
+        * Setter for subjectKeyIdentifier
+        * @since 2,8
+        * @param aSubjectKeyIdentifier X.509 subjectKeyIdentifier
+        */
+		IMPORT_C void SetSubjectKeyIdentifierL(
+            const TDesC8& aSubjectKeyIdentifier );
+
+        /**
+         * Setter for originatorKey
+         * @since 2.8
+         * @param aOriginatorKey includes algorithm identifier and
+         * public key
+         */
+        IMPORT_C void SetOriginatorKeyL(
+            const CCMSOriginatorPublicKey& aOriginatorKey );
+
+    public: // Functions from base classes
+
+        /**
+        * From MCMSModule
+        * @since 2.8
+        * @param aResult Allocates and sets result in this variable
+        * @return ?description
+        */
+        void EncodeL( HBufC8*& aResult ) const;
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber );
+
+        /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const TDesC8& aSubjectKeyIdentifier );
+
+        /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSOriginatorPublicKey& aOriginatorKey );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSOriginatorIdentifierOrKey();
+
+    private: // New functions
+
+        /**
+         * Deletes old value and changes the type of the choice.
+         * @param aNewType The type of the CHOICE will be set to
+         * aNewType.
+         */
+        void DeleteOldValueAndChangeTypeL( TType aNewType );
+
+        /**
+         * Creates Encoder for the SubjectKeyIdentifier value 
+         * @return ASN1 encoder
+         */
+        CASN1EncBase* EncoderSubjectKeyIdentifierLC() const;
+
+        /**
+         * Creates Encoder for the OriginatorKey value
+         * @return ASN1 encoder
+         */
+        CASN1EncBase* EncoderOriginatorKeyLC() const;
+        
+    private:    // Data
+
+        // defines the type of this CHOICE
+        TType iType;
+
+        // IssuerAndSerialNumber value. owned.
+        CCMSIssuerAndSerialNumber* iIssuerAndSerialNumber;
+
+        // SubjectKeyIdentifier value. owned.
+        HBufC8* iSubjectKeyIdentifier;
+
+        // OriginatorPublicKey value. owned.
+        CCMSOriginatorPublicKey* iOriginatorKey;
+
+    };
+
+#endif      // CCMSOriginatorIdentifierOrKey_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSOriginatorInfo.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,142 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef CCMSOriginatorInfo_H
+#define CCMSOriginatorInfo_H
+
+#include "CCMSSequence.h"
+
+// FORWARD DECLARATION
+class CCMSCertificateChoices;
+class CCMSX509CertificateList;
+
+// CLASS DECLARATION
+/**
+*  CMS OriginatorInfo type module
+*
+*  ASN.1 definition:
+*      OriginatorInfo ::= SEQUENCE {
+*        certs [0] IMPLICIT CertificateSet OPTIONAL,
+*        crls [1] IMPLICIT CertificateRevocationLists OPTIONAL } 
+*
+*      CertificateSet ::= SET OF CertificateChoices
+*
+*      CertificateRevocationLists ::= SET OF CertificateList
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSOriginatorInfo : public CCMSSequence
+    {
+
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSOriginatorInfo* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSOriginatorInfo();
+
+    public: // New functions
+
+        /**
+        * Getter for certs.
+        * @since 2.8
+        * @return CertificateSet or NULL
+        */
+		IMPORT_C const CArrayPtr< CCMSCertificateChoices >* Certs() const;
+
+        /**
+        * Getter for crls.
+        * @since 2.8
+        * @return CertificateRevocationLists or NULL
+        */
+		IMPORT_C const CArrayPtr< CCMSX509CertificateList >* Crls() const;
+
+        /**
+        * Setter for certs. Takes ownership.
+        * @since 2.8
+        * @param aCerts CertificateSet
+        */
+		IMPORT_C void
+        SetCerts( CArrayPtr< CCMSCertificateChoices >* aCerts );
+
+        /**
+        * Setter for crls. Takes ownership.
+        * @since 2.8
+        * @param aCrls CertificateRevocationLists
+        */
+		IMPORT_C void
+        SetCrls( CArrayPtr< CCMSX509CertificateList >* aCrls );
+
+        /**
+         * Decoder method with implicit tag checking.
+         * @since 2.8
+         * @param aRawData raw-data to be parsed in this instance
+         * @param aImplicitTag tag to be checked
+         */
+        void DecodeImplicitTagL( const TDesC8& aRawData,
+                                 const TTagType aImplicitTag );         
+        
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSOriginatorInfo( );
+
+    private: // New Methods
+
+        /**
+         * Decodes internal data from a array of ASN.1 decoders
+         * @param aItems items to internalize
+         */
+        void DecodeArrayL( CArrayPtr< TASN1DecGeneric >* aItems );
+        
+    private:    // Data
+        // certs, owned
+        CArrayPtr< CCMSCertificateChoices >* iCerts;
+
+        // crls, owned
+        CArrayPtr< CCMSX509CertificateList >* iCrls;
+        
+    };
+
+#endif      // CCMSOriginatorInfo_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSOriginatorPublicKey.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,156 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef CCMSOriginatorPublicKey_H
+#define CCMSOriginatorPublicKey_H
+
+#include "CCMSSequence.h"
+
+// FORWARD DECLARATIONS
+class CCMSX509AlgorithmIdentifier;
+
+// CLASS DECLARATION
+/**
+*  OriginatorPublicKey type module
+*
+*  ASN.1 definition:
+*  OriginatorPublicKey ::= SEQUENCE {
+*    algorithm AlgorithmIdentifier,
+*    publicKey BIT STRING }
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSOriginatorPublicKey : public CCMSSequence
+    {
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSOriginatorPublicKey* NewL();
+
+        /**
+         * Two-phased copy constructor.
+         */
+        IMPORT_C static CCMSOriginatorPublicKey* NewL(
+            const CCMSOriginatorPublicKey& aOriginatorPublicKey );
+
+        /**
+         * Two-phased copy constructor. Leaves the created object to
+         * cleanup stack.
+         */
+        IMPORT_C static CCMSOriginatorPublicKey* NewLC(
+            const CCMSOriginatorPublicKey& aOriginatorPublicKey );
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aAlgorithm Algorithm Identifier.
+        * @param aPublicKey The public key. Must be in big-endian order.
+        */
+        IMPORT_C static CCMSOriginatorPublicKey* NewL(
+            const CCMSX509AlgorithmIdentifier& aAlgorithm,
+            const TDesC8& aPublicKey );
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        * Leaves the created object to cleanup stack
+        *
+        * @param aAlgorithm Algorithm Identifier.
+        * @param aPublicKey The public key. Must be in big-endian order.
+        */
+        IMPORT_C static CCMSOriginatorPublicKey* NewLC(
+            const CCMSX509AlgorithmIdentifier& aAlgorithm,
+            const TDesC8& aPublicKey );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSOriginatorPublicKey();
+
+    public: // New functions
+        /**
+        * Getter for algorithm identifier
+        * @since 2.8
+        * @return The algorithm identifier
+        */
+		IMPORT_C const CCMSX509AlgorithmIdentifier& Algorithm() const;
+
+        /**
+        * Getter for public key
+        * @since 2,8
+        * @return public key
+        */
+		IMPORT_C const TDesC8& PublicKey() const;
+
+		/**
+        * Setter for algorithm identifier. Create a copy of the parameters.
+        * @since 2.8
+        * @param aAlgorithm the algorithm identifier
+        */
+		IMPORT_C void SetAlgorithmL(
+            const CCMSX509AlgorithmIdentifier& aAlgorithm );
+
+        /**
+        * Setter for public key. Creates a copy of the parameter.
+        * @since 2,8
+        * @param aPublicKey the public key in big-endian format
+        */
+		IMPORT_C void SetPublicKeyL( const TDesC8& aPublicKey );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL( const CCMSX509AlgorithmIdentifier& aAlgorithm,
+								  const TDesC8& aPublicKey );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSOriginatorPublicKey();
+
+    private:    // Data
+        // Issuer name, owned
+        CCMSX509AlgorithmIdentifier* iAlgorithm;
+        // public key, owned
+		HBufC8* iPublicKey;
+
+    };
+
+#endif      // CCMSOriginatorPublicKey_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSRecipientEncryptedKey.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,180 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef CCMSRecipientEncryptedKey_H
+#define CCMSRecipientEncryptedKey_H
+
+#include "CCMSSequence.h"
+
+// FORWARD DECLARATIONS
+class CCMSIssuerAndSerialNumber;
+class CCMSKeyIdentifier;
+
+// CLASS DECLARATION
+/**
+*  RecipientEncryptedKey type module
+*
+*  ASN.1 definition:
+*  RecipientEncryptedKey ::= SEQUENCE {
+*        rid KeyAgreeRecipientIdentifier,
+*        encryptedKey EncryptedKey }
+*
+*  KeyAgreeRecipientIdentifier ::= CHOICE {
+*        issuerAndSerialNumber IssuerAndSerialNumber,
+*        rKeyId [0] IMPLICIT RecipientKeyIdentifier }
+*
+*  EncryptedKey ::= OCTET STRING
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSRecipientEncryptedKey : public CCMSSequence
+    {
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSRecipientEncryptedKey* NewL();
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aIssuerAndSerialNumber rid (KeyAgreeRecipientIdentifier) value
+        * @param aEncryptedKey EncryptedKey value
+        */
+        IMPORT_C static CCMSRecipientEncryptedKey* NewL(
+            const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber,
+            const TDesC8& aEncryptedKey );
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aRKeyId rid (KeyAgreeRecipientIdentifier) value
+        * @param aEncryptedKey EncryptedKey value
+        */
+        IMPORT_C static CCMSRecipientEncryptedKey* NewL(
+            const CCMSKeyIdentifier& aRKeyId,
+            const TDesC8& aEncryptedKey );
+
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSRecipientEncryptedKey();
+
+    public: // New functions
+        /**
+        * Getter for EncryptedKey
+        * @since 2.8
+        * @return EncryptedKey
+        */
+		IMPORT_C const TDesC8& EncryptedKey() const;
+
+        /**
+        * Getter for IssuerAndSerialNumber. Ownership is not transferred.
+        * @since 2,8
+        * @return IssuerAndSerialNumber or NULL if rid is not
+        * IssuerAndSerialNumber
+        */
+		IMPORT_C const CCMSIssuerAndSerialNumber* IssuerAndSerialNumber() const;
+
+        /**
+        * Getter for rKeyId. Ownership is not transferred.
+        * @since 2,8
+        * @return rKeyId or NULL if rid is not rKeyId.
+        */
+		IMPORT_C const CCMSKeyIdentifier* RKeyId() const;
+
+		/**
+        * Setter for EncryptedKey. Creates a copy of the parameters.
+        * @since 2.8
+        * @param aEncryptedKey EncryptedKey value.
+        */
+		IMPORT_C void SetEncryptedKeyL(
+            const TDesC8& aEncryptedKey );
+
+		/**
+        * Setter for IssuerAndSerialNumber. Creates a copy of the parameters.
+        * Note that any existing rKeyId value is deleted.
+        * @since 2.8
+        * @param aIssuerAndSerialNumber IssuerAndSerialNumber value.
+        */
+		IMPORT_C void SetIssuerAndSerialNumberL(
+            const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber );
+
+		/**
+        * Setter for rKeyId. Creates a copy of the parameters.
+        * Note that any existing IssuerAndSerialNumber value is deleted.
+        * @since 2.8
+        * @param aRKeyId RecipientEncryptedKey value.
+        */
+		IMPORT_C void SetRKeyIdL(
+            const CCMSKeyIdentifier& aRKeyId );
+
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSIssuerAndSerialNumber& aIssuerAndSerialNumber,
+            const TDesC8& aEncryptedKey );
+
+       /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSKeyIdentifier& aRKeyId,
+            const TDesC8& aEncryptedKey );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSRecipientEncryptedKey();
+
+    private:    // Data
+        // EncryptedKey, owned
+        TDesC8* iEncryptedKey;
+        // IssuerAndSerialNumber, owned
+        CCMSIssuerAndSerialNumber* iIssuerAndSerialNumber;
+        // RecipientEncryptedKey, owned
+        CCMSKeyIdentifier* iRKeyId;
+
+    };
+
+#endif      // CCMSRecipientEncryptedKey_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSRecipientInfo.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,116 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+#ifndef CCMSRecipientInfo_H
+#define CCMSRecipientInfo_H
+
+//  INCLUDES
+#include 	"CCMSSequence.h"
+
+// FORWARD DECLARATIONS
+class CCMSX509AlgorithmIdentifier;
+
+// CLASS DECLARATION
+/**
+*  Base class for RecipientInfo -type modules
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSRecipientInfo : public CCMSSequence
+    {
+
+    public: // Destructor
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSRecipientInfo();
+        
+    public: // New functions
+
+        /**
+         * Returns the encoder wrapped within appropriate tag.
+         * Must be implemented in derived classes.
+         * @since 2.8
+         * @return encoder for a tagged object
+         */
+        virtual CASN1EncBase* TaggedEncoderLC() const = 0;
+        
+        /**
+         * Getter for version number.
+         * @since 2.8
+         * @return version (0, 2, 3 or 4)
+         */
+        IMPORT_C TInt Version() const;
+
+        /**
+         * Getter for keyEncryptionAlgorithm
+         * @since 2.8
+         * @return Algorithm identifier
+         */
+        IMPORT_C const CCMSX509AlgorithmIdentifier&
+        KeyEncryptionAlgorithm() const;
+
+        /**
+         * Setter for keyEncryptionAlgorithm. Makes a copy.
+         * @since 2.8
+         * @param aKeyEncryptionAlgorithm Algorithm identifier
+         */
+        IMPORT_C void SetKeyEncryptionAlgorithmL(
+            const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm );
+        
+    protected:  // New functions
+       /**
+        * C++ default constructor.
+        */
+        CCMSRecipientInfo( TInt aVersion );
+
+        /**
+         * Constructs the member variables. Makes a copy of
+         * aKeyEncryptionAlgorithm.
+         */
+        void BaseConstructL(
+            const CCMSX509AlgorithmIdentifier& aKeyEncryptionAlgorithm );
+
+        /**
+         * Adds version encoding to root sequence
+         * @param aRoot sequence where version encoding is added
+         */
+        void AddVersionL( CASN1EncSequence* aRoot ) const;
+
+        /**
+         * Adds keyEncryptionAlgorithm encoding to root sequence
+         * @param aRoot sequence where keyEncryptionAlgorithm encoding
+         * is added
+         */
+        void AddKeyEncryptionAlgorithmL( CASN1EncSequence* aRoot ) const;
+        
+    protected: // Data
+
+        // syntax version number.
+        TInt iVersion;
+
+        // KeyEncryptionAlgorithmIdentifier, owned
+        CCMSX509AlgorithmIdentifier* iKeyEncryptionAlgorithm;
+        
+    };
+
+#endif      // CCMSRecipientInfo_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSSequence.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,107 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef CCMSSequence_H
+#define CCMSSequence_H
+
+//  INCLUDES
+#include 	"MCMSModule.h"
+#include 	<asn1dec.h>
+#include 	<asn1enc.h>
+
+// CLASS DECLARATION
+/**
+*  Base class for sequence (or set) type of modules.
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSSequence : public CBase, public MCMSModule
+    {
+	public: // From MCMSModule
+		/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aResult Allocates and sets result in this variable
+        * @return ?description
+        */
+        void EncodeL( HBufC8*& aResult ) const;
+
+    protected:  // New functions
+       /**
+        * C++ default constructor.
+        */
+        CCMSSequence();
+
+        /**
+        * Decode a generic ASN1 sequence
+        * @since 2.8
+        * @param aRawData raw-data to be splitted in ASN.1 Modules
+        * @return Array of generic asn.1 modules.
+        */
+        IMPORT_C static CArrayPtr<TASN1DecGeneric>* DecodeSequenceLC( const TDesC8& aRawData );
+
+        /**
+		* Decode a generic ASN1 sequence, with a minimum/maximum number
+		* of top level terms. Will leave with KErrArgument if number of terms
+		* is not between valid range (including min and max)
+		* @since 2.8
+		* @param aRawData raw-data to be splitted in ASN.1 Modules
+		* @param aMinTerms minimum of top level terms.
+		* @param aMaxTerms maximum number of top level terms.
+		* @return Array of generic asn.1 modules.
+        */
+        IMPORT_C static CArrayPtr<TASN1DecGeneric>* DecodeSequenceLC( const TDesC8& aRawData,
+        															  TInt aMinTerms,
+        															  TInt aMaxTerms );
+		/**
+         * Creates DER encoded descriptor and leaves it to 
+		 * CleanupStack
+		 * @since 2.8
+		 * @param aEncoding base encoding to be encoded
+		 * @return new heap buffer containing der encoded content
+         */
+		IMPORT_C static HBufC8* CreateDerEncodingL( CASN1EncBase* aEncoding );
+
+    };
+
+// taken from MMF, did not want to make dependency to MMF
+template <class T>
+class CleanupResetAndDestroy
+	{
+public:
+	inline static void PushL(T& aRef);
+private:
+	static void ResetAndDestroy(TAny *aPtr);
+	};
+template <class T>
+inline void CleanupResetAndDestroyPushL(T& aRef);
+template <class T>
+inline void CleanupResetAndDestroy<T>::PushL(T& aRef)
+	{CleanupStack::PushL(TCleanupItem(&ResetAndDestroy,&aRef));}
+template <class T>
+void CleanupResetAndDestroy<T>::ResetAndDestroy(TAny *aPtr)
+	{(STATIC_CAST(T*,aPtr))->ResetAndDestroy();}
+template <class T>
+inline void CleanupResetAndDestroyPushL(T& aRef)
+	{CleanupResetAndDestroy<T>::PushL(aRef);}
+
+#endif      // CCMSSequence_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSSignedData.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,317 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef CCMSSignedData_H
+#define CCMSSignedData_H
+
+//  INCLUDES
+#include "CCMSSequence.h"
+#include "CCMSEncapsulatedContentInfo.h"
+#include "CCMSX509AlgorithmIdentifier.h"
+#include "CCMSSignerInfo.h"
+#include "CCMSX509CertificateList.h"
+#include "CCMSCertificateChoices.h"
+#include <badesca.h>
+
+// FORWARD DECLARATIONS
+
+// Extension
+class MCMSSignedDataExtension;
+
+
+// CLASS DECLARATION
+/**
+*  Attribute type module
+*
+*  ASN.1 Definition:
+*  SignedData ::= SEQUENCE {
+*  	 version CMSVersion,
+*    digestAlgorithms DigestAlgorithmIdentifiers,
+*    encapContentInfo EncapsulatedContentInfo,
+*    certificates [0] IMPLICIT CertificateSet OPTIONAL,
+*    crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
+*    signerInfos SignerInfos }
+*
+*  DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
+*
+*  SignerInfos ::= SET OF SignerInfo
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSSignedData : public CCMSSequence
+    {
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        * NOTE: Encrypt will leave with KErrArgument if
+        * valid parameters are not set.
+        */
+        IMPORT_C static CCMSSignedData* NewLC();
+
+        /**
+        * Two-phased constructor.
+        * Takes copy of all parameters.
+        * Leaves newly created instance in CleanupStack
+		*
+		* @param aDigestAlgorithmIdentifiers Array of digest algorithm 
+		*		 identifiers, mandatory
+        * @param aContentInfo Encapsulated content info, mandatory
+		* @param aSignerInfos, Array of signer infos, mandatory
+        */
+        IMPORT_C static CCMSSignedData* NewLC(
+			const CArrayPtr< CCMSX509AlgorithmIdentifier >& aDigestAlgorithmIdentifiers,
+        	const CCMSEncapsulatedContentInfo& aContentInfo,
+        	const CArrayPtr< CCMSSignerInfo >& aSignerInfos );
+
+		/**
+        * Two-phased constructor.
+        * Same as above although takes only one value
+		* Leaves newly created instance in CleanupStack
+		* @param aDigestAlgorithmIdentifiers Array of digest algorithm 
+		*		 identifiers, mandatory
+        * @param aContentInfo Encapsulated content info, mandatory
+		* @param aSignerInfos, Array of signer infos, mandatory
+		* @param aCertificates Array of certificates choices, optional
+		* @param aRevokedCertificates Array of revoked certificates, optional
+        */
+        IMPORT_C static CCMSSignedData* NewLC(
+			const CArrayPtr< CCMSX509AlgorithmIdentifier >& aDigestAlgorithmIdentifiers,
+        	const CCMSEncapsulatedContentInfo& aContentInfo,
+        	const CArrayPtr< CCMSSignerInfo >& aSignerInfos,
+        	const CArrayPtr< CCMSCertificateChoices >* aCertificates,
+        	const CArrayPtr< CCMSX509CertificateList >* aRevokedCertificates );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSSignedData();
+
+    public: // New functions
+
+    	/**
+		* Getter for Version
+		*
+		* Version is the syntax version number.  If no attribute
+		* certificates are present in the certificates field, the
+		* encapsulated content type is id-data, and all of the elements of
+		* SignerInfos are version 1, then the value of version shall be 1.
+		* Alternatively, if attribute certificates are present, the
+		* encapsulated content type is other than id-data, or any of the
+		* elements of SignerInfos are version 3, then the value of version
+		* shall be 3.
+		*
+		* @since 2.8
+		* @return version number, 1 or 3
+		*/
+		IMPORT_C TInt Version() const;
+
+    	/**
+		* Getter for DigestAlgorithmIdentifiers
+		*
+		* DigestAlgorithms is a collection of message digest algorithm
+		* identifiers.  There may be any number of elements in the
+		* collection, including zero.  Each element identifies the message
+		* digest algorithm, along with any associated parameters, used by
+		* one or more signer.  The collection is intended to list the
+		* message digest algorithms employed by all of the signers, in any
+		* order, to facilitate one-pass signature verification.
+		*
+		* @since 2.8
+		* @return Array of digest algorithm identifiers.
+		*/
+		IMPORT_C const CArrayPtr< CCMSX509AlgorithmIdentifier >& DigestAlgorithmIdentifiers() const;
+
+    	/**
+		* Getter for EncapsulatedContentInfo
+		*
+		* EncapsulatedContentInfo is the signed content, consisting of a content
+		* type identifier and the content itself.
+		* 
+		* @since 2.8
+		* @return Encapsulated content info.
+		*/
+        IMPORT_C const CCMSEncapsulatedContentInfo& EncapsulatedContentInfo() const;
+
+    	/**
+		* Getter for SignerInfos
+		*
+		* SignerInfos is a collection of per-signer information.  There may
+		* be any number of elements in the collection, including zero.
+		*
+		* @since 2.8
+		* @return Array of signer infos, array might be also empty
+		*/
+        IMPORT_C const CArrayPtr< CCMSSignerInfo >& SignerInfos() const;
+
+    	/**
+		* Getter for Certificate
+		*
+		* Certificates is a collection of certificates.  It is intended that
+		* the set of certificates be sufficient to contain chains from a
+		* recognized "root" or "top-level certification authority" to all of
+		* the signers in the signerInfos field.  There may be more
+		* certificates than necessary, and there may be certificates
+		* sufficient to contain chains from two or more independent top-
+		* level certification authorities.  There may also be fewer
+		* certificates than necessary, if it is expected that recipients
+		* have an alternate means of obtaining necessary certificates (e.g.,
+		* from a previous set of certificates).  
+		*
+		* @since 2.8
+		* @return Array of certificates or NULL if certificates are absent
+		*/
+        IMPORT_C const CArrayPtr< CCMSCertificateChoices >* Certificates() const;
+
+    	/**
+		* Getter for RevokedCertificates
+		*
+		* RevokedCertificates is a collection of certificate revocation lists (CRLs).  
+		* It is intended that the set contain information sufficient to
+		* determine whether or not the certificates in the certificates
+		* field are valid, but such correspondence is not necessary.  There
+		* may be more CRLs than necessary, and there may also be fewer CRLs
+		* than necessary.
+		*
+		* @since 2.8
+		* @return Array of revoked certificates or NULL if there is no revoked
+		*	      certificates
+		*/
+        IMPORT_C 
+		const CArrayPtr< CCMSX509CertificateList >* RevokedCertificates() const;
+
+		/**
+        * Setter for DigestAlgorithmIdentifiers, takes copy
+		*
+        * @since 2.8
+        * @param aDigestAlgorithmIdentifiers Array of digest algorithm identifiers
+        */
+		IMPORT_C void SetDigestAlgorithmIdentifiersL(
+			const CArrayPtr< CCMSX509AlgorithmIdentifier >&
+											aDigestAlgorithmIdentifiers );
+
+		/**
+        * Setter for EncapsulatedContentInfo, takes copy
+        * @since 2.8
+        * @param aContentInfo Encapsulated content info
+        */
+        IMPORT_C void SetEncapsulatedContentInfoL(
+			const CCMSEncapsulatedContentInfo& aContentInfo );
+
+		/**
+        * Setter for SignerInfos, takes copy
+        * @since 2.8
+        * @param aSignerInfos Array of signer info, array can be also empty
+        */
+        IMPORT_C void SetSignerInfosL(
+			const CArrayPtr< CCMSSignerInfo >& aSignerInfos );
+
+		/**
+        * Setter for Certificates, takes copy
+        * @since 2.8
+        * @param aCertificates Array of certificates or NULL if certificates
+		*	     are intented to remove from this instance
+        */
+        IMPORT_C void SetCertificatesL(
+			const CArrayPtr< CCMSCertificateChoices >* aCertificates );
+
+		/**
+        * Setter for RevokedCertificates, takes copy
+        * @since 2.8
+        * @param aRevokedCertificates Array of revoked certificates or NULL if
+		*		 removing revoked certificates from this instance
+        */
+        IMPORT_C void SetRevokedCertificatesL(
+			const CArrayPtr< CCMSX509CertificateList >* aRevokedCertificates );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL();
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+			const CArrayPtr< CCMSX509AlgorithmIdentifier >& aDigestAlgorithmIdentifiers,
+        	const CCMSEncapsulatedContentInfo& aContentInfo,
+        	const CArrayPtr< CCMSSignerInfo >& aSignerInfos,
+        	const CArrayPtr< CCMSCertificateChoices >* aCertificates,
+        	const CArrayPtr< CCMSX509CertificateList >* aRevokedCertificates );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSSignedData();
+
+	private:
+		
+		/**
+		 * Finds out right version with following rules:
+		 *
+		 * If no attribute certificates are present in the certificates field, the
+		 * encapsulated content type is id-data, and all of the elements of
+		 * SignerInfos are version 1, then the value of version shall be 1.
+		 *
+		 * Alternatively, if attribute certificates are present, the
+		 * encapsulated content type is other than id-data, or any of the
+		 * elements of SignerInfos are version 3, then the value of version
+		 * shall be 3.
+		 */
+		void ValidateVersion();
+
+    private:    // Data
+		TInt iVersion;
+
+		// DigestAlgorithmIdentifiers, owned
+		CArrayPtr< CCMSX509AlgorithmIdentifier >* iDigestAlgorithmIdentifiers;
+		// Encapsulate Content Info, owned
+		CCMSEncapsulatedContentInfo* iContentInfo;
+		// Signer Infos, owned
+		CArrayPtr< CCMSSignerInfo >* iSignerInfos;
+		// Certificates, owned, null if absent
+		CArrayPtr< CCMSCertificateChoices >* iCertificates;
+		// Revoked certificates, owned, null if absent
+		CArrayPtr< CCMSX509CertificateList >* iRevokedCertificates;
+
+		// Reserved for extensions
+		MCMSSignedDataExtension* iReserved;
+    };
+
+#endif      // CCMSSignedData_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSSignerInfo.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,327 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef CCMSSignerInfo_H
+#define CCMSSignerInfo_H
+
+//  INCLUDES
+#include "CCMSSequence.h"
+#include "CCMSIssuerAndSerialNumber.h"
+#include "CCMSAttribute.h"
+#include "CCMSX509AlgorithmIdentifier.h"
+#include "CCMSX509Certificate.h"
+
+#include <badesca.h>
+
+// FORWARD DECLARATIONS
+class CASN1EncBase;
+// Extension
+class MCMSSignerInfoExtension;
+
+
+// CLASS DECLARATION
+/**
+*  SignerInfo module
+*
+*  SignerInfo ::= SEQUENCE {
+*  version CMSVersion,
+*  sid SignerIdentifier,
+*  digestAlgorithm DigestAlgorithmIdentifier,
+*  signedAttrs [0] IMPLICIT SignedAttributes OPTIONAL,
+*  signatureAlgorithm SignatureAlgorithmIdentifier,
+*  signature SignatureValue,
+*  unsignedAttrs [1] IMPLICIT UnsignedAttributes OPTIONAL }
+*
+*  SignerIdentifier ::= CHOICE {
+*  issuerAndSerialNumber IssuerAndSerialNumber,
+*  subjectKeyIdentifier [0] SubjectKeyIdentifier }
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSSignerInfo : public CCMSSequence
+    {
+	private:
+		/*
+		 * Container for signer info data
+		 */
+		NONSHARABLE_CLASS( CSignerInfoData ) : public CBase
+			{
+			public: // Destructor
+				~CSignerInfoData();
+			public: // data
+				// version
+				TInt iVersion;
+
+				// Issuer and serial, owned
+				CCMSIssuerAndSerialNumber* iIssuerAndSerial;
+
+				// Subject Key ID, owned
+				HBufC8* iSubjectKeyIdentifier;
+
+				// Signed attributes, owned
+				CArrayPtrFlat<CCMSAttribute>* iSignedAttributes;
+				// Unsigned attribute, owned
+				CArrayPtrFlat<CCMSAttribute>* iUnsignedAttributes;
+
+				// Digested algorithm identifier, owned
+				CCMSX509AlgorithmIdentifier* iDigestAI;
+				// Signature algorithm identifier, owned
+				CCMSX509AlgorithmIdentifier* iSignatureAI;
+
+				// Signature value, owned
+				HBufC8* iSignatureValue;
+			};
+
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        * NOTE: Encrypt will leave with KErrBadDescriptor if
+        * valid Attribute Type has not setted.
+        */
+        IMPORT_C static CCMSSignerInfo* NewL();
+
+        /**
+        * Two-phased constructor.
+        * Takes copy of the both type and values.
+        * @param aCertificate		Used certificate
+        * @param aMessageDigest	    Message Digest value
+        */
+        IMPORT_C static CCMSSignerInfo* NewL( const CCMSX509Certificate& aCertificate,
+											  const TDesC8& aMessageDigest );
+
+		/**
+		* Two-phased constructor.
+		* Takes copy of the both type and values.
+		* @param aCertificateUrl	Used certificate url
+		* @param aSubjectKeyID		Subject Key ID
+		* @param aMessageDigest	    Message Digest value
+		*/
+		IMPORT_C static CCMSSignerInfo* NewL( const TDesC8& aCertificateUrl,
+											  const TDesC8& aSubjectKeyID,
+								  			  const TDesC8& aMessageDigest );
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSSignerInfo();
+
+    public: // New functions
+
+        /**
+		* Getter for Version
+		* @since 2,8
+		* @return Version number (1 or 3)
+		*/
+		IMPORT_C TInt CMSVersion() const;
+
+		/**
+		* Getter for IssuerAndSerialNumber
+		* This will be present when normal certificate is used
+		* @since 2,8
+		* @return IssuerAndSerialNumber or NULL if not present
+		*/
+		IMPORT_C const CCMSIssuerAndSerialNumber* IssuerAndSerialNumber() const;
+
+		/**
+		* Getter for SubjectKeyIdentifier
+		* This will be present only if certificate url is used
+		* @since 2,8
+		* @return SubjectKeyIdentifier or NULL if not present
+		*/
+		IMPORT_C const TDesC8* SubjectKeyIdentifier() const;
+
+		/**
+		* Getter for DigestAlgorithmIdentifier
+		* Default value is SHA-1
+		* @since 2,8
+		* @return DigestAlgorithmIdentifier in CX509AlgorithmIdentifier instance
+		*/
+		IMPORT_C const CCMSX509AlgorithmIdentifier& DigestAlgorithmIdentifier() const;
+
+		/**
+		* Getter for SignedAttributes
+		* @since 2,8
+		* @return SignedAttributes in pointer array
+		*/
+		IMPORT_C const CArrayPtrFlat<CCMSAttribute>& SignedAttributes() const;
+
+        /**
+         * Gets signedAttributes in encoded form, with SET OF tag instead of [0].
+         * This data is supposed to be signed.
+         * since 3.0
+         * @return encoded form of signedAttributes, NULL if there are no signedAttributes
+         */
+        IMPORT_C HBufC8* SignedAttributesEncodedL() const;
+        
+		/**
+		* Getter for SignatureAlgorithmIdentifier
+		* Default value is RSA
+		* @since 2,8
+		* @return SignatureAlgorithmIdentifier in CX509AlgorithmIdentifier instance
+		*/
+		IMPORT_C const CCMSX509AlgorithmIdentifier& SignatureAlgorithmIdentifier() const;
+
+		/**
+		* Getter for SignatureValue
+		* @since 2,8
+		* @return SignatureValue in TDesC8 reference
+		*/
+		IMPORT_C const TDesC8& SignatureValue() const;
+
+		/**
+		* Getter for UnsignedAttributes
+		*
+		* @since 2,8
+		* @return UnsignedAttributes in array
+		*/
+		IMPORT_C const CArrayPtrFlat<CCMSAttribute>& UnsignedAttributes() const;
+
+        /**
+		* Setter for Certificate
+		*
+		* @since 2,8
+		* @param aCertificate certificate to be set
+		*/
+		IMPORT_C void SetCertificateL( const CCMSX509Certificate& aCertificate );
+
+		/**
+		* Getter for SubjectKeyIdentifier
+		* @since 2,8
+		* @param aCertificateUrl certificate url to be set
+		* @param aSubjectKeyIdentifier SubjectKeyIdentifier to be set
+		*/
+		IMPORT_C void SetCertificateUrlL( const TDesC8& aCertificateUrl,
+										  const TDesC8& aSubjectKeyIdentifier );
+
+		/**
+		* Setter for DigestAlgorithmIdentifier
+		* Transfers ownership
+		* @since 2,8
+		* @param aDigestAI Digest algorithm identifier to be set
+		*/
+		IMPORT_C void SetDigestAlgorithmIdentifier(
+						CCMSX509AlgorithmIdentifier& aDigestAI );
+
+		/**
+		* Setter for SignatureAlgorithmIdentifier
+		* Transfers ownership
+		* @since 2,8
+		* @param aSignatureAI Signature algorithm identifier to be set
+		*/
+		IMPORT_C void SetSignatureAlgorithmIdentifier(
+						CCMSX509AlgorithmIdentifier& aSignatureAI );
+
+		/**
+		* Setter for SignatureValue
+		* @since 2,8
+		* @param aSignatureValue Signature value to be set
+		*/
+		IMPORT_C void SetSignatureValueL( const TDesC8& aSignatureValue );
+
+
+		/**
+		 * Setter for Signed attributes
+		 * Support for ContentType, MessageDigest,
+		 * SigningTime and SigningCert
+		 * If some of the parameters are not wanted to add use KNullDesC or
+		 * KNullDesC8
+		 * @since 2,8
+		 * @param aContentType ContentType in OID form, e.g. "1.2.840.113549.1.7.1"
+		 * @param aMessageDigest Message Digest
+		 * @param aSigningTime In most cases current time
+		 * @param aCertHash Certificate hash
+		 */
+		IMPORT_C void SetSignedAttributesL( const TDesC& aContentType,
+											const TDesC8& aMessageDigest,
+											const TTime& aSigningTime,
+											const TDesC8* aCertHash );
+		/**
+		 * Setter for Unsigned attributes
+		 * Transfers ownership
+		 * @since 2,8
+		 * @param aUnsignedAttributes Array of attributes,
+		 *							  to be set in unsigned attributes.
+		 */
+		IMPORT_C void SetUnsignedAttributesL( CArrayPtrFlat<CCMSAttribute>&
+											  aUnsignedAttributes );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL( const TDesC8& aCertificateUrl,
+        						  const TDesC8& aSubjectKeyID,
+								  const TDesC8& aMessageDigest );
+
+		/**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL( const CCMSX509Certificate& aCertificate,
+								  const TDesC8& aMessageDigest );
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSSignerInfo();
+
+        /**
+         * Default construction
+         */
+        virtual void BaseConstructL( const TDesC8& aMessageDigest );
+
+	private: // New functions
+
+		/**
+		 * Decodes attributes to array
+		 */
+		void DecodeAttributesL( const TDesC8& aRawData,
+								CArrayPtrFlat<CCMSAttribute>* aAttributes );
+
+		/**
+		 * Creates certificate url attribute
+		 */
+		CCMSAttribute* CreateCertificateUrlLC( const TDesC8& aCertificateUrl );
+
+    private:    // Data
+		// contains all members, owned
+		CSignerInfoData* iData;
+
+		// Reserved for extensions
+		MCMSSignerInfoExtension* iReserved;
+    };
+
+#endif      // CCMSSignerInfo_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSX509AlgorithmIdentifier.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,156 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ?Description
+*
+*/
+
+
+
+#ifndef CCMSX509AlgorithmIdentifier_H
+#define CCMSX509AlgorithmIdentifier_H
+
+//  INCLUDES
+#include "CCMSSequence.h"
+#include <signed.h>
+#include <x509cert.h>
+
+// FORWARD DECLARATIONS
+// Extension
+class MCMSX509AlgorithmIdentifier;
+
+
+// CLASS DECLARATION
+/**
+*  X509 algorith identifier extension
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSX509AlgorithmIdentifier : public CCMSSequence
+    {
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        * Default Algorith Identifier is RSA
+        */
+        IMPORT_C static CCMSX509AlgorithmIdentifier* NewL();
+
+        /**
+        * Two-phased constructor.
+        * @param aAlgorithmId	Used AlgorithmID
+        */
+        IMPORT_C static CCMSX509AlgorithmIdentifier* NewL(
+											const TAlgorithmId& aAlgorithmId );
+
+		/**
+        * Two-phased constructor.
+        * @param aAlgorithmIdentifier	The algorithm ID object to be used
+        */
+        IMPORT_C static CCMSX509AlgorithmIdentifier* NewL(
+							const CAlgorithmIdentifier& aAlgorithmIdentifier );
+
+	   /**
+        * Two-phased constructor.
+        * @param aAlgorithmIdentifier	The algorithm ID for algorithm
+		* @param aDigestIdentifier	The algorithm ID for digest
+        */
+        IMPORT_C static CCMSX509AlgorithmIdentifier* NewL(
+							const CAlgorithmIdentifier& aAlgorithmIdentifier,
+							const CAlgorithmIdentifier& aDigestIdentifier );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSX509AlgorithmIdentifier();
+
+    public: // New functions
+
+        /**
+		* Getter for AlgorithmIdentifier
+		* @since 2,8
+		* @return Algorithm identifier
+		*/
+		IMPORT_C const CAlgorithmIdentifier& AlgorithmIdentifier() const;
+
+        /**
+        * Setter for AlgorithmIdentifier
+        * @since 2.8
+		* @param aAlgorithmIdentifier	The algorithm ID
+        */
+		IMPORT_C void SetAlgorithmIdentifierL(
+							const CAlgorithmIdentifier& aAlgorithmIdentifier );
+
+		/**
+		* Getter for DigestAlgorithmIdentifier
+		* @since 2,8
+		* @return Digest algorithm identifier or NULL if absent
+		*/
+		IMPORT_C const CAlgorithmIdentifier* DigestAlgorithm() const;
+
+        /**
+        * Setter for DigestAlgorithmIdentifier
+        * @since 2.8
+		* @param aAlgorithmIdentifier The algorithm ID for digest or NULL if
+		*							  removing digest algorithm ID
+        */
+		IMPORT_C void SetDigestAlgorithmL(
+							const CAlgorithmIdentifier* aAlgorithmIdentifier );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+		/**
+		 * From MCMSModule
+		 * @since 2.8
+		 * @return Returns ASN1 encoder and leaves it in CleanupStack
+		 */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL( const TAlgorithmId& aAlgorihmId );
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL( const CAlgorithmIdentifier& aAlgorithmIdentifier );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSX509AlgorithmIdentifier();
+
+    private:    // Data
+        // Algorithm identifier, owned
+        CAlgorithmIdentifier* iAlgorithmIdentifier;
+
+		// Digest algorithm identifier, owned
+        CAlgorithmIdentifier* iDigestAlgorithmIdentifier;
+
+		// Reserved for extensions
+		MCMSX509AlgorithmIdentifier* iReserved;
+    };
+
+#endif      // CCMSX509AlgorithmIdentifier_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSX509AttributeCertificate.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,166 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  X.509 AttributeCertificate type
+*
+*/
+
+
+
+#ifndef CCMSX509AttributeCertificate_H
+#define CCMSX509AttributeCertificate_H
+
+#include "CCMSSequence.h"
+#include "CCMSX509Signed.h"
+
+// FORWARD DECLARATIONS
+class CCMSX509AttributeCertificateInfo;
+class CCMSX509AlgorithmIdentifier;
+
+// Extensions
+class MCMSX509AttributeCertificateExtension;
+
+// CLASS DECLARATION
+/**
+*  X.509 AttributeCertificateInfo type module
+*
+*  ASN.1 definition:
+* AttributeCertificate ::= SIGNED{AttributeCertificateInfo}
+*
+* SIGNATURE{ToBeSigned} ::= SEQUENCE {
+*  algorithmIdentifier  AlgorithmIdentifier,
+*  encrypted            ENCRYPTED-HASH{ToBeSigned}
+* }
+*
+* SIGNED{ToBeSigned} ::= SEQUENCE {
+*  toBeSigned  ToBeSigned,
+*  COMPONENTS OF SIGNATURE{ToBeSigned}
+* }
+*
+*  @lib cms.lib
+*  @since 3.0
+*/
+class CCMSX509AttributeCertificate : public CCMSX509Signed
+    {
+
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSX509AttributeCertificate* NewL();
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        * 
+        * @param aInfo AttributeCertificateInfo, contains the actual
+        * data of the certificate.
+        * @param aAlgorithmIdentifier identifies the algorithm used in
+        * the signature 
+        * @param aEncrypted must be the result of applying a hashing
+        * procedure to the DER-encoded octets of a value of
+        * aInfo and then applying an encipherment
+        * procedure to those octets
+        */
+        IMPORT_C static CCMSX509AttributeCertificate* NewL(
+            const CCMSX509AttributeCertificateInfo& aInfo,
+            const CCMSX509AlgorithmIdentifier& aAlgorithmIdentifier,
+            const TDesC8& aEncrypted
+            );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSX509AttributeCertificate();
+
+    public: // New functions
+        /**
+        * Getter for the info.
+        * @since 3.0
+        * @return X.509 AttributeCertificateInfo value
+        */
+		IMPORT_C const CCMSX509AttributeCertificateInfo& Info() const;
+
+        /**
+        * Setter for the info. Creates a copy.
+        * @since 3.0
+        * @param aInfo X.509 AttributeCertificateInfo
+        */
+		IMPORT_C void SetInfoL( const CCMSX509AttributeCertificateInfo& aInfo );
+
+        /**
+         * Decoder method with implicit tag checking.
+         * @since 3.0
+         * @param aRawData raw-data to be parsed in this instance
+         * @param aImplicitTag tag to be checked
+         */
+        void DecodeImplicitTagL( const TDesC8& aRawData,
+                                 const TTagType aImplicitTag );
+        
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSX509AttributeCertificateInfo& aInfo,
+            const CCMSX509AlgorithmIdentifier& aAlgorithmIdentifier,
+            const TDesC8& aEncrypted
+            );
+
+        /**
+         * Protected construction to allow derivation
+         */
+        IMPORT_C void ConstructL( );
+        
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSX509AttributeCertificate( );
+        
+    private: // New Methods
+
+        /**
+         * Decodes internal data from a array of ASN.1 decoders
+         * @param aItems items to internalize
+         */
+        void DecodeArrayL( CArrayPtr< TASN1DecGeneric >* aItems );
+
+    private:    // Data
+        // Contains the actual attribute certificate (without
+        // signature). Owned.
+        CCMSX509AttributeCertificateInfo* iInfo;
+
+        // Reserved for extensions
+        MCMSX509AttributeCertificateExtension* iReserved;
+        
+    };
+
+#endif      // CCMSX509AttributeCertificate_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSX509AttributeCertificateInfo.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,373 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  X.509 AttributeCertificateInfo type
+*
+*/
+
+
+
+#ifndef CCMSX509AttributeCertificateInfo_H
+#define CCMSX509AttributeCertificateInfo_H
+
+#include "CCMSSequence.h"
+
+// FORWARD DECLARATIONS
+class CCMSX509GeneralNames;
+class CCMSX509IssuerSerial;
+class CCMSX509AlgorithmIdentifier;
+class CCMSAttribute;
+
+// Extensions
+class MCMSX509AttributeCertificateInfoExtension;
+
+// CLASS DECLARATION
+/**
+*  X.509 AttributeCertificateInfo type module
+*
+*  ASN.1 definition:
+*   AttributeCertificateInfo ::= SEQUENCE {
+*    version                Version DEFAULT v1,
+*    subject
+*     CHOICE {baseCertificateID  [0]  IssuerSerial, --  associated
+*                                                with a Public Key Certificate--
+*             subjectName        [1]  GeneralNames}, --  associated  with a name
+*    issuer                 GeneralNames, --  CA issuing the attribute
+*                                             certificate
+*    signature              AlgorithmIdentifier,
+*    serialNumber           CertificateSerialNumber,
+*    attCertValidityPeriod  AttCertValidityPeriod,
+*    attributes             SEQUENCE OF Attribute,
+*    issuerUniqueID         UniqueIdentifier OPTIONAL,
+*    extensions             Extensions OPTIONAL
+*   }
+*
+*   CertificateSerialNumber ::= INTEGER
+*
+*   AttCertValidityPeriod ::= SEQUENCE {
+*    notBeforeTime  GeneralizedTime,
+*    notAfterTime   GeneralizedTime
+*   }
+*
+*  @lib cms.lib
+*  @since 3.0
+*/
+class CCMSX509AttributeCertificateInfo : public CCMSSequence
+    {
+
+    private:
+        /**
+         * Container for certificate data
+         */
+        NONSHARABLE_CLASS( CAttributeCertificateData ) : public CBase
+            {
+            public: // destructor
+                ~CAttributeCertificateData();
+            public: // data
+                // version
+                TInt iVersion;
+
+                // subject value, owned
+                CCMSX509IssuerSerial* iBaseCertificateID;
+                // subject value, owned
+                CCMSX509GeneralNames* iSubjectName;
+
+                // issuer, owned
+                CCMSX509GeneralNames* iIssuer;
+                // signature, owned
+                CCMSX509AlgorithmIdentifier* iSignature;
+                // serialNumber
+                TInt iSerialNumber;
+                
+                // attCertValidityPeriod not before time
+                TTime iNotBeforeTime;
+                // attCertValidityPeriod not after time
+                TTime iNotAfterTime;
+
+                // attributes, owned
+                CArrayPtr< CCMSAttribute >* iAttributes;
+
+                // issuerUniqueID, optional, owned
+                TDesC8* iIssuerUniqueID;
+            };
+        
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSX509AttributeCertificateInfo* NewL();
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        * 
+        * @param aBaseCertificateID subject, associated with a Public
+        * Key Certificate
+        * @param aIssuer CA issuing the attribute certificate
+        * @param aSignature signature value
+        * @param aSerialNumber serialNumber value
+        * @param aNotBeforeTime attCertValidityPeriod value
+        * @param aNotAfterTime attCertValidityPeriod value
+        * @param aAttributes attributes value
+        */
+        IMPORT_C static CCMSX509AttributeCertificateInfo* NewL(
+            const CCMSX509IssuerSerial& aBaseCertificateID,
+            const CCMSX509GeneralNames& aIssuer,
+            const CCMSX509AlgorithmIdentifier& aSignature,
+            const TInt aSerialNumber,
+            const TTime& aNotBeforeTime,
+            const TTime& aNotAfterTime,
+            const CArrayPtr< CCMSAttribute >& aAttributes );
+            
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        * 
+        * @param aSubjectName subject, associated with a name
+        * @param aIssuer CA issuing the attribute certificate
+        * @param aSignature signature value
+        * @param aSerialNumber serialNumber value
+        * @param aNotBeforeTime attCertValidityPeriod value
+        * @param aNotAfterTime attCertValidityPeriod value
+        * @param aAttributes attributes value
+        */
+        IMPORT_C static CCMSX509AttributeCertificateInfo* NewL(
+            const CCMSX509GeneralNames& aSubjectName,
+            const CCMSX509GeneralNames& aIssuer,
+            const CCMSX509AlgorithmIdentifier& aSignature,
+            const TInt aSerialNumber,
+            const TTime& aNotBeforeTime,
+            const TTime& aNotAfterTime,
+            const CArrayPtr< CCMSAttribute >& aAttributes );
+
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSX509AttributeCertificateInfo();
+
+    public: // New functions
+        /**
+        * Getter for Version.
+        * @since 3.0
+        * @return Version value
+        */
+		IMPORT_C TInt Version() const;
+
+        /**
+        * Getter for baseCertifiedID (subject value)
+        * @since 3.0
+        * @return X.509 IssuerSerial value, or NULL if subject is not
+        * baseCertificateID
+        */
+		IMPORT_C const CCMSX509IssuerSerial* BaseCertificateID() const;
+
+        /**
+        * Getter for subjectName (subject value)
+        * @since 3.0
+        * @return X.509 GeneralNames value, or NULL if subject
+        * is not subjectName
+        */
+		IMPORT_C const CCMSX509GeneralNames* SubjectName() const;
+
+        /**
+        * Getter for issuer.
+        * @since 3.0
+        * @return X.509 GeneralNames value
+        */
+		IMPORT_C const CCMSX509GeneralNames& Issuer() const;
+
+        /**
+        * Getter for signature.
+        * @since 3.0
+        * @return X.509 AlgorithmIdentifier value
+        */
+		IMPORT_C const CCMSX509AlgorithmIdentifier& Signature() const;
+
+        /**
+        * Getter for serialNumber.
+        * @since 3.0
+        * @return X.509 CertificateSerialNumber value
+        */
+		IMPORT_C TInt SerialNumber() const;
+
+        /**
+        * Getter for notBeforeTime (part of attCertValidityPeriod).
+        * @since 3.0
+        * @return notBeforeTime value
+        */
+		IMPORT_C const TTime& NotBeforeTime() const;
+
+        /**
+        * Getter for notAfterTime (part of attCertValidityPeriod).
+        * @since 3.0
+        * @return notAfterTime value
+        */
+		IMPORT_C const TTime& NotAfterTime() const;
+
+        /**
+        * Getter for attributes
+        * @since 3.0
+        * @return attribute array
+        */
+		IMPORT_C const CArrayPtr< CCMSAttribute >& Attributes() const;
+
+        /**
+        * Getter for issuerUniqueID
+        * @since 3.0
+        * @return X.509 UniqueIdentifier (BIT STRING), or NULL if
+        * issuerUniqueID is absent.
+        */
+		IMPORT_C const TDesC8* IssuerUniqueID() const;
+        
+        /**
+        * Setter for Version
+        * @since 3.0
+        * @param aVersion Version value.
+        */
+		IMPORT_C void SetVersion( const TInt aVersion );
+
+		/**
+        * Setter for baseCertificateID. Creates a copy. Deletes also
+        * subjectName value.
+        * @since 3.0
+        * @param aBaseCertificateID subject value, associated  with a
+        * Public Key Certificate 
+        */
+		IMPORT_C void SetBaseCertificateIDL(
+            const CCMSX509IssuerSerial& aBaseCertificateID );
+
+		/**
+        * Setter for subjectName. Creates a copy. Deletes also
+        * baseCertificateID value.
+        * @since 3.0
+        * @param aSubjectName subject value, associated  with a name
+        */
+		IMPORT_C void SetSubjectNameL(
+            const CCMSX509GeneralNames& aSubjectName );
+
+        /**
+        * Setter for issuer. Creates a copy.
+        * @since 3.0
+        * @param aIssuer X.509 GeneralNames value
+        */
+		IMPORT_C void SetIssuerL( const CCMSX509GeneralNames& aIssuer );
+
+        /**
+        * Setter for signature. Creates a copy.
+        * @since 3.0
+        * @param aSignature X.509 AlgorithmIdentifier value
+        */
+		IMPORT_C void
+        SetSignatureL( const CCMSX509AlgorithmIdentifier& aSignature );
+
+        /**
+        * Setter for serialNumber.
+        * @since 3.0
+        * @param aSerialNumber X.509 CertificateSerialNumber value
+        */
+		IMPORT_C void SetSerialNumber( const TInt aSerialNumber );
+
+        /**
+        * Setter for notBeforeTime (part of attCertValidityPeriod).
+        * Creates a copy
+        * @since 3.0
+        * @param aNotBeforeTime notBeforeTime value
+        */
+		IMPORT_C void SetNotBeforeTimeL( const TTime& aNotBeforeTime );
+
+        /**
+        * Setter for notAfterTime (part of attCertValidityPeriod).
+        * Creates a copy.
+        * @since 3.0
+        * @param aNotAfterTime notAfterTime value
+        */
+		IMPORT_C void SetNotAfterTimeL( const TTime& aNotAfterTime );
+
+        /**
+        * Setter for attributes. Creates a copy.
+        * @since 3.0
+        * @param aAttributes attribute array
+        */
+		IMPORT_C void
+        SetAttributesL( const CArrayPtr< CCMSAttribute >& aAttributes );
+
+        /**
+        * Setter for issuerUniqueID. Creates a copy.
+        * @since 3.0
+        * @param aIssuerUniqueID X.509 UniqueIdentifier (BIT STRING)
+        */
+		IMPORT_C void SetIssuerUniqueIDL( const TDesC8& aIssuerUniqueID );
+                
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSX509IssuerSerial& aBaseCertificateID,
+            const CCMSX509GeneralNames& aIssuer,
+            const CCMSX509AlgorithmIdentifier& aSignature,
+            const TInt aSerialNumber,
+            const TTime& aNotBeforeTime,
+            const TTime& aNotAfterTime,
+            const CArrayPtr< CCMSAttribute >& aAttributes );
+            
+       /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSX509GeneralNames& aSubjectName,
+            const CCMSX509GeneralNames& aIssuer,
+            const CCMSX509AlgorithmIdentifier& aSignature,
+            const TInt aSerialNumber,
+            const TTime& aNotBeforeTime,
+            const TTime& aNotAfterTime,
+            const CArrayPtr< CCMSAttribute >& aAttributes );
+
+        /**
+         * Protected construction to allow derivation
+         */
+        IMPORT_C void ConstructL( );
+        
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSX509AttributeCertificateInfo( );
+
+    private:    // Data
+        // Contains all members, owned
+        CAttributeCertificateData* iData;
+
+        // Reserved for extensions
+        MCMSX509AttributeCertificateInfoExtension* iReserved;
+        
+    };
+
+#endif      // CCMSX509AttributeCertificateInfo_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSX509Certificate.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,363 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  X.509 Certificate type
+*
+*/
+
+
+
+#ifndef CCMSX509Certificate_H
+#define CCMSX509Certificate_H
+
+#include "CCMSX509Signed.h"
+
+// FORWARD DECLARATIONS
+class CCMSX509AlgorithmIdentifier;
+class CCMSX509SubjectPublicKeyInfo;
+class CX500DistinguishedName;
+class CCMSX509Validity;
+class CX509CertExtension;
+class CX509Certificate;
+
+// Extensions
+class MCMSX509CertificateExtension;
+
+// CLASS DECLARATION
+/**
+*  X.509 CertificateInfo type module
+*
+*  ASN.1 definition:
+* --  basic certificate definition
+* Certificate ::=
+*   SIGNED
+*     {SEQUENCE {version                  [0]  Version DEFAULT v1,
+*                serialNumber             CertificateSerialNumber,
+*                signature                AlgorithmIdentifier,
+*                issuer                   Name,
+*                validity                 Validity,
+*                subject                  Name,
+*                subjectPublicKeyInfo     SubjectPublicKeyInfo,
+*                issuerUniqueIdentifier   [1] IMPLICIT UniqueIdentifier OPTIONAL,
+*                --  if present, version must be v2 or v3
+*                subjectUniqueIdentifier  [2] IMPLICIT UniqueIdentifier OPTIONAL,
+*                --  if present, version must be v2 or v3
+*                extensions               [3]  Extensions OPTIONAL
+*     }} --  If present, version must be v3 
+*
+*  @lib cms.lib
+*  @since 3.0
+*/
+class CCMSX509Certificate : public CCMSX509Signed
+    {
+
+    private:
+        /**
+         * Container for certificate data
+         */
+        NONSHARABLE_CLASS( CCertificateData ) : public CBase
+            {
+            public: // destructor
+                ~CCertificateData();
+
+            public: // data
+                // version
+                TInt iVersion;
+
+                // serialNumber, owned
+                HBufC8* iSerialNumber;
+
+                // signature AlgorithmIdentifier, owned
+                CCMSX509AlgorithmIdentifier* iSignature;
+
+                // issuer Name, owned
+                CX500DistinguishedName* iIssuer;
+
+                // validity, owned
+                CCMSX509Validity* iValidity;
+
+                // subject Name, owned
+                CX500DistinguishedName* iSubject;
+
+                // subjectPublicKeyInfo, owned
+                CCMSX509SubjectPublicKeyInfo* iSubjectPublicKeyInfo;
+
+                // issuerUniqueIdentifier UniqueIdentifier ::= BIT STRING, owned
+                HBufC8* iIssuerUniqueIdentifier;
+
+                // subjectUniqueIdentifier UniqueIdentifier, owned
+                HBufC8* iSubjectUniqueIdentifier;
+            };                
+        
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSX509Certificate* NewL();
+
+        /**
+         * Two-phased constructor. Copies the data from the
+         * CX509Certificate parameter.
+         *
+         * @param aCertificate Certificate from which the data is
+         * copied.
+         */
+        IMPORT_C static CCMSX509Certificate* NewL(
+            const CX509Certificate& aCertificate );
+        
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aSerialNumber CertificateSerialNumber value
+        * @param aSignature AlgorithmIdentifier value
+        * @param aIssuer Name value
+        * @param aValidity Validity value
+        * @param aSubject Name value
+        * @param aSubjectPublicKeyInfo SubjectPublicKeyInfo value
+        * @param aAlgorithmIdentifier identifies the algorithm used in
+        * the signature 
+        * @param aEncrypted must be the result of applying a hashing
+        * procedure to the DER-encoded octets of a value of
+        * toBeSigned and then applying an encipherment
+        * procedure to those octets
+        */
+        IMPORT_C static CCMSX509Certificate* NewL(
+            const TDesC8& aSerialNumber,
+            const CCMSX509AlgorithmIdentifier& aSignature,
+            const CX500DistinguishedName& aIssuer,
+            const CCMSX509Validity& aValidity,
+            const CX500DistinguishedName& aSubject,
+            const CCMSX509SubjectPublicKeyInfo& aSubjectPublicKeyInfo,
+            const CCMSX509AlgorithmIdentifier& aAlgorithmIdentifier,
+            const TDesC8& aEncrypted
+            );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSX509Certificate();
+
+    public: // New functions
+        /**
+        * Getter for the version.
+        * @since 3.0
+        * @return Version
+        */
+		IMPORT_C TInt Version() const;
+
+        /**
+        * Getter for the serialNumber.
+        * @since 3.0
+        * @return CertificateSerialNumber
+        */
+		IMPORT_C const TDesC8& SerialNumber() const;
+
+        /**
+        * Getter for the signature.
+        * @since 3.0
+        * @return AlgorithmIdentifier
+        */
+		IMPORT_C const CCMSX509AlgorithmIdentifier& Signature() const;
+
+        /**
+        * Getter for the issuer.
+        * @since 3.0
+        * @return X.500 DistinguishedName of the issuer of the certificate.
+        */
+		IMPORT_C const CX500DistinguishedName& Issuer() const;
+
+        /**
+        * Getter for the validity.
+        * @since 3.0
+        * @return Validity
+        */
+		IMPORT_C const CCMSX509Validity& Validity() const;
+
+        /**
+        * Getter for the subject.
+        * @since 3.0
+        * @return X.500 DistinguishedName of the subject of the certificate.
+        */
+		IMPORT_C const CX500DistinguishedName& Subject() const;
+
+        /**
+        * Getter for the subjectPublicKeyInfo.
+        * @since 3.0
+        * @return SubjectPublicKeyInfo
+        */
+		IMPORT_C const CCMSX509SubjectPublicKeyInfo&
+        SubjectPublicKeyInfo() const;
+
+        /**
+        * Getter for the issuerUniqueIdentifier.
+        * @since 3.0
+        * @return UniqueIdentifier or NULL
+        */
+		IMPORT_C const TDesC8*
+        IssuerUniqueIdentifier() const;
+
+        /**
+        * Getter for the subjectUniqueIdentifier.
+        * @since 3.0
+        * @return UniqueIdentifier or NULL
+        */
+		IMPORT_C const TDesC8*
+        SubjectUniqueIdentifier() const;
+
+        /**
+        * Setter for the version.
+        * @since 3.0
+        * @param aVersion Version
+        */
+		IMPORT_C void SetVersion( const TInt aVersion );
+
+        /**
+        * Setter for the serialNumber.
+        * @since 3.0
+        * @param aSerialNumber CertificateSerialNumber
+        */
+		IMPORT_C void SetSerialNumberL( const TDesC8& aSerialNumber );
+
+        /**
+        * Setter for the signature.
+        * @since 3.0
+        * @param aSignature AlgorithmIdentifier
+        */
+		IMPORT_C void
+        SetSignatureL( const CCMSX509AlgorithmIdentifier& aSignature );
+
+        /**
+        * Setter for the issuer.
+        * @since 3.0
+        * @param aIssuer The X.500 DistinguishedName of the issuer of
+        * the certificate
+        */
+		IMPORT_C void
+        SetIssuerL( const CX500DistinguishedName& aIssuer );
+
+        /**
+        * Setter for the validity.
+        * @since 3.0
+        * @param aValidity Validity
+        */
+		IMPORT_C void
+        SetValidityL( const CCMSX509Validity& aValidity );
+
+        /**
+        * Setter for the Subject.
+        * @since 3.0
+        * @param aSubject X.500 DistinguishedName of the subject of
+        * the certificate
+        */
+		IMPORT_C void
+        SetSubjectL( const CX500DistinguishedName& aSubject );
+
+        /**
+        * Setter for the SubjectPublicKeyInfo.
+        * @since 3.0
+        * @param aSubjectPublicKeyInfo SubjectPublicKeyInfo
+        */
+		IMPORT_C void SetSubjectPublicKeyInfoL(
+            const CCMSX509SubjectPublicKeyInfo& aSubjectPublicKeyInfo );
+
+        /**
+        * Setter for the issuerUniqueIdentifier. Also makes sure
+        * version is v2 or v3 (integer values 1 and 2). 
+        * @since 3.0
+        * @param aIssuerUniqueIdentifier UniqueIdentifier (BIT STRING)
+        */
+		IMPORT_C void SetIssuerUniqueIdentifierL(
+            const TDesC8& aIssuerUniqueIdentifier );
+
+        /**
+        * Setter for the subjectUniqueIdentifier. Also makes sure
+        * version is v2 or v3 (integer values 1 and 2).
+        * @since 3.0
+        * @param aSubjectUniqueIdentifier UniqueIdentifier (BIT STRING)
+        */
+		IMPORT_C void SetSubjectUniqueIdentifierL(
+            const TDesC8& aSubjectUniqueIdentifier );
+
+        /**
+         * Returns ASN1 encoder for the ToBeSigned part.
+         * @since 3.0
+         * @return ASN1 encoder for the ToBeSigned part.
+         */
+        IMPORT_C CASN1EncBase* ToBeSignedEncoderLC() const;
+        
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const TDesC8& aSerialNumber,
+            const CCMSX509AlgorithmIdentifier& aSignature,
+            const CX500DistinguishedName& aIssuer,
+            const CCMSX509Validity& aValidity,
+            const CX500DistinguishedName& aSubject,
+            const CCMSX509SubjectPublicKeyInfo& aSubjectPublicKeyInfo,
+            const CCMSX509AlgorithmIdentifier& aAlgorithmIdentifier,
+            const TDesC8& aEncrypted
+            );
+
+        /**
+         * Protected construction to allow derivation
+         */
+        IMPORT_C void ConstructL( );
+
+        /**
+         * Protected construction to allow derivation.
+         */
+        IMPORT_C void ConstructL( const CX509Certificate& aCertificate );
+        
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSX509Certificate( );
+
+    private: // New functions
+
+        /**
+         * Copies the data from the CX509Certificate object. 
+         */
+        void SetDataL( const CX509Certificate& aCertificate );
+        
+    private:    // Data
+        // Contains the actual data, owned
+        CCertificateData* iData;
+
+        // Reserved for extensions
+        MCMSX509CertificateExtension* iReserved;
+        
+    };
+
+#endif      // CCMSX509Certificate_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSX509CertificateList.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,238 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+#ifndef CCMSX509CertificateList_H
+#define CCMSX509CertificateList_H
+
+//  INCLUDES
+#include "CCMSSequence.h"
+#include <x509cert.h>
+
+// FORWARD DECLARATIONS
+class CCMSX509AlgorithmIdentifier;
+// Extension
+class MCMSX509CertificateList;
+
+// CLASS DECLARATION
+/**
+ * These two classes are containers for CertificateList data
+ */
+class CCMSX509RevokedCertificate : public CBase
+	{
+	public: // Constructor and destructor
+	   /**
+        * C++ default constructor.
+        */
+		IMPORT_C CCMSX509RevokedCertificate();
+
+       /**
+        * Destructor.
+        */
+		virtual ~CCMSX509RevokedCertificate();
+
+	public: // Data
+		TInt iUserCertificateSerialNumber;
+		TTime iRevokationDate;
+		// Owned extensions
+		CArrayPtrFlat< CX509CertExtension >* iExtensions;
+	};
+
+class CCMSX509CertificateListParameters : public CBase
+	{
+	public: // Constructor and destructor
+	   /**
+        * C++ default constructor.
+        */
+		IMPORT_C CCMSX509CertificateListParameters();
+
+       /**
+        * Destructor.
+        */
+		virtual ~CCMSX509CertificateListParameters();
+
+	public: // Data
+		TInt iVersion;
+		// Signature algorithm, owned
+		CCMSX509AlgorithmIdentifier* iSignatureAlgorithm;
+		// Issuer, owned
+		CX500DistinguishedName* iIssuer;
+		TTime iThisUpdate;
+		TTime iNextUpdate;
+		// Owned revoked certificates
+		CArrayPtrFlat< CCMSX509RevokedCertificate >* iRevokedCertificates;
+		// Owned extensions
+		CArrayPtrFlat< CX509CertExtension >* iExtensions;
+		// Owned signature
+		HBufC8* iSignature;
+	};
+
+// CLASS DECLARATION
+/**
+*  X509 CertificateList
+*
+*  CertificateList  ::=  SEQUENCE  {
+*       tbsCertList          TBSCertList,
+*       signatureAlgorithm   AlgorithmIdentifier,
+*       signature            BIT STRING  }
+*
+*  TBSCertList  ::=  SEQUENCE  {
+*       version                 Version OPTIONAL,
+*                                    -- if present, shall be v2
+*       signature               AlgorithmIdentifier,
+*       issuer                  Name,
+*       thisUpdate              Time,
+*       nextUpdate              Time OPTIONAL,
+*       revokedCertificates     SEQUENCE OF SEQUENCE  {
+*            userCertificate         CertificateSerialNumber,
+*            revocationDate          Time,
+*            crlEntryExtensions      Extensions OPTIONAL
+*                                           -- if present, shall be v2
+*                                 }  OPTIONAL,
+*       crlExtensions           [0] Extensions OPTIONAL
+*                                          -- if present, shall be v2 -- }
+*
+*  Name            ::=   CHOICE { -- only one possibility for now --
+*                                   rdnSequence  RDNSequence }
+*
+*  RDNSequence     ::=   SEQUENCE OF RelativeDistinguishedName
+*
+*  RelativeDistinguishedName  ::=
+*                      SET SIZE (1 .. MAX) OF AttributeTypeAndValue
+*
+*  Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
+*
+*  CertificateSerialNumber  ::=  INTEGER
+*
+*  Time ::= CHOICE {
+*       utcTime        UTCTime,
+*       generalTime    GeneralizedTime }
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSX509CertificateList : public CCMSSequence
+    {
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        * Leaves newly created instance in CleanupStack
+        */
+        IMPORT_C static CCMSX509CertificateList* NewLC();
+
+        /**
+        * Two-phased constructor.
+        * Leaves newly created instance in CleanupStack
+        * @param aSigningCertificate	Signing certificate
+        * @param aRevokedCertificates 	List of revoked certificates
+        */
+        IMPORT_C static CCMSX509CertificateList* NewLC(
+			const CX509Certificate& aSigningCertificate,
+			const CArrayPtrFlat<CX509Certificate>& aRevokedCertificates );
+        /**
+        * Two-phased constructor.
+        * Leaves newly created instance in CleanupStack
+        * @param aParameters	Parameters used for creating list,
+		*						ownership transferred
+        */
+		IMPORT_C static CCMSX509CertificateList* NewLC(
+			CCMSX509CertificateListParameters& aParameters );
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSX509CertificateList();
+
+    public: // New functions
+
+        /**
+		* Getter for CertificateList parameters
+		* @since 2,8
+		* @return Signing certificate in CX509Certificate reference
+		*/
+		IMPORT_C const CCMSX509CertificateListParameters&
+													Parameters() const;
+
+        /**
+        * Setter for CertificateList parameters, takes ownership
+        * @since 2.8
+        * @param aSigningCertificate X.509 certificate to be set as signing
+        */
+		IMPORT_C void SetParametersL(
+				CCMSX509CertificateListParameters& aSigningCertificate );
+
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL();
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL( const CX509Certificate& aSigningCertificate,
+				const CArrayPtrFlat<CX509Certificate>& aRevokedCertificates  );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSX509CertificateList();
+
+	private:	// New functions
+
+		/**
+		 * Encodes Extensions
+		 */
+		CASN1EncSequence* EncodeExtensionsLC(
+				const CArrayPtrFlat<CX509CertExtension>* aExtensions ) const;
+
+		/**
+		 * Decodes Extensions
+		 */
+		CArrayPtrFlat<CX509CertExtension>* DecodeExtensionsL(
+										const TASN1DecGeneric* aExtensions );
+
+
+    private:    // Data
+        // List parameters, owned
+        CCMSX509CertificateListParameters* iParams;
+
+		// Reserved for extensions
+		MCMSX509CertificateList* iReserved;
+    };
+
+#endif      // CCMSX509CertificateList_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSX509GeneralName.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,162 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  X.509 General Name type
+*
+*/
+
+
+
+#ifndef CCMSX509GeneralName_H
+#define CCMSX509GeneralName_H
+
+// INCLUDES
+#include <e32base.h>
+#include <asn1cons.h>
+#include "MCMSModule.h"
+
+// FORWARD DECLARATIONS
+// Extensions
+class MCMSX509GeneralNameExtension;
+
+// CLASS DECLARATION
+/**
+*  X.509 GeneralName type module
+*
+*  ASN.1 definition:
+*  GeneralName ::= CHOICE {
+*    otherName                  [0]  INSTANCE OF OTHER-NAME,
+*    rfc822Name                 [1]  IA5String,
+*    dNSName                    [2]  IA5String,
+*    x400Address                [3]  ORAddress,
+*    directoryName              [4]  Name,
+*    ediPartyName               [5]  EDIPartyName,
+*    uniformResourceIdentifier  [6]  IA5String,
+*    iPAddress                  [7]  OCTET STRING,
+*    registeredID               [8]  OBJECT IDENTIFIER
+*  }
+*
+*
+*  @lib cms.lib
+*  @since 3.0
+*/
+class CCMSX509GeneralName : public CBase, public MCMSModule
+    {
+
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSX509GeneralName* NewL();
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aTag the type of the choice
+        * @param aData The data in DER encoded format
+        */
+        IMPORT_C static CCMSX509GeneralName* NewL(
+            const TTagType aTag,
+            const TDesC8& aData );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSX509GeneralName();
+
+    public: // New functions
+
+        /**
+        * Getter for the tag.
+        * @since 3.0
+        * @return TTagType
+        */
+		IMPORT_C TTagType Tag() const;
+
+        /**
+        * Getter for the data
+        * @since 3.0
+        * @return data in DER encoded format
+        */
+		IMPORT_C const TDesC8& Data() const;
+
+		/**
+        * Setter for the tag
+        * @since 3.0
+        * @param aTag tag of the choice
+        */
+		IMPORT_C void SetTagL(
+            const TTagType aTag );
+
+        /**
+        * Setter for data
+        * @since 3.0
+        * @param aData data of the choice
+        */
+		IMPORT_C void SetDataL(
+            const TDesC8& aData );
+
+    public: // Functions from base classes
+
+        /**
+        * From MCMSModule
+        * @since 3.0
+        * @param aResult Allocates and sets result in this variable
+        */
+        void EncodeL( HBufC8*& aResult ) const;
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const TTagType aTag,
+            const TDesC8& aData );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSX509GeneralName( );
+
+
+    private:    // Data
+
+        // defines the type of this CHOICE
+        TTagType iTag;
+
+        // Data
+        HBufC8* iData;
+
+        // Reserved for extensions
+        MCMSX509GeneralNameExtension* iReserved;
+        
+    };
+
+#endif      // CCMSX509GeneralName_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSX509GeneralNames.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,127 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  X.509 GeneralNames type
+*
+*/
+
+
+
+#ifndef CCMSX509GeneralNames_H
+#define CCMSX509GeneralNames_H
+
+#include "CCMSSequence.h"
+
+// FORWARD DECLARATIONS
+class CCMSX509GeneralName;
+
+// Extensions
+class MCMSX509GeneralNamesExtension;
+
+// CLASS DECLARATION
+/**
+*  X.509 GeneralNames type module
+*
+*  ASN.1 definition:
+*    GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
+*
+*  @lib cms.lib
+*  @since 3.0
+*/
+class CCMSX509GeneralNames : public CCMSSequence
+    {
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSX509GeneralNames* NewL();
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aGeneralNames array of GeneralNames.
+        */
+        IMPORT_C static CCMSX509GeneralNames* NewL(
+            const CArrayPtr< CCMSX509GeneralName >& aGeneralNames );
+
+        /**
+         * Two-phased copy constructor.
+         * Note: You can't copy an empty GeneralNames. The only way to
+         * create an empty GeneralNames (usable only for decoding) is
+         * through the parameterless version of NewL().
+         * @param aGeneralNames source to be copied
+         */
+        IMPORT_C static CCMSX509GeneralNames* NewL(
+            const CCMSX509GeneralNames& aGeneralNames );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSX509GeneralNames();
+
+    public: // New functions
+        /**
+        * Getter for GeneralNames
+        * @since 3.0
+        * @return array of GeneralNames
+        */
+		IMPORT_C const CArrayPtr< CCMSX509GeneralName >& GeneralNames() const;
+
+		/**
+        * Setter for GeneralNames. Creates a copy of the parameters.
+        * @since 3.0
+        * @param aGeneralNames array of GeneralNames
+        */
+		IMPORT_C void SetGeneralNamesL(
+            const CArrayPtr< CCMSX509GeneralName >& aGeneralNames );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 3.0
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+		/**
+		* From MCMSModule
+		* @since 3.0
+		* @return Returns ASN1 encoder and leaves it in CleanupStack
+		*/
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CArrayPtr< CCMSX509GeneralName >& aGeneralNames );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSX509GeneralNames();
+
+    private:    // Data
+        // GeneralNames, owned
+        CArrayPtr< CCMSX509GeneralName >* iGeneralNames;
+
+        // Reserved for extensions
+        MCMSX509GeneralNamesExtension* iReserved;
+    };
+
+#endif      // CCMSX509GeneralNames_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSX509IssuerSerial.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,176 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+#ifndef CCMSX509IssuerSerial_H
+#define CCMSX509IssuerSerial_H
+
+#include "CCMSSequence.h"
+
+// FORWARD DECLARATIONS
+class CCMSX509GeneralNames;
+
+// CLASS DECLARATION
+/**
+*  X.509 IssuerSerial type module
+*
+*  ASN.1 definition:
+*   IssuerSerial ::= SEQUENCE {
+*    issuer     GeneralNames,
+*    serial     CertificateSerialNumber,
+*    issuerUID  UniqueIdentifier OPTIONAL
+*   }
+*
+*   CertificateSerialNumber ::= INTEGER
+*
+*   UniqueIdentifier ::= BIT STRING
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSX509IssuerSerial : public CCMSSequence
+    {
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSX509IssuerSerial* NewL();
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aIssuer X.509 GeneralNames value
+        * @param aSerial X.509 CertificateSerialNumber value
+        */
+        IMPORT_C static CCMSX509IssuerSerial* NewL(
+            const CCMSX509GeneralNames& aIssuer,
+            const TInt aSerial );
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        *
+        * @param aIssuer X.509 GeneralNames value
+        * @param aSerial X.509 CertificateSerialNumber value
+        * @param aIssuerUID X.509 UniqueIdentifier value
+        */
+        IMPORT_C static CCMSX509IssuerSerial* NewL(
+            const CCMSX509GeneralNames& aIssuer,
+            const TInt aSerial,
+            const TDesC8& aIssuerUID );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSX509IssuerSerial();
+
+    public: // New functions
+        /**
+        * Getter for Issuer.
+        * @since 2.8
+        * @return GeneralNames value
+        */
+		IMPORT_C const CCMSX509GeneralNames& Issuer() const;
+
+        /**
+        * Getter for Serial
+        * @since 2.8
+        * @return CertificateSerialNumber value
+        */
+		IMPORT_C TInt Serial() const;
+
+        /**
+        * Getter for IssuerUID
+        * @since 2.8
+        * @return X.509 UniqueIdentifier value or NULL
+        */
+		IMPORT_C const TDesC8* IssuerUID() const;
+
+		/**
+        * Setter for Issuer. Creates a copy of the parameters.
+        * @since 2.8
+        * @param aIssuer GeneralNames value.
+        */
+		IMPORT_C void SetIssuerL(
+            const CCMSX509GeneralNames& aIssuer );
+
+		/**
+        * Setter for Serial.
+        * @since 2.8
+        * @param aSerial CertificateSerialNumber value.
+        */
+		IMPORT_C void SetSerial(
+            const TInt aSerial );
+
+		/**
+        * Setter for IssuerUID. Creates a copy of the parameters.
+        * @since 2.8
+        * @param aIssuerUID UniqueIdentifier value
+        */
+		IMPORT_C void SetIssuerUIDL(
+            const TDesC8& aIssuerUID );
+
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSX509GeneralNames& aIssuer );
+        
+       /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSX509GeneralNames& aIssuer,
+            const TDesC8& aIssuerUID );
+            
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSX509IssuerSerial( const TInt aSerial );
+
+    private:    // Data
+        // Issuer, owned
+        CCMSX509GeneralNames* iIssuer;
+        // X.509 CertificateSerialNumber, owned
+        TInt iSerial;
+        // X.509 UniqueIdentifier, owned
+        TDesC8* iIssuerUID;
+
+    };
+
+#endif      // CCMSX509IssuerSerial_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSX509Signed.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,154 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef CCMSX509Signed_H
+#define CCMSX509Signed_H
+
+//  INCLUDES
+#include 	"CCMSSequence.h"
+
+// FORWARD DECLARATIONS
+class CCMSX509AlgorithmIdentifier;
+
+// CLASS DECLARATION
+/**
+*  Base class for X.509 SIGNED -type modules
+*
+*  ASN.1 notation:
+*
+* SIGNATURE{ToBeSigned} ::= SEQUENCE {
+*  algorithmIdentifier  AlgorithmIdentifier,
+*  encrypted            ENCRYPTED-HASH{ToBeSigned}
+* }
+* 
+* SIGNED{ToBeSigned} ::= SEQUENCE {
+*   toBeSigned  ToBeSigned,
+*   COMPONENTS OF SIGNATURE{ToBeSigned}
+* }
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSX509Signed : public CCMSSequence
+    {
+
+    public: // Destructor
+
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSX509Signed();
+        
+    public: // New functions
+
+        /**
+         * Getter for algorithmIdentifier
+         * @since 2.8
+         * @return Algorithm identifier
+         */
+        IMPORT_C const CCMSX509AlgorithmIdentifier&
+        AlgorithmIdentifier() const;
+
+        /**
+         * Getter for encrypted
+         * @since 2.8
+         * @return encrypted (BIT STRING in a descriptor)
+         */
+        IMPORT_C const TDesC8& Encrypted() const;
+        
+        /**
+         * Setter for algorithmIdentifier. Makes a copy.
+         * @since 2.8
+         * @param aAlgorithmIdentifier Algorithm identifier
+         */
+        IMPORT_C void SetAlgorithmIdentifierL(
+            const CCMSX509AlgorithmIdentifier& aAlgorithmIdentifier );
+
+        /**
+         * Setter for encrypted. Makes a copy.
+         * @since 2.8
+         * @param aEncrypted bit string
+         */
+        IMPORT_C void SetEncryptedL( const TDesC8& aEncrypted );
+        
+    protected:  // New functions
+       /**
+        * C++ default constructor.
+        */
+        CCMSX509Signed( );
+
+        /**
+         * Constructs the member variables. Makes a copy of
+         * the parameters
+         */
+        void BaseConstructL(
+            const CCMSX509AlgorithmIdentifier& aAlgorithmIdentifier,
+            const TDesC8& aEncrypted );
+
+        /**
+         * Creates a signed encoder.
+         * @param aToBeSigned ToBeSigned (see the ASN.1 notation). The
+         * object is popped from the cleanup stack.
+         * @return signed sequence, left in the cleanup stack. 
+         */
+        CASN1EncSequence* SignAndPopLC( CASN1EncBase* aToBeSigned ) const;
+
+        /**
+         * Decodes algorithmIdentifier and encrypted parts from the
+         * raw data.
+         * @param aRawData data to be decoded
+         * @param aAlgorithmIdentifier decoded algorithmIdentifier is
+         * stored here
+         * @param aEncrypted decoded encrypted is stored here
+         * @return ToBeSigned in a generic decoder.
+         */
+        TASN1DecGeneric DecodeSignatureL(
+            const TDesC8& aRawData,
+            CCMSX509AlgorithmIdentifier*& aAlgorithmIdentifier,
+            HBufC8*& aEncrypted ) const;
+
+        /**
+         * Decodes algorithmIdentifier and encrypted parts from an
+         * array of items. The first item is returned, and the second
+         * and third items are used in decoding process.
+         * @param aItemArray array of items
+         * @param aAlgorithmIdentifier decoded algorithmIdentifier is
+         * stored here
+         * @param aEncrypted decoded encrypted is stored here
+         * @return ToBeSigned in a generic decoder.
+         */
+        TASN1DecGeneric DecodeSignatureArrayL(
+            CArrayPtr< TASN1DecGeneric >& aItemArray,
+            CCMSX509AlgorithmIdentifier*& aAlgorithmIdentifier,
+            HBufC8*& aEncrypted ) const;
+
+        
+        
+    protected: // Data
+
+        // algorithmIdentifier, owned
+        CCMSX509AlgorithmIdentifier* iAlgorithmIdentifier;
+
+        // encrypted, owned
+        HBufC8* iEncrypted;
+        
+    };
+
+#endif      // CCMSX509Signed_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSX509SubjectPublicKeyInfo.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,157 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+#ifndef CCMSX509SubjectPublicKeyInfo_H
+#define CCMSX509SubjectPublicKeyInfo_H
+
+#include "CCMSSequence.h"
+
+// FORWARD DECLARATIONS
+class CCMSX509AlgorithmIdentifier;
+class CSubjectPublicKeyInfo;
+
+// CLASS DECLARATION
+/**
+*  X.509 SubjectPublicKeyInfo type module
+*
+*  ASN.1 definition:
+*   SubjectPublicKeyInfo ::= SEQUENCE {
+*    algorithm         AlgorithmIdentifier,
+*    subjectPublicKey  BIT STRING
+*   }
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSX509SubjectPublicKeyInfo : public CCMSSequence
+    {
+
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSX509SubjectPublicKeyInfo* NewL();
+
+        /**
+        * Two-phased constructor. Copies of the parameters are made.
+        * 
+        * @param aAlgorithm AlgorithmIdentifier
+        * @param aSubjectPublicKey bit string
+        */
+        IMPORT_C static CCMSX509SubjectPublicKeyInfo* NewL(
+            const CCMSX509AlgorithmIdentifier& aAlgorithm,
+            const TDesC8& aSubjectPublicKey );
+
+        /**
+         * Two-phased constructor.
+         *
+         * @param aSubjectPublicKeyInfo CSubjectPublicKeyInfo which
+         * the data is copied from.
+         */
+        IMPORT_C static CCMSX509SubjectPublicKeyInfo* NewL(
+            const CSubjectPublicKeyInfo& aSubjectPublicKeyInfo );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSX509SubjectPublicKeyInfo();
+
+    public: // New functions
+
+        /**
+        * Getter for algorithm.
+        * @since 2.8
+        * @return X.509 AlgorithmIdentifier value
+        */
+		IMPORT_C const CCMSX509AlgorithmIdentifier& Algorithm() const;
+
+        /**
+        * Getter for subjectPublicKey.
+        * @since 2.8
+        * @return bit string in a descriptor
+        */
+		IMPORT_C const TDesC8& SubjectPublicKey() const;
+
+        /**
+        * Setter for algorithm. Creates a copy.
+        * @since 2.8
+        * @param aAlgorithm X.509 AlgorithmIdentifier value
+        */
+		IMPORT_C void
+        SetAlgorithmL( const CCMSX509AlgorithmIdentifier& aAlgorithm );
+
+        /**
+        * Setter for subjectPublicKey.
+        * @since 2.8
+        * @param aSubjectPublicKey bit string
+        */
+		IMPORT_C void SetSubjectPublicKeyL( const TDesC8& aSubjectPublicKey );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+	   /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CCMSX509AlgorithmIdentifier& aAlgorithm,
+            const TDesC8& aSubjectPublicKey );
+       /**
+        * Protected construction to allow derivation
+        */
+        IMPORT_C void ConstructL(
+            const CSubjectPublicKeyInfo& aSubjectPublicKeyInfo );
+        
+        /**
+         * Protected construction to allow derivation
+         */
+        IMPORT_C void ConstructL( );
+        
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSX509SubjectPublicKeyInfo( );
+
+    private:    // Data
+        // AlgorithmIdentifier, owned
+        CCMSX509AlgorithmIdentifier* iAlgorithm;
+
+        // subjectPublicKey, owned
+        HBufC8* iSubjectPublicKey;
+
+    };
+
+#endif      // CCMSX509SubjectPublicKeyInfo_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/CCMSX509Validity.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,143 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+#ifndef CCMSX509Validity_H
+#define CCMSX509Validity_H
+
+#include "CCMSSequence.h"
+
+// FORWARD DECLARATIONS
+class CValidityPeriod;
+
+// CLASS DECLARATION
+/**
+*  X.509 Validity type module
+*
+*  ASN.1 definition:
+* Validity ::= SEQUENCE {notBefore  Time,
+*                        notAfter   Time
+* }
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class CCMSX509Validity : public CCMSSequence
+    {
+
+    public:  // Constructors and destructor
+		/**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CCMSX509Validity* NewL();
+
+        /**
+        * Two-phased constructor.
+        * 
+        * @param aNotBefore notBefore time
+        * @param aNotAfter notAfter time
+        */
+        IMPORT_C static CCMSX509Validity* NewL(
+            const TTime& aNotBefore,
+            const TTime& aNotAfter );
+
+        /**
+         * Two-phased constructor.
+         *
+         * @param aValidityPeriod CValidityPeriod which the data is copied from.
+         */
+        IMPORT_C static CCMSX509Validity* NewL(
+            const CValidityPeriod& aValidityPeriod );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CCMSX509Validity();
+
+    public: // New functions
+
+        /**
+        * Getter for notBefore.
+        * @since 2.8
+        * @return notBefore time value
+        */
+		IMPORT_C const TTime& NotBefore() const;
+
+        /**
+        * Getter for notAfter.
+        * @since 2.8
+        * @return notAfter time value
+        */
+		IMPORT_C const TTime& NotAfter() const;
+
+        /**
+        * Setter for notBefore.
+        * @since 2.8
+        * @param aNotBefore notBefore time
+        */
+		IMPORT_C void
+        SetNotBefore( const TTime& aNotBefore );
+
+        /**
+        * Setter for notAfter.
+        * @since 2.8
+        * @param aNotAfter notAfter time
+        */
+		IMPORT_C void SetNotAfter( const TTime& aNotAfter );
+
+    public: // Functions from base classes
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        void DecodeL( const TDesC8& aRawData );
+
+	 	/**
+        * From MCMSModule
+        * @since 2.8
+        * @return Returns ASN1 encoder and leaves it in CleanupStack
+        */
+        CASN1EncBase* EncoderLC() const;
+
+    protected:  // New functions
+
+        /**
+        * C++ constructor.
+        */
+        IMPORT_C CCMSX509Validity( const TTime& aNotBefore,
+                                   const TTime& aNotAfter );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CCMSX509Validity( );
+
+    private:    // Data
+        // notBefore
+        TTime iNotBefore;
+
+        // notAfter
+        TTime iNotAfter;
+        
+    };
+
+#endif      // CCMSX509Validity_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/cms_api/inc/MCMSModule.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,70 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+
+#ifndef MCMSModule_H
+#define MCMSModule_H
+
+//  INCLUDES
+#include <e32std.h>
+
+// FORWARD DECLARATIONS
+class CASN1EncBase;
+
+
+// CLASS DECLARATION
+/**
+*  Base class for all CMS modules
+*
+*  @lib cms.lib
+*  @since 2.8
+*/
+class MCMSModule
+    {
+
+    public: // New functions
+
+        /**
+        * To be implemented in derived classes, used to
+        * encrypt specified module to descriptor
+        * Will leave with KErrArgument if current instance of module is invalid
+        * @since 2.8
+        * @param aResult Allocates and sets result of encryption in this variable
+        */
+        virtual void EncodeL( HBufC8*& aResult ) const = 0;
+
+	 	/**
+        * To be implemented in derived classes, used to
+        * decrypt raw data to current instance.
+        * Will leave with KErrArgument if give data is not valid
+        * @since 2.8
+        * @param aRawData raw-data to be parsed in this instance
+        */
+        virtual void DecodeL( const TDesC8& aRawData ) = 0;
+
+		/**
+		 * To be implemented in derived classes, used to
+		 * retrieve ASN1 Encoder
+		 * Leaves returned encoder in CleanupStack
+		 */
+		virtual CASN1EncBase* EncoderLC() const = 0;
+    };
+
+#endif      // MCMSModule_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devencadaptation_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,28 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+:                FOTA Engine API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/DevEncEngineBase.h  			MW_LAYER_PLATFORM_EXPORT_PATH(DevEncEngineBase.h )
+../inc/DevEncEngineConstants.h  		MW_LAYER_PLATFORM_EXPORT_PATH(DevEncEngineConstants.h )
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devencadaptation_api/inc/DevEncEngineBase.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Enumerations used in the application UI.
+ *
+*/
+
+
+#ifndef __DEVENCENGINEBASE_H__
+#define __DEVENCENGINEBASE_H__
+
+//  Include Files
+#include <f32file.h>
+#include <e32base.h>    // CBase
+
+//  Class Definitions
+
+class CDevEncEngineBase : public CBase
+    {
+public:
+
+    virtual TInt Connect( TDriveNumber aNumber ) = 0;
+    virtual void Close() = 0;
+    virtual TInt StartDiskOperation( TInt aOp ) = 0;
+    virtual TInt DiskStatus( TInt& aStatus ) const = 0;
+    virtual TInt Progress( TInt& aProgress ) const = 0;
+    virtual TBool Connected() const = 0;
+    virtual TDriveNumber DriveNumber() const = 0;
+
+// For DiskUtils
+    virtual void TakeKeyInUseL( const TDesC8& aClearKey ) const = 0;
+    virtual TInt RandomDataGet( TDes8& aData, const TInt aLength ) = 0;
+    };
+
+#endif  // __DEVENCENGINEBASE_H__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devencadaptation_api/inc/DevEncEngineConstants.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,65 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Enumerations used in the application UI.
+ *
+*/
+
+
+#ifndef __DEVENCADAPTATION_H_
+#define __DEVENCADAPTATION_H_
+
+
+//  Constants
+
+_LIT(KEncryptionDll, "\\sys\\bin\\nfeengine.dll");
+
+enum TDiskStatus
+    {
+    EUnmounted 	= 0,
+    EDecrypted 	= 8,
+    EDecrypting = 9,
+    EEncrypted 	= 10,
+    EEncrypting = 11,
+    EWiping 	= 12,
+    ECorrupted 	= 13,
+    };
+
+enum TEncCommands
+    {
+    EDiskStatus	 = 0,
+    EEncryptDisk = 1,
+    EDecryptDisk = 2,
+    EWipeDisk    = 3
+    };
+
+//- Constants ---------------------------------------------------------------
+// The KFileServerUidValue which is defined in f32file.h.
+const TUid  KEncUtility = {0x100039e3};
+
+const TUint KDEToThreadKey 	= 1;
+const TUint KDEToUiKey 		= 2;
+const TUint KDEToExtKey 	= 3; 
+const TUint KDEProgressToUiKey 	= 4;
+const TUint KDEStatusToUiKey 	= 5;
+
+//- Macros ------------------------------------------------------------------
+// Calculates pub&sub key for given drive and id. Top 8 bits are used for the
+// drives. Bottom 8 bits are used for the ids. The rest of the bits are
+// reserved and use zero value. The key layout:
+//          dddddddd0000000000000000kkkkkkkk
+//          ^bit 31                        ^bit 0
+#define ENC_KEY(drive, id) (((drive) << 24) | (0xFF & (id)))
+
+
+#endif // __DEVENCADAPTATION_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devenccommonutils_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+:                FOTA Engine API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/DevEncDiskUtils.h			MW_LAYER_PLATFORM_EXPORT_PATH(DevEncDiskUtils.h)
+../inc/DevEncSession.h  			MW_LAYER_PLATFORM_EXPORT_PATH(DevEncSession.h )
+../inc/DevEncMmcObserver.h 			MW_LAYER_PLATFORM_EXPORT_PATH(DevEncMmcObserver.h)
+../inc/MmcInfo.h				MW_LAYER_PLATFORM_EXPORT_PATH(MmcInfo.h)
+../inc/DevEncKeyUtils.h				MW_LAYER_PLATFORM_EXPORT_PATH(DevEncKeyUtils.h)
+../inc/DevEncDiskStatusObserver.h 	MW_LAYER_PLATFORM_EXPORT_PATH(DevEncDiskStatusObserver.h)
+../inc/DevEncConstants.h			MW_LAYER_PLATFORM_EXPORT_PATH(DevEncConstants.h)
+../inc/DevEncExternalCRKeys.h MW_LAYER_PLATFORM_EXPORT_PATH(DevEncExternalCRKeys.h)
+../inc/DevEncProtectedPSKey.h       MW_LAYER_PLATFORM_EXPORT_PATH(DevEncProtectedPSKey.h)
+../inc/DevEncSessionBase.h  			MW_LAYER_PLATFORM_EXPORT_PATH(DevEncSessionBase.h )
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devenccommonutils_api/inc/DevEncConstants.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Enumerations used in the application UI.
+*
+*/
+
+
+#ifndef __DEVENCCONSTANTS_H__
+#define __DEVENCCONSTANTS_H__
+
+
+enum TDevEncUiMemoryType
+    {
+    EPhoneMemory,
+    EMemoryCard,
+    EPrimaryPhoneMemory
+    };
+
+enum TDevEncUiMemoryEntityState
+    {
+    EMemStateUnknown = 0,
+    EMemDecrypted    = 1,
+    EMemEncrypting   = 2,
+    EMemEncrypted    = 3,
+    EMemDecrypting   = 4,
+    EMemCorrupted    = 5
+    };
+
+enum TDevEncUiMmcStatus
+    {
+    EMmcNotPresent = 0,
+    EMmcNotReadable = 1,
+    EMmcOk = 2   
+    };
+    
+enum TDevEncControl
+    {
+    EDevEncUiFullControl   = 100, //DE UI has full control
+    EDMControlsPhoneMemory = 101, //DM controls phone memory
+    EDMControlsMmc         = 102, //DM controls Memory card
+    EDMFullControl         = 103  //DM has full control
+    };
+#endif // __DEVENCCONSTANTS_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devenccommonutils_api/inc/DevEncDiskStatusObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     
+*
+*/
+
+
+#ifndef DEVENCDISKSTATUSOBSERVER_H_
+#define DEVENCDISKSTATUSOBSERVER_H_
+
+#include <e32base.h>
+#include <e32property.h>
+#include <f32file.h>
+
+class MDiskStatusObserver
+    {
+    public:
+        /**
+         * Implement this method to be notified when disk status
+         * changes.
+         */
+        IMPORT_C virtual void DiskStatusChangedL( TInt aNfeStatus ) = 0;
+    };
+
+class CDiskStatusObserver : public CActive
+    {
+    public:
+        IMPORT_C static CDiskStatusObserver* NewL( MDiskStatusObserver* aObserver, TDriveNumber aDriveNumber );
+
+        void RunL();
+        void DoCancel();
+        ~CDiskStatusObserver();
+    
+    private:
+        void ConstructL( MDiskStatusObserver* aObserver, TDriveNumber aDriveNumber );   
+        CDiskStatusObserver();
+        TBool IsEncryptionOperationOngoing();
+
+    private:
+        MDiskStatusObserver* iObserver;
+        RProperty iNfeStatus;
+        TDriveNumber iDrive;
+    };
+
+#endif /*DEVENCDISKSTATUSOBSERVER_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devenccommonutils_api/inc/DevEncDiskUtils.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#ifndef DEVENCDISKUTILS_H
+#define DEVENCDISKUTILS_H
+
+#include <f32file.h>
+
+// Constants
+
+// Forward declarations
+//enum TDriveNumber; // Defined in f32file.h
+
+class CDevEncDiskUtils : public CBase
+    {
+    public:
+        //IMPORT_C static const TDesC& DriveLetter( TDriveNumber aNumber );
+        IMPORT_C static TInt DriveLetter( const TInt aNumber,
+                                          TDes& aResult );
+        IMPORT_C static void DrivePath( TDes& aDes,
+                                        const TDriveNumber aNumber );
+        IMPORT_C static void WriteTestFile();
+        IMPORT_C static void VerifyTestFile();
+        IMPORT_C static void DeleteTestFile();
+        IMPORT_C static TInt DiskFinalize( const TDriveNumber aNumber );
+
+    private:
+        static void DoWriteTestFileL();
+        static void DoVerifyTestFileL();
+        static TInt64 FindCriticalLevelTresholdL();
+        static TInt FindValueL( const TUid aRepositoryUid, const TUint aCRKey );
+        static TInt64 FindWarningLevelTresholdL();
+    };
+
+#endif // DEVENCDISKUTILS_H
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devenccommonutils_api/inc/DevEncExternalCRKeys.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,44 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Cenrep categories and keys related to Device Encryption
+*
+*/
+
+
+#ifndef DEVENCEXTERNALCRKEYS_H_
+#define DEVENCEXTERNALCRKEYS_H_
+
+#define KCRDevEncUiSettings           0x200025A6
+
+/**
+ * Setting for disabling user-based encryption control.
+ * 0: UI has full control
+ * 1: DM controls phone memory
+ * 2: DM controls memory card
+ * 3: DM has full control
+ **/
+#define KDevEncUiDmControl            0x01
+
+/**
+ * User setting for memory card encryption. Does not always reflect the actual encryption state.
+ * 0: Encryption off (decrypted)
+ * 1: Encryption on (encrypted)
+ **/
+#define KDevEncUserSettingMemoryCard  0x02
+
+// The KDevEncUiDmControl key can contain none, any or both of these values:
+#define KDmControlsPhoneMemory   0x01
+#define KDmControlsMemoryCard    0x02
+
+#endif /*DEVENCEXTERNALCRKEYS_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devenccommonutils_api/inc/DevEncKeyUtils.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,150 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Provides functions for creating and setting encryption keys.
+*
+*/
+
+
+#ifndef DEVENCKEYUTILS_H_
+#define DEVENCKEYUTILS_H_
+
+#include <e32base.h>
+#include <e32des16.h>
+#include <e32des8.h>
+
+class CFileStore;
+class CPBEncryptionData;
+class CPBEncryptElement;
+class CPBEncryptSet;
+class RFs;
+class CDevEncEngineBase;
+
+
+// CLASS DECLARATION
+/**
+* Provides functions for creating and setting encryption keys.
+*/
+class CDevEncKeyUtils: public CBase
+    {
+    public:
+        /**
+        * C++ constructor.
+        */
+        IMPORT_C CDevEncKeyUtils();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CDevEncKeyUtils();
+
+        // To connect the engine 
+        IMPORT_C TInt CDevEncKeyUtils::Connect();
+
+        // To close the connection with the engine
+        IMPORT_C void CDevEncKeyUtils::Close();
+
+        /**
+        * Creates a PKCS#5 key and takes it into use by loading it
+        * into the security driver. Asynchronous function.
+        * @param aStatus Contains system-wide error code on completion
+        * @param aResult On successful completion, contains PKCS#5
+        *   encrypted key (externalized encryption data and ciphertext)
+        * @param aPassword The user password to use for the key
+        * @param aLength The desired length of the key
+        */
+        IMPORT_C void CreateSetKey( TRequestStatus& aStatus,
+                                    HBufC8*& aResult,
+                                    const TDesC8& aPassword,
+                                    const TInt aLength ) const;
+
+        /**
+        * Creates a PKCS#5 key and takes it into use by loading it
+        * into the security driver. Asynchronous function. A random password
+        * is generated and the resulting key is ignored. After completion,
+        * the key exists only in the security driver and cannot be retrieved.
+        * @param aStatus Contains system-wide error code on completion
+        * @param aLength The desired length of the key
+        */
+        IMPORT_C void CreateSetKey( TRequestStatus& aStatus,
+                                    const TInt aLength ) const;
+
+        /**
+        * Sets the specified PKCS#5 key in the security driver.
+        * Asynchronous function.
+        * @param aStatus Contains system-wide error code on completion
+        * @param aPkcs5Key The encrypted PKCS#5 key data (externalized
+        *   encryption data and ciphertext)
+        * @param aPassword The user password to use for the key
+        */
+        IMPORT_C void SetKey( TRequestStatus& aStatus,
+                              const TDesC8& aPkcs5Key,
+                              const TDesC8& aPassword ) const;
+
+        /**
+        * Resets the key in the security driver. Asynchronous function.
+        * @param aStatus Contains system-wide error code on completion
+        */
+        IMPORT_C void ResetKey( TRequestStatus& aStatus ) const;
+        
+    private:
+    // Functions
+        void DoCreateSetKeyL( const TDesC8& aPassword,
+                              TInt aLength ) const;
+        void DoCreateSetKeyL( HBufC8*& aResult,
+                              const TDesC8& aPassword,
+                              const TInt aLength ) const;
+        void DoSetKeyL( const TDesC8& aPkcs5Key,
+                        const TDesC8& aPassword ) const;
+        
+        void Pkcs5RemovePadding( TPtr8& aInput ) const;
+
+        void GetNewFileStoreL( RFs& aFs,
+                               TDes& aFileName,
+                               CFileStore*& aStore ) const;
+        
+        void SaveKeyL( CFileStore* aStore,
+                       const CPBEncryptElement* aSet,
+                       const TDesC8& aCiphertext ) const;        
+        
+        void LoadKeyLC( RFs& aFs,
+                        const TFileName& aFileName,
+                        CPBEncryptionData*& aData,
+                        HBufC8*& aCiphertext ) const;
+
+        void InternalizeKeyL( CPBEncryptElement*& aElement,
+                              const TDesC8& aPassword,
+                              HBufC8*& aCiphertext,
+                              const TDesC8& aSource ) const;
+
+        void ExternalizeKeyL( const CPBEncryptElement* aElement,
+                              const TDesC8& aCiphertext,
+                              //HBufC8*& aResult ) const;
+                              TDes8& aResult ) const;
+
+        TBool ProcessHasCapability( TCapability aCapability ) const;
+
+        void LoadDevEncEngineL();
+
+        void UnloadDevEncEngine();
+
+    // Data
+    private:
+       CDevEncEngineBase* iDevEncEngine;
+       RLibrary iLibrary;
+       TBool iConnect;
+    };
+
+#endif /*DEVENCKEYUTILS_H_*/
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devenccommonutils_api/inc/DevEncMmcObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     
+*
+*/
+
+
+#ifndef __MMCOBSERVER_H__
+#define __MMCOBSERVER_H__
+
+#include <e32base.h>
+
+class RFs;
+
+class MMemoryCardObserver
+    {
+    public:
+        /**
+         * Implement this method to be notified when MMC status
+         * changes.
+         */
+        virtual void MMCStatusChangedL() = 0;
+    };
+
+class CMmcObserver : public CActive
+    {
+    public:
+        IMPORT_C static CMmcObserver* NewL( MMemoryCardObserver* aObserver,
+                                   RFs* aFileServerSession );
+        IMPORT_C void StartObserver();
+
+        // TBI
+        IMPORT_C TBool MMCCurrentlyInserted();
+
+        void RunL();
+        void DoCancel();
+        ~CMmcObserver();
+    
+    private:
+        void ConstructL( MMemoryCardObserver* aObserver,
+                         RFs* aFileServerSession );   
+        CMmcObserver();
+        MMemoryCardObserver* iObserver;
+        RFs* iFsSession;
+        CAsyncCallBack* iAsyncCallBack;
+    };
+
+#endif // __MMCOBSERVER_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devenccommonutils_api/inc/DevEncProtectedPSKey.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Ps key definition
+ *
+*/
+
+
+
+#ifndef DEVENCPROTECTEDPSKEY_H_
+#define DEVENCPROTECTEDPSKEY_H_
+
+enum TDevEncOperation
+	{
+	EOpIdle,
+	EOpEncrypting,
+	EOpDecrypting
+	};
+
+//same Uid as DevEncStarter which is the component defining and deleting it
+const TUid  KDevEncProtectedUid = {0x2000259B};          
+
+/**
+ * Store the last memory status changed
+ * 0: Idle. It can be Encrypted or Decrypted
+ * 1: Encrypting
+ * 2: Decrypting
+ **/
+const TUint KDevEncOperationKey = 0x01;
+
+#endif /* DEVENCPROTECTEDPSKEY_H_ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devenccommonutils_api/inc/DevEncSession.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,84 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef DEVENC_SESSION_H
+#define DEVENC_SESSION_H
+
+#include <f32file.h>
+#include <e32property.h>
+
+#include "DevEncSessionBase.h"
+class CDevEncEngineBase;
+// CONSTANTS
+
+
+
+// CLASS DECLARATION
+/**
+* A session object for communication between the UI and NFE extension.
+*/
+class CDevEncSession: public CDevEncSessionBase
+    {
+    public:
+        IMPORT_C explicit CDevEncSession();
+        IMPORT_C explicit CDevEncSession( TDriveNumber aNumber );
+        ~CDevEncSession();
+
+        IMPORT_C TInt Connect();
+        IMPORT_C void Close();
+        IMPORT_C TInt StartDiskEncrypt();
+        IMPORT_C TInt StartDiskDecrypt();
+        IMPORT_C TInt StartDiskWipe();
+        IMPORT_C TInt DiskStatus( TInt& aStatus ) const;
+        IMPORT_C TInt Progress( TInt& aProgress ) const;
+        IMPORT_C TBool Connected() const;
+        IMPORT_C TDriveNumber DriveNumber() const;
+        IMPORT_C void SetDrive( TDriveNumber aNumber );   
+        /**
+         * Sets the access control for device encryption
+         * @param aValue is of type TDevEncControl
+         * @return KErrNone or system wide error
+         */
+        IMPORT_C TInt SetDevEncControlL(TInt aValue);
+
+        /**
+         * Gets the access control value for device encryption
+         * @param aValue is set when the function returns
+         * @return KErrNone or system wide error
+         */
+        IMPORT_C TInt GetDevEncControlL(TInt& aValue);
+        
+    private:
+        TInt StartDiskOperation( TInt aOp );
+        void LoadDevEncEngineL();
+        void UnloadDevEncEngine();
+
+    private:
+        TBool iConnected;
+        TDriveNumber iDriveNumber;
+        mutable RProperty iToNfe;
+        mutable RProperty iFromNfe;
+        mutable RProperty iProgress;
+        mutable RProperty iNfeStatusToUi;
+        CDevEncEngineBase* iDevEncEngine;
+        RLibrary iLibrary;
+    };
+
+#endif // DEVENC_SESSION_H
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devenccommonutils_api/inc/DevEncSessionBase.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,65 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef DEVENCSESSIONBASE_H_
+#define DEVENCSESSIONBASE_H_
+
+#include <f32file.h>
+#include <e32property.h>
+
+// CONSTANTS
+
+const TUid KDevEncUid2 = { 0x1000008d };
+const TUid KDevEncUid3 = { 0x200025B7 };
+
+_LIT( KDevEncCommonUtils, "\\sys\\bin\\devenccommonutils.dll" );
+
+const TInt KMaxAutolockPeriod = 20;
+
+// CLASS DECLARATION
+/**
+* A session abstract object for communication between the UI and NFE extension. This abstract base class is needed
+* in order to allow runtime variation and dynamic linking outside this component.
+*/
+class CDevEncSessionBase: public CBase
+    {
+    public:
+
+        IMPORT_C virtual TInt Connect() = 0;
+        IMPORT_C virtual void Close() = 0;
+        IMPORT_C virtual TInt StartDiskEncrypt() = 0;
+        IMPORT_C virtual TInt StartDiskDecrypt() = 0;
+        IMPORT_C virtual TInt StartDiskWipe() = 0;
+        IMPORT_C virtual TInt DiskStatus( TInt& aStatus ) const = 0;
+        IMPORT_C virtual TInt Progress( TInt& aProgress ) const = 0;
+        IMPORT_C virtual TBool Connected() const = 0;
+        IMPORT_C virtual TDriveNumber DriveNumber() const = 0;
+        IMPORT_C virtual void SetDrive( TDriveNumber aNumber ) = 0;
+        /**
+         * Sets the access control for device encryption
+         * @param aValue is of type TDevEncControl
+         * @return KErrNone or system wide error
+         */
+        IMPORT_C virtual TInt SetDevEncControlL(TInt aValue) = 0;
+        /**
+         * Gets the access control value for device encryption
+         * @param aValue is set when the function returns
+         * @return KErrNone or system wide error
+         */
+        IMPORT_C virtual TInt GetDevEncControlL(TInt& aValue) = 0;
+    };
+
+#endif /*DEVENCSESSIONBASE_H_*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devenccommonutils_api/inc/MmcInfo.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,115 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     Holds information of an MMC.
+*
+*/
+
+
+#ifndef __TMMCINFO_H__
+#define __TMMCINFO_H__
+
+//  INCLUDES
+#include <f32file.h>
+
+const TInt KMaxMMCVolumeName = 11; // Limited by FAT
+
+//  CLASS DEFINITION
+class TMmcInfo
+    {
+    public:
+        /**
+        * @return Name of the MMC.
+        */
+        const TDesC& Name();
+
+        /**
+        * @return Total capacity of the MMC.
+        */
+        TInt64 Capacity();
+
+        /**
+        * @return Amount of free space on MMC.
+        */
+        TInt64 SpaceFree();
+
+        /**
+        * @return MMC ID.
+        */
+        TUint ID();
+
+        /**
+        * @return Boolean indicating if the MMC is formattable.
+        */
+        TBool IsFormattable();
+
+        /**
+        * @return Boolean indicating if the MMC is formatted.
+        */
+        TBool IsFormatted();
+
+        /**
+        * @return Boolean indicating if the MMC is lockable.
+        */
+        TBool IsLockable();
+
+        /**
+        * @return Boolean indicating if the MMC is locked.
+        */
+        TBool IsLocked();
+
+        /**
+        * @return Boolean indicating if the MMC is read only.
+        */
+        TBool IsReadOnly();
+
+        /**
+        * @return Boolean indicating if password is set in the MMC.
+        */
+        TBool IsPasswordSet();
+
+        /**
+        * @return Boolean indicating if MMC is inserted.
+        */
+        TBool IsInserted();
+
+        /**
+        * @return Boolean indicating if MMC is in use
+        */
+        TBool IsInUse();
+
+        /**
+        * @return Boolean indicating if a backup archive exists on the MMC.
+        */
+        TBool BackupExists();
+
+    //private:
+        TBufC< KMaxMMCVolumeName > iName;
+        TInt64 iCapacity;
+        TInt64 iSpaceFree;
+        TUint iUid;
+        TBool iIsFormattable;
+        TBool iIsFormatted;
+        TBool iIsLockable;
+        TBool iIsLocked;
+        TBool iIsReadOnly;
+        TBool iIsPasswordSet;
+        TBool iIsInserted;
+        TBool iBackupExists;
+        TBool iIsInUse;
+    };
+
+#endif      //  __TMMCINFO_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/device_key_store_encryption_plugin_api/device_key_store_encryption_plugin_api.metaxml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,17 @@
+<?xml version="1.0" ?>
+<api id="34baa37775ddd1801e07cd9b9e63084f" dataversion="1.0">
+  <name>Device Key Store Encryption Plug-in API</name>
+  <description>Plug-in interface to encrypt and decrypt private key related to device certificates</description>
+  <type>c++</type>
+  <subsystem>pkiutilities</subsystem>
+  <libs>
+  </libs>
+  <release category="domain"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>yes</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/device_key_store_encryption_plugin_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+:                Device Key Store Encryption Plug-in API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/KeyEncryptor.h     MW_LAYER_PLATFORM_EXPORT_PATH(keyencryptor.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/device_key_store_encryption_plugin_api/inc/KeyEncryptor.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,70 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  The header file of KeyEncryptor
+*
+*/
+
+
+#ifndef __KEYENCRYPTOR_H__
+#define __KEYENCRYPTOR_H__
+
+#include <e32des8.h>
+
+#define KEY_ENCRYPTOR 0x101FB670
+
+const TUid KKeyEncryptorInterfaceUID = { KEY_ENCRYPTOR };
+
+/**
+ * Key Encryptor Interface class
+ *
+ * This class defines the interface for key encryptor which is used
+ * to encrypt the key when it is stored to the keystore and decrypt it back
+ * when the key is used or exported.
+ * 
+ *  @lib 
+ *  @since S60 v3.2
+ */
+class MKeyEncryptor
+    {
+    public:
+
+       /**
+        * Encrypt the data in the given buffer
+        *
+        * @param aBuf data to be encrypted
+        * @return encrypted data
+        */
+        virtual HBufC8* EncryptL( TDesC8& aBuf )=0;
+
+       /**
+        * Decrypt the data in the given buffer
+        *
+        * @param aBuf data to be decrypted
+        * @return decrypted data
+        */
+        virtual HBufC8* DecryptL( TDesC8& aBuf )=0;
+        
+       /**
+        * release the encryptor when not needed
+        *
+        * @param 
+        * @return 
+        */
+        virtual void Release()=0;
+    };
+
+#endif //KEYENCRYPTOR_H  
+
+//EOF
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devicelock_access_api/group/ABLD.BAT	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,15 @@
+@ECHO OFF
+
+REM Bldmake-generated batch file - ABLD.BAT
+REM ** DO NOT EDIT **
+
+perl -S ABLD.PL "\s60\mw\devicemanagement\devmngt_dom\devicelock_access_api\group\\" %1 %2 %3 %4 %5 %6 %7 %8 %9
+if errorlevel==1 goto CheckPerl
+goto End
+
+:CheckPerl
+perl -v >NUL
+if errorlevel==1 echo Is Perl, version 5.003_07 or later, installed?
+goto End
+
+:End
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devicelock_access_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to Devicelock Access API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+../inc/devicelockaccessapi.h MW_LAYER_PLATFORM_EXPORT_PATH(devicelockaccessapi.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/devicelock_access_api/inc/devicelockaccessapi.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,116 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface to access devicelock.
+ *
+*/
+
+
+#ifndef __DEVICELOCKACCESSAPI_H__
+#define __DEVICELOCKACCESSAPI_H__
+
+#include <e32base.h>
+
+class RLockAccessExtension;
+
+/**
+ *  Three possible reason for devicelock: manual, remote, timer
+ *
+ *  @lib   lockapp
+ *  @since 5.0
+ */
+enum TDevicelockReason
+    {
+    EDevicelockManual = 1,
+    EDevicelockRemote
+    };
+
+/**
+ *  RDevicelockAccessApi class.
+ *  Client used to access/configure devicelock features.
+ *
+ *  @lib   lockapp
+ *  @since 5.0
+ */
+class CDevicelockAccessApi : public CBase
+    {
+    public:
+
+        /**
+         * Two-phased constructor.
+         */
+        IMPORT_C static CDevicelockAccessApi* NewL( );
+
+        /**
+         * Destructor.
+         */
+        IMPORT_C ~CDevicelockAccessApi( );
+
+    private:
+
+        /**
+         * Constructor for performing 1st stage construction
+         */
+        CDevicelockAccessApi( );
+
+        /**
+         * Default constructor for performing 2nd stage construction
+         */
+        void ConstructL( );
+
+    public:
+
+        /**
+         * Returns true if phone is keys are locked. Both keyguard
+         * and devicelock cannot be simultaneously enabled.
+         * @return ETrue if either keyguard or devicelock is enabled.
+         */
+        IMPORT_C TBool IsKeylockEnabled( );
+
+        /**
+         * Has devicelock been activated.
+         * @return ETrue if devicelock is enabled.
+         */
+        IMPORT_C TBool IsDevicelockEnabled( );
+
+        /**
+         * Enable devicelock.
+         * @return KErrNone if succeeded
+         *         KErrAlreadyExists if already enabled
+         *         KErrPermissionDenied if no required capabilities
+         */
+        IMPORT_C TInt EnableDevicelock( TDevicelockReason aReason = EDevicelockManual );
+
+        /**
+         * Currently not implemented !
+         * Offer to enable devicelock. Shows a query note to user.
+         */
+        IMPORT_C TInt OfferDevicelock( );
+
+        /**
+         * Remove this method eventually!
+         *
+         * Disable devicelock.
+         * @return KErrNone if succeeded
+         *         KErrAlreadyExists if already enabled
+         *         KErrPermissionDenied if no required capabilities
+         */
+        IMPORT_C TInt DisableDevicelock( );
+
+    private:
+
+        RLockAccessExtension* iLockAccessExtension;
+
+    };
+
+#endif // __DEVICELOCKACCESSAPI_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/gba_api/gba_api.metaxml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,18 @@
+<?xml version="1.0" ?>
+<api id="c204e64f29d830070a3c979b6e8cf367" dataversion="2.0">
+  <name>GBA API</name>
+  <description>Used to request bootstrap and key derivation</description>
+  <type>c++</type>
+  <collection>gba</collection>
+  <libs>
+    <lib name="gba.lib" />
+  </libs>
+  <release category="platform"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>no</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/gba_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+*               GBA API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+
+../inc/GbaUtility.h                 MW_LAYER_PLATFORM_EXPORT_PATH(GbaUtility.h)
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/gba_api/inc/GbaUtility.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,255 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: Utility to perform gba bootstrapping
+*
+*/
+
+
+#ifndef GBAUTILITY_H
+#define GBAUTILITY_H
+
+#include <e32base.h>
+
+// FORWARD DECLARATION
+class CGbaClientRequestHandler;
+
+//CONST
+const TInt KMaxBTIDLength=0xff;
+const TInt KMaxKNAFLength=0xff;
+const TInt KMaxURLLength=0xff;
+const TInt KMaxRANDLength=0xff;
+const TInt KMaxKIMPILength=0xff;
+const TInt KMaxUICCLabel=0x20;
+const TInt KMaxIMaterial=0xff;
+const TInt KMaxKeyUsage=0x05;
+
+_LIT8(KUSIM,"USIM");
+_LIT8(KSIM,"SIM"); //Not support yet
+_LIT8(KISIM,"ISIM"); //Not support yet
+
+enum EGBABootstrapFlags
+    {
+    // Use the cached if not expired
+    EGBADefault = 0,
+    // Do not use cached credentials, instead force bootraps with BSF
+    EGBAForce        
+    };
+
+// GBA_U 
+enum EGBARunType
+    {
+    ENoType = 0,
+    E2GGBA,     //2G GBA-specific functions are carried out in the ME
+    E3GGBAME,   //3G GBA-specific functions are carried out in the ME
+    EGBAU       //The UICC is GBA aware
+    };
+
+//Structure of Gba input
+typedef struct
+    {
+    //Input, FQDN of NAF
+    TBuf8<KMaxURLLength> iNAFName;
+    //Input, EGBADefault or EGBAForces
+    TUint iFlags;
+    //Input, the label of UICC apps that user wants to use
+    //KUSIM for example, if empty use default UICC apps
+    TBuf8<KMaxUICCLabel> iUICCLabel;                            //Currently not supported.
+    //Input, key usage identifier appended into NafName, for key derivation
+    TBuf8<KMaxKeyUsage> iProtocolIdentifier;
+    //the id of prefered access point for bootstrap, if no prefered one, set to -1.
+    TInt iAPID;
+    } TGBABootstrapInputParams;
+    
+
+//Structure of Gba output credentials
+typedef struct
+    {
+    //Output B-TID
+    TBuf8<KMaxBTIDLength>  iBTID;
+    //Output Ks_NAF
+    TBuf8<KMaxKNAFLength>  iKNAF;
+    //Output lifetime
+    TTime   iLifetime;               
+    //Output
+    TBuf8<KMaxKIMPILength> iKIMPI;         
+    EGBARunType            iGbaRunType;
+    //output, type of uicc application
+    TBuf8<KMaxUICCLabel> iOutputUICCLabel;
+    } TGBABootstrapOutputParams;
+    
+    
+    
+/**
+* Observer class for gba client
+*
+* @lib gba2.lib
+* @since S60 3.2
+*
+*/  
+class MGbaObserver
+    {
+    public:
+        
+        /**
+        * Callback function
+        * When bootstrap is done and credentials are ready, this function
+        * will be called.
+        *
+        * @since S60 3.2
+        * @return error: KErrNone in case of success bootstrap request                        
+        *                otherwise any of the standard Symbian error codes.                
+        */
+	      virtual void BootstrapComplete(TInt error) = 0;
+
+    };
+
+
+// CLASS DECLARATION
+/**
+ * Interface for handling gba bootstrapping
+ *
+ * @lib gba2.lib
+ * @since S60 3.2
+ *
+*/  
+class CGbaUtility : public CBase
+    {
+    public:
+        
+        /**
+        * NewL factory function with an observer. It is used with callback function
+        * which should be implemented by the client. The interface is defined in class
+        * MGbaObserver
+        *
+        * @since S60 3.2
+        * @param aObserver Client implemented observer that will be
+        *                  called when the bootstrap is done
+        * @return
+        */
+        IMPORT_C  static CGbaUtility* NewL(MGbaObserver& aObserver);
+
+        /**
+        * NewLC factory function with an observer. It is used with callback function
+        * which should be implemented by the client. The interface is defined in class
+        * MGbaObserver
+        *
+        * @since S60 3.2
+        * @param aObserver Client implemented observer that will be
+        *                  called when the bootstrap is done
+        * @return
+        */
+        IMPORT_C static CGbaUtility* NewLC(MGbaObserver& aObserver) ;
+        
+        
+        /**
+        * NewL factory function without observer. User should create its own state 
+        * machine.
+        *
+        * @since S60 3.2
+        * @param 
+        *
+        * @return
+        */
+        IMPORT_C  static CGbaUtility* NewL();
+
+        /**
+        * NewLC factory function without observer. User should create its own state 
+        * machine.
+        *
+        * @since S60 3.2
+        * @param 
+        *
+        * @return
+        */
+        IMPORT_C static CGbaUtility* NewLC() ;
+
+        
+        /**
+        * destructor
+        */
+        virtual ~CGbaUtility();
+
+    public:
+    
+        /**
+        * Bootstrap function. It is a asynchronous function with callback function.
+        * Performs a bootstrap and calls the callback function when bootstrap is done.
+        * This function should be used when the instance of CGbaUtility is 
+        * created by factory function with observer.
+        * This function requires ReadDeviceData capability
+        *
+        * @since S60 3.2
+        * @param aInput - structure to hold input  parameters,
+        *        aOutput - structure to hold output  parameters 
+        *        client must ensure that ouput buffer is available when boostrapping is completed
+        *
+        * @return KErrNone factory function and bootstrap match
+        *         KErrGeneral factory fucntion and boostrap function doesnot match
+        *         KErrInUse	if there any outstanding bootstrap request in place
+        */
+        IMPORT_C TInt Bootstrap( const TGBABootstrapInputParams aInput, TGBABootstrapOutputParams& aOutput);
+        
+        /**
+        * Performs asynchronous bootstrap.
+        * This function should be used when the instance of CGbaUtility is 
+        * created by factory function without observer.
+        * This function requires ReadDeviceData capability
+        *
+        * @since S60 3.2
+        * @param aInput - structure to hold input  parameters,
+        * aOutput - structure to hold output  parameters 
+        * client must ensure that ouput buffer is available when boostrapping is completed
+        *        aStatus  - KErrNone - in case the bootstrap request is completed successfully
+        *                 - KErrCancel - in case the bootstrap request is cancelled
+        *                 - KErrInUse - if there any outstanding bootstrap request in place
+        */
+        IMPORT_C void Bootstrap( const TGBABootstrapInputParams aInput, TGBABootstrapOutputParams& aOutput, TRequestStatus& aStatus);
+                
+        /**
+        * Cancel Bootstrap function
+        *
+        * @since S60 3.2
+        * @param 
+        * @return KErrNone if Cancel bootstrap request is success,otherwise return a standard symbian error.
+        */
+        IMPORT_C TInt CancelBootstrap();
+            
+        
+        /**
+         * Set the BSF address.
+         * required WriteDeviceData capability.
+         * The BSF address set by this function will overwrite
+         * the one calculated from IMPI.
+         * @since S60 3.2
+         * @param aNewVal contain the address
+         * @return KErrPermissionDenied, not enought capability
+         * */
+        IMPORT_C TInt SetBSFAddress( const TDesC8& aAddress );
+      
+    
+    private:
+      
+      CGbaUtility();
+      
+      void ConstructL( MGbaObserver& aObserver );
+      
+      void ConstructL();
+      
+    private:
+      CGbaClientRequestHandler* iGbaRequestHandler;
+    
+    };
+
+#endif //GBAUTILITY_H
+//EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Includes all the Domain API specific bld.inf files, which 
+*                export files.
+*
+*/
+
+
+#include "../cms_api/group/bld.inf"
+#include "../pkcs12_parser_api/group/bld.inf"
+#include "../java_utils_api/group/bld.inf"
+#include "../wim_cert_api/group/bld.inf"
+#include "../device_key_store_encryption_plugin_api/group/bld.inf"
+#include "../x509certnameparser_api/group/bld.inf"
+#include "../remote_lock_api/group/bld.inf"
+#include "../pkidialog_api/group/bld.inf"
+#include "../provisioning_api/group/bld.inf"
+#include "../keyguard_configuration_api/group/bld.inf"
+#include "../keylock_policy_api/group/bld.inf"
+#include "../security_code_ui_api/group/bld.inf"
+#include "../gba_api/group/bld.inf"
+#include "../keyguard_access_api/group/bld.inf"
+#include "../devicelock_access_api/group/bld.inf"
+#include "../lockapp_server_api/group/bld.inf"
+//Device Encryption Disk Utils
+#include "../devencadaptation_api/group/bld.inf"
+#include "../devenccommonutils_api/group/bld.inf"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/java_utils_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+*               Java Utils API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/JavaUtils.h     MW_LAYER_PLATFORM_EXPORT_PATH(JavaUtils.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/java_utils_api/inc/JavaUtils.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,379 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef JAVAUTILS_H
+#define JAVAUTILS_H
+
+//INCLUDES
+#include <e32base.h>
+
+const TInt   KPathMaxLength                = 8;
+const TInt   KLabelMaxLength               = 24;
+const TInt   KPINMaxLabelLength            = 64;
+
+typedef TBuf<KPINMaxLabelLength> TPINLabel;
+
+//FORWARD DECLARATIONS
+class RWimCertMgmt;
+class RWimMgmt;
+
+
+struct TJavaPINParams
+	{
+	TPINLabel iPINLabel;  
+	TInt      iFlags;
+	TInt      iAuthId;
+	TInt      iPinNumber;
+	TInt      iMinLength;
+	TInt      iMaxLength;
+	TInt      iPinType;
+	TInt      iStoredLength;
+	TInt      iPinReference;
+	TInt      iPadChar;
+	};
+	
+/**
+*  Reads Java provisioning information from Smart Card
+*
+*  @lib WimClient.lib
+*  @since S60 3.2
+*/
+class CWimJavaUtils : public CActive
+    {
+    public:
+
+        /**
+        * Two-phased constructor.
+        *
+        * @param
+        * @return
+        */
+        IMPORT_C static CWimJavaUtils* NewL();
+
+        /**
+        * Destructor
+        */
+        IMPORT_C virtual ~CWimJavaUtils();
+        
+        /**
+        * Initializes the WIM Server cache. This is the most time consuming call. 
+        *
+        * @param  aStatus  Indicates the result of this call. Values:
+        *         KErrNone, call was successull
+        *         KErrNotFound, no WIM was found
+        *         KErrNoMemory, no memory
+        *         KErrGeneral, any other error
+        * @return void
+        */
+        IMPORT_C void Initialize( TRequestStatus& aStatus );
+
+        /** 
+        * Cancels outgoing Initialize operation. 
+        *
+        * @param
+        * @return void
+        */
+        IMPORT_C void CancelInitialize();
+
+        /**
+        * Fetches the size of ACIF. 
+        * This information can be used as a notification of existing of provisioning 
+        * information. If the size is not included in Smart Card's
+        * DODF-JavaPROV file then the full length of the file containing the 
+        * provisioning information is returned.
+        *
+        * @param  aSize    The length of ACIF
+        * @param  aStatus  Indicates the result of this call.
+        *         KErrNone, no errors. NOTE: size can still be 0 indicating
+        *                   that no provisioning information was found.
+        *                   If aSize > 0 it means that provisioning information
+        *                   was found.
+        *         KErrNoMemory, No memory
+        *         KErrGeneral, any other error
+        * @return void
+        */
+        IMPORT_C void GetACIFSize( TInt& aSize,
+                                   TRequestStatus& aStatus );
+        
+        /**
+        * Fetches the size of ACF
+        *
+        * @param aSize  The lenght of ACF
+        * @param aACFPath The path of ACF on smart card
+        * @param  aStatus  Indicates the result of this call.
+        * @return void
+        */
+        IMPORT_C void GetACFSize( TInt& aSize, 
+                                  const TDesC8& aACFPath,
+                                  TRequestStatus& aStatus );
+                                  
+        /**
+        * Get the Authobj information
+        *
+        * @param aAuthIdList List of AuthObject ID
+        * @param aAuthObjsInfoList List of AuthObject Info
+        * @param  aStatus  Indicates the result of this call.
+        * @return void 
+        */
+        IMPORT_C void GetAuthObjsInfo( const RArray<TInt>& aAuthIdList, 
+                                       RArray<TJavaPINParams>& aAuthObjsInfoList,
+                                       TRequestStatus& aStatus );
+                                  
+        /** 
+        * Cancels outgoing GetACIFSize operation.
+        *
+        * @param 
+        * @return void
+        */
+        IMPORT_C void CancelGetACIFSize();
+        
+        /** 
+        * Cancels outgoing GetACFSize operation.
+        *
+        * @param
+        * @return void
+        */
+        IMPORT_C void CancelGetACFSize();
+        
+        /**
+        * Cancel outgoing GetAuthObjsInfo
+        *
+        * @param 
+        * @return void
+        */
+        IMPORT_C void CancelGetAuthObjsInfo();
+         
+        /**
+        * Fetches the whole data of ACIF file. 
+        *
+        * @param  aACIFData  ACIF binary data from smart card
+        * @param  aStatus  Indicates the result of this call.
+        *         KErrNone, no errors.
+        *         KErrNoMemory, No memory
+        *         KErrGeneral, any other error
+        * @return void
+        */
+        IMPORT_C void RetrieveACIFContent( TDes8& aACIFData,
+                                           TRequestStatus& aStatus );
+                                           
+        
+       /**
+        * Fetches the whole data of ACF file
+        *
+        * @param aACFData ACF binary data from smart card
+        * @param aACFPath ACF file path on smart card
+        * @param  aStatus  Indicates the result of this call.
+        * @return void
+        */
+        IMPORT_C void RetrieveACFContent( TDes8& aACFData,
+                                           const TDesC8& aACFPath,
+                                           TRequestStatus& aStatus );
+                                           
+        /**
+        * Fetches the wim label and path
+        *
+        * @param aWimLabel 
+        * @param aPath
+        * @param  aStatus  Indicates the result of this call.  
+        * @return void 
+        */
+        IMPORT_C void RetrieveWimLabelAndPath( TDes8& aWimLabel,
+                                               TDes8& aPath,
+                                               TRequestStatus& aStatus );                                   
+                                           
+        
+        /** 
+        * Cancels outgoing Retrieve operation.
+        *
+        * @return void
+        */
+        IMPORT_C void CancelRetrieveACIFContent();
+        
+        /** 
+        * Cancels outgoing Retrieve operation.
+        *
+        * @return void
+        */
+        IMPORT_C void CancelRetrieveACFContent();
+        
+        /**
+        * Cancel outgoing Retrieve operation
+        *
+        * @return void
+        */
+        IMPORT_C void CancelRetrieveWimLabelAndPath();
+
+    private:
+
+        /**
+        * Symbian constructor
+        * @return void
+        */
+        void ConstructL();
+
+        /**
+        * C++ default constructor.
+        */
+        CWimJavaUtils();
+
+    private: //from CActive
+        
+        /**
+        * Different phases are handled here.
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * Cancellation function
+        * Deallocates member variables and completes client status with
+        * KErrCancel error code.
+        * @return void
+        */
+        void DoCancel();
+
+        /**
+        * The active scheduler calls this function if this active 
+        * object's RunL() function leaves. 
+        * Handles necessary cleanup and completes request with
+        * received error code.
+        * @param aError -The error code which caused this function call.
+        * @return TInt  -Error code to active scheduler, is always KErrNone.
+        */ 
+        TInt RunError( TInt aError );
+
+    private:
+
+        /** 
+        * Sets own iStatus to KRequestPending, and signals it 
+        * with User::RequestComplete() -request. This gives chance 
+        * active scheduler to run other active objects. After a quick
+        * visit in active scheduler, signal returns to RunL() and starts next
+        * phase of operation. 
+        * @return void
+        */
+        void SignalOwnStatusAndComplete();
+
+        /** 
+        * Allocates memory for member variables, which are needed
+        * in Java Provisioning struct.
+        * @param aDataLength -The length of the data to be allocated
+        * @return void
+        */
+        void AllocMemoryForJavaProvStructL( const TInt aDataLength );
+        
+        /** 
+        * Allocates memory for path and label
+        * @return void
+        */
+        void AllocMemoryForPathAndLabelL();
+        /** 
+        * Deallocates memory from member variables
+        * @return void
+        */
+        void DeallocMemoryFromJavaProvStruct();
+        
+        /** 
+        * Deallocates memory from path and label
+        * @return void
+        */
+        void DeallocMemoryFromPathAndLabel();
+        
+    private:
+
+        enum TJavaUtilPhase
+            {
+            EInitialize,
+            EConnectClientSession,
+            EInitializeWim,
+            EInitializeDone,
+            EGetACIFSize,
+            EGetACIFSizeDone,
+            ERetrieveACIFContent,
+            ERetrieveACIFContentDone,
+            EGetACFSize,
+            EGetACFSizeDone,
+            ERetrieveACFContent,
+            ERetrieveACFContentDone,
+            EGetAuthObjsInfo,
+            EGetAuthObjsInfoDone,
+            ERetrieveWimLabelAndPath,
+            ERetrieveWimLabelAndPathDone
+            };
+
+        //Indicator for different phases
+        TJavaUtilPhase                  iPhase;
+        
+        //Client status is stored here while operation
+        //on the server side is done.
+        TRequestStatus*                 iClientStatus;
+        
+        //Handle to connection with server. Owned.
+        RWimCertMgmt*                   iConnectionHandle;
+
+        // Pointer to Client Session. Owned. 
+        RWimMgmt*                       iClientSession;
+
+        //Informs the size of provisioning string. Not owned.
+        TInt*                           iSize;
+        
+        //Descriptor to hold provisioning data. Not owned.
+        TDes8*                          iData;
+
+        //Buffer to hold Java provisioning data for server. Owned.
+        HBufC8*                         iJavaProvBuf;
+    
+        //Pointer to iJavaProvBuf. Owned.
+        TPtr8*                          iJavaProvBufPtr;
+        
+        //Flag to indicate errors during WIM -initialization.
+        TInt                            iWimStartErr;
+        
+        TBuf8<KPathMaxLength>           iACFPath;
+        
+        RArray<TInt>*                   iAuthIdList; //owed
+         
+        //saves pointer to user's array
+		RArray<TJavaPINParams>*         iClientsAuthObjsInfoList;//not owned
+		                                
+		//Array to hold authOjbectInfo data
+        RArray<TJavaPINParams>*         iAuthObjsInfoList; //owed
+        
+        TDes8*                          iLabel;
+        
+        TDes8*                          iPath;
+        
+        //Buffer to hold Label. Owned.
+        HBufC8*                         iLabelBuf;
+    
+        //Pointer to Label. Owned.
+        TPtr8*                          iLabelBufPtr;
+        
+        //Buffer to hold path. Owned.
+        HBufC8*                         iPathBuf;
+    
+        //Pointer to path. Owned.
+        TPtr8*                          iPathBufPtr;
+        
+        
+    };
+
+	
+#endif  // JAVAUTILS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/java_utils_api/java_utils_api.metaxml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,18 @@
+<?xml version="1.0" ?>
+<api id="7a43eb75d745e0a161a4f014eea67478" dataversion="1.0">
+  <name>Java Utils API</name>
+  <description>Reads Java provisioning information from Smart Card</description>
+  <type>c++</type>
+  <subsystem>WIM</subsystem>
+  <libs>
+    <lib name="WimClient.lib" />
+  </libs>
+  <release category="domain"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>yes</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/keyguard_access_api/group/ABLD.BAT	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,15 @@
+@ECHO OFF
+
+REM Bldmake-generated batch file - ABLD.BAT
+REM ** DO NOT EDIT **
+
+perl -S ABLD.PL "\s60\mw\devicemanagement\devmngt_dom\keyguard_access_api\group\\" %1 %2 %3 %4 %5 %6 %7 %8 %9
+if errorlevel==1 goto CheckPerl
+goto End
+
+:CheckPerl
+perl -v >NUL
+if errorlevel==1 echo Is Perl, version 5.003_07 or later, installed?
+goto End
+
+:End
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/keyguard_access_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to Keyguard Access API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+../inc/keyguardaccessapi.h MW_LAYER_PLATFORM_EXPORT_PATH(keyguardaccessapi.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/keyguard_access_api/inc/keyguardaccessapi.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,124 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface to access keyguard.
+ *
+*/
+
+
+#ifndef __KEYGUARDACCESSAPI_H__
+#define __KEYGUARDACCESSAPI_H__
+
+#include <e32base.h>
+
+class RLockAccessExtension;
+
+/**
+ *  RKeyguardAccessApi class.
+ *  Client used to access/configure keyguard features.
+ *
+ *  @lib   lockapp
+ *  @since 5.0
+ */
+class CKeyguardAccessApi : public CBase
+    {
+    public:
+
+        /**
+         * Two-phased constructor.
+         */
+        IMPORT_C static CKeyguardAccessApi* NewL( );
+
+        /**
+         * Destructor.
+         */
+        IMPORT_C ~CKeyguardAccessApi( );
+
+    private:
+
+        /**
+         * Constructor for performing 1st stage construction
+         */
+        CKeyguardAccessApi( );
+
+        /**
+         * Default constructor for performing 2nd stage construction
+         */
+        void ConstructL( );
+
+    public:
+
+        /**
+         * Returns true if phone is keys are locked. Both keyguard
+         * and devicelock cannot be simultaneously enabled.
+         * @return true if either keyguard or devicelock is enabled.
+         */
+        IMPORT_C TBool IsKeylockEnabled();
+
+        /**
+         * Has keyguard been activated.
+         * @return true if keyguard is enabled.
+         */
+        IMPORT_C TBool IsKeyguardEnabled();
+
+        /**
+         * Enable keyguard. Only works if devicelock is not enabled.
+         * @param  aWithNote should informing note be shown
+         * @return KErrNone if succeeded
+         *         KErrAlreadyExists if already enabled
+         *         KErrPermissionDenied if devicelock is activated
+         */
+        IMPORT_C TInt EnableKeyguard( TBool aWithNote );
+
+        /**
+         * Disable keyguard. Only works if devicelock is not enabled.
+         * @param  aWithNote should informing note be shown
+         * @return KErrNone if succeeded
+         *         KErrAlreadyExists if already disabled
+         *         KErrPermissionDenied if devicelock is activated
+         */
+        IMPORT_C TInt DisableKeyguard( TBool aWithNote );
+
+        /**
+         * Offer to enable keyguard. Shows a query note to user.
+         * @return KErrNone if succeeded
+         *         KErrPermissionDenied if keyguard/devicelock already activated
+         */
+        IMPORT_C TInt OfferKeyguard();
+
+        /**
+         * Shows note informing that keys are locked.
+         * Only works if keyguard is already enabled.
+         * @return KErrNone if succeeded '
+         *         KErrPermissionDenied if keyguard is not activated
+         */
+        IMPORT_C TInt ShowKeysLockedNote();
+
+
+        /**
+         * Test functions, return KErrNotSupported in release builds.
+         */
+        IMPORT_C TInt TestInternal( );
+
+        IMPORT_C TInt TestDestruct( );
+
+        IMPORT_C TInt TestPanicClient( );
+
+
+    private:
+
+        RLockAccessExtension* iLockAccessExtension;
+
+    };
+
+#endif // __KEYGUARDACCESSAPI_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/keyguard_configuration_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+*               Keyguard Configuration API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/LockDomainCRKeys.h     MW_LAYER_PLATFORM_EXPORT_PATH(LockDomainCRKeys.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/keyguard_configuration_api/inc/LockDomainCRKeys.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,208 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Internal Central Repository keys.
+ *
+ *
+*/
+
+
+#ifndef LOCK_DOMAIN_CR_KEYS_H
+#define LOCK_DOMAIN_CR_KEYS_H
+
+// INCLUDES
+#include <centralrepository.h>
+
+const TUid KCRUidLockConf = { 0x10283322 };
+
+/**
+ * Products must configure this value depending on 
+ * what lock/unlock approach is supported by the device hardware
+ *
+ * Possible product modes are are:
+ *
+ * EKeyguardDefaultHardware = 0 // no addional hardware support
+ * EKeyguardOnePositionSwitch = 1 // one position spring adjusted switch
+ * EKeyguardTwoPositionSwitch = 2 // on-off type keyguard switch
+ *
+ * EKeyguardDefaultHardware is default in the platform.
+ */
+const TUint32 KKeyguardHardwareConf = 0x00000001;
+
+enum TLockHardware
+    {
+    EKeyguardDefaultHardware = 0,
+    EKeyguardOnePositionSwitch,
+    EKeyguardTwoPositionSwitch
+    };
+
+/**
+ * Products and applications can set on run-time if keyguard
+ * feature should be momentarily disabled/enabled.
+ *
+ * Possible run-time modes are are:
+ *
+ * EKeyguardNotAllowed = 0 // enabling keyguard is not allowed
+ * EKeyguardAllowed = 1 // keyguard works normally
+ *
+ * EKeyguardAllowed is default in the platform.
+ */    
+const TUint32 KLockKeyguardAllow = 0x00000002;
+
+enum TKeyguardAllow
+    {
+    EKeyguardNotAllowed = 0,
+    EKeyguardAllowed = 1,
+    };
+
+/**
+ * Products and applications can configure lock timer 
+ * interval in microseconds.
+ *
+ * KLockDefaultInterval of 2000000 microseconds is default in the platform.
+ */       
+const TUint32 KLockTimerInterval = 0x00000003;
+
+/**
+ * Products and applications can change between different  
+ * Keylock policy configurations by changing policy mode.
+ * 
+ * Possible run-time modes are are:
+ *
+ * ELockDefault = 0 // Used key configuration in default setup
+ * ELockSlider = 1 // Used key configuration in slider setup
+ * 
+ * Products can define new modes if needed.
+ * 
+ * Configuration ELockDefault is default in the platform.
+ */       
+const TUint32 KLockPolicyMode = 0x00000004;
+
+/**  
+ * Physical keys (scan code) used for locking/unlocking/query have been stored 
+ * in central repository keys with identification value of defined as     
+ * 0x000000XX Key configurations supported in the mode+type, e.g. 00 = left soft key + right soft key, 01 = left soft key + Fn
+ * 0x00000X00 Key code sequence number. 1 = primary key , 2 = secondary key
+ * 0x0000X000 from TLockPolicyType, 1= activate lock, 2 = deactivate lock, 3 = devicelock query
+ * 0x000X0000 from TLockPolicyMode, 1 = default configuration, 2 = slider configuration
+ *
+ * The default platform locking/unlocking/query configurations have been listed below.
+ */    
+
+/**
+ * Pre-defined policymodes, 1 = default configuration, 2 = slider configuration
+ * Modes are identified in a hexadecimal reserved in mask 0x000X0000.
+ */
+enum TLockPolicyMode
+    {
+    ELockNone = 0,
+    ELockDefault = 1,
+    ELockSlider = 2,
+    };
+
+/**
+ * Key code sequence number. 1 = primary key , 2 = secondary key.
+ * Key number is identified in a hexadecimal reserved in mask 0x00000X00.
+ */
+const TUint32 KLockFirstPrimaryKey = 0x00000100;
+const TUint32 KLockFirstSecondaryKey= 0x00000200;
+
+/**
+ * ============================================================================
+ * Policy mode default (left soft key+* for unlock/lock and left soft key for device lock)
+ * (not used directly)
+ * ============================================================================
+ */ 
+    
+/**
+ * First scan code key used for locking the phone in the default mode.
+ * Works when mode = ELockDefault and type = EActivateKeyguard.
+ * Default value is left soft key value with scan code 0xa4.
+ */
+const TUint32 KLockDefaultLockPrimaryConf00 = 0x00011100;
+    
+/**
+ * Second scan code key used for locking the phone in the default mode.
+ * Works when mode = ELockDefault and type = EActivateKeyguard.
+ * Default value is star key on ITU-keypad with scan code 0x2a.
+ */
+const TUint32 KLockDefaultLockSecondaryConf00 = 0x00011200;
+
+/**
+ * First scan code key used for unlocking the phone in the default mode.
+ * Works when mode = ELockDefault and type = EDeactivateKeyguard.
+ * Default value is left soft key with scan code 0xa4.
+ */
+const TUint32 KLockDefaultUnlockPrimaryConf00 = 0x00012100;
+    
+/**
+ * Second scan code key used for unlocking the phone in the default mode.
+ * Works when mode = ELockDefault and type = EDeactivateKeyguard.
+ * Default value is star key with scan code 0x2a.
+ */
+const TUint32 KLockDefaultUnlockSecondaryConf00 = 0x00012200;
+
+/**
+ * Scan code key used for showing security query when device is locked 
+ * in the default mode.
+ * Works when mode = ELockDefault and type = EDevicelockQuery.
+ * Default value is left soft key with scan code 0xa4.
+ */
+const TUint32 KLockDefaultSecQueryPrimaryConf00 = 0x00013100;
+
+/**
+ * ============================================================================
+ * Policy mode slider (left soft key+right soft key for unlock/lock and left soft key for device lock)
+ * (not used directly)
+ * ============================================================================
+ */ 
+ 
+/**
+ * First scan code key used for locking the phone in the slider mode.
+ * Works when mode = ELockSlider and type = EActivateKeyguard.
+ * Default value is left soft key with scan code 0xa4.
+ */
+const TUint32 KLockSliderLockPrimaryConf00 = 0x00021100;
+
+/**
+ * Second scan code key used for locking the phone in the slider mode.
+ * Works when mode = ELockSlider and type = EActivateKeyguard.
+ * Default value is right soft key with scan code 0xa5.
+ */
+const TUint32 KLockSliderLockSecondaryConf00 = 0x00021200;
+
+/**
+ * First scan code key used for unlocking the phone in the slider mode.
+ * Works when mode = ELockSlider and type = EDeactivateKeyguard.
+ * Default value is left soft key with scan code 0xa4.
+ */
+const TUint32 KLockSliderUnlockPrimaryConf00 = 0x00022100;
+
+/**
+ * Second scan code key used for unlocking the phone in the slider mode.
+ * Works when mode = ELockSlider and type = EDeactivateKeyguard.
+ * Default value is right soft key with scan code 0xa5.
+ */
+const TUint32 KLockSliderUnlockSecondaryConf00 = 0x00022200;
+
+/**
+ * Scan code key used for showing security query when device is locked 
+ * in the slider mode.
+ * Works when mode = ELockSlider and type = EDevicelockQuery.
+ * Default value is left soft key with scan code 0xa4.
+ */
+const TUint32 KLockSliderSecQueryPrimaryConf00 = 0x00023100;
+
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/keyguard_configuration_api/keyguard_configuration_api.metaxml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,17 @@
+<?xml version="1.0" ?>
+<api id="9d54a63877186a137adf6646ec53216b" dataversion="1.0">
+  <name>Keyguard Configuration API</name>
+  <description>An interface for checking keyguard hardware implementation state.</description>
+  <type>c++</type>
+  <subsystem>securityuis</subsystem>
+  <libs>
+  </libs>
+  <release category="domain"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>yes</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/keylock_policy_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+*               Keylock Policy API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/keylockpolicyapi.h MW_LAYER_PLATFORM_EXPORT_PATH(keylockpolicyapi.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/keylock_policy_api/inc/keylockpolicyapi.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,169 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Keylock policy component offers a configuration support for keyguard
+*
+*/
+
+
+#ifndef ___CKEYLOCKPOLICYAPI__
+#define ___CKEYLOCKPOLICYAPI__
+
+#include <w32std.h>
+#include <e32base.h>
+
+/**
+ * Keylock policy component supports three policy types:
+ *
+ * EPolicyActivateKeyguard keys used for keyguard locking
+ * EPolicyDeactivateKeyguard keys used for keyguard unlocking
+ * EPolicyDevicelockQuery keys used for showing devicelock query
+ */
+enum TLockPolicyType
+	{
+	EPolicyActivateKeyguard = 1,
+	EPolicyDeactivateKeyguard,
+	EPolicyDevicelockQuery,
+	};
+
+// FORWARD DECLARATIONS
+class CKeyLockPolicyApiImpl;
+
+/**
+ *  CKeyLockPolicyApi. Trough CKeyLockPolicyApi users can
+ *
+ *  @lib keylockpolicy.lib
+ *  @since 3.2
+ */
+class CKeyLockPolicyApi : public CBase
+	{
+public:
+
+	/**
+	 * Use this to create keylock policy
+	 * @param TLockPolicyType aType the policy used
+	 */
+	IMPORT_C static CKeyLockPolicyApi* NewL( TLockPolicyType aType );
+
+	/**
+	 * Destructor.
+	 */
+	IMPORT_C ~CKeyLockPolicyApi();
+
+	/**
+	 * If no policy has been defined for the type it cannot be used.
+	 * @return ETrue if has succesfully loaded policy
+	 */
+	IMPORT_C TBool HasConfiguration();
+
+	/**
+	 * Activates support for keyguard feature so  the phone keys cannot
+	 * be locked with keyguard. Does not affect the devicelock.
+	 * @return standard Symbian error code
+	 */
+	IMPORT_C TInt EnableKeyguardFeature();
+
+	/**
+	 * Disables support for keyguard feature so the phone keys cannot
+	 * be locked with keyguard. Does not affect the devicelock.
+	 * @return standard Symbian error code
+	 */
+	IMPORT_C TInt DisableKeyguardFeature();
+
+	/**
+	 * Whether keyguard feature is currently enabled or disabled.
+	 * @return ETrue if keyguard can be locked.
+	 */
+	IMPORT_C TBool static KeyguardAllowed();
+
+	/**
+	 * Adds a key combination for the policy type defined in the construction.
+	 *
+	 * @param TUint scan code for primary key
+	 * @param TUint scan code for secondary key
+	 * @return standard Symbian error code
+	 */
+	IMPORT_C TInt AddKeyCombination(TUint32 aPrimaryKey, TUint32 aSecondaryKey);
+
+	/**
+	 * Removes a key combination for the policy type defined in the construction.
+	 *
+	 * @param TUint scan code for primary key
+	 * @param TUint scan code for secondary key
+	 * @return standard Symbian error code
+	 */
+	IMPORT_C TInt RemoveKeyCombination(TUint32 aPrimaryKey, TUint32 aSecondaryKey);
+
+	/**
+	 * Retrieve a key combination on the given index.
+	 *
+	 * @param TInt aIndex index on the list that stores key combinations
+	 * @param TUint key code for primary key
+	 * @param TUint key code for secondary key
+	 * @return standard Symbian error code
+	 */
+	IMPORT_C TInt GetKeyCombination(TInt aIndex, TUint32 &aPrimaryKey, TUint32 &aSecondaryKey);
+
+	/**
+	 * Clears all the defined key combinations from the policy.
+	 *
+	 * @return standard Symbian error code
+	 */
+	IMPORT_C TInt ClearKeycombinations();
+
+	/**
+	 * Handles Key events, returns ETrue the key events match any of the
+	 * defined key combinations. Only uses scancodes with type EEventKeyDown.
+	 *
+	 * @param TKeyEvent aKeyEvent the actual key event
+	 * @param TEventCode aType the type of the received key event
+	 * @return ETrue if a match was found.
+	 */
+	IMPORT_C TBool HandleKeyEventL(const TKeyEvent& aKeyEvent, const TEventCode aType );
+
+	/**
+	 * Returns true if primary button is pressed and note should be shown.
+	 * @return boolean true if primary key is pressed.
+	 */
+	IMPORT_C TBool PrimaryKeyPressed();
+
+	/**
+	 * Returns Primary key scan code that has been pressed last.
+	 * @return scan code value of the primary key if found, NULL if not
+	 */
+	IMPORT_C TUint GetLastPrimaryKey();
+
+private:
+
+	/**
+	 * C++ default constructor (private so cannot be derived).
+	 */
+	CKeyLockPolicyApi( );
+
+	/**
+	 * Second constructor initializes the policy
+	 * @param TLockPolicyType aType the policy (TLockPolicyType) used
+	 */
+	void ConstructL( TLockPolicyType aType );
+
+private:
+
+	/**
+	 * Actual implemetation.
+	 */
+	CKeyLockPolicyApiImpl* iKeylockpolicyImplementation;
+
+	};
+
+#endif // ___CKEYLOCKPOLICYAPI__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/keylock_policy_api/keylock_policy_api.metaxml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,13 @@
+<?xml version="1.0" ?>
+<api id="cd4b44aac9f6d77c6bc3f78b209a5751" dataversion="1.0">
+<name>Keylock Policy API</name>
+<description>An interface offerring a configuration support for keyguard.</description>
+<type>c++</type>
+<subsystem>devicemanagement</subsystem>
+<libs></libs>
+<release category="domain" sinceversion=""/>
+<attributes>
+<htmldocprovided>yes</htmldocprovided>
+<adaptation>no</adaptation>
+</attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/lockapp_server_api/group/ABLD.BAT	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,15 @@
+@ECHO OFF
+
+REM Bldmake-generated batch file - ABLD.BAT
+REM ** DO NOT EDIT **
+
+perl -S ABLD.PL "\s60\mw\devicemanagement\devmngt_dom\lockapp_server_api\group\\" %1 %2 %3 %4 %5 %6 %7 %8 %9
+if errorlevel==1 goto CheckPerl
+goto End
+
+:CheckPerl
+perl -v >NUL
+if errorlevel==1 echo Is Perl, version 5.003_07 or later, installed?
+goto End
+
+:End
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/lockapp_server_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to Lockapp Server API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+../inc/lockappclientserver.h MW_LAYER_PLATFORM_EXPORT_PATH(lockappclientserver.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/lockapp_server_api/inc/lockappclientserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,71 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  LockApp Server information
+ *
+*/
+
+
+#ifndef __LOCKAPPCLIENTSERVER_H__
+#define __LOCKAPPCLIENTSERVER_H__
+
+/**
+ * LockApp application Uid
+ */
+const TUid KLockAppUid =
+    {
+    0x10283322
+    };
+
+/**
+ * LockApp service Uid and differentiator
+ */
+const TUid KLockAppServiceUid =
+    {
+    0x00000001
+    };
+const TUint KLockAppServerDiff = 0x00000002;
+
+/**
+ * LockApp session version numbers
+ */
+const TUint KLockAppServMajorVersion = 1;
+const TUint KLockAppServMinorVersion = 0;
+const TUint KLockAppServBuildVersion = 0;
+
+/**
+ * LockApp name and process name
+ */
+_LIT( KLockAppServerName, "LockApp");
+_LIT( KLockAppServerImg, "LockApp");
+
+/**
+ * LockApp messages
+ */
+enum TLockAppMessageReason
+    {
+    ELockAppEnableKeyguard = 1,
+    ELockAppDisableKeyguard,
+    ELockAppEnableDevicelock,
+    ELockAppDisableDevicelock,
+    ELockAppOfferKeyguard,
+    ELockAppOfferDevicelock,
+    ELockAppShowKeysLockedNote,
+#ifdef _DEBUG
+    ELockAppTestInternal = 100,
+    ELockAppTestDestruct,
+    ELockAppTestPanicClient
+#endif
+    };
+
+#endif // __LOCKAPPCLIENTSERVER_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/pkcs12_parser_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+:                PKCS12 Parser API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/mpkcs12.h     MW_LAYER_PLATFORM_EXPORT_PATH(mpkcs12.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/pkcs12_parser_api/inc/mpkcs12.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,113 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Header file of the abstract PKCS#12 parser API
+*
+*/
+
+
+#ifndef __MPKCS12_H__
+#define __MPKCS12_H__
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <f32file.h>
+
+// CONSTANTS
+// Minimum data length needed to recognize PKCS#12 data.
+const TInt KPKCS12DataMinLength = 49;
+
+// FORWARD DECLARATIONS
+class CX509Certificate;
+
+// CLASS DECLARATION
+
+/**
+*  Class MPKCS12
+*  The MPKCS12 abstract base class for opening  a PKCS #12 file. 
+*  PKCS #12 is a format used to store and protect user's
+*  private data, i.e. his/her key pairs, certificates and other personal
+*  information.
+*
+*  @since Series 60 3.0
+*/
+class MPKCS12
+    {        
+    public: // Functions
+           
+        /**
+        * Executes actual parsing.
+        * @param aPKCS12 PKCS#12 encoded data
+        * @param aPassword Used to generate encryption key.
+        * @return ?description
+        */
+        virtual void ParseL(const TDesC8& aPKCS12, const TDesC16& aPassword) = 0;
+        
+        /**
+        * ?member_description.
+        * @since Series ?XX ?SeriesXX_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        virtual const CArrayPtr<CX509Certificate>& CACertificates() const = 0;
+        virtual const CArrayPtr<CX509Certificate>& UserCertificates() const = 0;        
+        virtual const CArrayPtr<HBufC8>& PrivateKeys() const = 0;
+        
+        // Returns number of SafeBags in PKCS #12 file.
+        virtual TUint SafeBagsCount() const = 0;
+        // Returns the number of iterations.
+		virtual TUint IterCount() const = 0;
+
+        /**
+	    * Frees resources of the MPKCS12 class
+	    */
+	    virtual void Release()=0;	   	    	    
+	    
+	    /**
+        * Recognizes PKCS#12 data
+        * @param aPKCS12 PKCS#12 encoded data        
+        * @return ETrue if data is recognized as PKCS12,
+        *         otherwise EFalse.
+        */
+        virtual TBool IsPKCS12Data(const TDesC8& aBinaryData) = 0;
+        
+    protected:  // Destructor       
+        
+        /**
+        * Destructor.
+        */
+        inline virtual ~MPKCS12()
+            {};
+                 
+    };
+
+
+/**
+ * Factory for creating the relevant concrete subclass of the pkcs#12 base class.
+ */
+class PKCS12Factory
+	{
+public:
+	/**
+	 * Creates an instance of a subclass of MPKCS12. Implement to create
+	 * the appropriate PKCS#12 parser
+	 * 
+	 * @return	An object that implements MPKCS12 functions
+	 */
+	IMPORT_C static MPKCS12* CreateL();	    
+	};
+
+#endif      // __MPKCS12_H__   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/pkcs12_parser_api/pkcs12_parser_api.metaxml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,17 @@
+<?xml version="1.0" ?>
+<api id="5d084e5558961bae321bc9a01bb37fd7" dataversion="1.0">
+  <name>PKCS12 Parser API</name>
+  <description>API to parse PKCS#12 file</description>
+  <type>c++</type>
+  <subsystem>pkiutilities</subsystem>
+  <libs>
+  </libs>
+  <release category="domain"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>yes</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/pkidialog_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+:                PKIDialog API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/PKIDlg.h     MW_LAYER_PLATFORM_EXPORT_PATH(PKIDlg.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/pkidialog_api/inc/PKIDlg.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,197 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface for PKI dialog
+*
+*/
+
+
+#ifndef MPKIDIALOG_H
+#define MPKIDIALOG_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <ct.h>
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+/**
+*  PKI Dialog interface
+*  
+*  @since Series60 3,0
+*/
+class MPKIDialog
+    {
+    public:
+        
+        /**
+        * TNoteType defines different possible note types.
+        */
+        enum TNoteType
+            {
+            ESignatureRequested = 0xFF00,   // Digital signature requested
+            ESignatureDone,                 // Digital signature done.
+            ESigningCancelled,              // Digital signing cancelled   
+            ENoMatchCert,                   // No matchig certificate found
+            ENoSecurityModule,              // Security Module unvailable
+            EInternalError                  // Error note in any other case
+            };
+    public: // New functions
+    
+        /**
+    	* User authentication dialogs
+    	* @param aCertHandleList	A selection of certificates to display to the user.
+    	*							All certificates are displayed if this is empty.
+    	* @param aCertHandle		On return, an identifier for the certificate the user selected.
+    	* 							aStatus - this will be set to KErrNotFound if no certificates
+    	*							could be presented to the user.
+    	* @param aStatus			This will be set to KErrNotFound if no certificates could
+    	* 							be presented to the user.
+    	*/
+    	virtual void UserAuthentication(
+                        const RArray<TCTTokenObjectHandle>& aCertHandleList, 
+    			        TCTTokenObjectHandle& aCertHandle,
+    				    TRequestStatus& aStatus ) = 0;
+        
+        /**
+    	* User authentication dialogs with text
+    	* 
+    	* @param aTextToSign		The text to be signed.
+    	* @param aCertHandleList	A selection of certificates to display to the user.
+    	*							All certificates are displayed if this is empty.
+    	* @param aCertHandle		On return, an identifier for the certificate the user selected.
+    	* 							aStatus - this will be set to KErrNotFound if no certificates
+    	*							could be presented to the user.
+    	* @param aStatus			This will be set to KErrNotFound if no certificates could
+    	* 							be presented to the user.
+    	*/
+    	virtual void UserAuthenticationText( 
+    	                const TDesC& aTextToSign,
+                        const RArray<TCTTokenObjectHandle>& aCertHandleList, 
+                        TCTTokenObjectHandle& aCertHandle,
+                        TRequestStatus& aStatus ) = 0;
+    						   
+    	/**
+    	* Certificate signing request dialog
+    	* 
+    	* @param aSubject		    Subject of the certificate
+    	* @param aKeyHandle      	An identifier of the private used in the CSR.                           
+    	* @param aStatus			This will be set to KErrNotFound if no certificates could
+    	* 							be presented to the user.
+    	*/
+    	virtual void CreateCSR( 
+                        const TDesC& aSubject,
+                        const TCTTokenObjectHandle& aKeyHandle,
+                        TRequestStatus& aStatus ) = 0;					  
+
+            
+        /**
+        * Shows details of the certificate
+        * @param aCertHandle	    An identifier of the certificate
+        * @param aStatus            KErrNone or KErrNotSupported
+        *                           KErrNotFound if no certificates could
+    	* 							be presented to the user.  
+        * @return void
+        */
+        virtual void CertificateDetails( 
+                        const TCTTokenObjectHandle& aCertHandle,
+                        TRequestStatus& aStatus  ) = 0;
+        /**
+        * Asks user's approval for certificate saving.
+        * @param aFormat		   The format of the certificate.
+        * @param aCertificateOwnerType	The owner type.
+        * @param aCert					The certificate to be added.
+        * @param aStatus            KErrNone, KErrCancel or KErrNotSupported,
+        *                           KErrArgument if error in certificate parsing
+        * @return void
+        */
+        virtual void SaveCertificate( 
+                        TCertificateFormat aFormat,
+                        TCertificateOwnerType aCertificateOwnerType, 
+                        const TDesC8& aCert, TRequestStatus& aStatus) = 0;
+        
+        /**
+        * Asks user's approval for certificate deleting.
+        * @param aCertHandle	    An identifier of the certificate
+        * @param aStatus            KErrNone, KErrCancel or KErrNotSupported,
+        *                           KErrNotFound if no certificates could
+    	* 							be presented to the user.    
+        * @return void
+        */
+        virtual void DeleteCertificate( 
+                        const TCTTokenObjectHandle& aCertHandle,
+                        TRequestStatus& aStatus  ) = 0;
+        
+        /**
+        * Informs the user during digital signing.
+        * @param aNoteType Identifies the note type.
+        * @param aStatus KErrNone or KErrNotSupported
+        * @return void
+        */
+        virtual void Note( MPKIDialog::TNoteType aNoteType,
+                           TRequestStatus& aStatus ) = 0;
+        
+        /**
+        * Saves receipt to Notepad if receipt saving is on.
+        * @param aSignedText Signed text in readable form.
+        * @param aStatus KErrNone or KErrNotSupported
+        * @return void
+        */
+        virtual void SaveSignedText( const TDesC& aSignedText,
+                                     TRequestStatus& aStatus ) = 0;
+        
+        /**
+        * Shows instructions how to unblock PIN.
+        * @param aLabel Label of the PIN.
+        * @param aStatus KErrNone or KErrNotSupported
+        * @return void
+        */
+        virtual void PINBlockedInfo( const TPINLabel& aLabel,
+                                     TRequestStatus& aStatus ) = 0;       
+        /**
+        * Release is called to free resources of the MDigSigningNote class
+        */
+        virtual void Release() = 0;
+
+    protected: 
+        
+        // Destructor
+        inline virtual ~MPKIDialog() = 0;
+
+    };
+
+inline MPKIDialog::~MPKIDialog(){}
+
+/**
+* Factory for creating the relevant concrete subclass
+* of the PKI Dialog.
+*/
+class PKIDialogFactory
+    {
+    public:
+    
+    /**
+     * Creates an instance of a subclass of MPKIDialog. 
+     * Implement to create the appropriate security dialog.
+     * 
+     * @param returns an object that implements MPKIDialog methods
+     */
+    IMPORT_C static MPKIDialog* CreateNoteL(); 
+    
+    };
+
+#endif      // MPKIDIALOG_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/pkidialog_api/pkidialog_api.metaxml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,18 @@
+<?xml version="1.0" ?>
+<api id="6f3edf5df0bebb708e5e4c0fd091b123" dataversion="1.0">
+  <name>PKIDialog API</name>
+  <description>Interface for PKI dialog</description>
+  <type>c++</type>
+  <subsystem>pkiutilities</subsystem>
+  <libs>
+    <lib name="ctsecdlgs.lib" />
+  </libs>
+  <release category="domain"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>yes</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/provisioning_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,28 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+*               Provisioning API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/ProvSC.h     MW_LAYER_PLATFORM_EXPORT_PATH(ProvSC.h)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/provisioning_api/inc/ProvSC.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,241 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Reads provisioning information from Smart Card 
+*
+*/
+
+
+#ifndef PROVSC_H
+#define PROVSC_H
+
+//INCLUDES
+#include <e32base.h>
+
+
+//FORWARD DECLARATIONS
+class RWimCertMgmt;
+class RWimMgmt;
+
+
+//TYPE DEFINITIONS
+enum TOMAType
+    {
+    EBootStrap,
+    EConfig1,
+    EConfig2
+    };
+
+
+/**
+*  Reads OMA Provisioning information from Smart Card
+*
+*  @lib WimClient
+*  @since Series60 2.6
+*/
+class CWimOMAProv : public CActive
+    {
+    public:
+
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CWimOMAProv* NewL();
+
+        /**
+        * Destructor
+        */
+        IMPORT_C virtual ~CWimOMAProv();
+        
+        /**
+        * Initializes the WIM Server cache. This is the most time consuming call. 
+        * @param  aStatus  Indicates the result of this call. Values:
+        *         KErrNone, call was successull
+        *         KErrNotFound, no WIM was found
+        *         KErrNoMemory, no memory
+        *         KErrGeneral, any other error
+        * @return void
+        */
+        IMPORT_C void Initialize( TRequestStatus& aStatus );
+
+        /** 
+        * Cancels outgoing Initialize operation. 
+        * @return void
+        */
+        IMPORT_C void CancelInitialize();
+
+        /**
+        * Fetches the size of provisioning information string. 
+        * This information can be used as a notification, does provisioning 
+        * information exist. If the size is not included in Smart Card's
+        * DODF-PROV file then the full length of the file containing the 
+        * provisioning information is returned.
+        * @param  aSize (OUT) The length of provisioning string
+        * @param  aOMAType (IN) OMA provisioning file type 
+        *         Pseudo values:
+        *         -Bootstrap
+        *         -Config 1
+        *         -Config 2
+        * @param  aStatus  Indicates the result of this call.
+        *         KErrNone, no errors. NOTE: size can still be 0 indicating
+        *                   that no provisioning information was found.
+        *                   If aSize > 0 it means that provisioning information
+        *                   was found.
+        *         KErrNoMemory, No memory
+        *         KErrGeneral, any other error
+        * @return void
+        */
+        IMPORT_C void GetSize( TInt& aSize,
+                               const TOMAType& aOMAType,
+                               TRequestStatus& aStatus );
+
+        /** 
+        * Cancels outgoing GetSize operation.
+        * @return void
+        */
+        IMPORT_C void CancelGetSize();
+
+        /**
+        * Fetches the whole data of provisioning information string. 
+        * @param  aOMAType (IN) The type of provisioning string
+        * @param  aOMAData (OUT) provisioning  binary data
+        * @param  aStatus  Indicates the result of this call.
+        *         KErrNone, no errors.
+        *         KErrNoMemory, No memory
+        *         KErrGeneral, any other error
+        * @return void
+        */
+        IMPORT_C void Retrieve( const TOMAType& aOMAType, 
+                                TDes8& aOMAData,
+                                TRequestStatus& aStatus );
+
+        /** 
+        * Cancels outgoing Retrieve operation.
+        * @return void
+        */
+        IMPORT_C void CancelRetrieve();
+
+    private:
+
+        /**
+        * Symbian constructor
+        * @return void
+        */
+        void ConstructL();
+
+        /**
+        * C++ default constructor.
+        */
+        CWimOMAProv();
+
+    private: //from CActive
+        
+        /**
+        * Different phases are handled here.
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * Cancellation function
+        * Deallocates member variables and completes client status with
+        * KErrCancel error code.
+        * @return void
+        */
+        void DoCancel();
+
+        /**
+        * The active scheduler calls this function if this active 
+        * object's RunL() function leaves. 
+        * Handles necessary cleanup and completes request with
+        * received error code.
+        * @param aError -The error code which caused this function call.
+        * @return TInt  -Error code to active scheduler, is always KErrNone.
+        */ 
+        TInt RunError( TInt aError );
+
+    private:
+
+        /** 
+        * Sets own iStatus to KRequestPending, and signals it 
+        * with User::RequestComplete() -request. This gives chance 
+        * active scheduler to run other active objects. After a quick
+        * visit in active scheduler, signal returns to RunL() and starts next
+        * phase of operation. 
+        * @return void
+        */
+        void SignalOwnStatusAndComplete();
+
+        /** 
+        * Allocates memory for member variables, which are needed
+        * in OMA Provisioning struct.
+        * @param aDataLength -The length of the data to be allocated
+        * @return void
+        */
+        void AllocMemoryForOmaProvStructL( const TInt aDataLength );
+
+        /** 
+        * Deallocates memory from member variables
+        * @return void
+        */
+        void DeallocMemoryFromOmaProvStruct();
+
+    private:
+
+        enum TOMAPhase
+            {
+            EInitialize,
+            EConnectClientSession,
+            EInitializeWim,
+            EInitializeDone,
+            EGetSize,
+            EGetSizeDone,
+            ERetrieve,
+            ERetrieveDone
+            };
+
+        //Indicator for different phases
+        TOMAPhase                       iPhase;
+        
+        //Client status is stored here while operation
+        //on the server side is done.
+        TRequestStatus*                 iClientStatus;
+        
+        //Handle to connection with server. Owned.
+        RWimCertMgmt*                   iConnectionHandle;
+
+        // Pointer to Client Session. Owned. 
+        RWimMgmt*                       iClientSession;
+        
+        //Informs the type:EBootStrap, EConfig1, EConfig2
+        TOMAType                        iOMAType;
+
+        //Informs the size of provisioning string. Not owned.
+        TInt*                           iSize;
+        
+        //Descriptor to hold provisioning data. Not owned.
+        TDes8*                          iData;
+
+        //Buffer to hold provisioning data for server. Owned.
+        HBufC8*                         iOmaProvBuf;
+    
+        //Pointer to iOmaProvBuf. Owned.
+        TPtr8*                          iOmaProvBufPtr;
+        
+        //Flag to indicate errors during WIM -initialization.
+        TInt                            iWimStartErr;
+    };
+
+#endif  // PROVSC_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/provisioning_api/provisioning_api.metaxml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,18 @@
+<?xml version="1.0" ?>
+<api id="b6229f7a9247a0702387b6d1a8b7a44c" dataversion="1.0">
+  <name>Provisioning API</name>
+  <description>Provides services for reading OMA provisioning files from SIM card</description>
+  <type>c++</type>
+  <subsystem>WIM</subsystem>
+  <libs>
+    <lib name="WimClient.lib" />
+  </libs>
+  <release category="domain"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>yes</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/remote_lock_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+*               Remote Lock API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/RemoteLockSettings.h     MW_LAYER_PLATFORM_EXPORT_PATH(RemoteLockSettings.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/remote_lock_api/inc/RemoteLockSettings.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,236 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  API for applications to access remote lock settings.
+*
+*/
+
+
+#ifndef REMOTELOCKSETTINGS_H
+#define REMOTELOCKSETTINGS_H
+
+
+// INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <e32cons.h>
+#include <cenrepnotifyhandler.h>      
+
+// CONSTANT
+
+// MACROS 
+/** Maximum length of user-given remote lock code */
+const TInt KRLockMaxLockCodeLength = 20;
+/** Minimum length of user-given remote lock code */
+const TInt KRLockMinLockCodeLength = 5;
+/** Length of the stored remote lock code */
+const TInt KRLockStoredLockCodeLength = 32;
+
+// DATA TYPES 
+
+// FUNCTION PROTOTYPES 
+
+// FORWARD DECLARATIONS 
+class MRemoteLockSettingsHandler;
+
+
+// CLASS DECLARATION
+/**
+* Interface for handling remote lock settings
+*
+* @lib rlocksettings.lib
+* @since S60 3.2
+*
+*/
+class CRemoteLockSettings: public CBase, public MCenRepNotifyHandlerCallback 
+    {
+    public:                
+        /**
+        * Two-Phased constructor
+        *
+        * @since S60 3.2
+        * @param aHandler Client implemented notification handler that will be
+        *                 called when remote lock settings are changed. 
+        *                 If the client doesn't need notification, then no 
+        *                 parameter needed.
+        * @return
+        */
+        IMPORT_C static CRemoteLockSettings* NewL( 
+            MRemoteLockSettingsHandler* aHandler = NULL );        
+         
+        /**
+        * Two-Phased constructor
+        *
+        * @since S60 3.2
+        * @param aHandler Client implemented notification handler that will be
+        *                 called when remote lock settings are changed. 
+        *                 If the client doesn't need notification, then no 
+        *                 parameter needed.
+        * @return
+        */              
+        IMPORT_C static CRemoteLockSettings* NewLC( 
+            MRemoteLockSettingsHandler* aHandler  = NULL);
+        
+        IMPORT_C virtual ~CRemoteLockSettings();
+
+        /**
+        * Gets the remote lock code. Note that the retrieved remote lock code 
+        * is not in plain format.
+        *
+        * @since S60 3.2
+        * @param aLockCode For retrieving the remote lock code. The length 
+        *                  must be at least KRLStoredLockCodeLength.
+        * @return ETrue if succeeded,
+        *         EFalse otherwise.
+        */
+        IMPORT_C TBool GetLockCode( TDes& aLockCode ) const;
+        
+        /**
+        * Gets the remote lock code. Note that the retrieved remote lock code 
+        * is not in plain format.
+        *
+        * @since S60 3.2
+        * @param aLockCode For retrieving the remote lock code. The length 
+        *                  must be at least KRLStoredLockCodeLength.
+        * @param aLockCodeTrimmed For retrieving the remote lock code. 
+        *                         The length must be at least 
+        *                         KRLStoredLockCodeLength. Same as aLockCode, 
+        *                         but formatted differently before storing: 
+        *                         leading and trailing space characters 
+        *                         removed, multiple spaces replaced with 
+        *                         single space.
+        * @return ETrue if succeeded,
+        *         EFalse otherwise.
+        */
+        IMPORT_C TBool GetLockCode( 
+        	TDes& aLockCode, 
+        	TDes& aLockCodeTrimmed ) const;
+        
+        /**
+        * Enables remote lock and stores the correct remote lock code.
+        *
+        * @since S60 3.2
+        * @param aLockCode New remote lock code.
+        * @return ETrue if succeeded,
+        *         EFalse otherwise. 
+        */
+        IMPORT_C TBool SetEnabledL( const TDesC& aLockCode );
+        
+        /**
+        * Disables remote lock.
+        *
+        * @since S60 3.2
+        * @param
+        * @return ETrue if succeeded,
+        *         EFalse otherwise. 
+        */
+        IMPORT_C TBool SetDisabled();
+
+        /**
+        * Gets the current remote lock status.
+        *
+        * @since S60 3.2
+        * @param aEnabled For retrieving the current remote lock status.
+        * @return ETrue if succeeded,
+        *         EFalse otherwise.
+        */
+        IMPORT_C TBool GetEnabled( TBool& aEnabled ) const;      
+        
+        /**
+        * Compares two remote lock codes.
+        *
+        * @since S60 3.2
+        * @param aLockCode The lock code to compare. This should be in plain 
+       	*        format.
+        * @param aCorrectLockCode The correct lock code to compare against. 
+        *        This should be the one retrieved using GetLockCode(), and 
+        *        thus is not in plain format.
+        * @return ETrue if the lock codes are the same,
+        *         EFalse otherwise.
+        */
+        IMPORT_C TBool CompareLockCodesL( 
+            const TDesC& aLockCode, 
+            const TDesC& aCorrectLockCode ) const;      
+        
+        /**
+        * Enables or disables remote lock settings notification. If the 
+        * settings are changed, the notification handler given in NewL()
+        * or NewLC() will be called.
+        *
+        * @since S60 3.2
+        * @param aNotifyEnable For enabling or disabling the remote lock 
+        *                      settings notification.
+        * @return ETrue if succeeded,
+        *         EFalse otherwise.
+        */
+        IMPORT_C TBool RemoteLockNotifyL( const TBool aNotifyEnable ); 
+   
+    private:
+        
+        /**
+        * Constructor.
+        *
+        * @since S60 3.2
+        * @param aHandler Client implemented notification handler that will be
+        *                 called when remote lock settings are changed. 
+        */   
+        CRemoteLockSettings( MRemoteLockSettingsHandler* aHandler );
+        
+        /**
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+        
+        // from base class MCenRepNotifyHandler
+        
+        /**
+        * From MCenRepNotifyHandler
+        * Notify handler.
+        */
+        void HandleNotifyGeneric( TUint32 aId );
+
+    public: // data
+        
+    private: // data
+    
+        CRepository* iSession;
+        CCenRepNotifyHandler* iNotifyHandler;
+        MRemoteLockSettingsHandler* iHandler;                  
+    };
+
+// CLASS DECLARATION
+
+/**
+* Abstract interface for handling the notification when remote lock settings 
+* are changed. User derives his class from this and implements 
+* HandleRemoteLockNotifyL().
+*
+* @lib rlocksettings.lib
+* @since S60 3.2
+*/
+class MRemoteLockSettingsHandler
+    {    
+    public:
+        /**
+        * This function will be called when the remote lock settings are 
+        * changed.
+        *
+        * @since S60 3.2
+        * @param
+        * @return 
+        */
+        virtual void HandleRemoteLockNotifyL() = 0; 
+    };
+
+#endif
+//End of File. 
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/remote_lock_api/remote_lock_api.metaxml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,18 @@
+<?xml version="1.0" ?>
+<api id="265c290ce3e6848b48351c0efeba17b9" dataversion="1.0">
+  <name>Remote Lock API</name>
+  <description>Used to change or retrieve remote lock settings.</description>
+  <type>c++</type>
+  <subsystem>remotelock</subsystem>
+  <libs>
+    <lib name="rlocksettings.lib" />
+  </libs>
+  <release category="domain"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>yes</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/security_code_ui_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+*               Security Code UI API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/SecUiSecurityHandler.h     MW_LAYER_PLATFORM_EXPORT_PATH(secuisecurityhandler.h)
+../inc/SecUiSecuritySettings.h     MW_LAYER_PLATFORM_EXPORT_PATH(secuisecuritysettings.h)
+../inc/SecUiManualSecuritySettings.h     MW_LAYER_PLATFORM_EXPORT_PATH(secuimanualsecuritysettings.h)
+../inc/SecUi.h     MW_LAYER_PLATFORM_EXPORT_PATH(secui.h)
+../inc/SecUiCodeQueryDialog.h     MW_LAYER_PLATFORM_EXPORT_PATH(secuicodequerydialog.h)
+../inc/SecUi.hrh     MW_LAYER_PLATFORM_EXPORT_PATH(secui.hrh)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/security_code_ui_api/inc/SecUi.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,83 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*		Provides initialization and uninitialization for SecUi resource file
+*
+*
+*/
+
+
+#ifndef     __SECUI_H
+#define     __SECUI_H
+
+class TSecUi
+	{
+	public:
+		/**
+		* Initializes SecUi resource file
+		*
+		* Should be called before using any other SecUi methods 
+		*/
+		IMPORT_C static void InitializeLibL();
+		/**
+		* Uninitializes SecUi resource file
+		*
+		* Should be called after finished using SecUi methods 
+		*/
+		IMPORT_C static void UnInitializeLib();
+		/**
+		* Returns the resource file name of SecurityUI dll.
+		*
+		* @return TFileName (resource file name) 
+		*/
+		static TFileName ResourceFileName();
+        	/**
+        * Check if SecUi can be uninitialized, i.e. if client count is zero (or less).
+        *
+        * @return ETrue if SecUi can be freed, EFalse otherwise.
+        */
+		TBool CanBeFreed();
+
+		/**
+        * Increse client count for this thread.
+        */
+		void IncreaseClientCount();
+
+		/**
+        * Decrease client count for this thread
+        */
+		void DecreaseClientCount();
+
+	private:
+		/**
+		* C++ default constructor.
+		*/
+		TSecUi();
+		/**
+		* Destructor.
+		*/
+		~TSecUi();
+		/**
+		* Symbian OS constructor.
+		*/
+		void ConstructL();
+	private:
+		TInt iResourceFileOffset;
+        TInt iClientCount;
+
+	};
+#endif
+
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/security_code_ui_api/inc/SecUi.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*	 
+*
+*
+*/
+
+
+#ifndef SECUI_HRH
+#define SECUI_HRH
+
+
+#define SEC_C_SECURITY_CODE_MAX_LENGTH			10
+#define SEC_C_SECURITY_CODE_MIN_LENGTH			5
+#define SEC_C_SECURITY_CODE_CHANGE_MAX_LENGTH	5
+#define SEC_C_MASTER_CODE_LENGTH	10
+#define SEC_C_PIN_CODE_MAX_LENGTH	8
+#define SEC_C_PIN_CODE_MIN_LENGTH	4
+#define SEC_C_PIN2_CODE_MAX_LENGTH	8
+#define SEC_C_PIN2_CODE_MIN_LENGTH	4
+#define SEC_C_PUK_CODE_MAX_LENGTH		8
+#define SEC_C_PUK_CODE_MIN_LENGTH		8
+#define SEC_C_PUK2_CODE_MAX_LENGTH		8
+#define SEC_C_PUK2_CODE_MIN_LENGTH		8
+#define SEC_REMOTELOCK_CODE_MAX_LENGTH    20
+#define SEC_REMOTELOCK_CODE_MIN_LENGTH    5
+
+enum TSecUiCommands
+	{
+	ESecUiCodeEtelReqest = 1,
+	ESecUiNone,
+	ESecUiPukRequired
+	};
+	
+enum TSecUiEvents
+	{
+	 ESecUiEmergencyCall = 972,
+	 ESecUiDeviceLocked
+	 };
+	 
+enum TSecUiObserverType
+    {
+      ESecUiDeviceLockObserver,
+      ESecUiRequestStateObserver,
+      ESecUiCallStateObserver  
+    };
+
+#endif  //  SecUi
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/security_code_ui_api/inc/SecUiCodeQueryDialog.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,113 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*		Dialog used for code queries. Inherits AknQueryDialog
+*
+*
+*/
+
+
+#ifndef __SECUICODEQUERYDIALOG__
+#define __SECUICODEQUERYDIALOG__
+
+#include <aknquerydialog.h>
+#include <aknnotedialog.h>
+#include <secui.hrh>
+
+class CCodeQueryDialog : public CAknTextQueryDialog
+	{
+	public://construction and destruction
+		/**
+        * C++ Constructor.
+        * @param aDataText TDes& (code which is entered in query)
+		* @param aMinLength TInt (code min length)
+		* @param aMaxLength TInt (code max length)
+		* @param aMode TInt (mode ESecUiCodeEtelReqest\ESecUiNone)
+		*/
+		IMPORT_C CCodeQueryDialog(TDes& aDataText, TInt aMinLength,TInt aMaxLength,TInt aMode, TBool aIsRemotelockQuery = EFalse);
+		/**
+        * Destructor.
+        */
+		~CCodeQueryDialog();
+	public:
+		/**
+		* Allows dismissing of code queries. Only mandatory requirement is that PIN
+		* queries are dismissed by the # 
+		*
+		* @param aKeyEvent TKeyEvent&
+		* @return ETrue query is dismissed
+		*		  EFalse not dismissed
+		*/
+		TBool NeedToDismissQueryL(const TKeyEvent& aKeyEvent);
+		/**
+		* Calls the dialog's TryExitL and passes the reason given as a parameter.
+		*
+		* @param TInt aReason (The reason for the cancel request)
+		*/
+		void TryCancelQueryL(TInt aReason);
+
+	protected://from CAknTextQueryDialog
+		/**
+		* From CAknTextQueryDialog This function is called by the UIKON dialog framework 
+		* just before the dialog is activated, after it has called
+		* PreLayoutDynInitL() and the dialog has been sized.
+		*/
+		void PreLayoutDynInitL();
+		/**
+		* From CAknTextQueryDialog This function is called by the UIKON framework 
+		* if the user activates a button in the button panel. 
+		* It is not called if the Cancel button is activated, 
+		* unless the EEikDialogFlagNotifyEsc flag is set.
+		* @param aButtonId  The ID of the button that was activated
+		* @return           Should return ETrue if the dialog should exit, and EFalse if it should not.
+		*/
+		TBool OkToExitL(TInt aButtonId);
+		/**
+		* From CAknTextQueryDialog This function is called by the UIKON dialog framework 
+        * just after a key is pressed
+		* @param aKeyEvent TKeyEvent& 
+		* @param aType TEventCode 
+        */
+		TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType);
+			/**
+   		* From MAknQueryControlObeserver; overrides the default implementation in CAknQueryDialog. 
+   		* Gets called by framework when editor sends state event
+    	*/	
+		TBool HandleQueryEditorStateEventL(CAknQueryControl* aQueryControl, TQueryControlEvent aEventType, TQueryValidationStatus aStatus);
+		
+		TBool CheckIfEntryTextOk() const;
+		
+		void UpdateLeftSoftKeyL();
+	private:	
+		void ShowWarningNoteL();
+		
+	    /*
+	    * SetIncallBubbleAllowedInUsualL
+	    */
+	    void SetIncallBubbleAllowedInUsualL(TBool aAllowed);
+
+	private: // DATA	
+		TInt	iMinLength;
+		TInt	iMaxLength;
+		TInt	iMode;
+		TBool	iFront;
+		TInt	iAppKey;
+		TInt	iVoiceKey1;
+		TInt	iVoiceKey2;
+		TInt	iEndKey;
+		TBool   iIsRemoteLockQuery;
+	};
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/security_code_ui_api/inc/SecUiManualSecuritySettings.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,171 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*    Provides api for changing security settings via PhoneApp
+*
+*
+*/
+
+
+#ifndef     __SECUIMANUALSECURITYSETTINGS_H
+#define     __SECUIMANUALSECURITYSETTINGS_H
+
+//  INCLUDES
+// #include <etelagsm.h>
+#include <etelmm.h>
+#include <aknnotedialog.h>
+#include <rmmcustomapi.h>
+
+class CWait;
+
+class CManualSecuritySettings : public CBase
+	{
+    public:
+		/**
+        * Creates instance of the CManualSecuritySettings class.
+        *
+		* @return Returns the instance just created.
+        */
+		IMPORT_C static CManualSecuritySettings* NewL();
+		/**
+        * Destructor.
+        */
+		IMPORT_C ~CManualSecuritySettings();		
+	public:
+		/**
+		* Enumerates pins.
+		*/
+		enum TPin
+			{
+			EPin1,
+			EPin2
+			};
+		
+		/**
+		* Changes pin.
+		*
+		* Note that contents of aOld, aNew & aVerifyNew haven't been checked. If they could not been parsed,
+		* they are empty strings (KNullDesC).
+		*
+		* @param aPin pin in question.
+		* @param aOld old pin.
+		* @param aNew new pin.
+		* @param aVerifyNew new pin, verification.
+		* @return ETrue iff pin was changed successfully.
+		*/
+		IMPORT_C TBool ChangePinL(TPin aPin,const TDesC& aOld,const TDesC& aNew,const TDesC& aVerifyNew );	
+
+		/**
+		* Cancels change pin operation.
+		*
+		* If there is no ongoing change pin operation, then
+		* this method does nothing.
+		*/
+		IMPORT_C void CancelChangePin();
+
+		/**
+		* Unblocks pin.
+		*
+		* Note that contents of aPuk, aNew & aVerifyNew haven't been checked. If they could not been parsed,
+		* they are empty strings (KNullDesC).
+		*
+		* @param aPin pin in question.
+		* @param aPuk puk code for the pin.
+		* @param aNew new pin.
+		* @param aVerifyNew new pin, verificatio.
+		* @return ETrue iff pin was unblocked successfully.
+		*/
+		IMPORT_C TBool UnblockPinL(TPin aPin,const TDesC& aPuk,const TDesC& aNew,const TDesC& aVerifyNew );
+
+		/**
+		* Cancels unblock pin operation.
+		*
+		* If there is no ongoing unblock pin operation, then
+		* this method does nothing.
+		*/
+		IMPORT_C void CancelUnblockPin();
+			
+		/**
+		* Locks sim.
+		*
+		* Note that contents of aLockCode & aType haven't been checked. If they could not been parsed, 
+		* they are empty strings (KNullDesC).
+		*
+		* @param aLockCode lock closing password.
+		* @param aType type of lock.
+		* @return ETrue iff SIM was locked successfully.
+		*/
+		IMPORT_C TBool LockSimL(const TDesC& aLockCode,const TDesC& aType );
+
+		/**
+		* Cancels lock sim operation.
+		*
+		* If there is no ongoing lock sim operation, then
+		* this method does nothing.
+		*/
+		IMPORT_C void CancelLockSim();
+
+		/**
+		* Unlocks sim.
+		*
+		* Note that contents of aUnlockCode & aType haven't been checked. If they could not been parsed, 
+		* they are empty strings (KNullDesC).
+		*
+		* @param aUnlockCode lock opening password.
+		* @param aType type of lock.
+		* @return ETrue if SIM was unlocked successfully.
+		*/
+		IMPORT_C TBool UnlockSimL(const TDesC& aUnlockCode,const TDesC& aType );
+
+		/**
+		* Cancels unlock sim operation.
+		*
+		* If there is no ongoing unlock sim operation, then
+		* this method does nothing.
+		*/
+		IMPORT_C void CancelUnlockSim();
+	public:
+		/**
+		* Shows operation results in note
+		*
+		* @param aTone CAknNoteDialog::TTone (tone which is played)
+		* @param aResourceID TInt (notes resource id)
+		*/
+		void ShowResultNoteL(CAknNoteDialog::TTone aTone, TInt aResourceID);
+	private: // constructors
+		/**
+        * C++ default constructor.
+        */
+        CManualSecuritySettings();
+		 /**
+		* Symbian OS constructor.
+        */
+        void ConstructL();	
+	private:  // data
+		/*****************************************************
+		*	Series 60 Customer / ETel
+		*	Series 60  ETel API
+		*****************************************************/
+		RMmCustomAPI	iCustomPhone;
+		RTelServer      iServer;
+		// RAdvGsmPhone    iPhone;
+		RMobilePhone	iPhone;
+		CAknNoteDialog* iNote;
+		TRequestStatus	iDummyStatus;
+		CWait*			iWait;
+
+	};
+#endif      
+            
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/security_code_ui_api/inc/SecUiSecurityHandler.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*		Provides api for handling security events.
+*
+*
+*/
+
+
+#ifndef     __CSECURIHANDLER_H__
+#define     __CSECURIHANDLER_H__
+
+//  INCLUDES
+
+#include <etelmm.h>
+#include <rmmcustomapi.h>
+#include <aknquerydialog.h>
+#include <aknnotedialog.h>
+
+
+// FORWARD DECLARATIONS
+class RTASecuritySession;
+class CCodeQueryDialog;
+
+//  CLASS DEFINITIONS 
+class CSecurityHandler : public CBase
+	{
+    public:  
+		/**
+        * C++ default constructor.
+        */
+		IMPORT_C CSecurityHandler(RMobilePhone& aPhone);	
+		/**
+        * Destructor.
+        */
+		IMPORT_C ~CSecurityHandler();
+	public:
+		/**
+		* Handles different security events. Called from security notifier
+		*
+		* @param aEvent MAdvGsmPhoneSecurity::TSecurityEvent
+		*/	
+		IMPORT_C void HandleEventL(RMobilePhone::TMobilePhoneSecurityEvent aEvent);
+        IMPORT_C void HandleEventL( RMobilePhone::TMobilePhoneSecurityEvent aEvent, TInt& aResult );
+        IMPORT_C void HandleEventL( RMobilePhone::TMobilePhoneSecurityEvent aEvent, TBool aStartup, TInt& aResult );
+		/**
+		* Asks and verifies the security code.
+        *
+		* @return ETrue: code was accepted
+        *         EFalse: user canceled the code query		  
+		*/			
+		IMPORT_C TBool AskSecCodeL();			
+		/**
+        * Clears activated security query. Called from security notifier when
+		* there is incoming call
+     	*/	
+		IMPORT_C void CancelSecCodeQuery();	
+		/**
+		* Asks and verifies the security code when device is locked.
+        * Unlocks the device if code was accepted
+		*
+		* @return ETrue: code was accepted and device is unlocked
+        *         EFalse: user canceled the code query		  
+		*/			
+		IMPORT_C TBool AskSecCodeInAutoLockL(); 		
+	private:    
+		/**
+        * Handles EPin1Required security event
+     	*/	
+        TInt Pin1RequiredL();
+		/**
+        * Handles EPuk1Required security event
+     	*/	
+        TInt Puk1RequiredL();
+		/**
+        * Handles EPin2Required security event
+     	*/	
+		void Pin2RequiredL();
+		/**
+        * Handles EPuk2Required security event
+     	*/	
+		void Puk2RequiredL();
+        /**
+        * Handles EUniversalPinRequired security event
+     	*/	
+        TInt UPinRequiredL();
+        /**
+        * Handles EUniversalPukRequired security event
+     	*/	
+        TInt UPukRequiredL();
+		/**
+        * Handles EPassPhraseRequired security event
+     	*/	
+        TInt PassPhraseRequiredL();
+		/**
+        * Handles sim lock pending event
+     	*/	
+		void SimLockEventL();
+        /**
+        *  Removes the splashscreen
+        */
+        void RemoveSplashScreenL() const;
+        
+        void ShowGenericErrorNoteL(TInt aStatus);
+	private: // DATA
+		/*****************************************************
+		*	Series 60 Customer / ETel
+		*	Series 60  ETel API
+		*****************************************************/
+		RMobilePhone& iPhone;
+		TBool iQueryCanceled;
+		CCodeQueryDialog* iSecurityDlg;
+		CAknNoteDialog* iNoteDlg;
+		TBool* iDestroyedPtr;
+        RMmCustomAPI iCustomPhone;
+        RTASecuritySession* iSecuritySession;
+        TBool iStartup; // System state: true means we are in the middle of a boot.
+	};
+#endif                  
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/security_code_ui_api/inc/SecUiSecuritySettings.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,200 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*		Provides api for changing security settings.  
+*
+*
+*/
+
+
+#ifndef     __CSECUISECURITYSETTINGS_H
+#define     __CSECUISECURITYSETTINGS_H
+
+//  INCLUDES
+#include <etelmm.h>
+#include <rmmcustomapi.h>
+#include <aknnotedialog.h>
+
+
+class CWait;
+class CSecurityHandler;
+
+//  CLASS DEFINITIONS 
+class CSecuritySettings : public CBase
+	{
+    public: 
+		/**
+        * Creates instance of the CSecuritySettings class.
+        *
+		* @return Returns the instance just created.
+        */
+		IMPORT_C static CSecuritySettings* NewL();
+		/**
+        * Destructor.
+        */
+		IMPORT_C ~CSecuritySettings();
+		/**
+        * C++ default constructor.
+        */
+		IMPORT_C CSecuritySettings();
+		/**
+		* Symbian OS constructor.
+        */
+		IMPORT_C void ConstructL();
+	public:
+		/**
+        * Launches dialogs for changing pin code 
+        */
+		IMPORT_C void  ChangePinL();
+        /**
+        * Launches dialogs for changing upin code
+        */
+		IMPORT_C void  ChangeUPinL();
+		/**
+        * Launches dialogs for changing pin2 code
+        */
+		IMPORT_C void  ChangePin2L();
+		/**
+        * Launches dialogs for changing security code
+        */
+		IMPORT_C void  ChangeSecCodeL();
+		/**
+        * Launches dialogs for changing autolock period
+        *
+		* @param aPeriod TInt (old autolock value)
+		* @return TInt (new autolock value) 
+		*/
+		IMPORT_C TInt  ChangeAutoLockPeriodL(TInt aPeriod);	
+		/**
+        * Launches dialogs for changing sim change security setting
+        *
+		* @return ETrue: successful
+		*         EFalse: user cancelled 
+		*/
+		IMPORT_C TBool ChangeSimSecurityL();				
+		/**
+        * Launches dialogs for changing pin request setting
+        *
+		* @return ETrue: successful
+		*         EFalse: user cancelled
+		*/
+		IMPORT_C TBool ChangePinRequestL();
+        /**
+        * Launches dialogs for changing upin request setting
+        *
+		* @return ETrue: successful
+		*         EFalse: user cancelled
+		*/
+		IMPORT_C TBool ChangeUPinRequestL();
+        /**
+        * Launches dialogs for changing code in use setting
+        *
+		* @return ETrue: successful
+		*         EFalse: user cancelled
+		*/
+		IMPORT_C TBool SwitchPinCodesL();
+		/**
+        * Is aLockType lock on or off
+        *
+		* @param aLockType RAdvGsmPhone::TLockType
+		* @return ETrue: lock is on
+        *         EFalse: lock is off
+		*/
+		IMPORT_C TBool IsLockEnabledL(RMobilePhone::TMobilePhoneLock aLockType);
+		/**
+        * Launches dialogs for fixed dialing settings
+        */
+		IMPORT_C void SetFdnModeL();		
+		/**
+		* Gets current fixed dialing mode
+		*
+		* @param aFdnMode RMobilePhone::TMobilePhoneFdnStatus& (fixed dialing mode)
+		* @return TInt: KErrNone (succesful) 
+		*/
+		IMPORT_C TInt GetFdnMode(RMobilePhone::TMobilePhoneFdnStatus& aFdnMode);		
+		/**
+		* Asks and verifies the security code.
+        *
+		* @return ETrue: code was accepted
+        *         EFalse: user canceled the code query		  
+		*/			
+		IMPORT_C TBool AskSecCodeL();			
+		/**
+		* Asks and verifies the pin2 code.
+		*
+		* @return ETrue: code was accepted
+		*         EFalse: user canceled the code query
+		*/
+		IMPORT_C TBool AskPin2L();
+		/**
+		* Checks whether UPIN code is supported.
+		*
+		* @return ETrue: UPIN code is supported.
+		*         EFalse: UPIN code is not supported.
+		*/
+		IMPORT_C TBool IsUpinSupportedL();
+		/**
+		* Checks whether a code is blocked.
+		*
+		* @return ETrue:  code is blocked.
+		*         EFalse: code is not blocked.
+		*/
+		IMPORT_C TBool IsUpinBlocked();
+        /**
+		* Checks whether a code is blocked.
+		*
+		* @return ETrue:  Upin is active.
+		*         EFalse: Upin is not active.
+		*/
+		IMPORT_C TBool IsUpinActive();
+        /**
+        * Shows error note 
+        *
+		* @return Void
+		*/			
+		static void ShowErrorNoteL(TInt aError);
+		/**
+        * Shows error note 
+        *
+		* @return Void
+		*/			
+		static void ShowResultNoteL(TInt aResourceID, CAknNoteDialog::TTone aTone);
+
+        IMPORT_C TInt ChangeRemoteLockStatusL( TBool& aRemoteLockStatus, TDes& aRemoteLockCode, TInt aAutoLockPeriod );
+        
+        TInt RemoteLockCodeQueryL( TDes& aRemoteLockCode );
+        
+    private:
+    
+        TInt RemoteLockSetLockSettingL( TBool aLockSetting );    
+        
+	private: // DATA	
+		TBool iPuk1;
+		TBool iPuk2;
+
+		/*****************************************************
+		*	Series 60 Customer / ETel
+		*	Series 60  ETel API
+		*****************************************************/
+		RTelServer      iServer;
+		RMobilePhone    iPhone;
+		RMmCustomAPI	iCustomPhone;
+		CWait*			iWait;
+        CSecurityHandler* iSecurityHandler;
+	};
+
+
+#endif      
+            
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/security_code_ui_api/security_code_ui_api.metaxml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,18 @@
+<?xml version="1.0" ?>
+<api id="bf95bd58a1d8a46647f0d609534b0c35" dataversion="1.0">
+  <name>Security Code UI API</name>
+  <description>Implements dialogs for quering PIN and Security Code, and an interface for locking the device</description>
+  <type>c++</type>
+  <subsystem>securityuis</subsystem>
+  <libs>
+    <lib name="secui.lib" />
+  </libs>
+  <release category="domain"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>yes</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/wim_cert_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+*               WIM Cert API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/WimCert.h     MW_LAYER_PLATFORM_EXPORT_PATH(WimCert.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/wim_cert_api/inc/WimCert.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,326 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Reads certificates bypassing crypto token framework
+*
+*/
+
+
+#ifndef WIMCERT_H
+#define WIMCERT_H
+
+
+//INCLUDES
+#include <e32base.h>
+#include <e32std.h>
+#include <ct.h>
+
+//TYPE DEFINITIONS
+typedef HBufC8* PHBufC8;
+typedef TPtr8* PTPtr8;
+
+enum TCertLocation
+    {
+    EUnknown_CDF,
+    ECertificates_CDF,
+    ETrustedCerts_CDF,
+    EUsefulCerts_CDF
+    };
+
+//FORWARD DECLARATIONS
+class RWimCertMgmt;
+class RWimMgmt;
+
+
+
+//CLASS DECLARATION
+/**
+*  Reads certificate extra information from Smart Card
+*
+*  @lib WimClient
+*  @since Series60 2.1
+*/
+class CWimCert : public CActive
+    {
+    public: // Member functions
+
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CWimCert* NewL();
+
+        /**
+        * Destructor
+        */
+        IMPORT_C virtual ~CWimCert();
+        
+        /**
+        * Initializes the WIM server cache and restores certificates to 
+        * WimClient memory area. This is the most time consuming call. 
+        * @param  aStatus  Indicates the result of this call. Values:
+        *         KErrNotFound, no certificates was found
+        *         KErrNone, call was successull and at least one certificate 
+        *         found.
+        *         KErrGeneral, any other error
+        *         KErrNoMemory, no memory
+        * @return void
+        */
+        IMPORT_C void Initialize( TRequestStatus& aStatus );
+
+        /** 
+        * Cancels outgoing Initialize operation.
+        * After necessary cleanup, caller (given aStatus) is signalled with 
+        * KErrCancel 
+        * @return void
+        */
+        IMPORT_C void CancelInitialize();
+
+        /**
+        * Fetches trusted usages and location information for Key ID.
+        * @param  aKeyId (IN) Key identifier (hash), which points to a 
+        *         certificate.
+        * @param  aTrustedUsages (OUT) An array of OID strings indicating 
+        *         trusted usage. The notation is dot delimited 
+        *         (for example 1.23.456.7), the length of OÌD can vary. 
+        *         (OID=Object IDentifier). Caller is responsible of
+        *         destroying array.
+        * @param  aLocation (OUT) Indicates certificate directory location 
+        *         in Smart Card.
+        * @param  aStatus  Indicates the result of this call. Values:
+        *         KErrNotFound, given certificate KeyId was not found from card
+        *         KErrNone, no errors, given certificate was found and trusted 
+        *                   usage was present and location were known
+        *         KErrPathNotFound, trusted usage was not found or location 
+        *                           was not known
+        *         KErrGeneral, any other error
+        *         KErrNoMemory, No memory
+        * @return void
+        */
+        IMPORT_C void GetExtras( const TDesC8& aKeyId, 
+                                 RCPointerArray<HBufC>& aTrustedUsages,
+                                 TCertLocation& aLocation,
+                                 TRequestStatus& aStatus );
+
+        /** 
+        * Cancels outgoing GetExtras operation.
+        * After necessary cleanup, caller is signalled with KErrCancel 
+        * @return void
+        */
+        IMPORT_C void CancelGetExtras();
+
+    private:
+
+        /**
+        * Symbian constructor
+        */
+        void ConstructL();
+
+        /**
+        * C++ default constructor.
+        */
+        CWimCert();
+
+    private: //from CActive
+        
+        /**
+        * Different phases are handled here.
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * Cancellation function
+        * Deallocates member variables and completes client status with
+        * KErrCancel error code.
+        * @return void
+        */
+        void DoCancel();
+
+        /**
+        * The active scheduler calls this function if this active 
+        * object's RunL() function leaves. 
+        * Handles necessary cleanup and completes request with
+        * received error code.
+        * @param aError -Error code which launched this event.
+        * @return TInt  Error code to active scheduler, is always KErrNone.
+        */ 
+        TInt RunError( TInt aError );
+        
+    private: // functions
+        
+        /**
+        * Tries to locate certificate by using retrieved KeyId.
+        * @return boolean -If certificate is found and it has extra data, 
+        * @return ETrue. Else return EFalse.
+        */
+        TBool CertificateLocated();
+
+        /**
+        * Fills caller's data area with requested extra data
+        * @return void
+        */
+        void ExtraDataFoundL();
+
+        /** 
+        * Handles cleanup for an object which is not derived from CBase
+        * @param aObject -object to be cleaned up
+        * @return void
+        */
+        static void Cleanup( TAny* aObject );
+
+        /** 
+        * Handles cleanup for an object which is not derived from CBase
+        * @param aObject -object to be cleaned up
+        * @return void
+        */
+        static void CleanupRefLst( TAny* aObject );
+        
+        /**
+        * Deallocates memory from the array.
+        * @return void
+        */
+        void DeallocWimCertInfo();   
+        
+        /**
+        * Sets own iStatus to KRequestPending, and signals it 
+        * with User::RequestComplete() request. This gives chance 
+        * to active scheduler to run other active objects. After a quick
+        * visit in actives cheduler, signal returns to RunL() and starts next
+        * phase of operation. 
+        * @return void
+        */
+        void SignalOwnStatusAndComplete();
+        
+        /** 
+        * Allocates variables when retrieving extra certificate data 
+        * from WimServer.
+        * @return void
+        */
+        void AllocMemoryForExtraDataRetrieveL();
+
+        /* 
+        * DeAllocates variables after extra data retrieving operation.
+        * @return void
+        */
+        void DeAllocMemoryForExtraDataRetrieve();
+
+        /* 
+        * DeAllocates member variable RArrays.
+        * @return void
+        */
+        void DeallocRArrays();
+
+    private: // data
+
+        /**
+        * Different states of this state machine
+        */
+        enum TPhase
+            {
+            EConnectClientSession,
+            ECreateNewSession,
+            EInitializeWim,
+            EListCertsFromWim,
+            EGetCertClientSession,
+            ELocateCertificate,
+            EGiveExtraData
+            };
+
+        //Client status is stored here while operation
+        //on the server side is done.
+        TRequestStatus*                 iClientStatus;
+                
+        //Handle to connection with server. Owned.
+        RWimCertMgmt*                   iConnectionHandle;
+
+        // Pointer to Client Session. Owned. 
+        // Valid as long as CWimSecModuleMgr is valid.
+        RWimMgmt*                       iClientSession;
+        
+        //Used to handle different phases.
+        TPhase                          iPhase;
+                        
+        //The count of certificates
+        TUint8                          iCertCount;
+        
+        //Buffer, which is used when fetching trustedusage from Server. Owned
+        HBufC*                          iCertHBufTrustedUsageFromServer;
+    
+        //Pointer, which used to point iCertHBufTrustedUsageFromServer. Owned
+        TPtr*                           iCertHBufTrustedUsageFromServerPtr;
+
+         //Array which is filled with trusted usage strings. Not owned.
+        RCPointerArray<HBufC>*          iTrustedUsages;
+
+        // Informs the certificate location to caller.
+        // Used when user has called GetExtras
+        TCertLocation*                  iLocation;
+
+        //The KeyId, which is received from caller. Used when user has called
+        //GetExtras
+        HBufC8*                         iKeyIdToBeMatched;
+        
+        //This tells the index of the certificate, from which we want
+        //the trusted usages taken out.
+        TUint8                          iCertIndex;
+
+        //Flag to indicate errors during WIM -initialization.
+        TInt                            iWimStartErr;
+
+        //Array for certificate type. 
+        RArray<TUint>                   iCertTypes;
+
+        //Array for trusted usage lengths
+        RArray<TUint>                   iTrustedUsageLengths;
+
+        //Arrray for usages
+        RArray<TUint>                   iUsages;
+
+        //Array for KeyIds.Owned
+        RArray<HBufC8*>                 iKeyIds;
+
+        //Used to point right keyId when retrieving extra data
+        TPtr8*                          iKeyIdPointer;
+
+        //Pointer to HBufC8*. This is used as an array when listing every
+        //certificate from WIM to an array during startup. Owned.
+        PHBufC8*                        iLabel;
+
+        //Pointer to HBufC8*. This is used as an array when listing every 
+        //certificate from WIM to an array during startup. Owned.
+        PHBufC8*                        iKeyId;
+
+        //Pointer to HBufC8*. This is used as an array when listing every 
+        //certificate from WIM to an array during startup. Owned.
+        PHBufC8*                        iCAId;
+
+        //Pointer to HBufC8*. This is used as an array when listing every 
+        //certificate from WIM to an array during startup. Owned.
+        PHBufC8*                        iIssuerHash;
+
+        //Pointer to iLabel. Also used as an array. Owned.        
+        PTPtr8*                         iLabelPtr;
+
+        //Pointer to iKeyId. Also used as an array. Owned.        
+        PTPtr8*                         iKeyIdPtr;
+
+        //Pointer to iCAId. Also used as an array. Owned.        
+        PTPtr8*                         iCAIdPtr;
+
+        //Pointer to iIssuerHash. Also used as an array. Owned.
+        PTPtr8*                         iIssuerHashPtr;
+    };
+
+#endif  // WIMCERT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/wim_cert_api/wim_cert_api.metaxml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,18 @@
+<?xml version="1.0" ?>
+<api id="a2b08c0a87307800a720ace91ca47895" dataversion="1.0">
+  <name>WIM Cert API</name>
+  <description>Provides additional MIDP 2.0 security information for certificates</description>
+  <type>c++</type>
+  <subsystem>WIM</subsystem>
+  <libs>
+    <lib name="WimClient.lib" />
+  </libs>
+  <release category="domain"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>yes</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/x509certnameparser_api/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  File that exports the files belonging to 
+*               X509CertNameParser API
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+../inc/x509CertNameParser.h     MW_LAYER_PLATFORM_EXPORT_PATH(X509CertNameParser.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/x509certnameparser_api/inc/x509CertNameParser.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,293 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Extracts relevant certificate information to be shown to user.
+*
+*/
+
+																				
+
+#ifndef X509CERTNAMEPARSER_H
+#define X509CERTNAMEPARSER_H
+
+//  INCLUDES
+#include <e32std.h> 
+#include <x509gn.h> // TGNType
+//------------------------------------------------------------------------------
+// CONSTANTS
+_LIT(KX509CNPComma,", ");
+
+// FORWARD DECLARATIONS
+class CX509Certificate;  
+class CX500DistinguishedName;
+class CX509CertExtension;
+class CX509AltNameExt;
+
+
+//------------------------------------------------------------------------------
+//
+// CLASS DECLARATION
+
+/**
+*  Static class CX509CertNameParser provides functions that extract relevant
+*  information for user from x.509 certificate. CX509CertNameParser 
+*  extracts the most important name info and tries to guarantee  uniqueness 
+*  in a list of certificates. 
+*  @lib X509CertNameParser.dll
+*  @since Series60_2.0
+*/
+class X509CertNameParser  
+	{
+    public: // Constructors and destructor
+        
+
+    public: // New functions
+																				        
+	    /**
+        * PrimaryAndSecondaryNameL_description. PrimaryAndSecondaryNameL 
+        * member function is used to collect Primary and Secondsry Name data of 
+        * certificate information. The first found non-empty naming element and 
+        * not equal with label  is Primary Name.
+        * The second available information element not equal with label is 
+        * Secondary Name.
+        * @since Series60_2.0
+        * @param aCertificate Certificate where the information is extracted.
+		* @param aPrimaryName IN null pointer, OUT first found name element 
+        * according to name element order or KNulDesC if Primary Name isn't 
+        * found.
+        * @param aSecondaryName IN null pointer, OUT second found name element 
+        * according to name element order or KNullDesC if Secondary Name isn't found.
+        * @param aLabel Label of the certificate. Found elements are compared to
+        * label to make sure that aPrimaryName and aSecondaryName differ from 
+        * label. If label doesn't exist, this can be left away.
+		* @return status, at the moment always KErrNone
+        */                                                                              
+        IMPORT_C static TInt PrimaryAndSecondaryNameL( 
+                                const CX509Certificate& aCertificate, 
+                                HBufC*& aPrimaryName, 
+                                HBufC*& aSecondaryName,
+                                const TDesC& aLabel =KNullDesC );
+		
+		/**
+        * SubjectFullNameL_description. SubjectFullNameL member function is 
+        * used to collect all relevant subject information from the subject 
+        * and from the subject alternative name extension of the certificate.
+        * @since Series60_2.0
+        * @param aCertificate Certificate where the information is extracted.
+        * @param aSubjectName IN null pointer, OUT Full subject name of the 
+        * certificate or KNullDesC if nothing is found.
+		* @param aLabel Label of the certificate. Found elements are compared to
+        * label to make sure that aPrimaryName and aSecondaryName differ from 
+        * label. If label doesn't exist, this can be left away.
+		* @return status, at the moment always KErrNone
+        */
+        IMPORT_C static TInt SubjectFullNameL( 
+                                const CX509Certificate& aCertificate,
+                                HBufC*& aSubjectName,
+			                    const TDesC& aLabel = KNullDesC );
+
+		/**
+        * IssuerFullNameL_description. IssuerFullNameL member function is 
+        * used to collect all the relevant Issuer information from the Issuer 
+        * and from the Issuer alternative name extension of the certificate.
+        * @since Series60_2.0
+        * @param aCertificate Certificate where the information is extracted.
+        * @param aIssuerName IN null pointer, OUT Full issuer name of the 
+        * certificate or KNullDesC if nothing is found..
+		* @return status, at the moment always KErrNone
+        */
+		IMPORT_C static TInt IssuerFullNameL( 
+                                const CX509Certificate& aCertificate,
+                                HBufC*& aIssuerName );
+	
+    public: // Functions from base classes
+       
+    protected:  // New functions
+        
+    protected:  // Functions from base classes
+
+    private: //Private data types
+
+	/**
+    * enum TX509CNPNameType declaration.
+	*
+    */
+    enum TX509CNPNameType
+		{	
+        EX509CNPPrimAndSecond,
+        EX509CNPFullName
+		};
+
+    /**
+    * enum TX509CNPNameElement declaration.
+	* This enum defines the naming element order that can be changed by 
+    * chancing the order of enum's members.
+    */
+    enum TX509CNPNameElement
+        {                           // DN = Distinguish name, Alt = Alternative name 
+        EDNCommonName = 1,          // common name of the subject 
+        ECritAltRFC822Name,         // rfc822Name of the critical subject alternative name
+        EDNOrganizationName,        // OrganizationName of the subject
+        EDNOrganizationalUnitName,  // OrganizationalUnitName of the subject
+        ECritAltDNSName,            // dNSName of the critical subject alternative name
+        ECritAltURI,                // URI of the critical subject alternative name
+        ECritAltDirectoryName,      // directoryName of the critical subject alternative name
+        ECritAltIPAddress,          // iPAddress of the critical subject alternative name                       
+        EAltRFC822Name,             // rfc822Name of the subject alternative name
+        EAltDNSName,                // dNSName of the subject alternative name
+        EAltURI,                    // URI of the subject alternative name
+        EDNCountryName,             // countryName of the subject
+        EDNStateOrProvinceName,     // stateOrProvinceName of the subject
+        EDNLocalityName,            // localityName of the subject
+        EAltDirectoryName,          // directoryName of the subject alternative name
+        EAltIPAddress               // iPAddress of the subject alternative name                       
+        };  
+       
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        X509CertNameParser();
+
+	
+    private: //New functions
+        
+        /**
+        * GetFullNameL_description.
+		* Common function for FullName functions.
+        * @since Series60_2.0
+        * @param aDN Distinguished name
+        * @param aExtension Pointer to Extension
+        * @param aSubjectName IN null pointer, OUT Full subject name of the 
+        * certificate or KNullDesC if nothing is found.
+        * @return TInt type value.
+        */
+        static TInt GetFullNameL( 
+                        const CX500DistinguishedName& aDN, 
+                        const CX509CertExtension* aExtension,
+                        HBufC*& aName,
+                        const TDesC& aLabel = KNullDesC );
+
+
+        /**
+        * GetNamePartsL_description.
+		* Collects all the name parts of the certificate to array. One name element
+        * is placed to one element of array.
+        * @since Series60_2.0
+        * @param aDN Distinguished name
+        * @param aExtension Pointer to Extension
+        * @param aNameArray Found name elements are appended to this array.
+        * @param aNameType EX509CNPPrimAndSecond or EX509CNPFullName
+        * @return TInt type value.
+        */
+        static TInt GetNamePartsL( 
+                        const CX500DistinguishedName& aDN, 
+                        const CX509CertExtension* aExtension, 
+                        CDesCArray& aNameArray, 
+                        TX509CNPNameType aNameType );
+                                                                                                                                           
+        /**
+        * GetDNPartL_description.
+		* Gets one name element of the DN identified by OID.
+        * @since Series60_2.0
+        * @param aDN Distinguished name
+        * @param aSubPartOID OID of the distinguished name subpart 
+        * @param aNameArray Found name element is appended to this array.
+        * @return void
+        */
+        static void GetDNPartL( 
+                        const CX500DistinguishedName& aDN, 
+                        const TDesC& aSubPartOID, 
+                        CDesCArray& aNameArray );
+
+        /**
+        * GetDNPartAllL_description.
+		* Gets all name elements of the DN identified by one OID.
+        * @since Series60_2.0
+        * @param aDN Distinguished name
+        * @param aSubPartOID OID of the distinguished name subpart 
+        * @param aNameArray Found name elements are appended to this array.
+        * @return void
+        */
+        static void GetDNPartAllL( 
+                        const CX500DistinguishedName& aDN, 
+                        const TDesC& aSubPartOID, 
+                        CDesCArray& aNameArray );
+
+        /**
+        * GetAltNamePartL_description.
+		* Gets all elements of alternative name identified by one OID.
+        * @since Series60_2.0
+        * @param aAltName Alternative name extension
+        * @param aSubPartType Type of the alternative name subpart
+        * @param aNameArray Found name elements are appended to this array.
+        * @return void
+        */
+        static void GetAltNamePartL( 
+                        const CX509AltNameExt& aAltName, 
+                        const TGNType& aSubPartType, 
+                        CDesCArray& aNameArray );
+
+        /**
+        * HandleAltNameL_description.
+        * Handles error. If error is KErrNone, KErrArgument or KErrNotSupported, it just
+        * returns aError, otherwise it leaves with aError.
+        * @since Series60_2.0
+        * @param aError Error
+        * @return TInt aError
+        */    
+        static TInt AddAltNameToArrayL( 
+                        TInt aError, 
+                        CX509DomainName* aDomainName,
+                        CDesCArray& aNameArray );
+
+        /**
+        * CompareAndAddNameL_description.
+		* Adds proposal to array if none of the elements of array isn't equal 
+        * with proposal.
+        * @since Series60_2.0
+        * @param aProposal 
+        * @param aNameArray 
+        * @return void.
+        */
+        static void CompareAndAddNameL( 
+                        const TDesC& aProposal, 
+                        CDesCArray& aNameArray );
+
+        /**
+        * AddToBufLC_description.
+		* Appends aName to aBuf. If aBuf isn't NULL, first aBuf is deleted and
+        * memory is allocated for existing data and for aName.
+        * @since Series60_2.0
+        * @param aName Desciptor that is appended to aBuf
+        * @param aBuf  IN Null pointer or buffer
+        * @return void.
+        */
+        static void AddToBufLD( const TDesC& aName, HBufC*& aBuf );
+
+        /**
+        * HandleErrorL_description.
+        * Handles error. If error is KErrNone, KErrArgument or KErrNotSupported, it just
+        * returns aError, otherwise it leaves with aError.
+        * @since Series60_2.0
+        * @param aError Error
+        * @return TInt aError
+        */    
+        static TInt HandleErrorL( TInt aError );
+
+    };
+
+#endif      // X509CERTNAMEPARSER_H
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/secsrv_plat/x509certnameparser_api/x509certnameparser_api.metaxml	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,18 @@
+<?xml version="1.0" ?>
+<api id="7598cbaa02c1dd1539c39e3477dfc6de" dataversion="1.0">
+  <name>X509CertNameParser API</name>
+  <description>Extracts relevant information for user from x.509 certificate</description>
+  <type>c++</type>
+  <subsystem>pkiutilities</subsystem>
+  <libs>
+    <lib name="x509certnameparser.lib" />
+  </libs>
+  <release category="domain"/>
+  <attributes>
+     <!-- This indicates wether the api provedes separate html documentation -->
+     <!-- or is the additional documentation generated from headers. -->
+     <!-- If you are unsuere then the value is "no" -->
+     <htmldocprovided>yes</htmldocprovided>
+     <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/CenRep/AutolockPrivateCRKeys.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Autolock local variation Central Repository keys.
+*
+*/
+
+
+#ifndef AUTOLOCKPRIVATECRKEYS_H
+#define AUTOLOCKPRIVATECRKEYS_H
+
+// =============================================================================
+// Autolock Configuration API
+// =============================================================================
+const TUid KCRUidAutolockConf = { 0x102824AE };
+
+/**
+* Bitmask used in configuring automatic keylock.
+*/
+const TUint32 KAutoKeyLockConf = 0x00000001;
+
+// =============================================================================
+// Automatic Keylock Local Variation constants (KAutoKeyLockConf)
+// =============================================================================
+
+/** 
+* KAutolockFeatureIdFlipOpenDisabled is an on/off setting for 
+* disabling automatic keyguard locking when flip is open. By default off.
+* Possible values: 0 (locking enabled), 1 (locking diabled) <-- 
+*/
+const TInt KAutoKeylockFeatureIdFlipOpenDisabled= 0x01;  // 2^0
+
+#endif
Binary file securitydialogs/Autolock/CenRep/keys_autolock.xls has changed
Binary file securitydialogs/Autolock/CenRep/keys_lock.xls has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/PubSub/SecurityUIsPrivatePSKeys.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,64 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Private Publish&Subscribe definitions of the
+*               Security UIs subsystem
+*
+*/
+
+
+#ifndef SECURITYUISPRIVATEPSKEYS_H
+#define SECURITYUISPRIVATEPSKEYS_H
+
+// INCLUDES
+
+//CONSTANTS
+
+const TUid KPSUidSecurityUIs = { 0x100059b5 };
+// =============================================================================
+// Security Code UI Originator API
+// =============================================================================
+
+// Use TUid KPSUidSecurityUIs = { 0x100059b5 } 
+
+/**
+* Used by SecUI to differentiate between ETel API originated and SecUI originated
+* security queries.
+* Old Shared Data constant name: KSecUIOriginatedQuery
+*/
+const TUint32 KSecurityUIsSecUIOriginatedQuery = 0x00000301;
+enum TSecurityUIsSecUIOriginatedQuery
+    {
+    ESecurityUIsSecUIOriginatedUninitialized = 0,
+    ESecurityUIsETelAPIOriginated,
+    ESecurityUIsSecUIOriginated,
+    ESecurityUIsSystemLockOriginated
+    };
+
+/**
+* Used by SecUI to tell if a query request set by some ETELMM API lock setting function (i.e. SetXXXXSetting)
+* has been canceled sinnce canceling the setting request does not prompt a query cancel event from ETEL.
+* Old Shared Data constant name: KSecUIOriginatedQuery
+*/    
+const TUint32 KSecurityUIsQueryRequestCancel = 0x00000302;
+enum TSecurityUIsQueryRequestCancel
+    {
+    ESecurityUIsQueryRequestUninitialized = 0,
+    ESecurityUIsQueryRequestOk,
+    ESecurityUIsQueryRequestCanceled
+    };
+
+#endif      // SECURITYUISPRIVATEPSKEYS_H
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/aif/Autolockaif.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     RSS for creating the aif file for Autolock.
+*     
+*
+*/
+
+
+#include <aiftool.rh>
+
+RESOURCE AIF_DATA
+{
+    app_uid=0x100059B5;
+    hidden = KAppIsHidden;
+    num_icons = 0;
+    embeddability = KAppNotEmbeddable;
+    newfile = KAppDoesNotSupportNewFile;
+}
+
+// End of File
Binary file securitydialogs/Autolock/conf/autolock.confml has changed
Binary file securitydialogs/Autolock/conf/autolock_102824AE.crml has changed
Binary file securitydialogs/Autolock/conf/lock.confml has changed
Binary file securitydialogs/Autolock/conf/lock_10283322.crml has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/data/Autolock.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,106 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     This file contains all the resources for the Autolock.
+*     
+*
+*/
+
+
+//  RESOURCE IDENTIFIER
+NAME    ALCK // 4 letter ID
+
+//  INCLUDES
+
+#include <eikon.rh>
+#include "autolock.hrh"
+#include <autolock.loc>
+#include "eikon.rsg"
+#include <avkon.rsg>
+#include <avkon.rh>
+#include <avkon.loc>
+#include <avkon.mbg>
+#include <autolock.mbg>
+
+
+//  RESOURCE DEFINITIONS 
+
+RESOURCE RSS_SIGNATURE { }
+
+RESOURCE TBUF { buf=""; }
+
+RESOURCE EIK_APP_INFO
+	{
+	status_pane = r_autolock_status_pane;
+	}
+
+RESOURCE STATUS_PANE_APP_MODEL r_autolock_status_pane
+    {
+    layout = R_AVKON_STATUS_PANE_LAYOUT_IDLE;
+    panes =
+        {
+        SPANE_PANE
+            {
+            id = EEikStatusPaneUidTitle;
+            type = EAknCtTitlePane;
+            resource = r_title_pane_locked;
+            }
+        };
+    }
+
+
+RESOURCE AVKON_VIEW r_locked_view
+	{
+	}
+
+
+
+RESOURCE CBA r_autolock_softkeys_unlock_empty
+    {
+    buttons = 
+        {
+        CBA_BUTTON{id=ESecUiCmdUnlock; txt= qtn_set_sec_unlock_system; },
+        CBA_BUTTON{id=EAknSoftkeyEmpty; txt=text_softkey_empty; },
+        CBA_BUTTON{id=EAknSoftkeyEmpty; txt=text_softkey_empty; }
+        };    
+    }
+
+
+RESOURCE TITLE_PANE r_title_pane_locked
+	{
+	txt = qtn_set_sec_title_locked;
+	}
+
+
+
+RESOURCE DIALOG r_emergency
+	{
+	flags = EEikDialogFlagNoDrag | EEikDialogFlagNoTitleBar |
+            EEikDialogFlagCbaButtons;
+	buttons=R_AVKON_SOFTKEYS_CANCEL;
+    items=
+		{
+		DLG_LINE
+			{
+	    	type=EAknCtNote;
+			id=EGeneralNote;
+			control= AVKON_NOTE 
+				{ 
+	                layout = EGeneralLayout;
+				};
+			}
+		};
+	}
+
+// end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/data/Autolock_reg.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,31 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  RSS for creating the registration file for Autolock.
+*
+*/
+
+
+#include <appinfo.rh>
+#include <Autolock.rsg>
+
+
+UID2 KUidAppRegistrationResourceFile
+UID3 0x100059B5 // application UID
+RESOURCE APP_REGISTRATION_INFO
+	{
+	app_file="Autolock"; // filename of application binary (minus extension)
+    hidden = KAppIsHidden;
+	embeddability = KAppNotEmbeddable;
+	newfile = KAppDoesNotSupportNewFile;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/group/Autolock.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,95 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Makefile
+*     
+*
+*/
+
+#include <platform_paths.hrh>
+
+#include <data_caging_paths.hrh>
+
+TARGET      autolock.exe
+TARGETTYPE  exe
+epocstacksize 0x5000
+
+UID  0x100039CE 0x100059B5
+
+VENDORID        VID_DEFAULT
+CAPABILITY      CAP_APPLICATION NetworkControl
+
+MACRO __NO_DOS__
+
+SOURCEPATH ../src
+SOURCE  AutolockApp.cpp 
+SOURCE  AutolockAppUi.cpp
+SOURCE  AutolockDocument.cpp
+SOURCE	AutolockContainer.cpp
+SOURCE  AutoLockModel.cpp
+SOURCE  AutoLockCenRepI.cpp
+SOURCE	AutoLockLockObserver.cpp
+SOURCE	AutoLockValueObserver.cpp
+SOURCE	AutoLockView.cpp
+SOURCE	AutolockWait.cpp
+SOURCE	AutoKeyGuardCenRepI.cpp
+SOURCE	AutoKeyguardObserver.cpp
+SOURCE  AutolockGripStatusObserver.cpp
+SOURCE  AutolockFpsStatusObserver.cpp
+
+
+START RESOURCE ../data/Autolock.rss
+HEADER
+
+TARGETPATH APP_RESOURCE_DIR
+
+LANGUAGE_IDS
+END //RESOURCE
+
+
+//s60 Integration
+START RESOURCE ../data/Autolock_reg.rss
+DEPENDS autolock.rsg
+TARGETPATH /private/10003a3f/apps
+END
+
+//S60 Integration
+
+USERINCLUDE . ../inc ../CenRep
+
+APP_LAYER_SYSTEMINCLUDE
+SYSTEMINCLUDE ../../../inc
+
+LIBRARY euser.lib apparc.lib cone.lib eikcore.lib 
+LIBRARY eikcoctl.lib avkon.lib
+LIBRARY	activitymanager.lib
+LIBRARY	apgrfx.lib
+LIBRARY ws32.lib secui.lib commonengine.lib
+LIBRARY etel.lib etelmm.lib eikdlg.lib 
+LIBRARY	sysutil.lib
+LIBRARY aknlayout.lib
+LIBRARY aknskins.lib
+LIBRARY centralrepository.lib
+LIBRARY cenrepnotifhandler.lib
+LIBRARY aknlayout2scalable.lib
+LIBRARY aknlayout2.lib 
+LIBRARY featmgr.lib
+LIBRARY aknicon.lib
+LIBRARY fbscli.lib
+LIBRARY scpclient.lib
+LIBRARY gdi.lib
+LIBRARY aknnotify.lib
+LIBRARY     customapi.lib
+
+
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/group/Autolock_Icons_dc.mk	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,72 @@
+#
+# Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description: 
+#
+
+ifeq (WINS,$(findstring WINS, $(PLATFORM)))
+ZDIR=\epoc32\release\$(PLATFORM)\$(CFG)\Z
+else
+ZDIR=\epoc32\data\z
+endif
+
+# ----------------------------------------------------------------------------
+# TARGET FILES: Configure these
+# ----------------------------------------------------------------------------
+
+TARGETDIR=$(ZDIR)\resource\apps
+ICONTARGETFILENAME=$(TARGETDIR)\autolock.mif
+
+HEADERDIR=\epoc32\include
+HEADERFILENAME=$(HEADERDIR)\autolock.mbg
+
+do_nothing :
+	@rem do_nothing
+
+MAKMAKE : do_nothing
+
+BLD : do_nothing
+
+CLEAN : do_nothing
+
+LIB : do_nothing
+
+CLEANLIB : do_nothing
+
+# ----------------------------------------------------------------------------
+# RESOURCE COMMAND: Configure these.
+#
+# NOTE 1: DO NOT DEFINE MASK FILE NAMES! They are included automatically by
+# MifConv if the mask detph is defined.
+#
+# NOTE 2: Usually, source paths should not be included in the bitmap
+# definitions. MifConv searches for the icons in all icon directories in a
+# predefined order, which is currently \s60\icons, \s60\bitmaps2, \s60\bitmaps.
+# The directory \s60\icons is included in the search only if the feature flag
+# __SCALABLE_ICONS is defined.
+# ----------------------------------------------------------------------------
+
+RESOURCE :
+	mifconv $(ICONTARGETFILENAME) /h$(HEADERFILENAME) \
+		/c8,8 qgn_graf_phone_locked /c8,8 qgn_indi_button_end_call \
+		
+
+FREEZE : do_nothing
+
+SAVESPACE : do_nothing
+
+RELEASABLES :
+	@echo $(HEADERFILENAME)&& \
+	@echo $(ICONTARGETFILENAME)
+
+FINAL : do_nothing
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,47 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This file provides the information required for building
+*               the whole autolock.
+*
+*/
+
+
+#include <platform_paths.hrh>
+PRJ_PLATFORMS
+
+DEFAULT
+
+PRJ_EXPORTS
+//Configuration tool migration
+../conf/autolock.confml          MW_LAYER_CONFML(autolock.confml)
+../conf/autolock_102824AE.crml 	 MW_LAYER_CRML(autolock_102824ae.crml)
+../conf/lock.confml              MW_LAYER_CONFML(lock.confml)
+../conf/lock_10283322.crml 	     MW_LAYER_CRML(lock_10283322.crml)
+
+../rom/Autolock.iby CORE_MW_LAYER_IBY_EXPORT_PATH(autolock.iby)
+../rom/AutolockResources.iby LANGUAGE_MW_LAYER_IBY_EXPORT_PATH(autolockresources.iby)
+../loc/autolock.loc MW_LAYER_LOC_EXPORT_PATH(autolock.loc)
+// taken from lockapp
+// ../PubSub/SecurityUIsPrivatePSKeys.h |../../../inc/SecurityUIsPrivatePSKeys.h
+
+PRJ_MMPFILES
+../group/Autolock.mmp
+
+PRJ_EXTENSIONS
+START EXTENSION s60/mifconv
+OPTION TARGETFILE autolock.mif
+OPTION HEADERFILE autolock.mbg
+OPTION SOURCES -c8,8 qgn_graf_phone_locked -c8,8 qgn_indi_button_end_call
+END
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/AutoKeyguardCenRepI.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,92 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef _AUTOKEYGUARDCENREPI_H__
+#define _AUTOKEYGUARDCENREPI_H__
+
+#include <e32std.h>
+#include <cenrepnotifyhandler.h> // link against CenRepNotifHandler.lib
+
+class CAutoKeyguardObserver;
+
+class CAutoKeyguardCenRepI : public CBase, public MCenRepNotifyHandlerCallback
+	{
+	public:
+		/**
+        * Creates instance of the CAutoKeyguardCenRepI class.
+        *
+		* @param aObserver (pointer to keyguard timeout observer)
+		* @return Returns the instance just created.
+        */
+		static CAutoKeyguardCenRepI* NewLC(CAutoKeyguardObserver* aObserver);
+		/**
+        * Creates instance of the CAutoKeyguardCenRepI class.
+        *
+		* @param aObserver (pointer to keyguard timeout observer)
+		* @return Returns the instance just created.
+        */
+		static CAutoKeyguardCenRepI* NewL(CAutoKeyguardObserver* aObserver);
+		/**
+        * Destructor.
+        */      
+		~CAutoKeyguardCenRepI();
+	public:
+		/**
+        * Current autokeyguard period
+        *
+		* @return TInt (curenst autokeyguard period in minutes) 
+		*/      
+		TInt Timeout();	
+        /**
+        * From MCenRepNotifyHandlerCallback. Handles period changed event. Called by CenRep.
+		*
+		* @param aId (The id of the changed setting)
+        * @param aNewValue (The new value of the changed setting)
+        * @return KErNone
+		*/
+        void HandleNotifyInt(TUint32 aId, TInt aNewValue);
+
+        void HandleNotifyError(TUint32 aId, TInt error, CCenRepNotifyHandler* aHandler);
+
+        void HandleNotifyGeneric(TUint32 aId);
+
+	private:
+		/**
+        * C++ default constructor.
+		*
+		* @param aObserver (pointer to keyguard timeout observer)
+        */
+		CAutoKeyguardCenRepI(CAutoKeyguardObserver* aObserver);
+		/**
+        * Symbian OS constructor.
+        */
+		void ConstructL();
+	private:
+		/**
+        * Tells observer that keyguard period has been changed
+		*/
+		void ResetInactivityTimeout();	
+	private: // data
+		CAutoKeyguardObserver* iObserver; //not owned!
+        CCenRepNotifyHandler* iNotifyHandler;
+        CRepository* iSession;
+
+	};
+
+#endif
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/AutoKeyguardObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,102 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef _AUTOKEYGUARDOBSERVER_H__
+#define _AUTOKEYGUARDOBSERVER_H__
+
+#include <e32base.h>
+#include <aknappui.h>
+#include <e32property.h>
+
+class CUserActivityManager;
+class CAutoKeyguardCenRepI;
+
+class CAutoKeyguardObserver : public CBase
+	{
+	public:
+		/**
+        * Creates instance of the CAutoKeyguardObserver class.
+        *
+		* @return Returns the instance just created.
+        */
+		static CAutoKeyguardObserver* NewL();
+		/**
+        * Symbian OS constructor.
+        */
+		void ConstructL( CAutoKeyguardObserver* aObserver );
+		/**
+        * Destructor.
+        */
+		~CAutoKeyguardObserver();
+	public:
+		/**
+        * Gets new autokeyguard period and starts monitoring user activity 
+        */
+		void ResetInactivityTimeout();
+		/**
+        * Activates keyguard 
+		*/
+		void LockKeysL();
+	private:
+		/**
+        * C++ default constructor.
+        */
+		CAutoKeyguardObserver(); 
+	private:
+		/**
+        * Return current autokeyguard period
+		*
+		* @return TInt (autokeyguard period in minutes)
+        */	
+		TInt AutoKeyguardTimeout();
+		/**
+        * Handles Active event. Called by ActivityManager
+		*
+		* @param aPtr 
+        * @return KErNone
+		*/
+		static TInt HandleActiveEventL(TAny* aPtr);
+		/**
+        * Handles Inactive event. Called by ActivityManager
+		*
+		* @param aPtr (pointer to CAutoKeyguardObserver)
+        * @return KErNone
+		*/
+		static TInt HandleInactiveEventL(TAny* aPtr);
+		/**
+        * Starts monitoring user activity
+        */		
+		void StartActivityMonitoringL();
+		/**
+        * Stop monitoring user activity.
+        */
+		void StopActivityMonitoring();
+		/**
+        * Initializes activymanager 
+        */
+		void SetActivityManagerL();
+		/**
+        * UnInitializes activymanager 
+        */
+		void CancelActivityManager();
+	private: //data
+		CUserActivityManager*    iActivityManager;
+        CAutoKeyguardCenRepI*    iCenRepI;
+	};
+#endif
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/AutoLockCenRepI.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,105 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef _AUTOLOCKCENREPI_H__
+#define _AUTOLOCKCENREPI_H__
+
+#include <e32std.h>
+#include <cenrepnotifyhandler.h> // link against CenRepNotifHandler.lib
+#include "AutolockAppUiPS.h"
+
+
+class CAutolockCenRepI : public CBase, public MCenRepNotifyHandlerCallback
+	{
+	public:
+		/**
+        * Creates instance of the CAutolockShareDataI class.
+        *
+		* @param aAppUi (pointer to autolock appui)
+		* @return Returns the instance just created.
+        */
+		static CAutolockCenRepI* NewLC(CAutolockAppUi* aAppUi);
+		/**
+        * Creates instance of the CAutolockShareDataI class.
+        *
+		* @param aAppUi (pointer to autolock appui)
+		* @return Returns the instance just created.
+        */
+		static CAutolockCenRepI* NewL(CAutolockAppUi* aAppUi);
+		/**
+        * Destructor.
+        */      
+		~CAutolockCenRepI();
+	public:
+		/**
+        * Currenst autolock period
+        *
+		* @return TInt (curenst autolock period in minutes) 
+		*/      
+		TInt Timeout();	
+		/**
+        * Sets device lock value in SharedData
+        *
+		* @param: aLocked (decice lock on/off) 
+		*/
+		void SetLockedL(TBool aLockValue);
+        /**
+        * From MCenRepNotifyHandlerCallback. Handles period changed event. Called by CenRep.
+		*
+		* @param aId (The id of the changed setting)
+        * @param aNewValue (The new value of the changed setting)
+        * @return KErNone
+		*/
+        void HandleNotifyInt(TUint32 aId, TInt aNewValue);
+
+        void HandleNotifyError(TUint32 aId, TInt error, CCenRepNotifyHandler* aHandler);
+
+        void HandleNotifyGeneric(TUint32 aId);
+
+	private:
+		/**
+        * C++ default constructor.
+		*
+		* @param aAppUi (pointer to autolock appui)
+        */
+		CAutolockCenRepI(CAutolockAppUi* aAppUi);
+		/**
+        * Symbian OS constructor.
+        */
+		void ConstructL();
+	private:
+		/**
+        * Handles period changed event. Called by CSharedDataInteger
+		*
+		* @param aPtr (pointer to CAutolockShareDataI)
+        * @return KErNone
+		*/
+		TInt HandleTimeoutChangedL();
+		/**
+        * Tells model that autolock period has been changed
+		*/
+		void ResetInactivityTimeout();	
+	private: // data
+		CAutolockAppUi*          iAppUi; //not owned!
+        CCenRepNotifyHandler* iNotifyHandler;
+        CRepository* iSession;
+
+	};
+
+#endif
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/AutoLockLockObserverPS.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,74 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*		Obsererver for Set System Locked event  
+*
+*
+*/
+
+
+#ifndef     __AUTOLOCKLOCKOBSERVERPS_H
+#define     __AUTOLOCKLOCKOBSERVERPS_H
+
+#include <e32svr.h>
+#include <e32property.h>
+#include "AutolockAppUiPS.h"
+
+class   CLockObserver: public CActive
+    {
+    public:
+		/**
+        * Creates instance of the CLockObserver class.
+        *
+		* @param aAppUi (pointer to autolock appui)
+		* @return Returns the instance just created.
+        */
+        static CLockObserver* NewL(CAutolockAppUi* aAppUi);
+		/**
+        * Destructor.
+        */
+		~CLockObserver();    
+	private:
+        /**
+        * Starts asynchronic listening KUidAutolockStatus event
+        *
+		* @return KErrNone: if no errors
+        * @return KErrInUse: if already listening
+		*/
+		TInt Start();            
+    private: // constructors
+		/**
+        * C++ default constructor.
+		*
+		* @param aAppUi (pointer to autolock appui)
+        */
+        CLockObserver(CAutolockAppUi* aAppUi);
+		 /**
+        * Symbian OS constructor.
+        */
+        void ConstructL();
+    private: // from CActive
+         /** @see CActive::RunL() */
+		void RunL();
+		/** @see CActive::DoCancel() */
+        void DoCancel();
+    private: // data
+    	CAutolockAppUi*      iAppUi; //not owned!
+        RProperty            iProperty;
+        RTelServer      iServer; // EMKK-7N3G7R
+        CWait*			 		wait;	// EMKK-7N3G7R
+    };
+
+#endif 
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/AutoLockModelPS.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,117 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef _AUTOLOCKMODELPS_H__
+#define _AUTOLOCKMODELPS_H__
+
+#include <e32base.h>
+#include <aknappui.h>
+#include <e32property.h>
+
+class CUserActivityManager;
+class CAutolockCenRepI;
+class CAutolockAppUi;
+class CLockObserver;
+
+class CAutoLockModel : public CBase
+	{
+	public:
+		/**
+        * Creates instance of the CAutoLockModel class.
+        *
+		* @param aAppUi (pointer to autolock appui)
+		* @return Returns the instance just created.
+        */
+		static CAutoLockModel* NewL(CAutolockAppUi* aAppUi, TBool aLocked );
+		/**
+        * Symbian OS constructor.
+        */
+		void ConstructL( TBool aLocked );
+		/**
+        * Destructor.
+        */
+		~CAutoLockModel();
+	public:
+		/**
+        * Gets new autolock period and starts monitoring user activity 
+        */
+		void ResetInactivityTimeout();
+		/**
+        * Brings autolock app to foreground and locks the system 
+		*/
+		void LockSystemL(TInt aAutolockState = 0);
+		/**
+        * Sets device lock value in SharedData and in SystemAgent 
+        *
+		* @param: aLocked (decice lock on/off) 
+		*/
+		void SetLockedL(TInt aAutolockState = 0);
+	private:
+		/**
+        * C++ default constructor.
+		*
+		* @param aAppUi (pointer to autolock appui)
+        */
+		CAutoLockModel(CAutolockAppUi*	aAppUi); 
+	private:
+		/**
+        * Return current autolock period
+		*
+		* @return TInt (autolock period in minutes)
+        */	
+		TInt AutoLockTimeout();
+		/**
+        * Handles Active event. Called by ActivityManager
+		*
+		* @param aPtr 
+        * @return KErNone
+		*/
+		static TInt HandleActiveEventL(TAny* aPtr);
+		/**
+        * Handles Inactive event. Called by ActivityManager
+		*
+		* @param aPtr (pointer to CAutoLockModel)
+        * @return KErNone
+		*/
+		static TInt HandleInactiveEventL(TAny* aPtr);
+		/**
+        * Starts monitoring user activity
+        */		
+		void StartActivityMonitoringL();
+		/**
+        * Stop monitoring user activity.
+        */
+		void StopActivityMonitoring();
+		/**
+        * Initializes activymanager 
+        */
+		void SetActivityManagerL();
+		/**
+        * UnInitializes activymanager 
+        */
+		void CancelActivityManager();
+	private: //data
+		CUserActivityManager*    iActivityManager;
+		CAutolockAppUi*			 iAppUi; //not owned!
+        CAutolockCenRepI*        iCenRepI;
+		CLockObserver*			 iLockObserver;
+		TBool					 iMonitoring;
+		RProperty                iProperty;
+	};
+#endif
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/AutoLockValueObserverPS.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,77 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*		Observer for phone events. Used to deactive/active the side-key
+*
+*
+*/
+
+
+#ifndef     __AUTOLOCKVALUEOBSERVERPS_H
+#define     __AUTOLOCKVALUEOBSERVERPS_H
+
+#include <e32svr.h>
+#include <e32property.h>
+
+class CAutolockAppUi;
+
+class   CValueObserver: public CActive
+    {
+    public:
+		/**
+        * Creates instance of the CValueObserver class.
+        *
+		* @param aAppUi (pointer to autolock appui)
+		* @return Returns the instance just created.
+        */
+        static CValueObserver* NewL(CAutolockAppUi* aAppUi);
+		/**
+        * Destructor.
+        */
+		~CValueObserver();    
+	public:
+		/**
+        * Starts asynchronic listening KUidCurrentCall event
+        *
+		* @return KErrNone: if no errors
+        * @return KErrInUse: if already listening
+		*/
+        TInt Start();
+		/**
+        * Stops asynchronic listening KUidAutolockStatus event
+    	*/
+		void Stop();
+    private: // constructors
+        /**
+        * C++ default constructor.
+		*
+		* @param aAppUi (pointer to autolock appui)
+        */
+		CValueObserver(CAutolockAppUi* aAppUi);
+        /**
+        * Symbian OS constructor.
+        */
+		void ConstructL();
+    private: // from CActive    
+		/** @see CActive::RunL() */
+		void RunL();
+		/** @see CActive::DoCancel() */
+        void DoCancel();
+    private: // data
+    	CAutolockAppUi*      iAppUi; //not owned!
+        RProperty            iProperty;
+    };
+
+#endif 
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/AutolockApp.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     Declares main application class.
+*
+*/
+
+
+#ifndef AUTOLOCKAPP_H
+#define AUTOLOCKAPP_H
+
+// INCLUDES
+#include <aknapp.h>
+
+// CONSTANTS
+// UID of the application
+const TUid KUidAutolock = { 0x100059B5 };
+
+// CLASS DECLARATION
+
+/**
+* CAutolockApp application class.
+* Provides factory to create concrete document object.
+* 
+*/
+class CAutolockApp : public CAknApplication
+    {
+    
+    private:
+
+        /**
+        * From CApaApplication, creates CAutolockDocument document object.
+        * @return A pointer to the created document object.
+        */
+        CApaDocument* CreateDocumentL();
+        
+        /**
+        * From CApaApplication, returns application's UID (KUidAutolock).
+        * @return The value of KUidAutolock.
+        */
+        TUid AppDllUid() const;
+    };
+
+#endif
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/AutolockAppUiPS.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,268 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     Declares UI class for application.
+*
+*/
+
+
+#ifndef AUTOLOCKAPPUIPS_H
+#define AUTOLOCKAPPUIPS_H
+
+// INCLUDES
+#include <e32std.h>
+#include <aknappui.h>
+#include <etelmm.h>
+#include <aknViewAppUi.h>
+#include <AknEcs.h>
+#include <aknnotedialog.h>
+#include <AknIncallBubbleNotify.h>
+#include <e32property.h>
+#include <rmmcustomapi.h>
+#include "AutolockWait.h"
+#include "AutoKeyguardObserver.h"
+
+#include "AutolockGripStatusObserver.h"
+#include "AutolockFpsStatusObserver.h"
+
+// FORWARD DECLARATIONS
+class CAutolockContainer;
+class CAutoLockModel;
+class CValueObserver;
+
+// CONSTANTS
+const TUid KAutoLockViewId = {101}; // CDMA StartUp needs this UID.
+
+// CLASS DECLARATIONS
+
+/**
+* part of emergency call handling when telephony+devicelock is active
+* this solution is meant only for 3.1 and 3.2
+*CEcsNote
+*It defines security note used in security view.
+*/
+class CEcsNote : public CAknNoteDialog
+    {
+    public: // Constructors and destructors
+        /**
+        * C++ constructor.
+        */
+        CEcsNote();
+    public: // new
+        /**
+        * Constructs sleeping note
+        */
+        void ConstructSleepingNoteL(TInt aResourceId);
+        /**
+        * Shows slpeeping note
+        */
+        TInt ShowNote();
+        /**
+        * Hides sleeping note
+        */
+        void SleepNote();
+
+        TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent,
+                                         TEventCode aType);
+                                         
+        /**
+        * API to set the emergency number to be displayed
+        *
+        * aMatchedNumber    text to display (e.g. "112" )
+        */
+        void SetEmergencyNumber( const TDesC& aMatchedNumber );
+                
+    public:
+        TBool iNoteOnScreen;        
+    };
+  
+
+/**
+* Application UI class.
+* Provides support for the following features:
+* - UIKON control architecture
+* 
+*/
+class CAutolockAppUi : public CAknViewAppUi, public MAknEcsObserver,
+                       public MAutolockGripStatusObserver,
+                       public MAutolockFpsStatusObserver
+    {
+    public: // // Constructors and destructor
+
+        /**
+        * Symbian OS default constructor.
+        */      
+        void ConstructL();
+
+        /**
+        * Destructor.
+        */      
+        ~CAutolockAppUi();
+        
+        /**
+         * From MAutolockGripStatusObserver
+         */
+        TBool DeviceLockQueryStatus();
+        
+        TBool DeviceLockStatus();
+
+        /**
+         * From MAutolockFpsStatusObserver
+         */
+        TBool DeviceFpsLock(TInt iStatus);
+
+   public: // New functions
+		/**
+        * Activates previous app
+        */     
+		void SwitchToPreviousAppL();
+		/**
+        * Activates device lock view
+        */     
+		void BringAppToForegroundL();
+		/**
+        * Pointer to model
+        *
+		* @return CAutoLockModel*
+		*/     
+		inline CAutoLockModel* Model() const;
+		/**
+        * Locks voice-key and app-key
+        */     
+		void LockKeysL();
+		/**
+        * UnLocks voice-key and app-key
+        */     
+		void UnLockKeys();
+		/**
+        * Locks voice-key
+        */     
+		void LockSideKeyL();
+		/**
+        * UnLocks voice-key
+        */     
+		void UnLockSideKey();
+        /**
+        * Returns ETrue if system is locked. 
+        */
+        inline TBool Locked() { return (iSideKey2 != 0); }
+        /**
+        * Checks whether PUK1 dialog is active. 
+        */
+		TBool IsPinBlocked();
+		/**
+        * Checks whether the phone has done hidden reset. 
+        */
+		TBool HiddenReset();
+		void EnableWGListChangeEventListening();
+		void DisableWGListChangeEventListening();
+
+    protected:    
+        /**
+        * From CEikAppUi, handles the TARM unlock message, other messages
+        * are propagated to the superclass handler.
+        * @param aClientHandleOfTargetWindowGroup The window group that the message was sent to.
+        * @param aMessageUid The message UID. 
+        * @param aMessageParameters The message parameters
+        * @return TMessageResponse EMessageHandled if the message was the TARM unlock message, 
+        * otherwise the return value from the superclass handler. 
+        */        
+        MCoeMessageObserver::TMessageResponse HandleMessageL(
+            TUint32 aClientHandleOfTargetWindowGroup,
+            TUid aMessageUid,
+            const TDesC8& aMessageParameters );
+            
+
+    private:
+        // From MEikMenuObserver
+        void DynInitMenuPaneL(TInt aResourceId,CEikMenuPane* aMenuPane);
+		
+		// from CCoeAppUi
+		void HandleForegroundEventL(TBool aForeground);
+        /**
+        * From CAknAppUi, called when screen layout changes 
+        */
+        void HandleScreenDeviceChangedL();
+    private:
+        /**
+        * From CEikAppUi, takes care of command handling.
+        * @param aCommand command to be handled
+        */
+        void HandleCommandL(TInt aCommand);
+
+        /**
+        * From CEikAppUi, handles key events.
+        * @param aKeyEvent Event to handled.
+        * @param aType Type of the key event. 
+        * @return Reponse code (EKeyWasConsumed, EKeyWasNotConsumed). 
+        */
+        virtual TKeyResponse HandleKeyEventL(
+            const TKeyEvent& aKeyEvent,TEventCode aType);
+    virtual void HandlePointerEventL(const TPointerEvent& aPointerEvent);
+     private:
+    	/**
+    	* From AknViewAppUi. Handles pointer-initiated view switch.
+    	* @param aEvent Window server event.
+    	* @param aDestination Pointer to the control which the event is targeted to.
+    	*/
+    	void HandleWsEventL( const TWsEvent& aEvent, CCoeControl* aDestination );
+
+        /**
+        * Used for communication with SysAp
+        * @param aMessage message enumeration defined in eikon.hrh
+        */        
+        void SendMessageToSysAp(TInt aMessage);
+    	
+    	/**
+        * From MAknEcsObserver
+        * part of emergency call handling when telephony+devicelock is active
+        * this solution is meant only for 3.1 and 3.2
+        * handles emergency call
+        */
+        virtual void HandleEcsEvent( CAknEcsDetector* aEcsDetector, CAknEcsDetector::TState aState );
+            
+        TBool TarmState();
+        void HandleWindowGroupListChange();
+    private: //Data
+   		CAutoLockModel*	 iModel;		 
+		RTelServer       iServer;
+	    RMobilePhone     iPhone;  
+	    TInt			 iAppKey;
+		TInt			 iSideKey1;
+		TInt			 iSideKey2;
+		CValueObserver*  iPhoneObserver;
+		TBool			 iLocked;
+		TBool            iDeviceLockQueryStatus;
+        // Idle Incall Bubbles.
+        CAknIncallBubble* iIncallBubble;
+        CAutoKeyguardObserver* iKeyguardObserver;
+        CAutolockGripStatusObserver* iGripStatusObserver;
+        CAutolockFpsStatusObserver* iFpsStatusObserver;
+        RMmCustomAPI	 iCustomPhone;
+        
+        // part of emergency call handling when t//iEmergencySupportReadyelephony+devicelock is active
+        // this solution is meant only for 3.1 and 3.2
+        CAknEcsDetector* iEcsDetector;
+        CEcsNote*		 iEcsNote;	
+        TBool            iEmergencySupportReady;
+        CWait*			 iWait;	
+		TRect aCallButtonRect;
+	};
+
+	inline CAutoLockModel* CAutolockAppUi::Model() const
+		{return iModel;}
+
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/AutolockContainer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,101 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     Declares container control for application.
+*
+*/
+
+
+#ifndef AUTOLOCKCONTAINER_H
+#define AUTOLOCKCONTAINER_H
+
+// INCLUDES
+#include <coecntrl.h>
+#include <eikimage.h>
+#include <eiklabel.h>
+#include <AknSkinnableClock.h>
+   
+// FORWARD DECLARATIONS
+
+class CAknsLayeredBackgroundControlContext;
+
+// CLASS DECLARATION
+
+/**
+*  CAutolockContainer  container control class.
+*  
+*/
+class CAutolockContainer : public CCoeControl, MCoeControlObserver
+    {
+    public: // Constructors and destructor
+        
+        /**
+        * Symbian OS default constructor.
+        * @param aRect Frame rectangle for container.
+        */
+        void ConstructL(const TRect& aRect);
+
+        /**
+        * Destructor.
+        */
+        ~CAutolockContainer();
+
+    public: // Functions from base classes
+        /**
+        * From CCoeControl, MopSupplyObject
+        */
+        TTypeUid::Ptr MopSupplyObject( TTypeUid aId );
+        void GiveCoords( TRect& aRect );
+
+    private: // Functions from base classes
+
+       /**
+        * From CoeControl,SizeChanged.
+        */
+        void SizeChanged();
+
+       /**
+        * From CoeControl,CountComponentControls.
+        */
+        TInt CountComponentControls() const;
+
+       /**
+        * From CCoeControl,ComponentControl.
+        */
+        CCoeControl* ComponentControl(TInt aIndex) const;
+
+       /**
+        * From CCoeControl,Draw.
+        */
+        void Draw(const TRect& aRect) const;
+
+        // event handling section
+        // e.g Listbox events
+        void HandleControlEventL(CCoeControl* aControl,TCoeEvent aEventType);
+        
+    private: //data
+        CEikImage* iEikBitmap;
+        CFbsBitmap* iBitmap;
+        CFbsBitmap* iMask;
+        CEikImage* iEikBitmapCall;
+        CFbsBitmap* iBitmapCall;
+        CFbsBitmap* iMaskCall;
+        // Owned background context.
+        CAknsLayeredBackgroundControlContext* iBgContext;
+        
+    };
+
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/AutolockDocument.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,75 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     Declares document for application.
+*
+*/
+
+
+#ifndef AUTOLOCKDOCUMENT_H
+#define AUTOLOCKDOCUMENT_H
+
+// INCLUDES
+#include <AknDoc.h>
+// CONSTANTS
+
+// FORWARD DECLARATIONS
+class  CEikAppUi;
+
+// CLASS DECLARATION
+
+/**
+*  CAutolockDocument application class.
+*/
+class CAutolockDocument : public CAknDocument 
+    {
+    public: // Constructors and destructor
+        /**
+        * Two-phased constructor.
+        */
+        static CAutolockDocument* NewL(CEikApplication& aApp);
+
+        /**
+        * Destructor.
+        */
+        virtual ~CAutolockDocument();
+
+    public: // From CEikDocument 
+		/**
+        * Updates task name --> Sets autolock hidden
+        *
+		* @param aWgName CApaWindowGroupName*
+		*/
+		void UpdateTaskNameL( CApaWindowGroupName* aWgName );
+
+    private:
+
+        /**
+        * Symbian OS default constructor.
+        */
+        CAutolockDocument(CEikApplication& aApp): CAknDocument(aApp) { }
+        void ConstructL();
+
+    private:
+
+        /**
+        * From CEikDocument, create CAutolockAppUi "App UI" object.
+        */
+        CEikAppUi* CreateAppUiL();
+    };
+
+#endif
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/AutolockFpsStatusObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     Declares UI class for application.
+*
+*/
+
+#ifndef AUTOLOCKFPSOBSERVER_H_
+#define AUTOLOCKFPSOBSERVER_H_
+
+#include <e32base.h>
+#include <e32property.h>
+#include <w32std.h>
+#include <hwrmdomainpskeys.h>
+
+
+class MAutolockFpsStatusObserver
+    {
+    public:
+        /**
+         * Implement this method to be notified when Fps status
+         * changes.
+         */
+        IMPORT_C virtual TInt DeviceFpsLock(TInt iStatus) = 0;
+        IMPORT_C virtual TInt DeviceLockStatus() = 0;
+    };
+
+class CAutolockFpsStatusObserver : public CActive
+    {
+    public:
+        IMPORT_C static CAutolockFpsStatusObserver* NewL( MAutolockFpsStatusObserver* aObserver, RWsSession& aSession );
+
+        void RunL();
+        void DoCancel();
+        ~CAutolockFpsStatusObserver();
+    
+    private:
+        void ConstructL( MAutolockFpsStatusObserver* aObserver );   
+        CAutolockFpsStatusObserver( RWsSession& aSession );
+        void FpsStatusChangedL( TInt aFpsStatus );
+
+    private:
+        MAutolockFpsStatusObserver* iObserver;
+        RProperty iFpsStatus;
+        RWsSession& iSession;
+    };
+
+
+#endif 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/AutolockGripStatusObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     Declares UI class for application.
+*
+*/
+
+#ifndef AUTOLOCKGRIPOBSERVER_H_
+#define AUTOLOCKGRIPOBSERVER_H_
+
+#include <e32base.h>
+#include <e32property.h>
+#include <w32std.h>
+#include <hwrmdomainpskeys.h>
+
+//CONSTANTS
+const TInt KCancelKeyCode( 165 );
+
+class MAutolockGripStatusObserver
+    {
+    public:
+        /**
+         * Implement this method to be notified when grip status
+         * changes.
+         */
+        IMPORT_C virtual TInt DeviceLockQueryStatus() = 0;
+        IMPORT_C virtual TInt DeviceLockStatus() = 0;
+    };
+
+class CAutolockGripStatusObserver : public CActive
+    {
+    public:
+        IMPORT_C static CAutolockGripStatusObserver* NewL( MAutolockGripStatusObserver* aObserver, RWsSession& aSession );
+
+        void RunL();
+        void DoCancel();
+        ~CAutolockGripStatusObserver();
+    
+    private:
+        void ConstructL( MAutolockGripStatusObserver* aObserver );   
+        CAutolockGripStatusObserver( RWsSession& aSession );
+        void GripStatusChangedL( TInt aGripStatus );
+
+    private:
+        MAutolockGripStatusObserver* iObserver;
+        RProperty iGripStatus;
+        RWsSession& iSession;
+    };
+
+
+#endif 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/AutolockView.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,75 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef __AUTOLOCKVIEW_H__
+#define __AUTOLOCKVIEW_H__
+
+#include <aknview.h>
+#include "AutolockContainer.h"
+
+class CAutolockView : public CAknView
+	{
+	public:
+		/**
+        * Symbian OS constructor.
+        */
+		void ConstructL();
+		/**
+        * Destructor.
+        */
+		~CAutolockView();
+	public: // from CAknView
+		/**
+        * Returns view id.
+        * @return An unsigned integer (view id).
+        */
+        TUid Id() const;
+		/**
+        * Handles commands.
+        * @param aCommand Command to be handled.
+        * @return void.
+        */
+		void HandleCommandL(TInt aCommand);
+		/**
+        * Handles statuspane changes
+        * @return void.
+        */
+		void HandleStatusPaneSizeChange();
+		/**
+        * Handles screen layout changes
+        */
+        void ScreenDeviceChanged();
+        void MakeVisible(TBool aVisibility);
+        void HandleCall(TInt aCommand, TRect &aRect );
+	private: // from CAknView
+		/**
+        * Activates the view.
+        * @param aPrevViewId ID of previous view
+        * @param aCustomMessageId customized message ID
+        * @param aCustomMessage sutomized message payload
+        */
+		void DoActivateL(const TVwsViewId& aPrevViewId,TUid aCustomMessageId,const TDesC8& aCustomMessage);
+		/**
+        * Deactivates view
+        */
+		void DoDeactivate();
+	private: // data
+		CAutolockContainer* iView;
+		};
+#endif 
+// end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/AutolockWait.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,97 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*	
+*
+*/
+
+
+#ifndef     __AUTOLOCKWAIT_H
+#define     __AUTOLOCKWAIT_H
+
+//  INCLUDES
+
+#include    <e32base.h>
+#include	<eikappui.h>
+#include    <coecntrl.h>
+
+//  CLASS DEFINITIONS 
+class  CWait : public CActive
+    {
+     public:
+       /**
+        * Creates instance of the CWait class.
+        *
+		* @return Returns the instance just created.
+        */
+		static CWait* NewL();
+		/**
+        * Destructor.
+        */
+        ~CWait();
+    public:
+        /**
+		* Starts waiting for aReqStatus. 
+		*/
+		TInt WaitForRequestL();
+    public:
+        /**
+        * Sets active request type. 
+        */
+        void SetRequestType(TInt aRequestType);
+        /**
+        * Gets active request type. 
+        */
+        TInt GetRequestType();
+	private:
+		/**
+		* C++ default constructor.
+		*/
+		CWait();
+		/**
+		* Symbian OS constructor.
+		*/
+		void ConstructL();
+	private: // from CActive
+        /** @see CActive::RunL() */
+		void RunL();
+		/** @see CActive::DoCancel() */
+        void DoCancel();
+		RTimer iTimer;
+		CActiveSchedulerWait iWait;
+		// Used if there is a need to cancel an active request;
+        // namely in situations where destructor is called when Wait
+        // is active.
+        TInt iRequestType;
+	};
+
+
+// CWaitAbsorbingControl, absorbs all the key presses.
+class CWaitAbsorbingControl : public CCoeControl
+    {
+    public:
+        static CWaitAbsorbingControl* NewLC();
+        virtual ~CWaitAbsorbingControl();
+    private:
+        virtual TKeyResponse OfferKeyEventL(const TKeyEvent& /*aKeyEvent*/,TEventCode /*aType*/);
+    private:
+        CWaitAbsorbingControl();
+        void ConstructL();
+    private: // Data
+         CEikAppUi*  iAppUi;
+    };
+
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/inc/autolock.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*     This file contains declarations for resources of Autolock.
+*     The file can be included in C++ or resource file.
+*
+*/
+
+#ifndef AUTOLOCK_HRH
+#define AUTOLOCK_HRH
+
+enum TAutoLockKeys
+	{
+	ESecUiCmdUnlock = 300
+	};
+#endif      //  AUTOLOCK
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/loc/autolock.loc	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is a localisation file for Autolock
+*
+*/
+
+
+
+// LOCALISATION STRINGS
+
+//d:Title pane text in System Lock View.(Phone is in locked mode)
+//l:title_pane_t2/opt9 
+//
+#define qtn_set_sec_title_locked "Locked"
+
+//d:Left Softkey text in System Lock View.
+//l:control_pane_t1/opt7
+//
+#define qtn_set_sec_unlock_system "Unlock"
+
+
+// End of File
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/rom/Autolock.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#ifndef __AUTOLOCK_IBY__
+#define __AUTOLOCK_IBY__
+
+S60_APP_EXE(Autolock)
+S60_APP_BITMAP(Autolock)
+S60_APP_AIF_RSC(Autolock)
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/rom/AutolockResources.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef __AUTOLOCK_RESOURCES_IBY__
+#define __AUTOLOCK_RESOURCES_IBY__
+
+//Resource file(s) for AUTOLOCK application
+
+S60_APP_RESOURCE(Autolock)
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/src/AutoKeyGuardCenRepI.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,154 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#include <centralrepository.h> 
+#include <settingsinternalcrkeys.h>
+#include "AutoKeyguardObserver.h"
+#include "AutoKeyguardCenRepI.h"
+ 
+
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CAutoKeyguardCenRepI::NewLC()
+// Two-phased constructor.
+// ----------------------------------------------------------
+//
+CAutoKeyguardCenRepI* CAutoKeyguardCenRepI::NewLC(CAutoKeyguardObserver* aObserver)
+	{
+	CAutoKeyguardCenRepI* self = new (ELeave) CAutoKeyguardCenRepI(aObserver);
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoKeyguardCenRepI::NewL()
+// Two-phased constructor.
+// ----------------------------------------------------------
+//
+CAutoKeyguardCenRepI* CAutoKeyguardCenRepI::NewL(CAutoKeyguardObserver* aObserver)
+	{
+	CAutoKeyguardCenRepI* self = NewLC(aObserver);
+	CleanupStack::Pop(); //self
+	return self;
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoKeyguardCenRepI::~CAutoKeyguardCenRepI()
+// Destructor
+// ----------------------------------------------------------
+//
+CAutoKeyguardCenRepI::~CAutoKeyguardCenRepI()
+	{
+	if(iNotifyHandler)
+	{
+		iNotifyHandler->StopListening();
+		delete iNotifyHandler;	
+	}
+    if(iSession)
+		delete iSession;
+	}
+//
+// ----------------------------------------------------------
+// CAutoKeyguardCenRepI::CAutoKeyguardCenRepI()
+// C++ default constructor
+// ----------------------------------------------------------
+//	
+CAutoKeyguardCenRepI::CAutoKeyguardCenRepI(CAutoKeyguardObserver* aObserver):iObserver(aObserver)
+	{
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoKeyguardCenRepI::ConstructL()
+// Symbian OS default constructor
+// ----------------------------------------------------------
+//	
+void CAutoKeyguardCenRepI::ConstructL()
+	{
+	// init cenrep connection	
+	iSession = CRepository::NewL(KCRUidSecuritySettings);
+
+    iNotifyHandler = CCenRepNotifyHandler::NewL(*this, *iSession, CCenRepNotifyHandler::EIntKey, KSettingsAutomaticKeyguardTime);
+    iNotifyHandler->StartListeningL();
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoKeyguardCenRepI::HandleNotifyInt()
+// Handles autoKeyguard period changes. Called by CenRep.
+// ----------------------------------------------------------
+//	
+void CAutoKeyguardCenRepI::HandleNotifyInt(TUint32 aId, TInt /*aNewValue*/)
+	{
+    if(aId == KSettingsAutomaticKeyguardTime)
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardCenRepI::HandleNotifyInt() Reset timeout"));
+    #endif
+	    ResetInactivityTimeout();
+    }
+	return;
+	}
+
+void CAutoKeyguardCenRepI::HandleNotifyError(TUint32 /*aId*/, TInt /*error*/, CCenRepNotifyHandler* /*aHandler*/)
+    {
+    return;
+    }
+
+void CAutoKeyguardCenRepI::HandleNotifyGeneric(TUint32 aId)
+    {
+        if ( aId == NCentralRepositoryConstants::KInvalidNotificationId )
+        {//Repository wide reset caused generic notification
+        #if defined(_DEBUG)
+    	RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardCenRepI::HandleNotifyGeneric() Reset timeout"));
+    	#endif
+            ResetInactivityTimeout();
+        }
+    return;
+    }
+
+//
+// ----------------------------------------------------------
+// CAutoKeyguardCenRepI::ResetInactivityTimeoutL()
+// Resets autoKeyguard timer
+// ----------------------------------------------------------
+//	
+void CAutoKeyguardCenRepI::ResetInactivityTimeout()
+	{
+	iObserver->ResetInactivityTimeout();
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoKeyguardCenRepI::Timeout()
+// Returns currents autoKeyguard period (in seconds)
+// ----------------------------------------------------------
+//	
+TInt CAutoKeyguardCenRepI::Timeout()
+	{
+    TInt period = 0;
+    iSession->Get(KSettingsAutomaticKeyguardTime, period);
+	return period;
+	}
+
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/src/AutoKeyguardObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,435 @@
+/*
+* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#include <aknappui.h>
+#include <aknkeylock.h>
+#include <AknUtils.h>
+#include <activitymanager.h>
+#include <AknNotifierController.h>
+#include <centralrepository.h> 
+#include <avkondomainpskeys.h>
+#include <e32property.h>
+#include <PSVariables.h>
+#include <startupdomainpskeys.h>
+#include <ctsydomainpskeys.h>
+#include <activeidle2domainpskeys.h>
+#include <coreapplicationuisdomainpskeys.h>
+#include <ScreensaverInternalPSKeys.h>
+#include <hwrmdomainpskeys.h>
+#include "AutoKeyguardCenRepI.h"
+#include "AutoKeyguardObserver.h"
+#include "AutolockPrivateCRKeys.h"
+
+const TInt AutoKeyguardOff(60000);
+// Screensaver "On" status value
+const TInt KSsOn = 1;
+// Screensaver started fron idle status value
+const TInt KSsStartedFromIdle = 1;
+//Flip open
+const TInt KFlipOpen = 1;
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CAutoKeyguardObserver::NewL()
+// ----------------------------------------------------------
+//
+
+CAutoKeyguardObserver* CAutoKeyguardObserver::NewL()
+	{
+	#ifdef RD_AUTO_KEYGUARD
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::NewL() BEGIN"));
+    #endif
+	CAutoKeyguardObserver* self = new (ELeave) CAutoKeyguardObserver();
+	CleanupStack::PushL(self);
+	self->ConstructL(self);
+	CleanupStack::Pop(); //self
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::NewL() END"));
+    #endif
+	return self;
+	#else
+	return NULL;
+	#endif //RD_AUTO_KEYGUARD
+	}
+//
+// ----------------------------------------------------------
+// CAutoKeyguardObserver::CAutoKeyguardObserver()
+// C++ default constructor
+// ----------------------------------------------------------
+// 
+CAutoKeyguardObserver::CAutoKeyguardObserver()	
+	{
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoKeyguardObserver::ConstructL()
+// Symbian OS default constructor
+// ----------------------------------------------------------
+//
+void CAutoKeyguardObserver::ConstructL(CAutoKeyguardObserver* aObserver)
+	{
+	#ifdef RD_AUTO_KEYGUARD
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::ConstructL() BEGIN"));
+    #endif	
+	//Central Repository handler
+    iCenRepI = CAutoKeyguardCenRepI::NewL(aObserver);
+	// Activitymanager
+	iActivityManager = CUserActivityManager::NewL(CActive::EPriorityStandard);
+	StartActivityMonitoringL();
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::ConstructL() END"));
+    #endif
+    #else // !RD_AUTO_KEYGUARD
+    iCenRepI = NULL;
+	iActivityManager = NULL;
+    #endif //RD_AUTO_KEYGUARD
+	}
+//
+// ----------------------------------------------------------
+// CAutoKeyguardObserver::StartActivityMonitoringL()
+// Start monitoring user activity
+// ----------------------------------------------------------
+//
+void CAutoKeyguardObserver::StartActivityMonitoringL()
+	{
+	#ifdef RD_AUTO_KEYGUARD	
+	SetActivityManagerL();
+	#endif //RD_AUTO_KEYGUARD
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoKeyguardObserver::StopActivityMonitoring()
+// Stop monitoring user activity
+// ----------------------------------------------------------
+//
+void CAutoKeyguardObserver::StopActivityMonitoring()
+	{
+	#ifdef RD_AUTO_KEYGUARD
+	CancelActivityManager();
+	#endif // RD_AUTO_KEYGUARD
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoKeyguardObserver::SetActivityManagerL()
+// Initializes activymanager   
+// ----------------------------------------------------------
+//
+void CAutoKeyguardObserver::SetActivityManagerL()
+	{
+	#ifdef RD_AUTO_KEYGUARD
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::SetActivityManagerL() BEGIN"));
+    #endif
+	if (AutoKeyguardTimeout() )
+		{
+		#if defined(_DEBUG)
+    	RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::SetActivityManagerL() ON: Start manager"));
+    	#endif
+		iActivityManager->Start(AutoKeyguardTimeout(), TCallBack(HandleInactiveEventL,this), 
+								TCallBack(HandleActiveEventL,this));
+		}
+	else
+		{
+		#if defined(_DEBUG)
+    	RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::SetActivityManagerL() OFF: Start manager"));
+    	#endif
+		iActivityManager->Start(AutoKeyguardOff, TCallBack(HandleInactiveEventL,this), 
+								TCallBack(HandleActiveEventL,this));
+		}
+
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::SetActivityManagerL() END"));
+    #endif
+    #endif //RD_AUTO_KEYGUARD
+	}
+//
+// ----------------------------------------------------------
+// CAutoKeyguardObserver::CancelActivityManager()
+// UnInitializes activymanager   
+// ----------------------------------------------------------
+//
+void CAutoKeyguardObserver::CancelActivityManager()
+	{
+	#ifdef RD_AUTO_KEYGUARD
+    if ( iActivityManager )
+        {
+	    iActivityManager->Cancel();
+        }
+    #endif //RD_AUTO_KEYGUARD
+	}
+//
+// ----------------------------------------------------------
+// CAutoKeyguardObserver::~CAutoKeyguardObserver()
+// Destructor   
+// ----------------------------------------------------------
+//
+CAutoKeyguardObserver::~CAutoKeyguardObserver()
+	{
+	#ifdef RD_AUTO_KEYGUARD
+	if(iCenRepI)
+    	delete iCenRepI;
+	if(iActivityManager)
+		{
+		StopActivityMonitoring();
+		delete iActivityManager;
+		iActivityManager = NULL;
+		}
+	#endif //RD_AUTO_KEYGUARD
+	}
+//
+// ----------------------------------------------------------
+// CAutoKeyguardObserver::AutoKeyguardTimeout()
+// Returns current AutoKeyguard period
+// ----------------------------------------------------------
+//
+TInt CAutoKeyguardObserver::AutoKeyguardTimeout()
+	{
+	#ifdef RD_AUTO_KEYGUARD
+    return iCenRepI->Timeout();
+    #else
+    return 0;
+    #endif //RD_AUTO_KEYGUARD
+	}
+//
+// ----------------------------------------------------------
+// CAutoKeyguardObserver::ResetInactivityTimeoutL()
+// Gets AutoKeyguard period and starts monitoring user activity 
+// ----------------------------------------------------------
+//
+void CAutoKeyguardObserver::ResetInactivityTimeout()
+	{
+	#ifdef RD_AUTO_KEYGUARD	
+	if (AutoKeyguardTimeout() )
+		{
+		#if defined(_DEBUG)
+    	RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::ResetInactivityTimeoutL() ON"));
+    	#endif
+		iActivityManager->SetInactivityTimeout(AutoKeyguardTimeout());
+		}
+	else
+		{
+		#if defined(_DEBUG)
+    	RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::ResetInactivityTimeoutL() OFF"));
+    	#endif
+		iActivityManager->SetInactivityTimeout(AutoKeyguardOff);
+		}
+	#endif //RD_AUTO_KEYGUARD
+	}
+//
+// ----------------------------------------------------------
+// CAutoKeyguardObserver::HandleActiveEventL()
+// Handles Active event. Called by ActivityManager
+// ----------------------------------------------------------
+//
+TInt CAutoKeyguardObserver::HandleActiveEventL(TAny* /*aPtr*/)
+	{
+	return KErrNone;
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoKeyguardObserver::HandleInactiveEventL()
+// Handles InActive event. Called by ActivityManager
+// ----------------------------------------------------------
+//
+TInt CAutoKeyguardObserver::HandleInactiveEventL(TAny* aPtr)
+	{
+	#ifdef RD_AUTO_KEYGUARD
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::HandleInactiveEventL() BEGIN"));
+    #endif
+	if ( STATIC_CAST(CAutoKeyguardObserver*, aPtr)->AutoKeyguardTimeout() )
+		{
+		#if defined(_DEBUG)
+    	RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::HandleInactiveEventL() Lock"));
+    	#endif
+		STATIC_CAST(CAutoKeyguardObserver*, aPtr)->LockKeysL();
+		}
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::HandleInactiveEventL() END"));
+    #endif
+    #endif //RD_AUTO_KEYGUARD
+	return KErrNone;
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoKeyguardObserver::LockKeysL()
+// Locks system
+// ----------------------------------------------------------
+//
+void CAutoKeyguardObserver::LockKeysL()
+	{
+	#ifdef RD_AUTO_KEYGUARD
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::LockKeysL() BEGIN"));
+    #endif
+    CRepository* repository = CRepository::NewL(KCRUidAutolockConf);
+    TInt keyguardConf(0);
+    //Check local keyguard variation key 
+    repository->Get(KAutoKeyLockConf, keyguardConf);
+    delete repository;
+    if(keyguardConf & KAutoKeylockFeatureIdFlipOpenDisabled)
+    {
+    	#if defined(_DEBUG)
+    	RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::LockKeysL() Flip variation"));
+    	#endif
+    	TInt flipState(KFlipOpen);
+    	RProperty::Get(KPSUidHWRM, KHWRMFlipStatus, flipState);
+	TInt lightStatus=EForcedLightsUninitialized; 
+	RProperty::Get(KPSUidCoreApplicationUIs,KLightsVTForcedLightsOn,lightStatus ); 
+
+	//If flip is open and feature flag is on. don't lock
+	if(flipState == KFlipOpen || lightStatus == EForcedLightsOn)
+    	{
+    		#if defined(_DEBUG)
+    		RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::LockKeysL() Flip open"));
+    		#endif
+    		return;
+    	}
+    		
+    }
+    
+	{	// REQ 414-5466 Prevention of device lock in context of Hands Free Voice UI
+	TInt vuiValue = 0;
+	TUid KHFVuiModePSUid = { 0x102818E7 };
+	enum THFVuiModePSKeys
+	    {
+	    EHFVuiPSModeId = 1000
+	    };
+	TInt tRet = RProperty::Get(KHFVuiModePSUid, EHFVuiPSModeId, vuiValue);	// also 0 if can't get because permissions or because doesn't exists
+	#if defined(_DEBUG)
+		RDebug::Printf( "%s %s (%u) gatting KHFVuiModePSUid+EHFVuiPSModeId=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, tRet );
+		RDebug::Printf( "%s %s (%u) vuiValue=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, vuiValue );
+	#endif
+	if(vuiValue)
+		{
+		#if defined(_DEBUG)
+		RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::LockKeysL() Voice functions active. No locking possible."));
+		#endif
+		return;
+		}
+	}
+
+	TInt value = 0;
+	TBool keylockOn = EFalse;
+	TBool autolockOn = EFalse;
+	TBool idle = EFalse;
+	TInt callState = EPSCTsyCallStateNone;
+	TBool okToLock = EFalse;
+	TBool screenSaverOn = EFalse;
+	TBool screenSaverStertedFromIdle = EFalse;
+        TBool startupOver = EFalse;
+    //Get keyguard status
+    RProperty::Get(KPSUidAvkonDomain, KAknKeyguardStatus, value);
+    keylockOn = (value == EKeyguardLocked);
+    //Get call state
+    RProperty::Get(KPSUidCtsyCallInformation, KCTsyCallState, callState);
+    
+    //See whether we are in idle
+ 		value = 0;   
+    RProperty::Get(KPSUidAiInformation, KActiveIdleState, value);
+    idle = (value == EPSAiForeground);
+    idle = ETrue; // don't care about idle state. Phone should autolock on any UI, not only HomeSreeen.
+    
+    value = 0;
+    RProperty::Get(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, value);
+    autolockOn = (value > EAutolockOff);
+	
+		value = 0;
+	  RProperty::Get(KPSUidScreenSaver, KScreenSaverOn, value);
+    screenSaverOn = (value == KSsOn);
+    
+    value = 0;
+    RProperty::Get(KPSUidScreenSaver, KScreenSaverActivatedFromIdle, value);
+    screenSaverStertedFromIdle = (value == KSsStartedFromIdle);
+    
+    //See if all the startup related queries and graphics has been displayed
+    value = 0;
+    RProperty::Get(KPSUidStartup, KPSStartupUiPhase, value);
+    startupOver = (value == EStartupUiPhaseAllDone);
+        
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::LockKeysL() startupOver: %d"), startupOver);
+    RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::LockKeysL() Startup state: %d"), value);
+    #endif
+    if (startupOver)
+        {
+        // If keylock is already ON, there is a ongoing call, 
+        // autolock is already ON or phone is not in idle, don't lock.
+        if (keylockOn || (callState > EPSCTsyCallStateNone) || autolockOn || !idle)
+            {
+        	    #if defined(_DEBUG)
+    		    RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::LockKeysL() Don't lock"));
+    		    RDebug::Print(_L("(AUTOLOCK)keylockstatus: %d"), keylockOn);
+    		    RDebug::Print(_L("(AUTOLOCK)callstate: %d"), callState);
+    		    RDebug::Print(_L("(AUTOLOCK)autolockstate: %d"), autolockOn);
+    		    RDebug::Print(_L("(AUTOLOCK)idlestate: %d"), idle);
+    		    RDebug::Print(_L("(AUTOLOCK)screenSaverOn: %d"), screenSaverOn);
+    		    RDebug::Print(_L("(AUTOLOCK)screenSaverStertedFromIdle: %d"), screenSaverStertedFromIdle);
+    		    #endif
+    		    //If screensaver is on, idle does not have foreground. If Screensaver was started from Idle, lock keys.
+    		    if(!idle && screenSaverOn && screenSaverStertedFromIdle && (callState <= EPSCTsyCallStateNone))
+    			    okToLock = ETrue;
+    		    else
+    		        okToLock = EFalse;
+            }
+         else //Otherwise there's no problem...
+         		okToLock = ETrue;
+        }
+    
+    
+    if (okToLock)
+        {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::LockKeysL() Lock"));
+            RDebug::Print(_L("(AUTOLOCK)keylockstatus: %d"), keylockOn);
+            RDebug::Print(_L("(AUTOLOCK)callstate: %d"), callState);
+            RDebug::Print(_L("(AUTOLOCK)autolockstate: %d"), autolockOn);
+            RDebug::Print(_L("(AUTOLOCK)idlestate: %d"), idle);
+            RDebug::Print(_L("(AUTOLOCK)screenSaverOn: %d"), screenSaverOn);
+            RDebug::Print(_L("(AUTOLOCK)screenSaverStertedFromIdle: %d"), screenSaverStertedFromIdle);
+            #endif
+		//Tell keylock to lock itself.
+		RAknKeyLock keylock;
+        if ( keylock.Connect() == KErrNone )
+          {
+          	#if defined(_DEBUG)
+    		RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::LockKeysL() Connect OK"));
+    		#endif
+    			 if(AknLayoutUtils::PenEnabled())
+    			     keylock.EnableWithoutNote(); //Enable without note
+    			 else
+    			     keylock.EnableKeyLock();
+           keylock.Close();
+          }
+		}
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoKeyguardObserver::LockKeysL() END"));
+    #endif
+    #endif //RD_AUTO_KEYGUARD
+} 
+	
+
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/src/AutoLockCenRepI.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,165 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#include <centralrepository.h> 
+#include <settingsinternalcrkeys.h>
+#include "AutoLockModelPS.h"
+#include "AutolockAppUiPS.h"
+#include "AutoLockCenRepI.h"
+ 
+
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CAutolockCenRepI::NewLC()
+// Two-phased constructor.
+// ----------------------------------------------------------
+//
+CAutolockCenRepI* CAutolockCenRepI::NewLC(CAutolockAppUi* aAppUi)
+	{
+	CAutolockCenRepI* self = new (ELeave) CAutolockCenRepI(aAppUi);
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+	}
+
+//
+// ----------------------------------------------------------
+// CAutolockCenRepI::NewL()
+// Two-phased constructor.
+// ----------------------------------------------------------
+//
+CAutolockCenRepI* CAutolockCenRepI::NewL(CAutolockAppUi* aAppUi)
+	{
+	CAutolockCenRepI* self = NewLC(aAppUi);
+	CleanupStack::Pop(); //self
+	return self;
+	}
+
+//
+// ----------------------------------------------------------
+// CAutolockCenRepI::~CAutolockCenRepI()
+// Destructor
+// ----------------------------------------------------------
+//
+CAutolockCenRepI::~CAutolockCenRepI()
+	{
+	if(iNotifyHandler)
+	{
+		iNotifyHandler->StopListening();
+		delete iNotifyHandler;	
+	}
+    if(iSession)
+		delete iSession;
+	}
+//
+// ----------------------------------------------------------
+// CAutolockCenRepI::CAutolockCenRepI()
+// C++ default constructor
+// ----------------------------------------------------------
+//	
+CAutolockCenRepI::CAutolockCenRepI(CAutolockAppUi* aAppUi):iAppUi(aAppUi)
+	{
+	}
+
+//
+// ----------------------------------------------------------
+// CAutolockCenRepI::ConstructL()
+// Symbian OS default constructor
+// ----------------------------------------------------------
+//	
+void CAutolockCenRepI::ConstructL()
+	{
+	// init cenrep connection	
+	iSession = CRepository::NewL(KCRUidSecuritySettings);
+
+    iNotifyHandler = CCenRepNotifyHandler::NewL(*this, *iSession, CCenRepNotifyHandler::EIntKey, KSettingsAutoLockTime);
+    iNotifyHandler->StartListeningL();
+	}
+
+//
+// ----------------------------------------------------------
+// CAutolockCenRepI::HandleNotifyInt()
+// Handles autolock period changes. Called by CenRep.
+// ----------------------------------------------------------
+//	
+void CAutolockCenRepI::HandleNotifyInt(TUint32 aId, TInt /*aNewValue*/)
+	{
+    if(aId == KSettingsAutoLockTime)
+    {
+	    ResetInactivityTimeout();
+    }
+	return;
+	}
+
+void CAutolockCenRepI::HandleNotifyError(TUint32 /*aId*/, TInt /*error*/, CCenRepNotifyHandler* /*aHandler*/)
+    {
+    return;
+    }
+
+void CAutolockCenRepI::HandleNotifyGeneric(TUint32 aId)
+    {
+        if ( aId == NCentralRepositoryConstants::KInvalidNotificationId )
+        {//Repository wide reset caused generic notification
+            ResetInactivityTimeout();
+        }
+    return;
+    }
+
+//
+// ----------------------------------------------------------
+// CAutolockCenRepI::ResetInactivityTimeoutL()
+// Resets autolock timer
+// ----------------------------------------------------------
+//	
+void CAutolockCenRepI::ResetInactivityTimeout()
+	{
+	iAppUi->Model()->ResetInactivityTimeout();
+	}
+
+//
+// ----------------------------------------------------------
+// CAutolockCenRepI::Timeout()
+// Returns currents autolock period (in seconds)
+// ----------------------------------------------------------
+//	
+TInt CAutolockCenRepI::Timeout()
+	{
+    TInt period = 0;
+    iSession->Get(KSettingsAutoLockTime, period);
+	return period * 60;
+	}
+//
+// ----------------------------------------------------------
+// CAutolockCenRepI::SetLocked ()
+// Sets lock on/off in CenRep
+// ----------------------------------------------------------
+//	
+void CAutolockCenRepI::SetLockedL(TBool aLockValue)
+	{
+	TInt lockValue = 0;
+	if (aLockValue)
+		{
+		lockValue = 1;
+		}
+    CRepository* repository = CRepository::NewL(KCRUidSecuritySettings);
+    repository->Set(KSettingsAutolockStatus, lockValue);
+    delete repository;
+	}
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/src/AutoLockLockObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,145 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia	Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*		Obsererver for Set System Locked event	
+*
+*
+*/
+
+#include		<bldvariant.hrh>
+#include		<e32property.h>
+#include	<PSVariables.h>
+#include		<coreapplicationuisdomainpskeys.h>
+#include <SCPClient.h>	// EMKK-7N3G7R
+#include		<startupdomainpskeys.h>	// EMKK-7N3G7R
+#include <mmtsy_names.h>	// EMKK-7N3G7R 
+#include	"AutoLockLockObserverPS.h"
+#include	"AutolockAppUiPS.h"
+#include	"AutoLockModelPS.h"
+
+
+// ================= MEMBER	FUNCTIONS	=======================
+//
+// ----------------------------------------------------------
+// CLockObserver::NewL()
+// Constructs	a	new	entry	with given values.
+// ----------------------------------------------------------
+//
+CLockObserver* CLockObserver::NewL(CAutolockAppUi* aAppUi)
+		{
+		CLockObserver* self	=	new	(ELeave) CLockObserver(aAppUi);
+		CleanupStack::PushL(self);
+		self->ConstructL();
+		CleanupStack::Pop();
+		return self;
+		}
+//
+// ----------------------------------------------------------
+// CLockObserver::CLockObserver()
+// Destructor
+// ----------------------------------------------------------
+//
+CLockObserver::~CLockObserver()
+		{
+		Cancel();
+		iProperty.Close();
+#ifdef FF_STARTUP_OMA_DM_SUPPORT	// New booting order	Start	EMKK-7N3G7R			
+		delete wait;
+		if (iServer.Handle())
+			{						
+				iServer.UnloadPhoneModule(KMmTsyModuleName);
+				iServer.Close();
+			}
+#endif	// End EMKK-7N3G7R	
+		}
+//
+// ----------------------------------------------------------
+// CNoSimCard::Start()
+// Starts	listening	KUidAutolockStatus event 
+// ----------------------------------------------------------
+//
+TInt CLockObserver::Start()
+		{
+		if (IsActive())
+				return KErrInUse;
+		iStatus	=	KRequestPending;
+		iProperty.Attach(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus);		 
+		iProperty.Subscribe(iStatus);
+		SetActive();
+		return KErrNone;
+		}
+//
+// ----------------------------------------------------------
+// CLockObserver::CLockObserver()
+// C++ constructor
+// ----------------------------------------------------------
+// 
+CLockObserver::CLockObserver(CAutolockAppUi* aAppUi) : CActive(0), iAppUi(aAppUi)
+	{														 
+		}
+//
+// ----------------------------------------------------------
+// CLockObserver::ConstructL()
+// Symbian OS	default	constructor
+// ----------------------------------------------------------
+// 
+void CLockObserver::ConstructL()
+		{
+	    
+		#if	defined(_DEBUG)	
+        RDebug::Print(_L("(AUTOLOCK)CLockObserver::ConstructL()"));
+    #endif
+        
+		// Add this	active object	to the scheduler.
+	CActiveScheduler::Add(this);
+	TInt ret;
+	_LIT_SECURITY_POLICY_PASS(KReadPolicy);	
+	_LIT_SECURITY_POLICY_C1(KWritePolicy,	ECapabilityWriteDeviceData);
+	
+	ret	=	RProperty::Define(KPSUidCoreApplicationUIs,	KCoreAppUIsAutolockStatus, RProperty::EInt,	KReadPolicy, KWritePolicy);
+		if(ret !=	KErrAlreadyExists)
+				User::LeaveIfError(ret);
+				    
+	// Begin obsering	PubSub event	
+	Start();	
+		}
+//
+// ----------------------------------------------------------
+// CLockObserver::RunL()
+// Called	when device	(autolock) is	activated	from menu.
+// ----------------------------------------------------------
+// 
+void CLockObserver::RunL()
+	{
+	// set ui	locked.
+		TInt autolockState;
+		iProperty.Get( autolockState );
+		if (autolockState	>	EAutolockOff)
+				{
+		iAppUi->Model()->LockSystemL(autolockState);
+		}
+	// Continue	observing	PubSub event	
+	Start();	
+	}
+//
+// ----------------------------------------------------------
+// CLockObserver::DoCancel()
+// Cancels event listening
+// ----------------------------------------------------------
+// 
+void CLockObserver::DoCancel()
+		{
+		iProperty.Cancel();
+		}
+// End of	file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/src/AutoLockModel.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,445 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#include <aknappui.h>
+#include <activitymanager.h>
+#include <bldvariant.hrh>
+#include <featmgr.h>
+#include <AknNotifierController.h>
+#include <featmgr.h>
+#include    <e32property.h>
+#include	<PSVariables.h>
+#include    <startupdomainpskeys.h>
+#include    <coreapplicationuisdomainpskeys.h>
+#include <ctsydomainpskeys.h>
+
+#include <SCPClient.h>
+
+#include    "AutoLockModelPS.h"  
+#include	"AutolockAppUiPS.h"
+#include    "AutoLockLockObserverPS.h"
+#include "AutoLockCenRepI.h"
+
+
+const TInt AutoLockOff(60000);
+
+
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CAutoLockModel::NewL()
+// ----------------------------------------------------------
+//
+
+CAutoLockModel* CAutoLockModel::NewL(CAutolockAppUi* aAppUi, TBool aLocked)
+	{
+	CAutoLockModel* self = new (ELeave) CAutoLockModel(aAppUi);
+	CleanupStack::PushL(self);
+	self->ConstructL( aLocked );
+	CleanupStack::Pop(); //self
+	return self;
+	}
+//
+// ----------------------------------------------------------
+// CAutoLockModel::CAutoLockModel()
+// C++ default constructor
+// ----------------------------------------------------------
+// 
+CAutoLockModel::CAutoLockModel(CAutolockAppUi* aAppUi) : 
+ iAppUi( aAppUi ), iMonitoring(EFalse)	
+	{
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoLockModel::ConstructL()
+// Symbian OS default constructor
+// ----------------------------------------------------------
+//
+void CAutoLockModel::ConstructL( TBool aLocked )
+	{
+		FeatureManager::InitializeLibL();
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::ConstructL() BEGIN"));
+  #endif	
+    iCenRepI = CAutolockCenRepI::NewL(iAppUi);
+	// lock status observer
+	iLockObserver = CLockObserver::NewL(iAppUi);
+	// Activitymanager
+	iActivityManager = CUserActivityManager::NewL(CActive::EPriorityStandard);
+	StartActivityMonitoringL();
+    // In GSM the device is always unlocked.
+    // In CDMA, SecClientUi will lock the device on boot-up if needed.
+ 
+ 	if ( aLocked == EAutolockStatusUninitialized )
+	{
+			RProperty::Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus,	EAutolockStatusUninitialized);
+	}
+	else
+	{
+	    RProperty::Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus,	EAutolockOff);
+  }
+       
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::ConstructL() END"));
+    #endif
+	}
+	//
+// ----------------------------------------------------------
+// CAutoLockModel::StartActivityMonitoringL()
+// Start monitoring user activity
+// ----------------------------------------------------------
+//
+void CAutoLockModel::StartActivityMonitoringL()
+	{	
+	SetActivityManagerL();
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoLockModel::StopActivityMonitoring()
+// Stop monitoring user activity
+// ----------------------------------------------------------
+//
+void CAutoLockModel::StopActivityMonitoring()
+	{
+	CancelActivityManager();
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoLockModel::SetActivityManagerL()
+// Initializes activymanager   
+// ----------------------------------------------------------
+//
+void CAutoLockModel::SetActivityManagerL()
+	{
+	if (AutoLockTimeout() )
+		{
+		iActivityManager->Start(AutoLockTimeout(), TCallBack(HandleInactiveEventL,this), 
+								TCallBack(HandleActiveEventL,this));
+		}
+	else
+		{
+		iActivityManager->Start(AutoLockOff, TCallBack(HandleInactiveEventL,this), 
+								TCallBack(HandleActiveEventL,this));
+		}
+
+	}
+//
+// ----------------------------------------------------------
+// CAutoLockModel::CancelActivityManager()
+// UnInitializes activymanager   
+// ----------------------------------------------------------
+//
+void CAutoLockModel::CancelActivityManager()
+	{
+    if ( iActivityManager )
+        {
+	    iActivityManager->Cancel();
+        }
+	delete iActivityManager;
+	iActivityManager = NULL;
+	}
+//
+// ----------------------------------------------------------
+// CAutoLockModel::~CAutoLockModel()
+// Destructor   
+// ----------------------------------------------------------
+//
+CAutoLockModel::~CAutoLockModel()
+	{
+    delete iCenRepI;
+	delete iLockObserver;
+	StopActivityMonitoring();
+	FeatureManager::UnInitializeLib();
+    // close custom phone
+	}
+//
+// ----------------------------------------------------------
+// CAutoLockModel::AutoLockTimeout()
+// Returns current autolock period
+// ----------------------------------------------------------
+//
+TInt CAutoLockModel::AutoLockTimeout()
+	{
+    return iCenRepI->Timeout();
+	}
+//
+// ----------------------------------------------------------
+// CAutoLockModel::ResetInactivityTimeoutL()
+// Gets autolock period and starts monitoring user activity 
+// ----------------------------------------------------------
+//
+void CAutoLockModel::ResetInactivityTimeout()
+	{	
+	if (AutoLockTimeout() )
+		{
+		iActivityManager->SetInactivityTimeout(AutoLockTimeout());
+		}
+	else
+		{
+		iActivityManager->SetInactivityTimeout(AutoLockOff);
+		}
+	}
+//
+// ----------------------------------------------------------
+// CAutoLockModel::HandleActiveEventL()
+// Handles Active event. Called by ActivityManager
+// ----------------------------------------------------------
+//
+TInt CAutoLockModel::HandleActiveEventL(TAny* /*aPtr*/)
+	{
+	return KErrNone;
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoLockModel::HandleInactiveEventL()
+// Handles InActive event. Called by ActivityManager
+// ----------------------------------------------------------
+//
+TInt CAutoLockModel::HandleInactiveEventL(TAny* aPtr)
+	{
+	if ( STATIC_CAST(CAutoLockModel*, aPtr)->AutoLockTimeout() )
+		{
+			TInt value(EStartupUiPhaseUninitialized);
+			RProperty::Get(KPSUidStartup, KPSStartupUiPhase, value);
+			//Don't lock unless boot is over.
+	    if(value == EStartupUiPhaseAllDone)
+		    {
+		    #if defined(_DEBUG)
+    		RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::HandleInactiveEventL() Boot over"));
+    		#endif
+				#ifdef RD_REMOTELOCK
+				STATIC_CAST(CAutoLockModel*, aPtr)->LockSystemL(ETimerLocked);
+				#else
+				STATIC_CAST(CAutoLockModel*, aPtr)->LockSystemL(EAutolockOn);
+				#endif //RD_REMOTELOCK
+			  }
+			else
+			{
+				#if defined(_DEBUG)
+    		RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::HandleInactiveEventL() In boot; don't lock"));
+    		#endif
+			}
+		}
+	return KErrNone;
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoLockModel::LockSystemL()
+// Locks system
+// ----------------------------------------------------------
+//
+void CAutoLockModel::LockSystemL(TInt aAutolockState)
+	{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::LockSystemL() BEGIN"));
+    #endif
+    // If already locked, do nothing. Otherwise we'll end up
+    // on top of Screensaver
+    // Check if iSideKey2 is zero or not (locked if nonzero)
+    // Also, phone should not be locked if PUK1 code query is up.
+#ifdef FF_STARTUP_OMA_DM_SUPPORT	// New booting order	Start	ID:	 MVKS-7PZDZ5
+		TInt autolock_value	=	0;
+		RProperty::Get(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus,	autolock_value);	
+		if (autolock_value ==	EAutolockStatusUninitialized)
+		{
+				return;					
+		}		
+#endif	//End	ID:	 MVKS-7PZDZ5
+    if (iAppUi->Locked() || iAppUi->IsPinBlocked())
+        {
+        return;
+        }
+	
+	TInt lightStatus=EForcedLightsUninitialized; 
+	RProperty::Get(KPSUidCoreApplicationUIs,KLightsVTForcedLightsOn,lightStatus ); 
+	//If display is forced on. don't lock 
+	if(lightStatus == EForcedLightsOn ) 
+		{
+		#if defined(_DEBUG) 
+		RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::LockSystemL() Display is forced on. Device not locked")); 
+		#endif 
+		return;
+		}
+
+    //Check which state we are in to see if it's OK to lock the phone
+    //In CDMA when there is no SIM (RUIM) support we should be able to lock
+    //the phone after reboot. In this case ESWStateNormal is too late to lock the phone
+    //and other states below are needed.
+    TBool okToLock = EFalse;
+    TInt sysState = 0;
+    iProperty.Get(KPSUidStartup, KPSGlobalSystemState, sysState);    
+    //If NOT in CDMA the Autolock should come up only after the phone has booted up.
+    if ( FeatureManager::FeatureSupported( KFeatureIdProtocolCdma ) || iAppUi->HiddenReset())
+        {
+        if( (sysState == ESwStateNormalRfOn       ||
+            sysState == ESwStateNormalRfOff       ||
+             sysState == ESwStateCriticalPhaseOK) &&
+            (aAutolockState > EAutolockOff) )	// EMKK-7N3G7R
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::LockSystemL() LOCKED AFTER HIDDEN RESET"));
+            #endif
+            okToLock = ETrue;
+            }
+        }
+    else //Feature Manager
+        {
+        if( (sysState == ESwStateNormalRfOn       ||
+             sysState == ESwStateNormalRfOff)      &&
+            (aAutolockState > EAutolockOff) ) // EMKK-7N3G7R
+            {
+            okToLock = ETrue;
+            }
+        }
+   TInt tarmFlag;
+if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))    
+{
+    // Get the TARM admin flag value
+	TInt tRet = RProperty::Get( KSCPSIDAutolock, SCP_TARM_ADMIN_FLAG_UID, tarmFlag );
+    
+    if ( tRet != KErrNone )
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::BringAppToForegroundL():\
+            Warning: failed to get TARM Admin Flag state"));
+        #endif
+        }
+    else
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::BringAppToForegroundL(): TARM flag: %d"),
+            tarmFlag );
+        #endif
+        }
+}
+    
+    TInt callState;
+    iProperty.Get(KPSUidCtsyCallInformation, KCTsyCallState, callState);
+TBool isConditionSatisfied = EFalse;
+if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))
+{        
+    if ( ( callState != EPSCTsyCallStateNone ) && (!( tarmFlag & KSCPFlagAdminLock )) )    
+    			isConditionSatisfied = ETrue;
+}
+else
+{
+    if ( callState != EPSCTsyCallStateNone )
+    		isConditionSatisfied = ETrue;
+}
+		if (isConditionSatisfied)
+        {
+        TBool remoteLocked(EFalse);
+        #ifdef RD_REMOTELOCK
+        remoteLocked = (aAutolockState == ERemoteLocked);
+        #endif //RD_REMOTELOCK
+         if(remoteLocked) 
+         {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::LockSystemL() REMOTE LOCKED"));
+            #endif
+            okToLock = ETrue;
+            
+         }
+         else
+            okToLock = EFalse;        
+        }
+       
+    if (!iAppUi->IsForeground() && okToLock)
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::LockSystemL() LOCK PHONE"));
+        #endif   
+		// close fast-swap window
+		CEikonEnv::Static()->DismissTaskList();
+		// inform Avokon & Other app that system is locked
+		// unless the value has already been set in secuisystemlock
+		#ifdef RD_REMOTELOCK
+		if(aAutolockState != EManualLocked)
+    		{
+    		    #if defined(_DEBUG)
+                RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::LockSystemL() Timer/Remote locked: %d"), aAutolockState);
+                #endif
+    		    SetLockedL(aAutolockState);		    
+    		}
+		else if((aAutolockState == EManualLocked)  && !iAppUi->Locked() && iAppUi->HiddenReset())
+		     {   //set the PubSub key if we are to be locked after a hidden reset has occurred.
+		         #if defined(_DEBUG)
+                 RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::LockSystemL() HIDDEN RESET LOCK"));
+                 #endif
+		         SetLockedL(aAutolockState);	   
+		     }
+		else
+		    {   //Normal manual lock from power key. Just set the CenRep key.
+		        iCenRepI->SetLockedL(okToLock);
+		    }
+		#else //! RD_REMOTELOCK
+		SetLockedL(aAutolockState);
+		#endif//RD_REMOTELOCK
+		// lock keys
+		iAppUi->LockKeysL();
+		// app to foreground
+		iAppUi->BringAppToForegroundL();
+         // Reset inactivity time so that Screensaver gets to
+        // run again after its timeout. We'll ignore the new
+        // inactivity timeout, if already locked
+        User::ResetInactivityTime();
+		}
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::LockSystemL() END"));
+    #endif
+} 
+	
+//
+// ----------------------------------------------------------
+// CAutoLockModel::SetLocked
+// Sets lockvalue in Publish & Subscribe and Central Repository
+// ----------------------------------------------------------
+//
+void CAutoLockModel::SetLockedL(TInt aAutolockState)
+	{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::SetLockedL() begin"));
+    #endif
+	TBool locked = (aAutolockState > EAutolockOff);
+	if (locked)
+		{
+        iProperty.Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, aAutolockState);
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::SetLockedL() LOCK"));
+        #endif
+		}		
+  else
+		{				
+        iProperty.Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, EAutolockOff);
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::SetLockedL() UNLOCK"));         
+        #endif
+    }
+
+    iCenRepI->SetLockedL(locked);
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutoLockModel::SetLockedL() end"));
+    #endif
+	}
+
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/src/AutoLockValueObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*		Observer for phone events. Used to deactive/active the side-key
+*
+*
+*/
+
+
+#include    <e32property.h>
+#include	<PSVariables.h>
+#include <ctsydomainpskeys.h>
+#include	"AutolockAppUiPS.h"
+#include	"AutoLockValueObserverPS.h"
+
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CValueObserver::NewL()
+// Constructs a new entry with given values.
+// ----------------------------------------------------------
+//
+CValueObserver* CValueObserver::NewL(CAutolockAppUi* aAppUi)
+    {
+    CValueObserver* self = new (ELeave) CValueObserver(aAppUi);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+//
+// ----------------------------------------------------------
+// CValueObserver::CValueObserver()
+// Destructor
+// ----------------------------------------------------------
+//
+CValueObserver::~CValueObserver()
+    {
+    Cancel();
+    }
+//
+// ----------------------------------------------------------
+// CValueObserver::Start()
+// Starts listening KUidCurrentCall event  
+// ----------------------------------------------------------
+//
+TInt CValueObserver::Start()
+    {
+    if (IsActive())
+        return KErrInUse;
+    iStatus = KRequestPending;
+    iProperty.Attach(KPSUidCtsyCallInformation, KCTsyCallState); 
+    iProperty.Subscribe(iStatus);
+    SetActive();
+    return KErrNone;
+    }
+//
+// ----------------------------------------------------------
+// CValueObserver::Stop()
+// Stops listening KUidCurrentCall event 
+// ----------------------------------------------------------
+//
+void CValueObserver::Stop()
+	{
+	Cancel();
+	}
+//
+// ----------------------------------------------------------
+// CLockObserver::CLockObserver()
+// C++ constructor
+// ----------------------------------------------------------
+// 
+CValueObserver::CValueObserver(CAutolockAppUi* aAppUi) : CActive(0), iAppUi(aAppUi)
+	{                            
+    }
+//
+// ----------------------------------------------------------
+// CLockObserver::ConstructL()
+// Symbian OS default constructor
+// ----------------------------------------------------------
+// 
+void CValueObserver::ConstructL()
+    {
+    // Add this active object to the scheduler.
+	CActiveScheduler::Add(this);	
+    }
+//
+// ----------------------------------------------------------
+// CValueObserver::RunL()
+// 
+// ----------------------------------------------------------
+// 
+void CValueObserver::RunL()
+	{
+    TInt callState;
+    iProperty.Get( callState );
+    if (callState == EPSCTsyCallStateNone && !iAppUi->IsForeground())
+        {
+		// app back to foreground
+		iAppUi->BringAppToForegroundL();
+		}
+    else
+		{
+		Start();
+		}
+	
+	}
+//
+// ----------------------------------------------------------
+// CValueObserver::DoCancel()
+// Cancels event listening
+// ----------------------------------------------------------
+// 
+void CValueObserver::DoCancel()
+    {
+    iProperty.Cancel();
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/src/AutoLockView.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,269 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#include <e32std.h>
+#include <eiklabel.h>
+#include <eikfutil.h>
+#include <aknconsts.h>
+#include <akntitle.h>
+#include <avkon.mbg>
+#include <aknview.h>
+#include <aknViewAppUi.h>
+#include <Autolock.rsg>
+#include "autolock.hrh"
+#include <aknlayoutscalable_avkon.cdl.h>
+#include <layoutmetadata.cdl.h>
+#include <AknUtils.h>
+#include "AutolockAppUiPS.h"
+#include "AutoLockModelPS.h"
+#include "AutolockView.h"
+#include "AutolockContainer.h"
+
+
+
+
+// CONSTANTS
+
+const TUid KUidStartUp = { 0x100058F4 };
+const TInt KPhoneAppOrdinalPosition = 1; // used to pull phone app closer to foreground
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------
+// CAutolockView::ConstructL()
+// Symbian OS default constructor can leave..
+// ----------------------------------------------------
+//
+void CAutolockView::ConstructL()
+	{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockView::ConstructL()"));
+    #endif
+    BaseConstructL();
+	}
+// ----------------------------------------------------
+// CAutolockView::~CAutolockView()
+// Destructor
+// ----------------------------------------------------
+//
+CAutolockView::~CAutolockView()
+	{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockView::~CAutolockView()"));
+    #endif
+    CAutolockContainer* view = iView;
+    iView = NULL;
+	if (view)
+        {
+		AppUi()->RemoveFromStack(view);
+        }
+	delete view;
+	}
+// ----------------------------------------------------
+// CAutolockView::Id()
+// Returns view Id
+// ----------------------------------------------------
+//
+TUid CAutolockView::Id() const
+    {
+    return KAutoLockViewId;
+    }
+// ----------------------------------------------------
+// CAutolockView::HandleCommandL()
+// Handles user inputs
+// ----------------------------------------------------
+//
+void CAutolockView::HandleCommandL(TInt aCommand)
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockView::HandleCommandL()"));
+    #endif   
+    AppUi()->HandleCommandL(aCommand);
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockView::HandleCommandL END()"));
+    #endif
+    }
+void CAutolockView::HandleCall(TInt aCommand, TRect &aRect)
+    {
+    	RDebug::Printf( "%s %s (%u) aCommand=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aCommand );
+    if (iView)
+    	{
+        TRect cr = ClientRect();
+        iView->SetRect( cr );
+    		RDebug::Printf( "%s %s (%u) got 2 cr=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aCommand );
+        iView->DrawNow( );
+        iView->GiveCoords( aRect );
+			}
+    else
+			{
+			RDebug::Printf( "%s %s (%u) !iView ???=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iView );
+			}
+    }
+void CAutolockView::MakeVisible(TBool aVisibility)
+    {
+    #if defined(_DEBUG)
+    RDebug::Printf( "%s %s (%u) aVisibility=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aVisibility );
+    #endif   
+    if (iView)
+	iView->MakeVisible( aVisibility );
+    else
+	{
+	#if defined(_DEBUG)
+	RDebug::Printf( "%s %s (%u) !iView ???=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iView );
+	#endif   
+	}
+    #if defined(_DEBUG)
+    RDebug::Printf( "%s %s (%u) aVisibility=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aVisibility );
+    #endif
+    }
+// ----------------------------------------------------
+// CAutolockView::HandleStatusPaneSizeChange()
+// Handles StatusPane Size Change
+// ----------------------------------------------------
+//
+void CAutolockView::HandleStatusPaneSizeChange()
+	{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockView::HandleStatusPaneSizeChange()"));
+    #endif
+    if (iView)
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)CAutolockView::HandleStatusPaneSizeChange() SET RECT"));
+        #endif
+        TRect cr = ClientRect();
+        iView->SetRect( cr );
+        }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockView::HandleStatusPaneSizeChange() END"));
+    #endif
+	}
+// ----------------------------------------------------
+// CAutolockView::DoActivateL
+// Activates the view
+// ----------------------------------------------------
+//
+void CAutolockView::DoActivateL(const TVwsViewId& /*aPrevViewId*/,TUid aCustomMessageId,const TDesC8& /*aCustomMessage*/)
+	{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockView::DoActivateL"));
+    #endif	
+	iView = new(ELeave) CAutolockContainer;
+
+    TRect screen( iAvkonAppUi->ApplicationRect() );
+    TAknLayoutRect applicationWindow;
+    applicationWindow.LayoutRect(screen, AknLayoutScalable_Avkon::application_window(0));
+    TInt mainPaneVariety = 0;
+    if((AknLayoutUtils::PenEnabled()) && !(Layout_Meta_Data::IsLandscapeOrientation()))
+        {//Use main pane without softkey area
+            mainPaneVariety = 5;
+        }
+    else if (Layout_Meta_Data::IsLandscapeOrientation())
+        {
+            mainPaneVariety = 4;
+        }
+    else
+        {
+            mainPaneVariety = 3;
+        }
+
+    
+    
+    TAknLayoutRect mainPane;
+    mainPane.LayoutRect(applicationWindow.Rect(), AknLayoutScalable_Avkon::main_pane(mainPaneVariety));     	
+	iView->ConstructL( mainPane.Rect() );
+    AppUi()->AddToStackL(*this,iView);
+
+    // Message comes from start-up. We need to lock the device.
+    if ( aCustomMessageId == KUidStartUp )
+        {
+        static_cast<CAutolockAppUi*>(AppUi())->Model()->LockSystemL();
+
+        // Set phone app window group to position 2. This is the same position 
+        // as the phone app set is self when it goes to background.
+        TVwsViewId phoneAppId;
+        TApaTaskList taskList( iEikonEnv->WsSession() );
+        User::LeaveIfError( AknDef::GetPhoneIdleViewId(phoneAppId) );
+        const TInt phoneWgId = taskList.FindApp( phoneAppId.iAppUid ).WgId();
+        User::LeaveIfError( iCoeEnv->WsSession().SetWindowGroupOrdinalPosition( phoneWgId, KPhoneAppOrdinalPosition ) );
+        }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockView::DoActivateL END"));
+    #endif
+    }
+// ----------------------------------------------------
+// CAutolockView::DoDeActivateL
+// Deactivates the view
+// ----------------------------------------------------
+//
+void CAutolockView::DoDeactivate()
+	{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockView::DoDeActivateL"));
+    #endif
+    CAutolockContainer* view = iView;
+    iView = NULL;
+	if (view)
+        {
+		AppUi()->RemoveFromStack(view);
+        }
+	delete view;
+    }
+// ----------------------------------------------------
+// CAutolockView::ScreenDeviceChanged()
+// Handles screen layout changes
+// ----------------------------------------------------
+//
+void CAutolockView::ScreenDeviceChanged()
+{
+ if (Layout_Meta_Data::IsLandscapeOrientation() && AknLayoutUtils::PenEnabled())
+        {//do not change layout in touch device to conserve battery
+        #if defined(_DEBUG)
+    		RDebug::Print(_L("(AUTOLOCK)CAutolockView::ScreenDeviceChanged(): Do Nothing"));
+    		#endif
+        return;
+        }
+        
+ if (iView)
+    {
+    TRect screen( iAvkonAppUi->ApplicationRect() );
+    TAknLayoutRect applicationWindow;
+    applicationWindow.LayoutRect(screen, AknLayoutScalable_Avkon::application_window(0));
+
+    TInt mainPaneVariety = 0;
+    if((AknLayoutUtils::PenEnabled()) && !(Layout_Meta_Data::IsLandscapeOrientation()))
+        {//Use main pane without softkey area
+            mainPaneVariety = 5;
+        }
+    else if (Layout_Meta_Data::IsLandscapeOrientation())
+        {
+            mainPaneVariety = 4;
+        }
+    else
+        {
+            mainPaneVariety = 3;
+        }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockView::ScreenDeviceChanged() variety: %d"), mainPaneVariety);
+    #endif
+    TAknLayoutRect mainPane;
+    mainPane.LayoutRect(applicationWindow.Rect(), AknLayoutScalable_Avkon::main_pane(mainPaneVariety));     
+    iView->SetRect(mainPane.Rect());        
+    }
+}
+// end of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/src/AutolockApp.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,61 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+// INCLUDE FILES
+#include    "AutolockApp.h"
+#include    "AutolockDocument.h"
+#include <eikstart.h>
+
+
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CAutolockApp::AppDllUid()
+// Returns application UID
+// ---------------------------------------------------------
+//
+TUid CAutolockApp::AppDllUid() const
+    {
+    return KUidAutolock;
+    }
+
+// ---------------------------------------------------------
+// CAutolockApp::CreateDocumentL()
+// Creates CAutolockDocument object
+// ---------------------------------------------------------
+//
+CApaDocument* CAutolockApp::CreateDocumentL()
+    {
+    return CAutolockDocument::NewL( *this );
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS ==============
+//
+
+LOCAL_C CApaApplication* NewApplication()
+    {
+    return new CAutolockApp;
+    }
+
+GLDEF_C TInt E32Main()
+    {
+    return EikStart::RunApplication(NewApplication);
+    }
+
+// End of File  
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/src/AutolockAppUi.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1450 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#include <apgtask.h>
+#include <etelmm.h>
+#include <AknEcs.h>
+#include <aknnotedialog.h>
+#include <aknkeylock.h>
+#include <AknLayoutDef.h>
+#include <AknLayout.lag>
+#include <bldvariant.hrh>
+#include <aknappui.h> 
+#include <centralrepository.h>
+#include <settingsinternalcrkeys.h>
+#include <secuisecurityhandler.h>
+#include <secui.h>
+#include <featmgr.h>
+#include <Autolock.rsg>
+#include <mmtsy_names.h>
+#include <e32property.h>
+#include <PSVariables.h>   // Property values
+#include <coreapplicationuisdomainpskeys.h>
+#include <startupdomainpskeys.h>
+#include <ctsydomainpskeys.h>
+#include <securityuisprivatepskeys.h>
+#include <AknSgcc.h>
+
+#include "AutolockAppUiPS.h"
+#include "AutoLockValueObserverPS.h"
+#include "AutoLockModelPS.h"
+#include "AutolockApp.h"
+#include "autolock.hrh"
+#include "AutolockView.h"
+
+#include <SCPClient.h>
+#include <AknSoftNotifier.h>
+
+// sysap uid and message enums defined in eikon.hrh
+// for sending messages to sysap
+#include <eikon.hrh>
+#include <apgwgnam.h>
+#include <aknlayoutscalable_avkon.cdl.h>
+
+//  LOCAL CONSTANTS AND MACROS  
+#define KSysApUid TUid::Uid(0x100058F3)
+
+const TInt KTriesToConnectServer( 2 );
+const TInt KTimeBeforeRetryingServerConnection( 50000 );
+const TInt PhoneIndex( 0 );
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CAutolockAppUi::ConstructL()
+// ?implementation_description
+// ----------------------------------------------------------
+//
+void CAutolockAppUi::ConstructL()
+    {
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL"));
+    #endif
+    
+    BaseConstructL( EAknEnableSkin | EAknEnableMSK );
+    
+    //Disable priority control so that Autolock process priority isn't set to "background" by 
+	//window server when it is not active.
+	iEikonEnv->WsSession().ComputeMode( RWsSession::EPriorityControlDisabled ); 
+	RThread().SetProcessPriority( EPriorityHigh );
+
+    FeatureManager::InitializeLibL();
+
+	RTelServer::TPhoneInfo PhoneInfo;
+	// prevent autolock shutdown
+	iEikonEnv->SetSystem( ETrue ); 
+
+	iSideKey1 = 0;
+	iSideKey2 = 0;
+	iAppKey = 0;
+
+	aCallButtonRect = TRect (0,0,0,0);
+	//connect to ETel
+
+	TInt err( KErrGeneral );
+    TInt thisTry( 0 );
+    
+	/*All server connections are tried to be made KTiesToConnectServer times because occasional
+    fails on connections are possible at least on some servers*/
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() connect to etel server"));
+    #endif
+	// connect etel server
+	while ( ( err = iServer.Connect() ) != KErrNone && ( thisTry++ ) <= KTriesToConnectServer )
+        {
+        User::After( KTimeBeforeRetryingServerConnection );
+        }
+    User::LeaveIfError( err );
+
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() load tsy"));
+    #endif
+    // load tsy
+    err = iServer.LoadPhoneModule( KMmTsyModuleName );
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() load tsy ERROR: %d"), err);
+    #endif
+    if ( err != KErrAlreadyExists )
+        {
+        // may return also KErrAlreadyExists if some other
+        // is already loaded the tsy module. And that is
+        // not an error.
+        User::LeaveIfError( err );
+        }
+	
+	thisTry = 0;
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() open phone"));
+    #endif
+	//open phone
+	User::LeaveIfError(iServer.SetExtendedErrorGranularity(RTelServer::EErrorExtended));
+	User::LeaveIfError(iServer.GetPhoneInfo(PhoneIndex, PhoneInfo));
+	User::LeaveIfError(iPhone.Open(iServer,PhoneInfo.iName));
+    User::LeaveIfError(iCustomPhone.Open(iPhone));
+ 	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() phone opened"));
+    #endif
+
+    TBool systemLocked = EFalse;
+	TBool autolockValue = EAutolockStatusUninitialized;
+
+    iWait = NULL;
+    iWait = CWait::NewL();
+
+	#ifndef __WINS__
+
+
+	/*****************************************************
+	*	Series 60 Customer / ETEL
+	*	Series 60 ETEL API
+	*****************************************************/
+
+	// set autolock period to 0, if lock is disabled in DOS side
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() set autolock period to 0"));
+    #endif
+	RMobilePhone::TMobilePhoneLock lockType = RMobilePhone::ELockPhoneDevice;
+	RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;
+	RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
+    
+	iWait->SetRequestType(EMobilePhoneGetLockInfo);
+	iPhone.GetLockInfo(iWait->iStatus, lockType, lockInfoPkg);
+	TInt res = iWait->WaitForRequestL();
+	User::LeaveIfError(res);
+    TInt lockValue = 0;
+    CRepository* repository = CRepository::NewL(KCRUidSecuritySettings);
+    TInt cRresult = repository->Get(KSettingsAutolockStatus, lockValue);
+    TBool hiddenReset = HiddenReset();
+    #if defined(_DEBUG)
+    if(hiddenReset)
+        RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() Hidden reset"));
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() CR get result: %d"), cRresult);
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() CR lock value: %d"), lockValue);
+    #endif
+	if (lockInfo.iSetting == RMobilePhone::ELockSetDisabled)
+		{
+        repository->Set(KSettingsAutoLockTime, 0);
+        if ( FeatureManager::FeatureSupported( KFeatureIdProtocolCdma ) )
+            {
+            repository->Set(KSettingsLockOnPowerUp, 0);
+            }
+        }
+    // In CDMA, the system can stay locked on after the boot-up sequence.
+    else if ( FeatureManager::FeatureSupported( KFeatureIdProtocolCdma ) || (hiddenReset && (lockValue == 1)))
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() Hidden reset when locked"));
+        #endif
+        systemLocked = ETrue;
+        }
+
+        
+ 		if ( lockInfo.iSetting == RMobilePhone::ELockSetEnabled && lockValue != EAutolockOff && !hiddenReset)
+		{
+		    #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() EAutolockStatusUninitialized %d"),EAutolockStatusUninitialized);
+        #endif
+        autolockValue = EAutolockStatusUninitialized;					            
+    }
+    else if (lockInfo.iSetting == RMobilePhone::ELockSetDisabled || (hiddenReset && (lockValue == 0)) )
+		{
+		    #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() EAutolockOff %d"),EAutolockOff);
+        #endif
+        autolockValue = EAutolockOff;
+    }
+     
+    delete repository;
+	#endif   //__WINS__
+
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() Enable emergency call support"));
+    #endif
+	
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() Autolock view"));
+    #endif
+    
+
+
+    // -------------------------------------------------------------------------------------------------------------
+    // part of emergency call handling when telephony+devicelock is active
+    // this solution is meant only for 3.1 and 3.2
+
+    iEcsNote = new (ELeave) CEcsNote();
+    iEcsNote->ConstructSleepingNoteL(R_AVKON_EMERGENCY_CALL_NOTE);
+    iEcsNote->ButtonGroupContainer().ButtonGroup()->AsControl()->DrawableWindow()->SetOrdinalPosition(0,2);
+    
+    if (AknLayoutUtils::PenEnabled())	// on touch devices, if Autolock is activated from IdleScreen in landscape, the buttons need to be drawn.
+	{
+	iEcsNote->ButtonGroupContainer().SetCommandL( 0, _L("") );	// as keyboard is locked, these buttons do nothing. Better to hide their labels.
+  	iEcsNote->ButtonGroupContainer().SetCommandL( EAknSoftkeyCancel, _L("") );
+	iEcsNote->ButtonGroupContainer().ButtonGroup()->AsControl()->MakeVisible(ETrue);
+  	}
+
+	// Emergency call support
+    iEcsDetector = CAknEcsDetector::NewL();
+    iEcsDetector->SetObserver( this );
+	iEmergencySupportReady = ETrue;
+    // -------------------------------------------------------------------------------------------------------------
+        
+
+	// Autolock view	
+	CAutolockView* lockView = new(ELeave) CAutolockView;
+    CleanupStack::PushL(lockView);
+    lockView->ConstructL();
+    CleanupStack::Pop();	// lockView
+    AddViewL(lockView);    // transfer ownership to CAknViewAppUi
+	SetDefaultViewL(*lockView);
+
+	// start autolock timer
+	iModel = CAutoLockModel::NewL(this, autolockValue);	
+
+	// phone event observer
+	iPhoneObserver = CValueObserver::NewL(this);
+	//call bubble
+	iIncallBubble = CAknIncallBubble::NewL();
+
+	//Autokeyguard Period observer
+	#ifdef RD_AUTO_KEYGUARD
+	iKeyguardObserver = CAutoKeyguardObserver::NewL();
+	#else //!RD_AUTO_KEYGUARD
+	iKeyguardObserver = NULL;
+	#endif //RD_AUTO_KEYGUARD
+    // Create the write policy. Also processes with write device data can write the value.
+    TSecurityPolicy writePolicy( ECapabilityWriteDeviceData ); 
+	// Create the read policy. Also processes with read device data can read the value.	
+	TSecurityPolicy readPolicy( ECapabilityReadDeviceData ); 
+	
+	TInt tRet = RProperty::Define( KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, RProperty::EInt, readPolicy, writePolicy );
+        
+    if ( tRet != KErrNone )
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL():\
+            FAILED to define the SECUI query Flag: %d"), tRet);
+        #endif
+        }	
+    
+    tRet = RProperty::Define( KPSUidSecurityUIs, KSecurityUIsQueryRequestCancel, RProperty::EInt, readPolicy, writePolicy );
+    if ( tRet != KErrNone )
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL():\
+            FAILED to define the SECUI query request state Flag: %d"), tRet);
+        #endif
+        }
+
+if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))  
+{
+
+    // Define the TARM admin flag.
+    
+    tRet = RProperty::Define( KSCPSIDAutolock, SCP_TARM_ADMIN_FLAG_UID, RProperty::EInt,
+        readPolicy, writePolicy );    
+    if ( tRet != KErrNone )
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL():\
+            FAILED to define the TARM Admin Flag"));
+        #endif
+        }
+        
+    // The following sequence is used to validate the configuration on SCP server.
+    // This is needed on the first boot (initial or RFS) or if the C-drive has been formatted
+    // (3-button format) and Autolock is not active.
+
+    RSCPClient scpClient;
+    if ( scpClient.Connect() == KErrNone )
+        {
+        TInt confStatus = scpClient.CheckConfiguration( KSCPInitial );
+        
+        if ( confStatus == KErrAccessDenied )
+            {
+            #ifndef __WINS__            
+            if ( ( lockInfo.iSetting == RMobilePhone::ELockSetDisabled ) )    
+            #else // __WINS__                    
+            if ( 1 ) // DOS lock is never active in WINS            
+            #endif // __WINS__     
+		        {					
+		        // DOS lock is not active. Note that if DOS is locked, checking the code here will
+		        // mess up the query sequence. On initial startup DOS is not locked.		                
+                
+                TInt finalConfStatus = scpClient.CheckConfiguration( KSCPComplete );
+                
+                if ( finalConfStatus == KErrAccessDenied )
+                    {                
+                    #ifdef __WINS__   
+                    #if defined(_DEBUG)
+                    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL():\
+                        DOS validation FAILED in WINS, something wrong!"));
+                    #endif                                  
+                    #else // !__WINS__                                            
+
+                    // The SCP server is out of sync and Autolock is not active. (c-drive formatted)
+                    // We must ask the security code. ( Note that it is very rare that this is executed )
+	                #if defined(_DEBUG)
+                    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL():\
+                        Lock setting disabled, calling setlocksetting"));
+                    #endif
+                
+                    // Wait here until the startup is complete
+                
+                    TInt tarmErr = KErrNone;
+                    while ( tarmErr == KErrNone )
+                        {                              
+                        TInt sysState=0;
+                            tarmErr = RProperty::Get(KPSUidStartup, KPSGlobalSystemState, sysState);
+
+                            if ((sysState == ESwStateNormalRfOn) || (sysState == ESwStateNormalRfOff) 
+                                 || (sysState == ESwStateNormalBTSap))
+                                {
+                                break;
+                                }                                        
+                        User::After(500000);
+                        }
+                
+                    // Just change the lock setting again to disabled to request the security code.
+                    // Set the TARM flag so SecUi knows it should display the "login" query.
+	                TInt tarmFlag=0;
+	                tRet = RProperty::Get( KSCPSIDAutolock, SCP_TARM_ADMIN_FLAG_UID, tarmFlag );
+	                if ( tRet == KErrNone )
+    	                {
+	                    tarmFlag |= KSCPFlagResyncQuery;
+	                    tRet = RProperty::Set( KSCPSIDAutolock, SCP_TARM_ADMIN_FLAG_UID, tarmFlag );
+	                    }
+	            
+	                if ( tRet != KErrNone )
+                        {
+                        #if defined(_DEBUG)
+                        RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL():\
+                            FAILED to set TARM Admin Flag"));
+                        #endif
+                        }
+	            
+    	            RMobilePhone::TMobilePhoneLockSetting lockChange;
+	                lockChange = RMobilePhone::ELockSetDisabled;
+	                iWait->SetRequestType(EMobilePhoneSetLockSetting);
+                    iPhone.SetLockSetting(iWait->iStatus, lockType, lockChange);
+                
+                    res = iWait->WaitForRequestL();
+                    #endif // __WINS__                                 
+                    }
+                }                        
+                                   
+            } // if ( confStatus == KErrAccessDenied )
+            
+        scpClient.Close();               
+        }
+      
+}
+
+    // Eventhough we might lock the device on boot-up (systemLocked == ETrue), we
+    // want to hide the app until the handshake is done. StartUp application will
+    // active the app when it is finished.
+    if( !systemLocked )
+        {// app to background
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() app to background"));
+        #endif
+        TApaTask self(iCoeEnv->WsSession());
+        self.SetWgId(iCoeEnv->RootWin().Identifier());
+        self.SendToBackground();
+        // flush
+        iCoeEnv->WsSession().Flush();      
+        }
+    else
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL() LOCK SYSTEM"));
+        #endif
+        TInt lockState = 0;
+        
+        #ifdef RD_REMOTELOCK
+	    lockState = EManualLocked; 	    
+	    #else //!RD_REMOTELOCK	    
+	    lockState = EAutolockOn; 	    
+	    #endif//RD_REMOTELOCK
+        iModel->LockSystemL(lockState);  
+        }
+        
+    iGripStatusObserver = CAutolockGripStatusObserver::NewL( this, iEikonEnv->WsSession() ); 
+    iFpsStatusObserver = CAutolockFpsStatusObserver::NewL( this, iEikonEnv->WsSession() ); 
+    iDeviceLockQueryStatus = EFalse;
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::ConstructL()  END"));
+    #endif
+	}
+// ----------------------------------------------------
+// CAutolockAppUi::~CAutolockAppUi()
+// Destructor
+// Frees reserved resources
+// ----------------------------------------------------
+//
+CAutolockAppUi::~CAutolockAppUi()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::~CAutolockAppUi() BEGIN"));
+    #endif
+
+    if(iWait)
+        {
+        // Cancel active requests
+        if(iWait->IsActive())
+            {
+            #if defined(_DEBUG)
+	        RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::~CAutolockAppUi() CANCEL REQ"));
+	        #endif
+            iPhone.CancelAsyncRequest(iWait->GetRequestType());
+            }
+        }
+    //close ETel connections
+    if (iCustomPhone.SubSessionHandle())
+        iCustomPhone.Close();
+    
+    if (iPhone.SubSessionHandle())
+    	iPhone.Close();
+    
+    if (iServer.Handle())
+        {           
+        iServer.UnloadPhoneModule(KMmTsyModuleName);
+        iServer.Close();
+        }
+	delete iModel;
+	delete iPhoneObserver;
+	delete iIncallBubble;
+#ifdef RD_AUTO_KEYGUARD
+	delete iKeyguardObserver;
+#endif
+
+    delete iEcsDetector;
+    delete iEcsNote; // Ecs change
+    delete iWait;
+    FeatureManager::UnInitializeLib();
+    delete iGripStatusObserver;
+    delete iFpsStatusObserver;
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::~CAutolockAppUi() END"));
+    #endif
+	}
+// ----------------------------------------------------
+// CAutolockAppUi::HandleForegroundEventL()
+// Handles foreground event.
+// ----------------------------------------------------
+//
+void CAutolockAppUi::HandleForegroundEventL(TBool aForeground)
+	{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::HandleForegroundEventL()"));
+    #endif
+	if (aForeground )
+		{
+		if (iLocked)
+			{
+			// lock voice key 
+			LockSideKeyL();			
+			}
+		else
+			{
+			// app back to background
+			TApaTask self(iCoeEnv->WsSession());
+			self.SetWgId(iCoeEnv->RootWin().Identifier());
+			self.SendToBackground();
+			}
+		}
+
+	if (!aForeground && iLocked)
+		{
+        TInt callState=0;
+        TInt simStatus=0;
+        RProperty::Get(KPSUidCtsyCallInformation, KCTsyCallState, callState );
+        RProperty::Get(KPSUidStartup, KPSSimStatus, simStatus);
+
+        if (callState == EPSCTsyCallStateNone && simStatus != ESimNotPresent)
+			{	
+			// try put autolock back to foreground
+			TApaTask self(iCoeEnv->WsSession());
+			self.SetWgId(iCoeEnv->RootWin().Identifier());
+			self.BringToForeground();		
+			}
+		else
+			{
+			// unlock voice key while there is active call
+			UnLockSideKey();
+			}
+		}
+
+	CAknAppUi::HandleForegroundEventL(aForeground);
+	
+	}
+	
+
+// ----------------------------------------------------
+// CAutolockAppUi::HandleMessageL
+//
+// Handles the TARM command to unlock the phone.
+// ----------------------------------------------------
+//	
+MCoeMessageObserver::TMessageResponse CAutolockAppUi::HandleMessageL( 
+                                TUint32 aClientHandleOfTargetWindowGroup, 
+                                TUid aMessageUid, 
+                                const TDesC8& aMessageParameters 
+                               )
+    {
+    	
+    	if(!FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))  
+    	{
+    		User::Leave(KErrNotSupported);
+    	}
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::HandleMessageL()"));
+    #endif
+    
+    MCoeMessageObserver::TMessageResponse messageResponse( EMessageHandled );
+    
+    if ( aMessageUid.iUid == SCP_CMDUID_UNLOCK )
+        {        
+        // For security reasons we must check from the SCP server did this 
+        // command originate from it.                                
+        RSCPClient scpClient;
+        if ( scpClient.Connect() == KErrNone )
+            {
+            CleanupClosePushL( scpClient );
+        
+            if ( scpClient.QueryAdminCmd( ESCPCommandUnlockPhone ) )
+                {
+                // Switch autolock to BG
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::HandleMessageL():\
+                    Admin command received, unlocking"));
+                #endif            
+            
+                if ( !iLocked )
+                    {
+                    #if defined(_DEBUG)
+                    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::HandleMessageL():\
+                        Ignoring Unlock message - not locked."));
+                    #endif            
+                    }   
+                else
+                    {
+                    iLocked = EFalse;
+                  DisableWGListChangeEventListening();  
+	                UnLockKeys();
+	                iModel->SetLockedL(EFalse);
+			// Disable keyguard after remote unlock
+	                RAknKeyLock iKeyLock;
+	                TInt tempResult = iKeyLock.Connect();
+	                iKeyLock.DisableKeyLock();
+	                // end Disable keyguard after remote unlock
+	                SwitchToPreviousAppL();
+                    }   
+                }           
+            else
+                {
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::HandleMessageL():\
+                    Unauthorized attempt to unlock"));
+                #endif
+                }
+        
+            CleanupStack::PopAndDestroy(); // scpClient                               
+            }
+        else
+            {          
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::HandleMessageL():\
+                Failed to connect to SCP, ignoring unlock-message."));
+            #endif            
+            
+            }
+        }               
+    else // aMessageUid.iUid != SCP_CMDUID_UNLOCK 
+        {
+        messageResponse = CAknAppUi::HandleMessageL( aClientHandleOfTargetWindowGroup, 
+                                                     aMessageUid,
+                                                     aMessageParameters
+                                                   );
+        }
+    
+    return messageResponse;
+    }
+    	 	
+ 	
+// ------------------------------------------------------------------------------
+// CAutolockAppUi::::DynInitMenuPaneL(TInt aResourceId,CEikMenuPane* aMenuPane)
+//  This function is called by the UIKON framework just before it displays
+//  a menu pane. Its default implementation is empty, and by overriding it,
+//  the application can set the state of menu items dynamically according
+//  to the state of application data.
+// ------------------------------------------------------------------------------
+//
+void CAutolockAppUi::DynInitMenuPaneL(
+    TInt /*aResourceId*/,CEikMenuPane* /*aMenuPane*/)
+    {
+    }
+
+void CAutolockAppUi::HandlePointerEventL(const TPointerEvent& aPointerEvent)
+    {
+    RDebug::Printf( "%s %s (%u) value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+		}
+// ----------------------------------------------------
+// CAutolockAppUi::HandleKeyEventL(
+//     const TKeyEvent& aKeyEvent,TEventCode /*aType*/)
+// ----------------------------------------------------
+//
+TKeyResponse CAutolockAppUi::HandleKeyEventL(
+    const TKeyEvent& aKeyEvent,TEventCode aType)
+    {
+	if ( aKeyEvent.iCode == EKeyBell)
+ 		{
+ 		HandleCommandL(ESecUiCmdUnlock);
+ 		return EKeyWasConsumed; 
+ 		}
+
+    TBool featureNoPowerkey = FeatureManager::FeatureSupported( KFeatureIdNoPowerkey );
+    // If power key pressed, tell SysAp about if
+    if( (aKeyEvent.iScanCode == EStdKeyDevice2 && aType == EEventKeyDown )
+        || (aType == EEventKey && featureNoPowerkey && aKeyEvent.iCode == EKeyNo))
+        {
+        SendMessageToSysAp(EEikKeyLockPowerKeyPressed);
+        if ( featureNoPowerkey )
+            {
+            SendMessageToSysAp(EEikKeyLockLightsOnRequest);              
+            }
+        }
+    return EKeyWasNotConsumed;
+    }
+
+void CAutolockAppUi::SendMessageToSysAp(TInt aMessage)
+    {
+    RWsSession& ws = iEikonEnv->WsSession();
+    TInt wgId=0;
+    CApaWindowGroupName::FindByAppUid(KSysApUid, ws, wgId);
+    if (wgId)
+        {
+        TWsEvent event;
+        event.SetType(aMessage);
+        event.SetTimeNow();
+        ws.SendEventToWindowGroup(wgId, event);
+        }
+    }
+
+// ----------------------------------------------------
+// HideSoftNotification()
+// dismiss all the pending notes just before asking the unlocking code
+// ----------------------------------------------------
+//
+void HideSoftNotification()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)HideSoftNotification"));
+    #endif
+    CAknSoftNotifier *softNotifier = NULL;
+    TRAPD (err, {
+            softNotifier = CAknSoftNotifier::NewL();
+            softNotifier->AddNotificationL(ESetIdleState, 0);
+    };)
+    delete softNotifier;
+    }
+// CAutolockAppUi::HandleCommandL(TInt aCommand)
+// ----------------------------------------------------
+//
+void CAutolockAppUi::HandleCommandL(TInt aCommand)
+    {
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::HandleCommandL()"));
+    #endif
+	switch ( aCommand )
+        {
+        case EEikCmdExit:
+			{
+			#if defined(_DEBUG)
+			RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::HandleCommandL() EEikCmdExit"));
+			#endif
+            Exit();
+            break;
+			}
+        case ESecUiCmdUnlock:
+			{
+			#if defined(_DEBUG)
+			RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::HandleCommandL() ESecUiCmdUnlock"));
+			#endif
+			// stop observing emergency call event
+			iEmergencySupportReady = EFalse;
+			iEcsDetector->Reset(); // Ecs queue is cleared; keys up til here are forgotten
+			// ask secuity code
+			CSecurityHandler* handler = new (ELeave) CSecurityHandler(iPhone);
+			CleanupStack::PushL(handler);
+			TSecUi::InitializeLibL();	
+	        
+	        // Put the lights on when security query is shown
+	        SendMessageToSysAp( EEikSecurityQueryLights );
+	        HideSoftNotification();	// dismiss all the pending notes just before asking the unlocking code
+	        
+            TRAPD(err,
+			{
+			iDeviceLockQueryStatus = ETrue;
+			if(handler->AskSecCodeInAutoLockL())
+				{		
+				iLocked = EFalse;
+				DisableWGListChangeEventListening();
+				iDeviceLockQueryStatus = EFalse;
+				UnLockKeys();
+				iModel->SetLockedL(EFalse);
+				SwitchToPreviousAppL();
+				}
+            else
+				{  // make sure that we will be topmost still
+				    iDeviceLockQueryStatus = EFalse;
+                    TInt callState;
+                    RProperty::Get( KPSUidCtsyCallInformation, KCTsyCallState, callState );
+                if ( callState == EPSCTsyCallStateNone &&
+                     !FeatureManager::FeatureSupported( KFeatureIdProtocolCdma ) )
+                    {
+				    TApaTask self(CCoeEnv::Static()->WsSession());
+				    self.SetWgId(CCoeEnv::Static()->RootWin().Identifier());
+				    self.BringToForeground();
+                    TBool featureNoPowerkey = FeatureManager::FeatureSupported( KFeatureIdNoPowerkey );
+                    if ( featureNoPowerkey )
+                        {//set lights on in case user pressed "red button". If he pressed cancel the lights are on anyway so it doesn't matter.
+                        SendMessageToSysAp(EEikKeyLockLightsOnRequest);              
+                        }
+				    // we don't want enable lock if call in progress    
+                    RProperty::Get( KPSUidCtsyCallInformation, KCTsyCallState, callState );
+                    TInt keyguardDisableState(ECoreAppUIsDisableKeyguardUninitialized);
+                    //If there is alarm on the keyguard status is set to disabled. In that case don't enable keyguard as it will be done by SysAp 
+                    //after the alarm has been disabled/snoozed. Otherwise the alarm CBA is left under keyguard CBA.
+                    RProperty::Get( KPSUidCoreApplicationUIs, KCoreAppUIsDisableKeyguard, keyguardDisableState );
+                    if ((callState == EPSCTsyCallStateNone) && (keyguardDisableState != ECoreAppUIsDisableKeyguard))
+                        {   
+				    	RAknKeyLock keylock;
+					    if ( keylock.Connect() == KErrNone )
+						    {
+						    keylock.EnableAutoLockEmulation();
+						    keylock.Close();
+						    }
+					    }
+                    }
+                }
+			};)
+
+			// start observing emergency call event
+			iEmergencySupportReady = ETrue;
+			CleanupStack::PopAndDestroy(handler); // handler
+			TSecUi::UnInitializeLib();  // secui 		
+			
+			User::LeaveIfError(err);
+
+			break;
+			}
+        default:
+            break;      
+        } 
+    }
+
+// ----------------------------------------------------
+// CAutolockAppUi::SwitchToPreviousAppL()
+// Activates previous app 
+//----------------------------------------------------
+//
+void CAutolockAppUi::SwitchToPreviousAppL()
+	{
+	#if defined(_DEBUG)
+	RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::SwitchToPreviousAppL()"));
+	#endif
+	iEcsDetector->Reset(); // Ecs queue is cleared; keys up til here are forgotten
+	// stop observing phone events
+	iPhoneObserver->Stop();
+	CAknView* view = View(KAutoLockViewId);
+	if(view)
+	  {
+	  STATIC_CAST(CAutolockView*, view)->MakeVisible(EFalse);
+	  }
+	else
+	  {
+	  #if defined(_DEBUG)
+	  RDebug::Printf( "%s %s (%u) no view ????=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, view );
+	  #endif
+	  }
+	// app to background
+	TApaTask self(iCoeEnv->WsSession());
+	self.SetWgId(iCoeEnv->RootWin().Identifier());
+	self.SendToBackground();
+	// flush
+	iCoeEnv->WsSession().Flush();
+	}
+// ----------------------------------------------------
+// CAutolockAppUi::BringAppToForegroundL()
+// Activates autolock app
+//----------------------------------------------------
+//
+void CAutolockAppUi::BringAppToForegroundL()
+	{
+	#if defined(_DEBUG)
+	RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::BringAppToForegroundL()"));
+	#endif
+	TBool tarmAdminFlag(EFalse);
+	TBool remotelockState(EFalse);
+if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))
+{
+    tarmAdminFlag = TarmState();
+}
+
+#ifdef RD_REMOTELOCK
+        TInt autolockState;
+        RProperty::Get(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, autolockState);
+        remotelockState = (autolockState == ERemoteLocked);           
+#endif//RD_REMOTELOCK
+	// If TARM admin flag is set, bring Autolock to foreground regardless of call state.
+	if(!tarmAdminFlag)
+	{   //If phone has been remote locked bring Autolock to foreground regardless of call state.
+	    if(!remotelockState)
+	    {   // check if there is active call
+    	    TInt callState;
+    	    RProperty::Get( KPSUidCtsyCallInformation, KCTsyCallState, callState );
+            if (callState != EPSCTsyCallStateNone )
+                {
+    		    iModel->SetLockedL(EFalse);
+    		    iModel->ResetInactivityTimeout();
+    		    UnLockKeys();
+    		    return;
+    		    }   
+	    }
+	    
+	}
+         		
+
+	#ifndef __WINS__
+
+	#ifndef __NO_DOS__
+
+		/*****************************************************
+		*	Series 60 Customer / ETEL
+		*	Series 60 ETEL API
+		*****************************************************/
+
+	// check that device locked in DOS side too
+	RMobilePhone::TMobilePhoneLock lockType = RMobilePhone::ELockPhoneDevice;
+	RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;
+	RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
+
+	#if defined(_DEBUG)
+	RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::BringAppToForegroundL() GetLockInfo"));
+	#endif
+	iWait->SetRequestType(EMobilePhoneGetLockInfo);
+	iPhone.GetLockInfo(iWait->iStatus, lockType, lockInfoPkg);
+	TInt res = iWait->WaitForRequestL();
+	User::LeaveIfError(res);
+	if (iWait->iStatus == KErrNone)
+		{
+		// if not don't lock ui either
+		#if defined(_DEBUG)
+		RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::BringAppToForegroundL() KErrNone"));
+		#endif
+		if (lockInfo.iSetting == RMobilePhone::ELockSetDisabled)
+			{
+			iModel->SetLockedL(EFalse);
+			UnLockKeys();
+			return;
+			}
+		}
+	#endif
+
+	#endif
+
+	// in case Telephone-app is topmost, then the user is confused because he sees but can't use it.
+	// therefore it's required to hide it, by sending to background. ETMA-7M8A2Y 20090105
+	if ( AknLayoutUtils::PenEnabled() )
+     	{ 		
+   			TApaTaskList apaTaskList(CCoeEnv::Static()->WsSession());
+   			#define KPhoneAppUid TUid::Uid(0x100058B3)
+
+   			TApaTask apaTask = apaTaskList.FindApp(KPhoneAppUid);
+   			if (apaTask.Exists())
+       	{
+			 		#if defined(_DEBUG)
+			 			RDebug::Print(_L("(AUTOLOCK)CAknKeyLockControl::EnableKeylock() Bring phone to background"));
+			 		#endif
+       		// Bring phone to background
+       		apaTask.SendToBackground();
+       	}
+			}	
+	
+	iPhoneObserver->Start();
+	iLocked = ETrue;
+	// app to foreground	
+	TApaTask self(iCoeEnv->WsSession());
+	self.SetWgId(iCoeEnv->RootWin().Identifier());
+	self.BringToForeground();
+	ActivateLocalViewL(KAutoLockViewId);
+	CAknView* view = View(KAutoLockViewId);
+	if(view)
+	  {
+	  STATIC_CAST(CAutolockView*, view)->MakeVisible(ETrue);
+	  }
+	else
+	  {
+	  #if defined(_DEBUG)
+	  RDebug::Printf( "%s %s (%u) no view ????=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, view );
+	  #endif
+	  }
+	}
+
+// ----------------------------------------------------
+// CAutolockAppUi::LockKeysL()
+// locks keys 
+//----------------------------------------------------
+//
+void CAutolockAppUi::LockKeysL()
+	{
+	#if defined(_DEBUG)
+	RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::LockKeysL()"));
+	#endif
+	// capture appkey & volume key
+	if (!iAppKey)
+		{
+		RWindowGroup& groupWin=iCoeEnv->RootWin();
+		iAppKey = groupWin.CaptureKeyUpAndDowns(EStdKeyApplication0, 0, 0); // Capture app key
+		}
+	LockSideKeyL();
+	}
+// ----------------------------------------------------
+// CAutolockAppUi::UnLockKeys()
+// unlocks keys 
+//----------------------------------------------------
+//
+void CAutolockAppUi::UnLockKeys()
+	{
+	#if defined(_DEBUG)
+	RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::UnLockKeysL()"));
+	#endif
+	// uncapture appkey
+	if (iAppKey)
+		{
+		RWindowGroup& groupWin=iCoeEnv->RootWin();
+		groupWin.CancelCaptureKeyUpAndDowns(iAppKey);
+		iAppKey = 0;
+		}
+	UnLockSideKey();
+	}
+// ----------------------------------------------------
+// CAutolockAppUi::LockSideKeyL()
+// unlocks side-key 
+//----------------------------------------------------
+//
+void CAutolockAppUi::LockSideKeyL()
+	{
+	#if defined(_DEBUG)
+	RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::LockSideKeyL()"));
+	#endif
+	if (!iSideKey1)
+		{
+		RWindowGroup& groupWin=iCoeEnv->RootWin();
+		iSideKey1 = groupWin.CaptureKey(EKeySide,0,0);
+		iSideKey2 = groupWin.CaptureKeyUpAndDowns(EStdKeyDevice6, 0, 0);
+		}
+	}
+
+// -------------------------------------------------------------------------------------------------------------
+// part of emergency call handling when telephony+devicelock is active
+// this solution is meant only for 3.1 and 3.2
+void CAutolockAppUi::HandleEcsEvent( CAknEcsDetector* aEcsDetector, CAknEcsDetector::TState aState )
+    {
+    switch ( aState )
+        {
+        case CAknEcsDetector::ECompleteMatchThenSendKey:
+            // Do nothing since note will be removed on ECallAttempted event
+            break;
+        case CAknEcsDetector::ECompleteMatch:
+            iEcsNote->SetEmergencyNumber( aEcsDetector->CurrentMatch() );
+            
+            // Tell sysAp to switch lights on
+            SendMessageToSysAp( EEikEcsQueryLights );
+            
+            iEcsNote->ShowNote();
+            iEcsNote->iNoteOnScreen =ETrue;
+            break;
+        case CAknEcsDetector::EPartialMatch:
+            iEcsNote->SleepNote();
+            break;
+        case CAknEcsDetector::ECallAttempted:
+            iEcsNote->SleepNote();
+            break;
+        case CAknEcsDetector::EEmpty:
+            iEcsNote->SleepNote();
+            break;
+        case CAknEcsDetector::ENoMatch:
+            iEcsNote->SleepNote();
+            break;
+        default:
+            break;
+        }
+    }
+
+CEcsNote::CEcsNote() : iNoteOnScreen( EFalse )
+    {}
+    
+void CEcsNote::ConstructSleepingNoteL(TInt aResourceId)
+    {
+    CAknNoteDialog::ConstructSleepingDialogL(aResourceId);
+    }
+    
+TInt CEcsNote::ShowNote()
+    {
+    ReportUserActivity();
+    iTimeoutInMicroseconds = CAknNoteDialog::EUndefinedTimeout;
+    iTone = CAknNoteDialog::ENoTone;    
+    if (!iNoteOnScreen)
+        {  
+        return RouseSleepingDialog();
+        }
+        // return value not used
+    else
+        // return value not used
+        return NULL;
+    }
+
+void CEcsNote::SleepNote()
+    {
+    if (iNoteOnScreen)
+        ExitSleepingDialog(); // Causes flicker to other notes if called when note is not on screen
+    iNoteOnScreen = EFalse;
+    }
+
+TKeyResponse CEcsNote::OfferKeyEventL(const TKeyEvent& /*aKeyEvent*/, TEventCode /*aType*/)
+    {
+    return EKeyWasConsumed;
+    }
+
+void CEcsNote::SetEmergencyNumber( const TDesC& aMatchedNumber )
+    {
+    TRect screen(iAvkonAppUi->ApplicationRect());
+    TAknLayoutRect mainPane;
+    mainPane.LayoutRect(screen, AKN_LAYOUT_WINDOW_main_pane(screen, 0, 1, 1));
+    TAknLayoutRect popupNoteWindow;
+    AknLayoutUtils::TAknCbaLocation cbaLocation( AknLayoutUtils::CbaLocation() );
+    TInt variety( 0 );
+    if ( cbaLocation == AknLayoutUtils::EAknCbaLocationRight )
+        {
+        variety = 5;
+        }
+    else if ( cbaLocation == AknLayoutUtils::EAknCbaLocationLeft )
+        {
+        variety = 8;
+        }
+    else
+        {
+        variety = 2;
+        }
+
+    popupNoteWindow.LayoutRect(mainPane.Rect(), AknLayoutScalable_Avkon::popup_note_window( variety ));
+    TAknLayoutText textRect;
+    textRect.LayoutText(popupNoteWindow.Rect(), AKN_LAYOUT_TEXT_Note_pop_up_window_texts_Line_1(4));
+
+    // Size of a temporary buffer that contains new lines, spaces and 
+    // emergency number for a note.
+    TBuf16<KAknEcsMaxMatchingLength+80> number;
+    number.Append('\n');
+    number.Append('\n');
+
+    TInt spaceCharWidthInPixels = textRect.Font()->CharWidthInPixels(' ');
+    if (spaceCharWidthInPixels < 1)
+        {
+        // Avoid divide by zero situation even the space char would have zero length.
+        spaceCharWidthInPixels = 1;
+        }
+    
+    TInt length = (textRect.TextRect().Width() - textRect.Font()->TextWidthInPixels(aMatchedNumber))
+                    / spaceCharWidthInPixels;
+
+    const TInt matchedNumberLength = aMatchedNumber.Length();
+    const TInt numberLength = number.Length();
+    const TInt numberMaxLength = number.MaxLength();
+    
+    if ( numberLength + length + matchedNumberLength > numberMaxLength)
+        {
+        // To make sure that buffer overflow does not happen.
+        length = numberMaxLength - numberLength - matchedNumberLength;
+        }
+    for (int i = 0; i < length ; i++)
+        {
+        number.Append(' ');
+        }
+
+    number.Append(aMatchedNumber);
+    TRAP_IGNORE(SetTextL(number));
+
+    }
+        
+// -------------------------------------------------------------------------------------------------------------
+	
+// ----------------------------------------------------
+// CAutolockAppUi::UnLockSideKey()
+// unlocks side-key 
+//----------------------------------------------------
+//
+void CAutolockAppUi::UnLockSideKey()
+	{
+	#if defined(_DEBUG)
+	RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::UnLockSideKeyL()"));
+	#endif
+	if (iSideKey1)
+		{
+		RWindowGroup& groupWin=iCoeEnv->RootWin();
+		groupWin.CancelCaptureKeyUpAndDowns(iSideKey2);
+		groupWin.CancelCaptureKey(iSideKey1);
+		iSideKey1 = 0;
+		iSideKey2 = 0;
+		}
+	}
+	
+
+//
+// ---------------------------------------------------------
+// CAutolockAppUi::HandleScreenDeviceChangedL()
+// Handles screen layout changes, called by CCoeAppUi
+// ---------------------------------------------------------
+//
+void CAutolockAppUi::HandleScreenDeviceChangedL()
+{
+  CAknAppUiBase::HandleScreenDeviceChangedL();
+   //get autolock view from CAknViewAppUi
+  CAknView* view = View(KAutoLockViewId);
+  if(view)
+    {
+        STATIC_CAST(CAutolockView*, view)->ScreenDeviceChanged();
+    }
+  
+}
+
+//
+// ----------------------------------------------------------
+// CAutolockAppUi::IsPinBlocked()
+// Checks whether PIN1/UPIN is blocked
+// ----------------------------------------------------------
+//
+TBool CAutolockAppUi::IsPinBlocked()
+{
+	RMmCustomAPI::TSecurityCodeType secCodeType;
+	TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+	TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+
+	if(wcdmaSupported || upinSupported)
+	  {
+    	RMobilePhone::TMobilePhoneSecurityCode activePin;
+    	iCustomPhone.GetActivePin(activePin);
+    	if(activePin == RMobilePhone::ESecurityUniversalPin)
+    		secCodeType = RMmCustomAPI::ESecurityUniversalPin;
+    	else
+    		secCodeType = RMmCustomAPI::ESecurityCodePin1;
+	  }
+	else 
+	    secCodeType = RMmCustomAPI::ESecurityCodePin1;
+	
+	TBool isBlocked = EFalse;
+    iCustomPhone.IsBlocked(secCodeType,isBlocked);
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::IsPinBlocked result: %d"), isBlocked);
+    #endif
+	return isBlocked;
+}
+
+//
+// ----------------------------------------------------------
+// CAutolockAppUi::HandleWsEventL()
+// 
+// ----------------------------------------------------------
+//
+void CAutolockAppUi::HandleWsEventL( const TWsEvent& aEvent,CCoeControl* aDestination )
+    {
+    	const TInt type = aEvent.Type();
+    	
+    	switch ( type )
+    	{
+    		case KAknFullOrPartialForegroundLost: // partial or full fg lost
+    			if( iIncallBubble )
+                    {
+                    #if defined(_DEBUG)
+    				RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::HandleWsEventL: DISABLE call bubble"));
+    				#endif                    
+                    iIncallBubble->SetIncallBubbleAllowedInIdleL( EFalse );
+                    }
+				break;
+		    case KAknFullOrPartialForegroundGained: // partial or full fg gained
+		    	if( iIncallBubble )
+		           	{
+		             	#if defined(_DEBUG)
+		    			RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::HandleWsEventL: ENABLE call bubble"));
+		    			#endif                      
+		                iIncallBubble->SetIncallBubbleAllowedInIdleL( ETrue );
+		            }
+		    	break;	
+    	    case EEventWindowGroupListChanged:
+    	        HandleWindowGroupListChange();
+    	        break;
+    	    case EEventPointer:
+    	    case EEventDragDrop:
+    	    		{
+    	    		TInt callState = 0;
+    	    		RProperty::Get( KPSUidCtsyCallInformation, KCTsyCallState, callState );
+			        if ( 1==1 || callState == EPSCTsyCallStateNone || callState == EPSCTsyCallStateUninitialized )
+			        	{
+	    	        TPointerEvent *pointer = aEvent.Pointer();
+	    	          CAknView* view = View(KAutoLockViewId);
+								  if(view)
+								    {	
+								        STATIC_CAST(CAutolockView*, view)->ScreenDeviceChanged();
+								    	TRect aCallRect;
+								        STATIC_CAST(CAutolockView*, view)->HandleCall(1, aCallRect);
+   								    	if(aCallButtonRect.iBr.iX==0)
+   								    		aCallButtonRect = TRect (aCallRect);
+								    }
+	    	        if(pointer->iType==TPointerEvent::EButton1Up)
+	    	        	{
+		    	        TPoint iPosition = pointer->iPosition;
+						if(aCallButtonRect.iBr.iX<iPosition.iX && iPosition.iX<aCallButtonRect.iBr.iX+aCallButtonRect.iTl.iX && iPosition.iY<400 )
+	    		        	{
+	    		        		#define KPhoneAppUid1 TUid::Uid(0x100058B3)
+	    		        		TApaTaskList tasklist( iCoeEnv->WsSession() );
+                      TApaTask phonetask = tasklist.FindApp( KPhoneAppUid1 );
+	    		        		if ( phonetask.Exists() )
+                        {
+										    TRawEvent event;
+										    event.Set(TRawEvent::EKeyDown, EStdKeyNo);
+										    iEikonEnv->WsSession().SimulateRawEvent(event);
+                        					User::After(1000);
+										    event.Set(TRawEvent::EKeyUp, EStdKeyNo);
+										    iEikonEnv->WsSession().SimulateRawEvent(event);
+                        }
+	    		        	}
+	    		        }
+	    		      }
+    		      }
+    	        break;
+    	    case EEventKeyUp:	// on touch devices, this happens only for the switch-key, which should turn on the lights.
+    	    case EEventKey:
+    	    case EEventKeyDown:
+    		if(iLocked)
+	    	        SendMessageToSysAp( EEikSecurityQueryLights );
+	    	        break;
+		    default:
+		    	break;
+    	}
+    	
+    	// All events are sent to base class.
+    	CAknViewAppUi::HandleWsEventL( aEvent, aDestination );
+        
+        // part of emergency call handling when telephony+devicelock is active
+        // this solution is meant only for 3.1 and 3.2
+        // Emergency detector only handles key down events
+        if ( iEmergencySupportReady )
+        	iEcsDetector->HandleWsEventL( aEvent, aDestination);    	
+    }
+
+TBool CAutolockAppUi::DeviceLockQueryStatus()
+    {
+    return iDeviceLockQueryStatus;
+    }
+
+TBool CAutolockAppUi::DeviceLockStatus()
+    {
+    return iLocked;
+    }
+
+TBool CAutolockAppUi::DeviceFpsLock(TInt iStatus)
+    {
+		if(iStatus)
+			HandleCommandL(ESecUiCmdUnlock);
+		else
+			iModel->SetLockedL(ETimerLocked);
+    return ETrue;
+    }
+void CAutolockAppUi::HandleWindowGroupListChange()
+    {
+    if ( !iLocked )
+        {
+        // System is not locked, make sure app is not on the foreground.
+        if ( !iCoeEnv->RootWin().OrdinalPosition() )
+            {
+            CAknSgcClient::MoveApp(
+                iCoeEnv->RootWin().Identifier(), 
+                ESgcMoveAppToBackground );
+            }
+        }
+    else
+        {
+		            CAknView* view = View(KAutoLockViewId);
+								  if(view)
+								    {	
+								    	TRect aCallRect;
+								        STATIC_CAST(CAutolockView*, view)->HandleCall(10, aCallRect);
+												if(aCallButtonRect.iBr.iX==0)
+   								    		aCallButtonRect = TRect (aCallRect);
+								    }
+        // So now system is locked. When call is not ongoing, autolock should
+        // be on the foreground.
+        TInt callState = 0;
+        RProperty::Get( KPSUidCtsyCallInformation, KCTsyCallState, callState );
+        if ( callState == EPSCTsyCallStateNone || 
+             callState == EPSCTsyCallStateUninitialized )
+            {
+            // No calls ongoing.
+            if ( iCoeEnv->RootWin().OrdinalPosition() > 0 ) 
+                {
+                // Not on foreground
+                CAknSgcClient::MoveApp(
+                    iCoeEnv->RootWin().Identifier(), 
+                    ESgcMoveAppToForeground );
+                }
+            }
+        }
+    }
+
+TBool CAutolockAppUi::TarmState()
+{
+TBool ret(EFalse);
+if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))
+{
+    // Get the TARM admin flag value
+    TInt tarmFlag;
+	TInt tRet = RProperty::Get( KSCPSIDAutolock, SCP_TARM_ADMIN_FLAG_UID, tarmFlag );
+    
+    if ( tRet != KErrNone )
+        {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::BringAppToForegroundL(): Warning: failed to get TARM Admin Flag state"));
+            #endif
+        }
+    else
+        {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::BringAppToForegroundL(): TARM flag: %d"),
+                tarmFlag );
+            #endif
+        }
+        
+    // Unset the admin flag if set
+    if ( tarmFlag & KSCPFlagAdminLock )
+        {
+        ret = ETrue;
+        TInt tRet = RProperty::Get( KSCPSIDAutolock, SCP_TARM_ADMIN_FLAG_UID, tarmFlag );
+        
+        if ( tRet == KErrNone )
+            {
+            tarmFlag &= ~KSCPFlagAdminLock;
+            tRet = RProperty::Set( KSCPSIDAutolock, SCP_TARM_ADMIN_FLAG_UID, tarmFlag );
+            }
+
+        if ( tRet != KErrNone )
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::BringAppToForegroundL(): FAILED to unset TARM Admin Flag"));
+            #endif
+            }                    
+        }  
+
+}
+return ret;
+}
+
+// ---------------------------------------------------------
+// CAutolockAppUi::HiddenReset()
+// ---------------------------------------------------------
+TBool CAutolockAppUi::HiddenReset()
+    {
+    #if defined(_DEBUG)
+	RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::HiddenReset() begin"));
+	#endif	    				    			
+
+    TBool ret_val ( EFalse );
+	TInt startupReason(ENormalStartup);
+	TInt errorCode(KErrNone);
+	
+	RProperty::Get(KPSUidStartup, KPSStartupReason, startupReason);
+	
+	if ( errorCode != KErrNone )
+		{
+		    #if defined(_DEBUG)
+	        RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::HiddenReset() error getting startup reason"));
+	        #endif
+	    }
+    ret_val = (startupReason != ENormalStartup);
+    #if defined(_DEBUG)
+	RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::HiddenReset() END: %d"), ret_val);
+	#endif
+    return ret_val;
+    }
+void CAutolockAppUi::EnableWGListChangeEventListening()
+{
+	#if defined(_DEBUG)
+	RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::EnableWGListChangeEventListening()"));
+	#endif
+    RWindowGroup& rootWin = iCoeEnv->RootWin();
+    rootWin.EnableGroupListChangeEvents();
+    rootWin.EnableScreenChangeEvents();
+}
+void CAutolockAppUi::DisableWGListChangeEventListening()
+{
+	#if defined(_DEBUG)
+	RDebug::Print(_L("(AUTOLOCK)CAutolockAppUi::DisableWGListChangeEventListening()"));
+	#endif
+    RWindowGroup& rootWin = iCoeEnv->RootWin();
+    rootWin.DisableGroupListChangeEvents();
+    rootWin.DisableScreenChangeEvents();
+}
+// End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/src/AutolockContainer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,355 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+// INCLUDE FILES
+#include "AutolockContainer.h"
+#include <eikenv.h>
+#include <autolock.mbg>
+#include <avkon.hrh>
+#include <aknlayoutscalable_avkon.cdl.h>
+#include <aknlayoutscalable_apps.cdl.h>
+#include <layoutmetadata.cdl.h>
+#include <data_caging_path_literals.hrh>
+#include "AutolockAppUiPS.h"
+#include <Autolock.rsg>
+#include "autolock.hrh"
+#include <eikdef.h>
+
+#include <coreapplicationuisdomainpskeys.h>
+
+#include <AknsLayeredBackgroundControlContext.h>
+#include <AknsDrawUtils.h>
+#include <AknBitmapAnimation.h>
+#include    <AknsUtils.h>
+#include	<AknUtils.h>
+
+#include <e32property.h>
+#include <PSVariables.h>   // Property values
+#include <coreapplicationuisdomainpskeys.h>
+#include <StartupDomainPSKeys.h>
+#include <ctsydomainpskeys.h>
+_LIT(BitmapName,"AutoLock.mbm");
+
+// CONSTANTS
+
+#ifdef RD_FULLSCREEN_WALLPAPER
+enum TAutolockBgLayers
+    {
+    EAutolockBgLayerWallpaper      = 0,    
+    EAutolockBgLayerBackground     = 1,
+    EAutolockBgLayersN             = 2
+    };
+#else
+enum TAutolockBgLayers
+    {
+    EAutolockBgLayerBackground     = 0,
+    EAutolockBgLayerWallpaper      = 1,
+    EAutolockBgLayersN             = 2
+    };
+#endif //RD_FULLSCREEN_WALLPAPER
+
+        TInt aCallRect_x;
+        TInt aCallRect_y;
+        TInt aCallRect_width;
+        TInt aCallRect_height;
+// ================= MEMBER FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// CAutolockContainer::ConstructL(const TRect& aRect)
+// Symbian OS two phased constructor
+// ---------------------------------------------------------
+//
+void CAutolockContainer::ConstructL(const TRect& aRect)
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockContainer::ConstructL"));
+    #endif
+    CreateWindowL();
+
+    HBufC* bitMapPath = HBufC::NewLC(KMaxPath);
+    TPtr BitmapFile(bitMapPath->Des());
+    BitmapFile.Append(_L("Z:"));
+    BitmapFile.Append(KDC_APP_BITMAP_DIR);
+    BitmapFile.Append(BitmapName);
+
+    iEikBitmap = 0;
+    iEikBitmapCall = 0;
+    AknsUtils::CreateIconL( 
+        AknsUtils::SkinInstance(), 
+        KAknsIIDQgnGrafPhoneLocked,
+        iBitmap,
+        iMask,
+        BitmapFile,
+        EMbmAutolockQgn_graf_phone_locked, 
+        EMbmAutolockQgn_graf_phone_locked_mask );
+    AknsUtils::CreateIconL( 
+        AknsUtils::SkinInstance(), 
+        KAknsIIDQgnGrafPhoneLocked,
+        iBitmapCall,
+        iMaskCall,
+        BitmapFile,
+        EMbmAutolockQgn_indi_button_end_call, 
+        EMbmAutolockQgn_indi_button_end_call_mask );
+    
+#ifdef RD_FULLSCREEN_WALLPAPER
+    TSize screenSize = iCoeEnv->ScreenDevice()->SizeInPixels();
+    TRect wallpaperRect( TPoint(0,0), screenSize );    
+    iBgContext = CAknsLayeredBackgroundControlContext::NewL(
+    KAknsIIDWallpaper, wallpaperRect, ETrue, EAutolockBgLayersN );
+    SetRect(aRect);
+#else    
+    // Create background control context for skins. Use parent absolute mode,
+    // as this is window owning control
+    iBgContext = CAknsLayeredBackgroundControlContext::NewL(
+        KAknsIIDQsnBgAreaMainIdle, aRect, ETrue, EAutolockBgLayersN );
+    iBgContext->SetLayerImage( EAutolockBgLayerWallpaper, KAknsIIDWallpaper );
+    iBgContext->SetLayerRect( EAutolockBgLayerWallpaper, aRect );
+    SetRect(aRect);
+#endif // RD_FULLSCREEN_WALLPAPER
+    ActivateL();
+
+    CleanupStack::PopAndDestroy(bitMapPath); //bitMapPath
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockContainer::ConstructL END"));
+    #endif
+    }
+
+
+// ---------------------------------------------------------
+// CAutolockContainer::~CAutolockContainer()
+// Destructor
+// ---------------------------------------------------------
+//
+CAutolockContainer::~CAutolockContainer()
+    {
+    delete iBgContext;
+    delete iBitmap;
+    delete iMask;
+    delete iBitmapCall;
+    delete iMaskCall;
+
+	}
+// ---------------------------------------------------------
+// CAutolockContainer::SizeChanged()
+// Called by framework when the view size is changed
+// ---------------------------------------------------------
+//
+void CAutolockContainer::SizeChanged()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockContainer::SizeChanged()"));
+    #endif
+    
+    TRect mainPaneRect(Rect());
+    TAknLayoutRect idleTradPane;
+    idleTradPane.LayoutRect(mainPaneRect, AknLayoutScalable_Avkon::main_idle_trad_pane());
+
+    TInt variety = 3;
+    if (Layout_Meta_Data::IsLandscapeOrientation())
+        {
+        variety = 2;
+        }
+
+
+    TAknLayoutRect idlePaneG2;
+    idlePaneG2.LayoutRect(idleTradPane.Rect(), AknLayoutScalable_Avkon::main_idle_pane_g2(variety));
+
+    TInt callState = 0;
+	  RProperty::Get( KPSUidCtsyCallInformation, KCTsyCallState, callState );
+    if ( callState == EPSCTsyCallStateNone || callState == EPSCTsyCallStateUninitialized )
+    	{
+    AknIconUtils::SetSize( iBitmap, idlePaneG2.Rect().Size() );
+    	}
+    else
+    	{
+		  TSize lockSize = TSize(0.8 * idlePaneG2.Rect().Size().iWidth, 0.8 * idlePaneG2.Rect().Size().iHeight);
+	    AknIconUtils::SetSize( iBitmap, lockSize );
+    	}
+		TSize callSize = TSize(60,60);
+    AknIconUtils::SetSize( iBitmapCall, callSize );
+    
+#ifdef  RD_FULLSCREEN_WALLPAPER
+    TSize screenSize = iCoeEnv->ScreenDevice()->SizeInPixels();
+    TRect wallpaperRect( TPoint(0,0), screenSize );    
+    iBgContext->SetLayerRect( EAutolockBgLayerBackground, Rect() ) ;
+    iBgContext->SetLayerRect( EAutolockBgLayerWallpaper, wallpaperRect ) ;
+    
+    TPoint origo( 0, 0);
+    iBgContext->SetParentPos(origo);
+#else
+
+    iBgContext->SetLayerRect( EAutolockBgLayerBackground, Rect() ) ;
+    iBgContext->SetLayerRect( EAutolockBgLayerWallpaper, Rect() ) ;
+     
+    TPoint positionRelativeToScreen = PositionRelativeToScreen();
+    //parent must be set when using parent absolute mode.
+    iBgContext->SetParentPos(positionRelativeToScreen);
+#endif //RD_FULLSCREEN_WALLPAPER
+
+        RRegion autolockRegion;
+#ifdef  RD_FULLSCREEN_WALLPAPER    	
+    	autolockRegion.AddRect( wallpaperRect);
+#else    	
+    	autolockRegion.AddRect(Rect());
+#endif //RD_FULLSCREEN_WALLPAPER   
+        Window().SetShape(autolockRegion);
+        autolockRegion.Close();
+    
+     #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockContainer::SizeChanged() END"));
+    #endif
+	 }
+// ---------------------------------------------------------
+// CAutolockContainer::CountComponentControls() const
+// ---------------------------------------------------------
+//
+TInt CAutolockContainer::CountComponentControls() const
+    {
+    TInt controlCount = 0;
+
+    return controlCount;
+    }
+
+// ---------------------------------------------------------
+// CAutolockContainer::ComponentControl(TInt aIndex) const
+// ---------------------------------------------------------
+//
+CCoeControl* CAutolockContainer::ComponentControl(TInt /*aIndex*/) const
+    {
+    return NULL;
+	} 
+ // ---------------------------------------------------------
+// CAutolockContainer::Draw(const TRect& aRect) const
+// ---------------------------------------------------------
+//
+void CAutolockContainer::Draw(const TRect& aRect) const
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockContainer::Draw"));
+    #endif
+    if (AknLayoutUtils::PenEnabled() )
+    	{
+			TInt value = 0;
+			RProperty::Get(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, value);	    
+			if(value <= EAutolockOff)
+				{	// Avoid displaying the icon
+				#if defined(_DEBUG)
+				RDebug::Printf( "%s %s (%u) no Draw value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, value );
+				#endif
+				return;
+				}
+			}
+
+    CWindowGc& gc = SystemGc();
+    gc.SetPenStyle(CGraphicsContext::ENullPen);
+    gc.SetBrushColor(KRgbWhite); 
+    gc.SetBrushStyle(CGraphicsContext::ESolidBrush);
+    MAknsSkinInstance* skin = AknsUtils::SkinInstance();
+    MAknsControlContext* cc = AknsDrawUtils::ControlContext( this );
+    AknsDrawUtils::Background( skin, cc, this, gc, aRect );
+
+    // Draw "lock" icon centered to this control    
+    // fist calculate the correct x coordinate based on this 
+    // controls rect and bitmap width    
+    TInt x = Rect().Width()/2 - iBitmap->SizeInPixels().iWidth /2;
+    // and do same with y
+    TInt y = Rect().Height()/2 - iBitmap->SizeInPixels().iHeight/2;
+		TInt width =iBitmap->SizeInPixels().iWidth;
+		TInt height =iBitmap->SizeInPixels().iHeight;
+      TInt callState = 0;
+  	  RProperty::Get( KPSUidCtsyCallInformation, KCTsyCallState, callState );
+    if ( callState == EPSCTsyCallStateNone || callState == EPSCTsyCallStateUninitialized )
+    	{
+    	}
+    else
+    	{
+    	y-=100;
+    	}
+    
+    if (iBitmap && iMask)
+        {
+          // gc.BitBltMasked(TPoint(x,y),iBitmap,TRect(TPoint(0,0),iBitmap->SizeInPixels()), iMask, ETrue);
+          gc.BitBltMasked(TPoint(x,y),iBitmap,TRect(TPoint(0,0),TPoint(width,height)), iMask, ETrue);
+    	  if ( callState == EPSCTsyCallStateNone || callState == EPSCTsyCallStateUninitialized )
+    	  	{
+    	  }
+    	  else
+    	  	{
+   	    	aCallRect_x=Rect().Width()/2 - iBitmapCall->SizeInPixels().iWidth/2;
+		    	aCallRect_y=Rect().Height() * 0.75;
+		    	aCallRect_width=iBitmapCall->SizeInPixels().iWidth;
+		    	aCallRect_height=iBitmapCall->SizeInPixels().iHeight;
+    	  	TSize cornerSize(20,20); 
+    	  	TSize cornerEllipseSize(cornerSize.iHeight*2,cornerSize.iWidth*2);
+    	  	TRect box(aCallRect_x-3*10	, aCallRect_y-3*10, aCallRect_x+aCallRect_width+3*10, aCallRect_y+aCallRect_height+3*10);
+					TRect cornerRectTl(box.iTl,cornerEllipseSize);
+					gc.SetBrushColor(KRgbRed); 
+					gc.SetBrushStyle(CGraphicsContext::ESolidBrush);
+					gc.SetPenStyle(CGraphicsContext::EDottedPen);
+					gc.DrawRoundRect(box,cornerSize);
+        	gc.BitBltMasked(TPoint(aCallRect_x,aCallRect_y),iBitmapCall,TRect(TPoint(0,0),TPoint(aCallRect_width,aCallRect_height)), iMaskCall, ETrue);
+    	  	aCallRect_y+=100;	// coordinates are realtive to TRect, not to Screen
+        	}
+        }
+    else if (iBitmap && !iMask)
+        {
+        gc.BitBlt(TPoint(x,y),iBitmap);
+    	  if ( callState == EPSCTsyCallStateNone || callState == EPSCTsyCallStateUninitialized )
+    	  	{
+    	  	}
+    	  else
+    	  	{
+        	gc.BitBlt(TPoint(x,y+iBitmap->SizeInPixels().iHeight),iBitmapCall);
+        	}
+        }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockContainer::Draw END"));
+    #endif
+    }
+
+// ---------------------------------------------------------
+// CAutolockContainer::HandleControlEventL(
+//     CCoeControl* aControl,TCoeEvent aEventType)
+// ---------------------------------------------------------
+//
+void CAutolockContainer::HandleControlEventL(
+    CCoeControl* /*aControl*/,TCoeEvent /*aEventType*/)
+    {
+    }
+
+// ---------------------------------------------------------
+// CAutolockContainer::MopSupplyObject
+// 
+// ---------------------------------------------------------
+//
+TTypeUid::Ptr CAutolockContainer::MopSupplyObject( TTypeUid aId )
+    {
+    if (aId.iUid == MAknsControlContext::ETypeId)
+        {
+        return MAknsControlContext::SupplyMopObject( aId, iBgContext );
+        }
+    return CCoeControl::MopSupplyObject( aId );
+    }
+void CAutolockContainer::GiveCoords( TRect& aRect )
+    {
+    	aRect.iBr.iX=aCallRect_x;
+    	aRect.iBr.iY=aCallRect_y;
+    	aRect.iTl.iX=aCallRect_width+2*3*10;
+    	aRect.iTl.iY=aCallRect_height+2*3*10;
+    }
+// End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/src/AutolockDocument.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,75 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+// INCLUDE FILES
+#include <apgwgnam.h>
+#include "AutolockDocument.h"
+#include "AutolockAppUiPS.h"
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------
+// CAutolockDocument::ConstructL()
+// destructor.
+// ----------------------------------------------------
+//
+CAutolockDocument::~CAutolockDocument()
+    {
+    }
+// ----------------------------------------------------
+// CAutolockDocument::ConstructL()
+// Symbian OS default constructor can leave..
+// ----------------------------------------------------
+//
+void CAutolockDocument::ConstructL()
+    {
+    }
+// ----------------------------------------------------
+// CAutolockDocument::NewL()
+// Two-phased constructor.
+// ----------------------------------------------------
+//
+CAutolockDocument* CAutolockDocument::NewL(CEikApplication& aApp)     
+    {
+    CAutolockDocument* self = new (ELeave) CAutolockDocument( aApp );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+// ----------------------------------------------------
+// CAutolockDocument::CreateAppUiL()
+// constructs CAutolockAppUi
+// ----------------------------------------------------
+//
+CEikAppUi* CAutolockDocument::CreateAppUiL()
+    {
+    return new (ELeave) CAutolockAppUi;
+    }
+
+// ----------------------------------------------------
+// CAutolockDocument::UpdateTaskNameL()
+// Sets app hidden...
+// ----------------------------------------------------
+//
+void CAutolockDocument::UpdateTaskNameL( CApaWindowGroupName* aWgName )
+	{
+	CEikDocument::UpdateTaskNameL( aWgName );
+	aWgName->SetHidden( ETrue );
+	}
+// End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/src/AutolockFpsStatusObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,119 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#include <e32base.h>
+#include <e32debug.h>
+#include <AknCapServerDefs.h>
+#include <apgtask.h>
+#include "AutolockFpsStatusObserver.h"
+
+
+EXPORT_C CAutolockFpsStatusObserver* CAutolockFpsStatusObserver::NewL( MAutolockFpsStatusObserver* aObserver, RWsSession& aSession )
+    {
+    CAutolockFpsStatusObserver* self = new (ELeave) CAutolockFpsStatusObserver( aSession );
+    CleanupStack::PushL( self );
+    self->ConstructL( aObserver );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+void CAutolockFpsStatusObserver::ConstructL( MAutolockFpsStatusObserver* aObserver )
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockFpsStatusObserver::ConstructL") );
+    #endif
+const TUid KUidFpsCategory = {0x1020507E };
+
+// PnS key
+const TUint32 KFpsAuthenticationKey = 0x00000001;
+
+    TInt err = iFpsStatus.Attach( KUidFpsCategory, KFpsAuthenticationKey );
+    if ( err )
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)ERROR: Attach failed, err %d"), err );
+        #endif
+        }
+    iObserver = aObserver;
+    CActiveScheduler::Add( this );
+    iFpsStatus.Subscribe( iStatus );
+    SetActive();
+    }
+
+CAutolockFpsStatusObserver::CAutolockFpsStatusObserver( RWsSession& aSession ) : CActive( EPriorityIdle ), iSession( aSession )
+    {
+    }
+
+CAutolockFpsStatusObserver::~CAutolockFpsStatusObserver()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockFpsStatusObserver::~CAutolockFpsStatusObserver") );
+    #endif
+    Cancel();
+    iFpsStatus.Close();
+    }
+
+void CAutolockFpsStatusObserver::DoCancel()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockFpsStatusObserver::DoCancel") );
+    #endif
+    iFpsStatus.Cancel();
+    }
+
+void CAutolockFpsStatusObserver::RunL()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockFpsStatusObserver::RunL") );
+    #endif
+    iFpsStatus.Subscribe( iStatus );
+    SetActive();
+    
+    TInt FpsStatus;
+    TInt err = iFpsStatus.Get( FpsStatus );
+    if( !err )
+    	{
+        FpsStatusChangedL( FpsStatus );
+        }
+    }
+
+void CAutolockFpsStatusObserver::FpsStatusChangedL( TInt aFpsStatus )
+    {
+const TUint32 ESwipeValid = 0x00000001;
+    if( aFpsStatus == ESwipeValid )
+    	{
+        #if defined(_DEBUG)
+    	RDebug::Print(_L("(AUTOLOCK)CAutolockFpsStatusObserver::FpsStatusChangedL => Fps opened"));
+    	#endif 
+    	if( iObserver->DeviceLockStatus() )
+    		{
+            #if defined(_DEBUG)
+        	RDebug::Print(_L("(AUTOLOCK)CAutolockFpsStatusObserver::FpsStatusChangedL => unlocking"));
+        	#endif
+		iObserver->DeviceFpsLock(1);
+    		}
+    	else
+    		{
+            #if defined(_DEBUG)
+        	RDebug::Print(_L("(AUTOLOCK)CAutolockFpsStatusObserver::FpsStatusChangedL => locking"));
+        	#endif
+		iObserver->DeviceFpsLock(0);
+    		}
+        }
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/src/AutolockGripStatusObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,139 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#include <e32base.h>
+#include <e32debug.h>
+#include <AknCapServerDefs.h>
+#include <apgtask.h>
+#include "AutolockGripStatusObserver.h"
+
+
+EXPORT_C CAutolockGripStatusObserver* CAutolockGripStatusObserver::NewL( MAutolockGripStatusObserver* aObserver, RWsSession& aSession )
+    {
+    CAutolockGripStatusObserver* self = new (ELeave) CAutolockGripStatusObserver( aSession );
+    CleanupStack::PushL( self );
+    self->ConstructL( aObserver );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+void CAutolockGripStatusObserver::ConstructL( MAutolockGripStatusObserver* aObserver )
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockGripStatusObserver::ConstructL") );
+    #endif
+    TInt err = iGripStatus.Attach( KPSUidHWRM, KHWRMGripStatus );
+    if ( err )
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(AUTOLOCK)ERROR: Attach failed, err %d"), err );
+        #endif
+        }
+    iObserver = aObserver;
+    CActiveScheduler::Add( this );
+    iGripStatus.Subscribe( iStatus );
+    SetActive();
+    }
+
+CAutolockGripStatusObserver::CAutolockGripStatusObserver( RWsSession& aSession ) : CActive( EPriorityIdle ), iSession( aSession )
+    {
+    }
+
+CAutolockGripStatusObserver::~CAutolockGripStatusObserver()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockGripStatusObserver::~CAutolockGripStatusObserver") );
+    #endif
+    Cancel();
+    iGripStatus.Close();
+    }
+
+void CAutolockGripStatusObserver::DoCancel()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockGripStatusObserver::DoCancel") );
+    #endif
+    iGripStatus.Cancel();
+    }
+
+void CAutolockGripStatusObserver::RunL()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(AUTOLOCK)CAutolockGripStatusObserver::RunL") );
+    #endif
+    iGripStatus.Subscribe( iStatus );
+    SetActive();
+    
+    TInt gripStatus;
+    TInt err = iGripStatus.Get( gripStatus );
+    if( !err )
+    	{
+        GripStatusChangedL( gripStatus );
+        }
+    }
+
+void CAutolockGripStatusObserver::GripStatusChangedL( TInt aGripStatus )
+    {
+    #if defined(_DEBUG)
+	RDebug::Print(_L("(AUTOLOCK)CAutolockGripStatusObserver::::GripStatusChangedL"));
+	#endif   
+    if( aGripStatus == EPSHWRMGripOpen ) 
+    	{
+        #if defined(_DEBUG)
+    	RDebug::Print(_L("(AUTOLOCK)CAutolockGripStatusObserver::::GripStatusChangedL => Grip opened"));
+    	#endif 
+    	if( !iObserver->DeviceLockQueryStatus() && iObserver->DeviceLockStatus() )
+    		{
+            #if defined(_DEBUG)
+        	RDebug::Print(_L("(AUTOLOCK)CAutolockGripStatusObserver::::GripStatusChangedL => send command"));
+        	#endif
+    	    //Grip opened
+        	TApaTaskList tasklist( iSession );
+        	TApaTask capserver = tasklist.FindApp( KAknCapServerUid );
+        	if( capserver.Exists() )
+        	    {
+        	    TKeyEvent key;
+        	    key.iCode = EKeyDevice0;
+        	    key.iModifiers = 0;
+        	    key.iRepeats = 0;
+        	    key.iScanCode = EStdKeyDevice0;
+        	    capserver.SendKey( key );
+        	    }
+
+    		}
+        }
+    else
+        {
+        #if defined(_DEBUG)
+    	RDebug::Print(_L("(AUTOLOCK)CAutolockGripStatusObserver::::GripStatusChangedL => Grip closed"));
+    	#endif 
+        //Grip closed
+        if( iObserver->DeviceLockQueryStatus() )
+        	{
+            #if defined(_DEBUG)
+        	RDebug::Print(_L("(AUTOLOCK)CAutolockGripStatusObserver::::GripStatusChangedL => send key event"));
+        	#endif
+            //the device lock query is on top
+        	//generate cancel key event
+        	TRawEvent rawEvent;
+        	rawEvent.Set( TRawEvent::EKeyDown, KCancelKeyCode );
+        	iSession.SimulateRawEvent( rawEvent );        	
+            }
+        }
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Autolock/src/AutolockWait.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,168 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*	
+*
+*/
+
+
+
+#include    <e32base.h>
+#include	<eikenv.h>
+#include	<eikappui.h>
+#include	"AutolockWait.h"
+
+
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CWait::NewL()	
+// 
+// ----------------------------------------------------------
+// 
+CWait* CWait::NewL()
+    {
+    CWait* self = new(ELeave) CWait();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+//
+// ----------------------------------------------------------
+// CSystemLock::ConstructL()	
+// 
+// ----------------------------------------------------------
+// 
+void CWait::ConstructL()	
+	{	
+	CActiveScheduler::Add(this);			
+	}	
+//
+// ----------------------------------------------------------
+// CWait::CWait()
+// 
+// ----------------------------------------------------------
+//
+CWait::CWait() : CActive(0)
+	{ 
+	}
+//
+// ----------------------------------------------------------
+// CWait::~CWait()
+// Destructor
+// ----------------------------------------------------------
+//
+CWait::~CWait()
+    {
+        Cancel();
+	}
+//
+// ----------------------------------------------------------
+// CWait::StartWaitForRequest
+// 
+// ----------------------------------------------------------
+//
+TInt CWait::WaitForRequestL()
+    {	
+	CWaitAbsorbingControl* absorbing = CWaitAbsorbingControl::NewLC();
+	SetActive();
+	iWait.Start();
+	CleanupStack::PopAndDestroy(absorbing);
+	return iStatus.Int();
+	}
+//
+// ----------------------------------------------------------
+// CWait::RunL()
+// 
+// ----------------------------------------------------------
+// 
+void CWait::RunL()
+	{
+	if(iWait.IsStarted())		
+	    iWait.AsyncStop();
+	}
+//
+// ----------------------------------------------------------
+// CWait::DoCancel()
+// Cancels code request
+// ----------------------------------------------------------
+//
+void CWait::DoCancel()
+    {
+    if(iWait.IsStarted())
+	    iWait.AsyncStop();
+    }
+
+//
+// ----------------------------------------------------------
+// CWait::SetRequestType
+// Sets active request type
+// ----------------------------------------------------------
+//
+void CWait::SetRequestType(TInt aRequestType)
+{
+    iRequestType = aRequestType;
+}
+
+//
+// ----------------------------------------------------------
+// CWait::GetRequestType
+// Gets active request type
+// ----------------------------------------------------------
+//
+TInt CWait::GetRequestType()
+{
+    return iRequestType;
+}
+
+//
+// class CWaitAbsorbingControl
+//
+CWaitAbsorbingControl::CWaitAbsorbingControl()
+	{
+	}
+
+CWaitAbsorbingControl::~CWaitAbsorbingControl()
+	{
+	if (iCoeEnv && iAppUi)
+		iAppUi->RemoveFromStack(this);
+	}
+
+CWaitAbsorbingControl* CWaitAbsorbingControl::NewLC()
+	{
+	CWaitAbsorbingControl* self= new(ELeave) CWaitAbsorbingControl();
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	return self;
+	}
+
+void CWaitAbsorbingControl::ConstructL()
+	{
+	CreateWindowL();
+	SetExtent(TPoint(0,0), TSize(0,0));
+	ActivateL();
+	SetPointerCapture(ETrue);
+	ClaimPointerGrab(ETrue);
+	iAppUi=iEikonEnv->EikAppUi();
+	iAppUi->AddToStackL(this, ECoeStackPriorityEnvironmentFilter);
+	}
+
+TKeyResponse CWaitAbsorbingControl::OfferKeyEventL(const TKeyEvent& /*aKeyEvent*/,TEventCode /*aType*/)
+	{
+	return EKeyWasConsumed;
+	}
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/BWinsCw/SECUI_EKA2U.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,49 @@
+EXPORTS
+	??0CCodeQueryDialog@@QAE@AAVTDes16@@HHHH@Z @ 1 NONAME ; CCodeQueryDialog::CCodeQueryDialog(class TDes16 &, int, int, int, int)
+	??0CSecurityHandler@@QAE@AAVRMobilePhone@@@Z @ 2 NONAME ; CSecurityHandler::CSecurityHandler(class RMobilePhone &)
+	??0CSecuritySettings@@QAE@XZ @ 3 NONAME ; CSecuritySettings::CSecuritySettings(void)
+	??1CManualSecuritySettings@@UAE@XZ @ 4 NONAME ; CManualSecuritySettings::~CManualSecuritySettings(void)
+	??1CSecurityHandler@@UAE@XZ @ 5 NONAME ; CSecurityHandler::~CSecurityHandler(void)
+	??1CSecuritySettings@@UAE@XZ @ 6 NONAME ; CSecuritySettings::~CSecuritySettings(void)
+	??1CSystemLock@@UAE@XZ @ 7 NONAME ; CSystemLock::~CSystemLock(void)
+	?AskPin2L@CSecuritySettings@@QAEHXZ @ 8 NONAME ; int CSecuritySettings::AskPin2L(void)
+	?AskSecCodeInAutoLockL@CSecurityHandler@@QAEHXZ @ 9 NONAME ; int CSecurityHandler::AskSecCodeInAutoLockL(void)
+	?AskSecCodeL@CSecurityHandler@@QAEHXZ @ 10 NONAME ; int CSecurityHandler::AskSecCodeL(void)
+	?AskSecCodeL@CSecuritySettings@@QAEHXZ @ 11 NONAME ; int CSecuritySettings::AskSecCodeL(void)
+	?CancelChangePin@CManualSecuritySettings@@QAEXXZ @ 12 NONAME ; void CManualSecuritySettings::CancelChangePin(void)
+	?CancelLockSim@CManualSecuritySettings@@QAEXXZ @ 13 NONAME ; void CManualSecuritySettings::CancelLockSim(void)
+	?CancelSecCodeQuery@CSecurityHandler@@QAEXXZ @ 14 NONAME ; void CSecurityHandler::CancelSecCodeQuery(void)
+	?CancelUnblockPin@CManualSecuritySettings@@QAEXXZ @ 15 NONAME ; void CManualSecuritySettings::CancelUnblockPin(void)
+	?CancelUnlockSim@CManualSecuritySettings@@QAEXXZ @ 16 NONAME ; void CManualSecuritySettings::CancelUnlockSim(void)
+	?ChangeAutoLockPeriodL@CSecuritySettings@@QAEHH@Z @ 17 NONAME ; int CSecuritySettings::ChangeAutoLockPeriodL(int)
+	?ChangePin2L@CSecuritySettings@@QAEXXZ @ 18 NONAME ; void CSecuritySettings::ChangePin2L(void)
+	?ChangePinL@CManualSecuritySettings@@QAEHW4TPin@1@ABVTDesC16@@11@Z @ 19 NONAME ; int CManualSecuritySettings::ChangePinL(enum CManualSecuritySettings::TPin, class TDesC16 const &, class TDesC16 const &, class TDesC16 const &)
+	?ChangePinL@CSecuritySettings@@QAEXXZ @ 20 NONAME ; void CSecuritySettings::ChangePinL(void)
+	?ChangePinRequestL@CSecuritySettings@@QAEHXZ @ 21 NONAME ; int CSecuritySettings::ChangePinRequestL(void)
+	?ChangeRemoteLockStatusL@CSecuritySettings@@QAEHAAHAAVTDes16@@H@Z @ 22 NONAME ; int CSecuritySettings::ChangeRemoteLockStatusL(int &, class TDes16 &, int)
+	?ChangeSecCodeL@CSecuritySettings@@QAEXXZ @ 23 NONAME ; void CSecuritySettings::ChangeSecCodeL(void)
+	?ChangeSimSecurityL@CSecuritySettings@@QAEHXZ @ 24 NONAME ; int CSecuritySettings::ChangeSimSecurityL(void)
+	?ChangeUPinL@CSecuritySettings@@QAEXXZ @ 25 NONAME ; void CSecuritySettings::ChangeUPinL(void)
+	?ChangeUPinRequestL@CSecuritySettings@@QAEHXZ @ 26 NONAME ; int CSecuritySettings::ChangeUPinRequestL(void)
+	?ConstructL@CSecuritySettings@@QAEXXZ @ 27 NONAME ; void CSecuritySettings::ConstructL(void)
+	?GetFdnMode@CSecuritySettings@@QAEHAAW4TMobilePhoneFdnStatus@RMobilePhone@@@Z @ 28 NONAME ; int CSecuritySettings::GetFdnMode(enum RMobilePhone::TMobilePhoneFdnStatus &)
+	?HandleEventL@CSecurityHandler@@QAEXW4TMobilePhoneSecurityEvent@RMobilePhone@@@Z @ 29 NONAME ; void CSecurityHandler::HandleEventL(enum RMobilePhone::TMobilePhoneSecurityEvent)
+	?HandleEventL@CSecurityHandler@@QAEXW4TMobilePhoneSecurityEvent@RMobilePhone@@AAH@Z @ 30 NONAME ; void CSecurityHandler::HandleEventL(enum RMobilePhone::TMobilePhoneSecurityEvent, int &)
+	?InitializeLibL@TSecUi@@SAXXZ @ 31 NONAME ; void TSecUi::InitializeLibL(void)
+	?IsLockEnabledL@CSecuritySettings@@QAEHW4TMobilePhoneLock@RMobilePhone@@@Z @ 32 NONAME ; int CSecuritySettings::IsLockEnabledL(enum RMobilePhone::TMobilePhoneLock)
+	?IsUpinActive@CSecuritySettings@@QAEHXZ @ 33 NONAME ; int CSecuritySettings::IsUpinActive(void)
+	?IsUpinBlocked@CSecuritySettings@@QAEHXZ @ 34 NONAME ; int CSecuritySettings::IsUpinBlocked(void)
+	?IsUpinSupportedL@CSecuritySettings@@QAEHXZ @ 35 NONAME ; int CSecuritySettings::IsUpinSupportedL(void)
+	?LockSimL@CManualSecuritySettings@@QAEHABVTDesC16@@0@Z @ 36 NONAME ; int CManualSecuritySettings::LockSimL(class TDesC16 const &, class TDesC16 const &)
+	?NewL@CManualSecuritySettings@@SAPAV1@XZ @ 37 NONAME ; class CManualSecuritySettings * CManualSecuritySettings::NewL(void)
+	?NewL@CSecuritySettings@@SAPAV1@XZ @ 38 NONAME ; class CSecuritySettings * CSecuritySettings::NewL(void)
+	?NewL@CSystemLock@@SAPAV1@XZ @ 39 NONAME ; class CSystemLock * CSystemLock::NewL(void)
+	?SetFdnModeL@CSecuritySettings@@QAEXXZ @ 40 NONAME ; void CSecuritySettings::SetFdnModeL(void)
+	?SetLockedL@CSystemLock@@QAEXXZ @ 41 NONAME ; void CSystemLock::SetLockedL(void)
+	?StartObserverL@TObsStarter@@SAXXZ @ 42 NONAME ; void TObsStarter::StartObserverL(void)
+	?SwitchPinCodesL@CSecuritySettings@@QAEHXZ @ 43 NONAME ; int CSecuritySettings::SwitchPinCodesL(void)
+	?UnInitializeLib@TSecUi@@SAXXZ @ 44 NONAME ; void TSecUi::UnInitializeLib(void)
+	?UnblockPinL@CManualSecuritySettings@@QAEHW4TPin@1@ABVTDesC16@@11@Z @ 45 NONAME ; int CManualSecuritySettings::UnblockPinL(enum CManualSecuritySettings::TPin, class TDesC16 const &, class TDesC16 const &, class TDesC16 const &)
+	?UnlockSimL@CManualSecuritySettings@@QAEHABVTDesC16@@0@Z @ 46 NONAME ; int CManualSecuritySettings::UnlockSimL(class TDesC16 const &, class TDesC16 const &)
+	?HandleEventL@CSecurityHandler@@QAEXW4TMobilePhoneSecurityEvent@RMobilePhone@@HAAH@Z @ 47 NONAME ; void CSecurityHandler::HandleEventL(enum RMobilePhone::TMobilePhoneSecurityEvent, int, int &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Bmarm/Secuiu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,46 @@
+EXPORTS
+	__17CSecuritySettings @ 1 NONAME R3UNUSED ; CSecuritySettings::CSecuritySettings(void)
+	AskSecCodeInAutoLockL__16CSecurityHandler @ 2 NONAME R3UNUSED ; CSecurityHandler::AskSecCodeInAutoLockL(void)
+	AskSecCodeL__16CSecurityHandler @ 3 NONAME R3UNUSED ; CSecurityHandler::AskSecCodeL(void)
+	CancelChangePin__23CManualSecuritySettings @ 4 NONAME R3UNUSED ; CManualSecuritySettings::CancelChangePin(void)
+	CancelLockSim__23CManualSecuritySettings @ 5 NONAME R3UNUSED ; CManualSecuritySettings::CancelLockSim(void)
+	CancelSecCodeQuery__16CSecurityHandler @ 6 NONAME R3UNUSED ; CSecurityHandler::CancelSecCodeQuery(void)
+	CancelUnblockPin__23CManualSecuritySettings @ 7 NONAME R3UNUSED ; CManualSecuritySettings::CancelUnblockPin(void)
+	CancelUnlockSim__23CManualSecuritySettings @ 8 NONAME R3UNUSED ; CManualSecuritySettings::CancelUnlockSim(void)
+	ChangeAutoLockPeriodL__17CSecuritySettingsi @ 9 NONAME R3UNUSED ; CSecuritySettings::ChangeAutoLockPeriodL(int)
+	ChangePin2L__17CSecuritySettings @ 10 NONAME R3UNUSED ; CSecuritySettings::ChangePin2L(void)
+	ChangePinL__17CSecuritySettings @ 11 NONAME R3UNUSED ; CSecuritySettings::ChangePinL(void)
+	ChangePinL__23CManualSecuritySettingsQ223CManualSecuritySettings4TPinRC7TDesC16N22 @ 12 NONAME ; CManualSecuritySettings::ChangePinL(CManualSecuritySettings::TPin, TDesC16 const &, TDesC16 const &, TDesC16 const &)
+	ChangePinRequestL__17CSecuritySettings @ 13 NONAME R3UNUSED ; CSecuritySettings::ChangePinRequestL(void)
+	ChangeSecCodeL__17CSecuritySettings @ 14 NONAME R3UNUSED ; CSecuritySettings::ChangeSecCodeL(void)
+	ChangeSimSecurityL__17CSecuritySettings @ 15 NONAME R3UNUSED ; CSecuritySettings::ChangeSimSecurityL(void)
+	ConstructL__17CSecuritySettings @ 16 NONAME R3UNUSED ; CSecuritySettings::ConstructL(void)
+	E32Dll__F10TDllReason @ 17 NONAME R3UNUSED ; E32Dll(TDllReason)
+	GetFdnMode__17CSecuritySettingsRQ212RMobilePhone21TMobilePhoneFdnStatus @ 18 NONAME R3UNUSED ; CSecuritySettings::GetFdnMode(RMobilePhone::TMobilePhoneFdnStatus &)
+	HandleEventL__16CSecurityHandlerQ212RMobilePhone25TMobilePhoneSecurityEvent @ 19 NONAME R3UNUSED ; CSecurityHandler::HandleEventL(RMobilePhone::TMobilePhoneSecurityEvent)
+	InitializeLibL__6TSecUi @ 20 NONAME R3UNUSED ; TSecUi::InitializeLibL(void)
+	IsLockEnabledL__17CSecuritySettingsQ212RMobilePhone16TMobilePhoneLock @ 21 NONAME R3UNUSED ; CSecuritySettings::IsLockEnabledL(RMobilePhone::TMobilePhoneLock)
+	LockSimL__23CManualSecuritySettingsRC7TDesC16T1 @ 22 NONAME R3UNUSED ; CManualSecuritySettings::LockSimL(TDesC16 const &, TDesC16 const &)
+	NewL__11CSystemLock @ 23 NONAME R3UNUSED ; CSystemLock::NewL(void)
+	NewL__17CSecuritySettings @ 24 NONAME R3UNUSED ; CSecuritySettings::NewL(void)
+	NewL__23CManualSecuritySettings @ 25 NONAME R3UNUSED ; CManualSecuritySettings::NewL(void)
+	SetFdnModeL__17CSecuritySettings @ 26 NONAME R3UNUSED ; CSecuritySettings::SetFdnModeL(void)
+	SetLockedL__11CSystemLock @ 27 NONAME R3UNUSED ; CSystemLock::SetLockedL(void)
+	StartObserver__11TObsStarter @ 28 NONAME R3UNUSED ; TObsStarter::StartObserver(void)
+	UnInitializeLib__6TSecUi @ 29 NONAME R3UNUSED ; TSecUi::UnInitializeLib(void)
+	UnblockPinL__23CManualSecuritySettingsQ223CManualSecuritySettings4TPinRC7TDesC16N22 @ 30 NONAME ; CManualSecuritySettings::UnblockPinL(CManualSecuritySettings::TPin, TDesC16 const &, TDesC16 const &, TDesC16 const &)
+	UnlockSimL__23CManualSecuritySettingsRC7TDesC16T1 @ 31 NONAME R3UNUSED ; CManualSecuritySettings::UnlockSimL(TDesC16 const &, TDesC16 const &)
+	"_._11CSystemLock" @ 32 NONAME R3UNUSED ; CSystemLock::~CSystemLock(void)
+	"_._16CSecurityHandler" @ 33 NONAME R3UNUSED ; CSecurityHandler::~CSecurityHandler(void)
+	"_._17CSecuritySettings" @ 34 NONAME R3UNUSED ; CSecuritySettings::~CSecuritySettings(void)
+	"_._23CManualSecuritySettings" @ 35 NONAME R3UNUSED ; CManualSecuritySettings::~CManualSecuritySettings(void)
+	__16CCodeQueryDialogR6TDes16iii @ 36 NONAME ; CCodeQueryDialog::CCodeQueryDialog(TDes16 &, int, int, int)
+	__16CSecurityHandlerR12RMobilePhone @ 37 NONAME R3UNUSED ; CSecurityHandler::CSecurityHandler(RMobilePhone &)
+	AskPin2L__17CSecuritySettings @ 38 NONAME R3UNUSED ; CSecuritySettings::AskPin2L(void)
+	ChangeUPinL__17CSecuritySettings @ 39 NONAME R3UNUSED ; CSecuritySettings::ChangeUPinL(void)
+	ChangeUPinRequestL__17CSecuritySettings @ 40 NONAME R3UNUSED ; CSecuritySettings::ChangeUPinRequestL(void)
+	IsUpinActive__17CSecuritySettings @ 41 NONAME R3UNUSED ; CSecuritySettings::IsUpinActive(void)
+	IsUpinBlocked__17CSecuritySettings @ 42 NONAME R3UNUSED ; CSecuritySettings::IsUpinBlocked(void)
+	IsUpinSupported__17CSecuritySettings @ 43 NONAME R3UNUSED ; CSecuritySettings::IsUpinSupported(void)
+	SwitchPinCodesL__17CSecuritySettings @ 44 NONAME R3UNUSED ; CSecuritySettings::SwitchPinCodesL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Bwins/Secuiu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,46 @@
+EXPORTS
+	??0CCodeQueryDialog@@QAE@AAVTDes16@@HHH@Z @ 1 NONAME ; public: __thiscall CCodeQueryDialog::CCodeQueryDialog(class TDes16 &,int,int,int)
+	??0CSecurityHandler@@QAE@AAVRMobilePhone@@@Z @ 2 NONAME ; public: __thiscall CSecurityHandler::CSecurityHandler(class RMobilePhone &)
+	??0CSecuritySettings@@QAE@XZ @ 3 NONAME ; public: __thiscall CSecuritySettings::CSecuritySettings(void)
+	??1CManualSecuritySettings@@UAE@XZ @ 4 NONAME ; public: virtual __thiscall CManualSecuritySettings::~CManualSecuritySettings(void)
+	??1CSecurityHandler@@UAE@XZ @ 5 NONAME ; public: virtual __thiscall CSecurityHandler::~CSecurityHandler(void)
+	??1CSecuritySettings@@UAE@XZ @ 6 NONAME ; public: virtual __thiscall CSecuritySettings::~CSecuritySettings(void)
+	??1CSystemLock@@UAE@XZ @ 7 NONAME ; public: virtual __thiscall CSystemLock::~CSystemLock(void)
+	?AskPin2L@CSecuritySettings@@QAEHXZ @ 8 NONAME ; public: int __thiscall CSecuritySettings::AskPin2L(void)
+	?AskSecCodeInAutoLockL@CSecurityHandler@@QAEHXZ @ 9 NONAME ; public: int __thiscall CSecurityHandler::AskSecCodeInAutoLockL(void)
+	?AskSecCodeL@CSecurityHandler@@QAEHXZ @ 10 NONAME ; public: int __thiscall CSecurityHandler::AskSecCodeL(void)
+	?CancelChangePin@CManualSecuritySettings@@QAEXXZ @ 11 NONAME ; public: void __thiscall CManualSecuritySettings::CancelChangePin(void)
+	?CancelLockSim@CManualSecuritySettings@@QAEXXZ @ 12 NONAME ; public: void __thiscall CManualSecuritySettings::CancelLockSim(void)
+	?CancelSecCodeQuery@CSecurityHandler@@QAEXXZ @ 13 NONAME ; public: void __thiscall CSecurityHandler::CancelSecCodeQuery(void)
+	?CancelUnblockPin@CManualSecuritySettings@@QAEXXZ @ 14 NONAME ; public: void __thiscall CManualSecuritySettings::CancelUnblockPin(void)
+	?CancelUnlockSim@CManualSecuritySettings@@QAEXXZ @ 15 NONAME ; public: void __thiscall CManualSecuritySettings::CancelUnlockSim(void)
+	?ChangeAutoLockPeriodL@CSecuritySettings@@QAEHH@Z @ 16 NONAME ; public: int __thiscall CSecuritySettings::ChangeAutoLockPeriodL(int)
+	?ChangePin2L@CSecuritySettings@@QAEXXZ @ 17 NONAME ; public: void __thiscall CSecuritySettings::ChangePin2L(void)
+	?ChangePinL@CManualSecuritySettings@@QAEHW4TPin@1@ABVTDesC16@@11@Z @ 18 NONAME ; public: int __thiscall CManualSecuritySettings::ChangePinL(enum CManualSecuritySettings::TPin,class TDesC16 const &,class TDesC16 const &,class TDesC16 const &)
+	?ChangePinL@CSecuritySettings@@QAEXXZ @ 19 NONAME ; public: void __thiscall CSecuritySettings::ChangePinL(void)
+	?ChangePinRequestL@CSecuritySettings@@QAEHXZ @ 20 NONAME ; public: int __thiscall CSecuritySettings::ChangePinRequestL(void)
+	?ChangeSecCodeL@CSecuritySettings@@QAEXXZ @ 21 NONAME ; public: void __thiscall CSecuritySettings::ChangeSecCodeL(void)
+	?ChangeSimSecurityL@CSecuritySettings@@QAEHXZ @ 22 NONAME ; public: int __thiscall CSecuritySettings::ChangeSimSecurityL(void)
+	?ConstructL@CSecuritySettings@@QAEXXZ @ 23 NONAME ; public: void __thiscall CSecuritySettings::ConstructL(void)
+	?E32Dll@@YAHW4TDllReason@@@Z @ 24 NONAME ; int __cdecl E32Dll(enum TDllReason)
+	?GetFdnMode@CSecuritySettings@@QAEHAAW4TMobilePhoneFdnStatus@RMobilePhone@@@Z @ 25 NONAME ; public: int __thiscall CSecuritySettings::GetFdnMode(enum RMobilePhone::TMobilePhoneFdnStatus &)
+	?HandleEventL@CSecurityHandler@@QAEXW4TMobilePhoneSecurityEvent@RMobilePhone@@@Z @ 26 NONAME ; public: void __thiscall CSecurityHandler::HandleEventL(enum RMobilePhone::TMobilePhoneSecurityEvent)
+	?InitializeLibL@TSecUi@@SAXXZ @ 27 NONAME ; public: static void __cdecl TSecUi::InitializeLibL(void)
+	?IsLockEnabledL@CSecuritySettings@@QAEHW4TMobilePhoneLock@RMobilePhone@@@Z @ 28 NONAME ; public: int __thiscall CSecuritySettings::IsLockEnabledL(enum RMobilePhone::TMobilePhoneLock)
+	?LockSimL@CManualSecuritySettings@@QAEHABVTDesC16@@0@Z @ 29 NONAME ; public: int __thiscall CManualSecuritySettings::LockSimL(class TDesC16 const &,class TDesC16 const &)
+	?NewL@CManualSecuritySettings@@SAPAV1@XZ @ 30 NONAME ; public: static class CManualSecuritySettings * __cdecl CManualSecuritySettings::NewL(void)
+	?NewL@CSecuritySettings@@SAPAV1@XZ @ 31 NONAME ; public: static class CSecuritySettings * __cdecl CSecuritySettings::NewL(void)
+	?NewL@CSystemLock@@SAPAV1@XZ @ 32 NONAME ; public: static class CSystemLock * __cdecl CSystemLock::NewL(void)
+	?SetFdnModeL@CSecuritySettings@@QAEXXZ @ 33 NONAME ; public: void __thiscall CSecuritySettings::SetFdnModeL(void)
+	?SetLockedL@CSystemLock@@QAEXXZ @ 34 NONAME ; public: void __thiscall CSystemLock::SetLockedL(void)
+	?StartObserver@TObsStarter@@SAXXZ @ 35 NONAME ; public: static void __cdecl TObsStarter::StartObserver(void)
+	?UnInitializeLib@TSecUi@@SAXXZ @ 36 NONAME ; public: static void __cdecl TSecUi::UnInitializeLib(void)
+	?UnblockPinL@CManualSecuritySettings@@QAEHW4TPin@1@ABVTDesC16@@11@Z @ 37 NONAME ; public: int __thiscall CManualSecuritySettings::UnblockPinL(enum CManualSecuritySettings::TPin,class TDesC16 const &,class TDesC16 const &,class TDesC16 const &)
+	?UnlockSimL@CManualSecuritySettings@@QAEHABVTDesC16@@0@Z @ 38 NONAME ; public: int __thiscall CManualSecuritySettings::UnlockSimL(class TDesC16 const &,class TDesC16 const &)
+	?ChangeUPinL@CSecuritySettings@@QAEXXZ @ 39 NONAME ; public: void __thiscall CSecuritySettings::ChangeUPinL(void)
+	?ChangeUPinRequestL@CSecuritySettings@@QAEHXZ @ 40 NONAME ; public: int __thiscall CSecuritySettings::ChangeUPinRequestL(void)
+	?IsUpinActive@CSecuritySettings@@QAEHXZ @ 41 NONAME ; public: int __thiscall CSecuritySettings::IsUpinActive(void)
+	?IsUpinBlocked@CSecuritySettings@@QAEHXZ @ 42 NONAME ; public: int __thiscall CSecuritySettings::IsUpinBlocked(void)
+	?IsUpinSupported@CSecuritySettings@@QAEHXZ @ 43 NONAME ; public: int __thiscall CSecuritySettings::IsUpinSupported(void)
+	?SwitchPinCodesL@CSecuritySettings@@QAEHXZ @ 44 NONAME ; public: int __thiscall CSecuritySettings::SwitchPinCodesL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Data/SecUi.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1527 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource file
+*    
+*
+*
+*/
+
+
+
+NAME SECU
+
+#include <eikon.rh>
+#include <eikcore.rsg>
+
+#include <avkon.loc>
+#include <secui.loc>
+#include <secui.hrh>
+
+#include <avkon.rsg>
+#include <avkon.rh>
+#include <avkon.hrh>
+#include <avkon.mbg>
+
+
+RESOURCE RSS_SIGNATURE { }
+
+RESOURCE TBUF16 { buf="SecUi"; }
+
+
+#define ESecUiNoteFlags (EEikDialogFlagWait | EEikDialogFlagNoDrag | EEikDialogFlagNoTitleBar | EEikDialogFlagCbaButtons | EEikDialogFlagNotifyEsc)
+#define ESecUiQueryFlags (EGeneralQueryFlags | EEikDialogFlagNotifyEsc)
+
+RESOURCE AVKON_SETTING_PAGE r_autolock_setting_page
+    { 
+    label= qtn_set_autolock;
+    softkey_resource = R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    type =  EAknSetListBox;
+    editor_resource_id= r_autolock_listbox;
+    }
+
+RESOURCE LISTBOX r_autolock_listbox
+    {
+    array_id = r_autolock_lbx;
+    flags = EEikListBoxMultipleSelection;
+    }
+
+//As SecUi loads one resource file manualy in Secui.cpp and because in CDMA we have
+//only this one difference in list box it's easier and cleaner to do the variation 
+//here than having a variation in mmp with a cdma resource file and feature manager in Secui.cpp
+#ifdef __PROTOCOL_CDMA
+
+    RESOURCE ARRAY r_autolock_lbx
+        {
+        items =
+            {
+            LBUF
+                {//autolock off
+                txt = qtn_set_autolock_off;
+                },
+            LBUF
+                {//Power up only
+                txt = qtn_set_lock_on_power_up_only;
+                },
+            LBUF
+                {//user defined (timed and on power up)
+                txt = qtn_set_timed_and_on_power_up;
+                }
+            };      
+        }
+
+#else //If GSM:
+
+    RESOURCE ARRAY r_autolock_lbx
+        {
+        items =
+            {
+            LBUF
+                {//autolock off
+                txt = qtn_set_autolock_off;
+                },
+            LBUF
+                {//user defined
+                txt = qtn_set_autolock_defined;
+                }
+            };      
+    }
+
+#endif //__PROTOCOL_CDMA
+#ifdef RD_REMOTELOCK
+RESOURCE AVKON_SETTING_PAGE r_remotelock_setting_page
+    {
+    label              = qtn_set_remotelock_status;
+    softkey_resource   = R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    type               = EAknSetListBox;
+    editor_resource_id = r_remotelock_listbox;
+    }
+
+RESOURCE LISTBOX r_remotelock_listbox
+    {
+    array_id = r_remotelock_lbx;
+    flags    = EEikListBoxMultipleSelection;
+    }
+
+RESOURCE ARRAY r_remotelock_lbx
+    {
+    items =
+        {
+        LBUF
+            {// Remote Lock enable
+            txt = qtn_set_remotelock_on;
+            },
+        LBUF
+            {// Remote Lock disable
+            txt = qtn_set_remotelock_off;
+            }
+        };
+    }
+
+// Note texts
+RESOURCE TBUF r_remotelock_note_code_error           { buf = qtn_set_remotelock_note_code_error;     }
+RESOURCE TBUF r_remotelock_note_invalid_code         { buf = qtn_set_remotelock_note_invalid_code;   }
+
+// Query prompts
+RESOURCE TBUF r_remotelock_code_prompt               { buf = qtn_set_remotelock_code_prompt;         }
+RESOURCE TBUF r_remotelock_code_confirm_prompt       { buf = qtn_set_remotelock_code_confirm_prompt; }
+
+#endif //RD_REMOTELOCK
+
+
+RESOURCE AVKON_SETTING_PAGE r_fdn_setting_page
+    { 
+    label= text_menu_fdn;
+    softkey_resource = R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    type =  EAknSetListBox;
+    editor_resource_id= r_fdn_listbox;
+    }
+
+RESOURCE LISTBOX r_fdn_listbox
+    {
+    array_id = r_fdn_lbx;
+    flags = EEikListBoxMultipleSelection;
+    }
+
+
+RESOURCE ARRAY r_fdn_lbx
+    {
+    items =
+        {
+        LBUF
+            {//fnd on
+            txt = text_fdn_on;
+            },
+        LBUF
+            {//off
+            txt = text_fdn_off;
+            }
+
+        };  
+    
+    }
+
+
+RESOURCE AVKON_SETTING_PAGE r_pin_setting_page
+    { 
+    label= text_pin_code_cntrl;
+    softkey_resource = R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    type =  EAknSetListBox;
+    editor_resource_id= r_pin_listbox;
+    }
+
+RESOURCE LISTBOX r_pin_listbox
+    {
+    array_id = r_pin_lbx;
+    flags = EEikListBoxMultipleSelection;
+    }
+
+
+RESOURCE ARRAY r_pin_lbx
+    {
+	items =
+		{
+		LBUF
+			{//pin code request on
+			txt = text_pin_code_on;
+			},
+		LBUF
+			{//off
+			txt = text_pin_code_off;
+			}
+
+		};	
+	
+	}
+
+RESOURCE AVKON_SETTING_PAGE r_upin_setting_page
+	{ 
+	label= qtn_set_upin_code_req;
+	softkey_resource = R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+	type =  EAknSetListBox;
+	editor_resource_id= r_upin_listbox;
+	}
+
+RESOURCE LISTBOX r_upin_listbox
+	{
+	array_id = r_upin_lbx;
+	flags = EEikListBoxMultipleSelection;
+	}
+
+
+RESOURCE ARRAY r_upin_lbx
+    {
+	items =
+		{
+		LBUF
+			{//upin code request on
+			txt = text_pin_code_on;
+			},
+		LBUF
+			{//off
+			txt = text_pin_code_off;
+			}
+
+		};	
+	
+	}
+
+RESOURCE AVKON_SETTING_PAGE r_code_in_use_setting_page
+	{ 
+	label= qtn_set_code_in_use;
+	softkey_resource = R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+	type =  EAknSetListBox;
+	editor_resource_id= r_code_listbox;
+	}
+
+RESOURCE LISTBOX r_code_listbox
+	{
+	array_id = r_code_lbx;
+	flags = EEikListBoxMultipleSelection;
+	}
+
+
+RESOURCE ARRAY r_code_lbx
+    {
+	items =
+		{
+		LBUF
+			{//Pin code
+			txt = qtn_set_pin;
+			},
+		LBUF
+			{//Upin code
+			txt = qtn_set_upin;
+			}
+
+		};	
+	
+	}
+
+RESOURCE AVKON_SETTING_PAGE r_security_setting_page
+    { 
+    label= qtn_set_sim_change_sec;
+    softkey_resource = R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    type =  EAknSetListBox;
+    editor_resource_id= r_security_listbox;
+    }
+
+RESOURCE LISTBOX r_security_listbox
+    {
+    array_id = r_security_lbx;
+    flags = EEikListBoxMultipleSelection;
+    }
+
+
+RESOURCE ARRAY r_security_lbx
+    {
+    items =
+        {
+        LBUF
+            {//sim change security on 
+            txt = qtn_set_sim_change_sec_on;
+            },
+        LBUF
+            {//off
+            txt = qtn_set_sim_change_sec_off;
+            }
+
+        };  
+    
+    }
+
+
+
+RESOURCE CBA r_softkeys_call_empty
+{
+buttons =
+        {
+        CBA_BUTTON
+            {
+            id = EAknSoftkeyCall;
+            txt = text_softkey_call;
+            },
+        CBA_BUTTON
+            {
+            id = EAknSoftkeyEmpty;
+            txt = text_softkey_empty;
+            }
+        };
+}
+
+RESOURCE DIALOG r_upin_request_query
+	{
+	flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+	buttons=R_AVKON_SOFTKEYS_OK_EMPTY__OK;
+    items=
+		{
+		DLG_LINE
+			{
+			type=EAknCtQuery;
+			id=EGeneralQuery;
+			control= AVKON_DATA_QUERY 
+				{ 
+					layout = EPinLayout;
+					label = qtn_enter_upin;
+					control = SECRETED
+				{ 
+ 						num_letters=SEC_C_PIN_CODE_MAX_LENGTH;
+						};
+				};
+			}
+		};
+	}
+
+
+RESOURCE DIALOG r_upuk_request_query
+	{
+	flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+	buttons=R_AVKON_SOFTKEYS_OK_EMPTY__OK;
+    items=
+		{
+		DLG_LINE
+			{
+			type=EAknCtQuery;
+			id=EGeneralQuery;
+			control= AVKON_DATA_QUERY 
+				{ 
+					layout = EPinLayout;
+					label = qtn_enter_upuk;
+					control = SECRETED
+				{ 
+ 						num_letters=SEC_C_PUK_CODE_MAX_LENGTH;
+						};
+				};
+			}
+		};
+	}
+
+RESOURCE DIALOG r_upin_query
+	{
+	flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+	buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+		{
+		DLG_LINE
+			{
+			type=EAknCtQuery;
+			id=EGeneralQuery;
+			control= AVKON_DATA_QUERY 
+				{ 
+					layout = EPinLayout;
+					label = qtn_enter_upin;
+					control = SECRETED
+				{ 
+ 						num_letters=SEC_C_PIN_CODE_MAX_LENGTH;
+						};
+				};
+			}
+		};
+	}
+
+RESOURCE DIALOG r_new_upin_code_query
+	{
+	flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+	buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+		{
+		DLG_LINE
+			{
+			type=EAknCtQuery;
+			id=EGeneralQuery;
+			control= AVKON_DATA_QUERY 
+				{ 
+					layout = EPinLayout;
+					label = qtn_set_new_upin;
+					control = SECRETED
+				{ 
+ 						num_letters=SEC_C_PIN_CODE_MAX_LENGTH;
+						};
+				};
+			}
+		};
+	}
+
+RESOURCE DIALOG r_new_upin_code_request_query
+	{
+	flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+	buttons=R_AVKON_SOFTKEYS_OK_EMPTY__OK;
+    items=
+		{
+		DLG_LINE
+			{
+			type=EAknCtQuery;
+			id=EGeneralQuery;
+			control= AVKON_DATA_QUERY 
+				{ 
+					layout = EPinLayout;
+					label = qtn_set_new_upin;
+					control = SECRETED
+				{ 
+ 						num_letters=SEC_C_PIN_CODE_MAX_LENGTH;
+						};
+				};
+			}
+		};
+	}
+
+RESOURCE DIALOG r_verify_new_upin_code_query
+	{
+	flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+	buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+		{
+		DLG_LINE
+			{
+			type=EAknCtQuery;
+			id=EGeneralQuery;
+			control= AVKON_DATA_QUERY 
+				{ 
+					layout = EPinLayout;
+					label = qtn_verify_new_upin;
+					control = SECRETED
+				{ 
+ 						num_letters=SEC_C_PIN_CODE_MAX_LENGTH;
+						};
+				};
+			}
+		};
+	}
+
+RESOURCE DIALOG r_verify_new_upin_code_request_query
+	{
+	flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+	buttons=R_AVKON_SOFTKEYS_OK_EMPTY__OK;
+    items=
+		{
+		DLG_LINE
+			{
+			type=EAknCtQuery;
+			id=EGeneralQuery;
+			control= AVKON_DATA_QUERY 
+				{ 
+					layout = EPinLayout;
+					label = qtn_verify_new_upin;
+					control = SECRETED
+				{ 
+ 						num_letters=SEC_C_PIN_CODE_MAX_LENGTH;
+						};
+				};
+			}
+		};
+	}
+
+
+RESOURCE DIALOG r_pin_request_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_EMPTY__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = text_pin;
+                    control = SECRETED
+                { 
+                        num_letters=SEC_C_PIN_CODE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+
+RESOURCE DIALOG r_puk_request_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_EMPTY__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = qtn_simcd_enter_puk;
+                    control = SECRETED
+                { 
+                        num_letters=SEC_C_PUK_CODE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_puk2_request_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = qtn_simcd_enter_puk2;
+                    control = SECRETED
+                { 
+                        num_letters=SEC_C_PUK2_CODE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+
+
+
+RESOURCE DIALOG r_security_request_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_EMPTY__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = qtn_set_enter_sec_code;
+                    control = SECRETED
+                { 
+                        num_letters=SEC_C_SECURITY_CODE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+
+
+
+RESOURCE DIALOG r_autolock_time_query
+    {
+    flags=ESecUiQueryFlags;
+    buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = ENumberLayout;
+                    label = qtn_set_autolock_define_time;
+                    control = AVKON_INTEGER_EDWIN
+                        {
+                        maxlength = 3;
+                        min=0;
+                        max=999;
+                        unset_value = 0;
+                        };
+                };
+            }
+        };
+    }
+//This is used when KFeatureIdSapDeviceLockEnhancements is defined   
+RESOURCE DIALOG r_sap_autolock_time_query
+    {
+    flags=ESecUiQueryFlags;
+    buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = ENumberLayout;
+                    label = qtn_set_autolock_define_time;
+                    control = AVKON_INTEGER_EDWIN
+                        {
+                        maxlength = 4;
+                        min=0;
+                        max=1440;
+                        unset_value = 0;
+                        };
+                };
+            }
+        };
+    }
+
+#ifdef RD_REMOTELOCK
+RESOURCE DIALOG r_remotelock_code_query
+    {
+    flags   = ESecUiQueryFlags;
+    buttons = R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items   =
+        {
+        DLG_LINE
+            {
+            type    = EAknCtQuery;
+            id      = EGeneralQuery;
+            control = AVKON_DATA_QUERY 
+                {
+                layout  = ECodeLayout;
+                label   = qtn_set_remotelock_code_prompt;
+                control = SECRETED
+                    {
+                    num_letters = SEC_REMOTELOCK_CODE_MAX_LENGTH;
+                    };
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_verify_remotelock_code_query
+    {
+    flags   = ESecUiQueryFlags;
+    buttons = R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items   =
+        {
+        DLG_LINE
+            {
+            type    = EAknCtQuery;
+            id      = EGeneralQuery;
+            control = AVKON_DATA_QUERY 
+                {
+                layout  = ECodeLayout;
+                label   = qtn_set_remotelock_code_confirm_prompt;
+                control = SECRETED
+                    {
+                    num_letters = SEC_REMOTELOCK_CODE_MAX_LENGTH;
+                    };
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_remotelock_codes_dont_match
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = qtn_set_remotelock_note_code_error;
+                    animation = R_QGN_NOTE_ERROR_ANIM;
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_remotelock_invalid_code
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = qtn_set_remotelock_note_invalid_code;
+                    animation = R_QGN_NOTE_ERROR_ANIM;
+                };
+            }
+        };
+    }
+#endif // RD_REMOTELOCK
+
+
+RESOURCE DIALOG r_pin_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = text_pin;
+                    control = SECRETED
+                { 
+                        num_letters=SEC_C_PIN_CODE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+
+RESOURCE DIALOG r_pin2_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = text_pin2;
+                    control = SECRETED
+                        { 
+                        num_letters=SEC_C_PIN2_CODE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+
+RESOURCE DIALOG r_security_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = qtn_set_enter_sec_code;
+                    control = SECRETED
+                        { 
+                        num_letters=SEC_C_SECURITY_CODE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+
+RESOURCE DIALOG r_new_pin_code_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = text_new_pin;
+                    control = SECRETED
+                { 
+                        num_letters=SEC_C_PIN_CODE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_new_pin_code_request_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_EMPTY__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = text_new_pin;
+                    control = SECRETED
+                { 
+                        num_letters=SEC_C_PIN_CODE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+
+
+
+RESOURCE DIALOG r_verify_new_pin_code_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = text_verify_pin;
+                    control = SECRETED
+                { 
+                        num_letters=SEC_C_PIN_CODE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_verify_new_pin_code_request_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_EMPTY__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = text_verify_pin;
+                    control = SECRETED
+                { 
+                        num_letters=SEC_C_PIN_CODE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+
+RESOURCE DIALOG r_new_pin2_code_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = text_new_pin2;
+                    control = SECRETED
+                { 
+                        num_letters=SEC_C_PIN2_CODE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+
+RESOURCE DIALOG r_verify_new_pin2_code_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = text_verify_pin2;
+                    control = SECRETED
+                { 
+                        num_letters=SEC_C_PIN2_CODE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+
+
+RESOURCE DIALOG r_new_security_code_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = qtn_set_new_sec_code;
+                    control = SECRETED
+                { 
+                        num_letters=SEC_C_SECURITY_CODE_CHANGE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+
+RESOURCE DIALOG r_verify_new_security_code_query
+    {
+    flags=ESecUiQueryFlags | EEikDialogFlagVirtualInput;
+    buttons=R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY 
+                { 
+                    layout = EPinLayout;
+                    label = qtn_set_verify_sec_code;
+                    control = SECRETED
+                { 
+                        num_letters=SEC_C_SECURITY_CODE_CHANGE_MAX_LENGTH;
+                        };
+                };
+            }
+        };
+    }
+
+
+
+RESOURCE DIALOG r_confirmation_note
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralQuery;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = text_code_accepted;
+                    animation = R_QGN_NOTE_OK_ANIM;
+                };
+            }
+        };
+    }
+
+
+RESOURCE DIALOG r_security_code_changed_note
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralQuery;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = qtn_set_new_sec_code_changed;
+                    animation = R_QGN_NOTE_OK_ANIM;
+                };
+            }
+        };
+    }
+
+
+
+
+RESOURCE DIALOG r_pin_code_changed_note
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralQuery;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = text_pin_changed;
+                    animation = R_QGN_NOTE_OK_ANIM;
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_upin_code_changed_note
+	{
+	flags=ESecUiNoteFlags;
+	buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+		{
+		DLG_LINE
+			{
+			type=EAknCtNote;
+			id=EGeneralQuery;
+			control= AVKON_NOTE 
+				{ 
+					layout = EGeneralLayout;
+					singular_label = qtn_set_upin_changed;
+					animation = R_QGN_NOTE_OK_ANIM;
+				};
+			}
+		};
+	}
+
+RESOURCE DIALOG r_pin2_code_changed_note
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralQuery;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = text_pin2_changed;
+                    animation = R_QGN_NOTE_OK_ANIM;
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_codes_dont_match
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = text_codes_do_not_match;
+                    animation = R_QGN_NOTE_ERROR_ANIM;
+                };
+            }
+        };
+    }
+
+
+RESOURCE DIALOG r_code_error
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = text_code_error;
+                    animation = R_QGN_NOTE_ERROR_ANIM;
+                };
+            }
+        };
+    }
+
+
+
+RESOURCE DIALOG r_pin_not_allowed
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = text_pin_code_cntrl_set;
+                    animation = R_QGN_NOTE_ERROR_ANIM;
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_upin_not_allowed
+	{
+	flags=ESecUiNoteFlags;
+	buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+		{
+		DLG_LINE
+			{
+	    	type=EAknCtNote;
+			id=EGeneralNote;
+			control= AVKON_NOTE 
+				{ 
+	                layout = EGeneralLayout;
+					singular_label = qtn_set_upin_on;
+					animation = R_QGN_NOTE_ERROR_ANIM;
+				};
+			}
+		};
+	}
+
+RESOURCE DIALOG r_upin_rejected
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = qtn_error_upin_rejected;
+                    animation = R_QGN_NOTE_INFO_ANIM;
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_pin2_rejected
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = text_pin2_rejected;
+                    animation = R_QGN_NOTE_INFO_ANIM;
+                };
+            }
+        };
+    }
+
+
+
+RESOURCE DIALOG r_sec_blocked
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = qtn_set_sec_code_error_wait;
+                    animation = R_QGN_NOTE_ERROR_ANIM;
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_pin2_blocked_note
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = qtn_simcd_enter_puk2;
+                    animation = R_QGN_NOTE_ERROR_ANIM;
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_pin_blocked_note
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = qtn_simcd_enter_puk;
+                    animation = R_QGN_NOTE_ERROR_ANIM;
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_sim_on
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = text_sim_lock_closed;
+                    animation = R_QGN_NOTE_OK_ANIM;
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_sim_off
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = text_sim_lock_opened;
+                    animation = R_QGN_NOTE_OK_ANIM;
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_sim_not_allowed
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = text_sim_lock_not_done;
+                    animation = R_QGN_NOTE_ERROR_ANIM;
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_sim_allready_on
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = text_sim_lock_already_closed;
+                    animation = R_QGN_NOTE_INFO_ANIM;
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_sim_allready_off
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = text_sim_lock_already_open;
+                    animation = R_QGN_NOTE_INFO_ANIM;
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_operation_not_allowed
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = text_not_allowed;
+                    animation = R_QGN_NOTE_ERROR_ANIM;
+                };
+            }
+        };
+    }
+
+RESOURCE DIALOG r_insert_sim
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = qtn_su_note_insert_sim;
+                    animation = R_QGN_NOTE_INFO_ANIM;
+                };
+            }
+        };
+    }
+    
+RESOURCE DIALOG r_emergency_calls_only
+    {
+    flags=ESecUiNoteFlags;
+    buttons=R_AVKON_SOFTKEYS_EMPTY;
+    items=
+        {
+        DLG_LINE
+            {
+            type=EAknCtNote;
+            id=EGeneralNote;
+            control= AVKON_NOTE 
+                { 
+                    layout = EGeneralLayout;
+                    singular_label = qtn_emerg_emergency_only;
+                    animation = R_QGN_NOTE_ERROR_ANIM;
+                };
+            }
+        };
+    }
+    
+#ifdef __SAP_TERMINAL_CONTROL_FW
+    
+RESOURCE TBUF r_secui_text_autolock_must_be_active
+    {   
+    buf = qtn_set_autolock_must_be_active;
+    }
+
+RESOURCE TBUF r_secui_text_enter_sec_code
+    {   
+     buf = qtn_set_enter_sec_code;
+    }
+    
+RESOURCE TBUF r_secui_text_enter_new_sec_code
+    {   
+      buf = qtn_set_new_sec_code;
+    }
+ 
+RESOURCE TBUF r_secui_text_verify_new_sec_code
+    {   
+      buf = qtn_set_verify_sec_code;
+    }                   
+      
+ 
+#endif // __SAP_TERMINAL_CONTROL_FW
+
+//Remaining attempt resource buffers
+
+RESOURCE TBUF r_secui_remaining_pin_attempts
+    {
+      buf = qtn_simcd_attempt_count_pin;
+    }   
+
+RESOURCE TBUF r_secui_remaining_pin2_attempts
+    {
+      buf = qtn_simcd_attempt_count_pin2;
+    }
+
+RESOURCE TBUF r_secui_remaining_upin_attempts
+    {
+      buf = qtn_simcd_attempt_count_upin;
+    }
+
+RESOURCE TBUF r_secui_remaining_puk_attempts
+    {
+      buf = qtn_simcd_attempt_count_puk;
+    }   
+
+RESOURCE TBUF r_secui_remaining_puk2_attempts
+    {
+      buf = qtn_simcd_attempt_count_puk2;
+    }
+
+RESOURCE TBUF r_secui_remaining_upuk_attempts
+    {
+      buf = qtn_simcd_attempt_count_upuk;
+    }
+
+RESOURCE TBUF r_secui_final_pin_attempt
+    {
+      buf = qtn_simcd_final_attempt_pin;
+    }   
+
+RESOURCE TBUF r_secui_final_pin2_attempt
+    {
+      buf = qtn_simcd_final_attempt_pin2;
+    }
+
+RESOURCE TBUF r_secui_final_upin_attempt
+    {
+      buf = qtn_simcd_final_attempt_upin;
+    }
+
+RESOURCE TBUF r_secui_final_puk_attempt
+    {
+      buf = qtn_simcd_final_attempt_puk;
+    }   
+
+RESOURCE TBUF r_secui_final_puk2_attempt
+    {
+      buf = qtn_simcd_final_attempt_puk2;
+    }
+
+RESOURCE TBUF r_secui_final_upuk_attempt
+    {
+      buf = qtn_simcd_final_attempt_upuk;
+    }
+    
+// end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/EABI/Secuiu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,78 @@
+EXPORTS
+	_ZN11CSystemLock10SetLockedLEv @ 1 NONAME
+	_ZN11CSystemLock4NewLEv @ 2 NONAME
+	_ZN11CSystemLockD0Ev @ 3 NONAME
+	_ZN11CSystemLockD1Ev @ 4 NONAME
+	_ZN11CSystemLockD2Ev @ 5 NONAME
+	_ZN11TObsStarter14StartObserverLEv @ 6 NONAME
+	_ZN16CCodeQueryDialogC1ER6TDes16iiii @ 7 NONAME
+	_ZN16CCodeQueryDialogC2ER6TDes16iiii @ 8 NONAME
+	_ZN16CSecurityHandler11AskSecCodeLEv @ 9 NONAME
+	_ZN16CSecurityHandler12HandleEventLEN12RMobilePhone25TMobilePhoneSecurityEventE @ 10 NONAME
+	_ZN16CSecurityHandler12HandleEventLEN12RMobilePhone25TMobilePhoneSecurityEventERi @ 11 NONAME
+	_ZN16CSecurityHandler18CancelSecCodeQueryEv @ 12 NONAME
+	_ZN16CSecurityHandler21AskSecCodeInAutoLockLEv @ 13 NONAME
+	_ZN16CSecurityHandlerC1ER12RMobilePhone @ 14 NONAME
+	_ZN16CSecurityHandlerC2ER12RMobilePhone @ 15 NONAME
+	_ZN16CSecurityHandlerD0Ev @ 16 NONAME
+	_ZN16CSecurityHandlerD1Ev @ 17 NONAME
+	_ZN16CSecurityHandlerD2Ev @ 18 NONAME
+	_ZN17CSecuritySettings10ChangePinLEv @ 19 NONAME
+	_ZN17CSecuritySettings10ConstructLEv @ 20 NONAME
+	_ZN17CSecuritySettings10GetFdnModeERN12RMobilePhone21TMobilePhoneFdnStatusE @ 21 NONAME
+	_ZN17CSecuritySettings11AskSecCodeLEv @ 22 NONAME
+	_ZN17CSecuritySettings11ChangePin2LEv @ 23 NONAME
+	_ZN17CSecuritySettings11ChangeUPinLEv @ 24 NONAME
+	_ZN17CSecuritySettings11SetFdnModeLEv @ 25 NONAME
+	_ZN17CSecuritySettings12IsUpinActiveEv @ 26 NONAME
+	_ZN17CSecuritySettings13IsUpinBlockedEv @ 27 NONAME
+	_ZN17CSecuritySettings14ChangeSecCodeLEv @ 28 NONAME
+	_ZN17CSecuritySettings14IsLockEnabledLEN12RMobilePhone16TMobilePhoneLockE @ 29 NONAME
+	_ZN17CSecuritySettings15SwitchPinCodesLEv @ 30 NONAME
+	_ZN17CSecuritySettings16IsUpinSupportedLEv @ 31 NONAME
+	_ZN17CSecuritySettings17ChangePinRequestLEv @ 32 NONAME
+	_ZN17CSecuritySettings18ChangeSimSecurityLEv @ 33 NONAME
+	_ZN17CSecuritySettings18ChangeUPinRequestLEv @ 34 NONAME
+	_ZN17CSecuritySettings21ChangeAutoLockPeriodLEi @ 35 NONAME
+	_ZN17CSecuritySettings23ChangeRemoteLockStatusLERiR6TDes16i @ 36 NONAME
+	_ZN17CSecuritySettings4NewLEv @ 37 NONAME
+	_ZN17CSecuritySettings8AskPin2LEv @ 38 NONAME
+	_ZN17CSecuritySettingsC1Ev @ 39 NONAME
+	_ZN17CSecuritySettingsC2Ev @ 40 NONAME
+	_ZN17CSecuritySettingsD0Ev @ 41 NONAME
+	_ZN17CSecuritySettingsD1Ev @ 42 NONAME
+	_ZN17CSecuritySettingsD2Ev @ 43 NONAME
+	_ZN23CManualSecuritySettings10ChangePinLENS_4TPinERK7TDesC16S3_S3_ @ 44 NONAME
+	_ZN23CManualSecuritySettings10UnlockSimLERK7TDesC16S2_ @ 45 NONAME
+	_ZN23CManualSecuritySettings11UnblockPinLENS_4TPinERK7TDesC16S3_S3_ @ 46 NONAME
+	_ZN23CManualSecuritySettings13CancelLockSimEv @ 47 NONAME
+	_ZN23CManualSecuritySettings15CancelChangePinEv @ 48 NONAME
+	_ZN23CManualSecuritySettings15CancelUnlockSimEv @ 49 NONAME
+	_ZN23CManualSecuritySettings16CancelUnblockPinEv @ 50 NONAME
+	_ZN23CManualSecuritySettings4NewLEv @ 51 NONAME
+	_ZN23CManualSecuritySettings8LockSimLERK7TDesC16S2_ @ 52 NONAME
+	_ZN23CManualSecuritySettingsD0Ev @ 53 NONAME
+	_ZN23CManualSecuritySettingsD1Ev @ 54 NONAME
+	_ZN23CManualSecuritySettingsD2Ev @ 55 NONAME
+	_ZN6TSecUi14InitializeLibLEv @ 56 NONAME
+	_ZN6TSecUi15UnInitializeLibEv @ 57 NONAME
+	_ZTI11CSystemLock @ 58 NONAME ; #<TI>#
+	_ZTI14CAutolockQuery @ 59 NONAME ; #<TI>#
+	_ZTI16CCodeQueryDialog @ 60 NONAME ; #<TI>#
+	_ZTI16CSecurityHandler @ 61 NONAME ; #<TI>#
+	_ZTI17CSecuritySettings @ 62 NONAME ; #<TI>#
+	_ZTI20CAutoLockSettingPage @ 63 NONAME ; #<TI>#
+	_ZTI21CWaitAbsorbingControl @ 64 NONAME ; #<TI>#
+	_ZTI23CManualSecuritySettings @ 65 NONAME ; #<TI>#
+	_ZTI5CWait @ 66 NONAME ; #<TI>#
+	_ZTV11CSystemLock @ 67 NONAME ; #<VT>#
+	_ZTV14CAutolockQuery @ 68 NONAME ; #<VT>#
+	_ZTV16CCodeQueryDialog @ 69 NONAME ; #<VT>#
+	_ZTV16CSecurityHandler @ 70 NONAME ; #<VT>#
+	_ZTV17CSecuritySettings @ 71 NONAME ; #<VT>#
+	_ZTV20CAutoLockSettingPage @ 72 NONAME ; #<VT>#
+	_ZTV21CWaitAbsorbingControl @ 73 NONAME ; #<VT>#
+	_ZTV23CManualSecuritySettings @ 74 NONAME ; #<VT>#
+	_ZTV5CWait @ 75 NONAME ; #<VT>#
+	_ZN16CSecurityHandler12HandleEventLEN12RMobilePhone25TMobilePhoneSecurityEventEiRi @ 76 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/Data/10207438.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM plugin resource file for Device & SIM Security plugin.
+*
+*/
+
+// INCLUDES
+#include <ecom/registryinfo.rh>
+
+
+RESOURCE REGISTRY_INFO theInfo
+	{
+	dll_uid     = 0x10207438;
+	interfaces  = 
+		{
+		INTERFACE_INFO
+			{
+			interface_uid   = 0x10207236;
+			implementations = 
+				{
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid  = 0x10207439;
+					version_no          = 1;
+					display_name        = "Device & SIM Security Plugin";
+					default_data        = "0x1020743A";
+					opaque_data         = "0";//Order number
+					}
+				};
+			}
+		};
+	}
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/Data/GSSimSecPluginRsc.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,609 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource file for General Settings
+*
+*/
+
+
+
+//  RESOURCE IDENTIFIER
+NAME    SIMS // 4 letter ID
+
+//  INCLUDES
+#include <gssecurity.loc>
+#include "GSSimSecPlugin.hrh"
+#include "GSSimSecPlugin.rh"
+
+#include <avkon.loc> // Avkon localized strings
+#include <avkon.mbg>
+#include <avkon.rsg>
+#include <eikcore.rsg>
+#include <uikon.rh>
+#include <eikon.rh>
+#include <avkon.rh>
+
+// CONSTANTS
+
+//  RESOURCE DEFINITIONS 
+
+RESOURCE RSS_SIGNATURE
+    {
+    }
+
+
+
+//----------------------------------------------------
+//  r_gs_sim_security_view_caption
+// 
+// Security view caption for plugin
+//----------------------------------------------------
+//
+RESOURCE TBUF r_gs_sim_security_view_caption
+    {
+    buf = qtn_set_dev_sim_security;
+    }
+
+
+//----------------------------------------------------
+//   
+//    r_gs_sim_security_view_title
+//    Security view title
+//
+//----------------------------------------------------
+//
+
+RESOURCE TITLE_PANE r_gs_sim_security_view_title
+    {
+    txt = qtn_set_title_security_phone_and_sim;        
+    }
+
+//----------------------------------------------------
+//   
+//    r_gs_sim_security_softkeys_options_back__change
+//    SIM security view's CBA resource
+//
+//----------------------------------------------------
+//
+RESOURCE CBA r_gs_sim_security_softkeys_options_back__change
+    {
+    buttons =
+        {
+        CBA_BUTTON {id=EAknSoftkeyOptions; txt = text_softkey_option;},
+        CBA_BUTTON {id=EAknSoftkeyBack; txt = text_softkey_back; },
+        CBA_BUTTON {id=EAknSoftkeyChange; txt= qtn_msk_change; }
+        };
+    }
+
+//----------------------------------------------------
+//   
+//    r_gs_sim_security_view
+//    SIM security view's menu
+//
+//----------------------------------------------------
+//
+RESOURCE AVKON_VIEW r_gs_sim_security_view
+    {
+    menubar = r_gs_sim_sec_menubar_change_exit;  
+    cba = r_gs_sim_security_softkeys_options_back__change;
+    }
+
+// -----------------------------------------------------------------------------
+//
+// r_gs_menubar_change_exit
+// GS menu with 'change' and 'exit' items.
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE MENU_BAR r_gs_sim_sec_menubar_change_exit
+    {
+    titles =
+        {
+        MENU_TITLE
+            {
+            menu_pane = r_gs_sim_sec_menu_item_exit;
+            },
+        MENU_TITLE
+            {
+            menu_pane = r_gs_sim_sec_menu_item_help;
+            },
+        MENU_TITLE
+            {
+            menu_pane = r_gs_sim_sec_menu_item_change;
+            }
+        };
+    }
+
+// -----------------------------------------------------------------------------
+//
+// r_gs_menu_item_exit
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE MENU_PANE r_gs_sim_sec_menu_item_exit
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            command = EAknCmdExit;
+            txt = qtn_options_exit;
+            }
+        };
+    }
+
+
+// -----------------------------------------------------------------------------
+//
+// r_gs_menu_item_change
+// Change item.
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE MENU_PANE r_gs_sim_sec_menu_item_change
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            flags = EEikMenuItemAction;
+            command = EGSCmdAppChange;
+            txt = qtn_options_change;
+            }
+        };
+    }
+
+// -----------------------------------------------------------------------------
+//
+// r_gs_menu_item_help
+// Change item.
+//
+// -----------------------------------------------------------------------------
+//
+RESOURCE MENU_PANE r_gs_sim_sec_menu_item_help
+    {
+    items =
+        {
+        MENU_ITEM
+            {
+            command = EAknCmdHelp;
+            txt = qtn_options_help;
+            }
+        };
+    }
+
+//----------------------------------------------------
+//   
+//    r_sim_security_lbx
+//    SIM security view's list box items
+//
+//----------------------------------------------------
+//
+RESOURCE SIM_SEC_FEATURE_ARRAY r_sim_security_lbx
+    {
+    items =
+        {
+        SIM_SEC_FEATURE
+            {
+            txt = " \t"qtn_set_code_in_use"\t\t";
+            item = EGSSettIdCodeInUse;
+            type = EGSListBoxItemTypeIsDynamic;
+            },
+        SIM_SEC_FEATURE
+            {
+            txt = " \t"qtn_set_upin_code_req"\t\t";
+            item = EGSSettIdUpinRequest;
+            type = EGSListBoxItemTypeIsDynamic;            
+            },
+        SIM_SEC_FEATURE
+            {
+            txt = " \t"text_pin_code_cntrl"\t\t";
+            item = EGSSettIdPinRequest;
+	    type = EGSListBoxItemTypeIsDynamic;            
+            },
+        SIM_SEC_FEATURE
+            {
+            txt = " \t"text_pin_change"\t\t";
+            item = EGSSettIdPinCode;
+            type = EGSListBoxItemTypeIsDynamic;
+            },
+        SIM_SEC_FEATURE
+            {
+            txt = " \t"qtn_set_upin_code"\t\t";
+            item = EGSSettIdUpinCode;
+            type = EGSListBoxItemTypeIsDynamic;
+            },
+        SIM_SEC_FEATURE
+            {
+            txt = " \t"text_pin2_change"\t\t";
+            item = EGSSettIdPin2Code;
+            },
+        SIM_SEC_FEATURE
+            {
+            txt = " \t"qtn_set_autolock"\t\t";
+            item = EGSSettIdAutolock;
+            },
+        SIM_SEC_FEATURE
+            {
+            txt = " \t"qtn_set_sec_code"\t\t";
+            item = EGSSettIdSecurityCode;
+            },
+        SIM_SEC_FEATURE
+            {
+            txt = " \t"qtn_set_sim_change_sec"\t\t";
+            item = EGSSettIdSimChange;
+            },
+
+#ifdef RD_REMOTELOCK
+        SIM_SEC_FEATURE
+            {
+            txt = " \t"qtn_set_remotelock_status"\t\t";
+            item = EGSSettIdRemoteLock;
+            },
+#endif //RD_REMOTELOCK
+
+        SIM_SEC_FEATURE
+            {
+            txt = " \t"text_closed_user_groups"\t\t";
+            item = EGSSettIdClosedUserGroup;
+            type = EGSListBoxItemTypeIsDynamic;
+            },
+        SIM_SEC_FEATURE
+            {
+            txt = " \t"text_simatk_setting"\t\t";
+            item = EGSSettIdSatOperations;
+            type = EGSListBoxItemTypeIsDynamic;
+            },
+        SIM_SEC_FEATURE
+            {
+            txt = " \t"qtn_op_set_trusted_prov_server"\t\t ";
+            item = EGSSettIdTPServer;
+            type = EGSListBoxItemTypeIsDynamic;
+            }
+        };
+}
+
+//----------------------------------------------------
+//   
+//    r_autolock_array
+//    Autolock array items
+//
+//----------------------------------------------------
+//
+RESOURCE ARRAY r_autolock_array
+    {
+    items =
+        {
+        LBUF
+            {
+            txt = qtn_set_autolock_off;
+            },
+        LBUF
+            {
+            txt = qtn_set_autolock_min_one;
+            },
+        LBUF
+            {
+            txt = qtn_set_autolock_value_min;
+            }
+        };    
+    }
+
+#ifdef RD_REMOTELOCK
+//----------------------------------------------------
+//   
+//    r_remotelock_array
+//    Remote Lock status (on/off) array items
+//
+//----------------------------------------------------
+//
+RESOURCE ARRAY r_remotelock_array
+    {
+    items =
+        {
+        LBUF
+            {
+            txt = qtn_set_remotelock_on;
+            },
+        LBUF
+            {
+            txt = qtn_set_remotelock_off;
+            }
+        };    
+    }
+#endif // RD_REMOTELOCK
+
+//----------------------------------------------------
+//   
+//    r_pin_array
+//    PIN array items
+//
+//----------------------------------------------------
+//
+RESOURCE ARRAY r_pin_array
+    {
+    items =
+        {
+        LBUF
+            {
+            txt = text_pin_code_on;
+            },
+        LBUF
+            {
+            txt = text_pin_code_off;
+            }
+        };    
+    }
+
+//----------------------------------------------------
+//   
+//    r_upin_array
+//    UPIN array items
+//
+//----------------------------------------------------
+//
+RESOURCE ARRAY r_upin_array
+    {
+    items =
+        {
+        LBUF
+            {
+            txt = text_pin_code_on;
+            },
+        LBUF
+            {
+            txt = text_pin_code_off;
+            }
+        };    
+    }
+
+//----------------------------------------------------
+//   
+//    r_code_array
+//    Code in use array items
+//
+//----------------------------------------------------
+//
+RESOURCE ARRAY r_code_array
+    {
+    items =
+        {
+        LBUF
+            {
+            txt = qtn_set_pin;
+            },
+        LBUF
+            {
+            txt = qtn_set_upin;
+            }
+        };    
+    }
+
+
+//----------------------------------------------------
+//   
+//    r_security_array
+//    Security array items
+//
+//----------------------------------------------------
+//
+RESOURCE ARRAY r_security_array
+    {
+    items =
+        {
+        LBUF
+            {
+            txt = qtn_set_sim_change_sec_on;
+            },
+        LBUF
+            {
+            txt = qtn_set_sim_change_sec_off;
+            }
+        };    
+    }
+
+
+//----------------------------------------------------
+//   
+//    r_sat_array
+//    SAT array items
+//
+//----------------------------------------------------
+//
+RESOURCE ARRAY r_sat_array
+    {
+    items =
+        {
+        LBUF
+            {
+            txt = text_simatk_notes_off;
+            },
+        LBUF
+            {
+            txt = text_simatk_notes_on;
+            }
+        };    
+    }
+
+//----------------------------------------------------
+//   
+//    r_cug_network_default
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_cug_network_default { buf = text_cug_default; }
+
+//----------------------------------------------------
+//   
+//    r_cug_on
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_cug_on { buf = text_cug_group; }
+
+//----------------------------------------------------
+//   
+//    r_cug_off
+//
+//----------------------------------------------------
+//
+RESOURCE TBUF r_cug_off { buf = text_cug_suppress; }
+
+//----------------------------------------------------
+//   
+//    r_cug_index
+//    CUG Index dialog resource
+//
+//----------------------------------------------------
+//
+RESOURCE DIALOG r_cug_index
+    {
+    flags=EGeneralQueryFlags; 
+    buttons = R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    items =
+        {
+        DLG_LINE
+            {
+            type=EAknCtQuery;
+            id=EGeneralQuery;
+            control= AVKON_DATA_QUERY             
+                { 
+                layout = ENumberLayout;
+                label = text_give_group_number;
+                control = AVKON_INTEGER_EDWIN         
+                    {
+                    maxlength = 5;
+                    min=0;
+                    max=99999;
+                    };
+
+                };
+            }
+        };
+    }
+  
+//----------------------------------------------------
+//   
+//    r_cug_index_error_note
+//    CUG Index error note dialog resource
+//
+//----------------------------------------------------
+//  
+RESOURCE DIALOG r_cug_index_error_note
+    {
+    flags = EEikDialogFlagNoDrag | EEikDialogFlagNoTitleBar |
+            EEikDialogFlagCbaButtons | EEikDialogFlagWait;
+    buttons = R_AVKON_SOFTKEYS_EMPTY;
+    items =
+        {
+        DLG_LINE
+            {
+            type = EAknCtNote;
+            id = ECugIndexErrorNote;
+            control = AVKON_NOTE 
+                { 
+                layout = EGeneralLayout;
+                singular_label = text_cug_error;
+                animation = R_QGN_NOTE_ERROR_ANIM;
+                };
+            }
+        };
+    }            
+
+
+//----------------------------------------------------
+//   
+//    r_cug_setting_page
+//    CUG setting page dialog resource
+//
+//----------------------------------------------------
+//  
+RESOURCE AVKON_SETTING_PAGE r_cug_setting_page
+    { 
+    label= text_closed_user_groups;
+    softkey_resource = R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    type =  EAknSetListBox;
+    editor_resource_id= r_cug_listbox;
+    }
+
+//----------------------------------------------------
+//   
+//    r_cug_listbox
+//    CUG list box resource
+//
+//----------------------------------------------------
+//  
+RESOURCE LISTBOX r_cug_listbox
+    {
+    array_id = r_cug_lbx;
+    flags = EEikListBoxMultipleSelection;
+    }
+
+
+//----------------------------------------------------
+//   
+//    r_cug_lbx
+//    CUG list box items
+//
+//----------------------------------------------------
+//  
+RESOURCE ARRAY r_cug_lbx
+    {
+    items =
+        {
+        LBUF
+            {
+            txt = text_cug_default;
+            },
+        LBUF
+            {
+            txt = text_cug_group;
+            },
+        LBUF
+            {
+            txt = text_cug_suppress;
+            }
+
+        };
+    }    
+
+
+//----------------------------------------------------
+//   
+//    r_sat_setting_page
+//    SAT setting page resource
+//
+//----------------------------------------------------
+//  
+RESOURCE AVKON_SETTING_PAGE r_sat_setting_page
+    { 
+    label= text_simatk_setting;
+    softkey_resource = R_AVKON_SOFTKEYS_OK_CANCEL__OK;
+    type =  EAknSetListBox;
+    editor_resource_id= r_sat_listbox;
+    }
+
+//----------------------------------------------------
+//   
+//    r_sat_listbox
+//    SAT list box resource
+//
+//----------------------------------------------------
+//  
+RESOURCE LISTBOX r_sat_listbox
+    {
+    array_id = r_sat_array;
+    flags = EEikListBoxMultipleSelection;
+    }
+
+//End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/GSSimSecPlugin.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,91 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project specification file.
+*
+*/
+
+#include <platform_paths.hrh>
+
+#include  <data_caging_paths.hrh>    // For RESOURCE_FILES_DIR
+
+CAPABILITY          CAP_ECOM_PLUGIN
+TARGET              gssimsecplugin.dll
+TARGETTYPE          PLUGIN
+UID                 0x10009D8D 0x10207438
+VENDORID            VID_DEFAULT
+
+
+SOURCEPATH  Src
+SOURCE   GSSimSecPluginImplementationTable.cpp
+SOURCE   GSSimSecPlugin.cpp
+SOURCE   GSSimSecPluginContainer.cpp
+SOURCE   GSSimSecPluginModel.cpp
+SOURCE   GSPubSubsListener.cpp
+
+
+//User include paths
+USERINCLUDE     Inc
+USERINCLUDE     Data // For *.rh
+
+//System include paths
+APP_LAYER_SYSTEMINCLUDE
+
+
+SOURCEPATH      Data
+
+START RESOURCE  10207438.rss
+TARGET          gssimsecplugin.rsc
+END
+
+START RESOURCE  GSSimSecPluginRsc.rss
+HEADER
+TARGETPATH      RESOURCE_FILES_DIR
+LANGUAGE_IDS
+END
+
+
+
+LIBRARY   euser.lib
+LIBRARY   ecom.lib
+LIBRARY   efsrv.lib
+LIBRARY   avkon.lib
+LIBRARY   bafl.lib 
+LIBRARY   cone.lib 
+LIBRARY   eikcoctl.lib 
+LIBRARY   eikcore.lib 
+LIBRARY   egul.lib
+LIBRARY   eikdlg.lib            // eikon dialogs
+LIBRARY   flogger.lib           // File logging
+LIBRARY   commonengine.lib      // For RConeResourceLoader
+LIBRARY   featmgr.lib           // Feature manager 
+LIBRARY   centralrepository.lib
+LIBRARY   aknskinsrv.lib        // for enhanced skinning
+LIBRARY   aknskins.lib          // for enhanced skinning
+LIBRARY   secui.lib             // security
+LIBRARY   etelmm.lib            // security
+LIBRARY   sssettings.lib        // ss settings
+LIBRARY   hlplch.lib            // for "Help" options menu
+LIBRARY   gsecomplugin.lib
+LIBRARY   gsframework.lib       // For base classes
+LIBRARY   gslistbox.lib         // For CGSListBoxItemTextArray
+
+LIBRARY   scpclient.lib
+
+#ifdef RD_REMOTELOCK
+LIBRARY  rlocksettings.lib
+#endif
+
+SMPSAFE
+
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/Inc/GSPubSubsListener.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,129 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Listener for Publish and subscribe data.
+*
+*/
+
+
+#ifndef GSPUBSUBSLISTENER_H
+#define GSPUBSUBSLISTENER_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <e32std.h>
+#include <e32property.h>
+
+// FORWARD DECLARATIONS
+class MGSSettingPSObserver;
+
+// CLASS DECLARATION
+
+/**
+*  RProperty poller.
+*
+*  @lib gs.lib
+*  @since Series 60 3.0
+*/
+NONSHARABLE_CLASS( CGSPubSubsListener ) : public CActive
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        * @param aUid the Uid to use
+        * @param aKey item's key
+        * @param aObserver callback interface for notification
+        * @return instance of CGSPubSubsListener
+        */
+        static CGSPubSubsListener* NewL( const TUid aUid, const TInt aKey, 
+                                         MGSSettingPSObserver* aObserver );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CGSPubSubsListener();
+        
+    public: // New functions.
+
+        /**
+        * Gets integer value from P & S.
+        * @param aVal a value in return
+        * @return error code
+        */       
+        TInt Get( TInt& aVal );
+
+        /**
+        * Gets 8 bit string value from P&S.
+        * @param aVal a value in return
+        * @return error code
+        */
+        TInt Get( TDes8& aVal );
+        
+        /**
+        * Gets 16 bit descriptor value from P&S.
+        * @param aVal a value in return
+        * @return error code
+        */
+        TInt Get( TDes16& aVal );
+        
+    private: // From CActive.
+
+        /** @see CActive::RunL */
+        virtual void RunL();
+
+        /** @see CActive::Cancel */
+        virtual void DoCancel();
+
+        /** @see CActive::RunError */
+        virtual TInt RunError( TInt aError );
+
+        /**
+        * Starts the listening (RunL).
+        */
+        void StartListening();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        * @param aUid the Uid to use
+        * @param aKey item's key
+        * @param aObserver callback interface for notification
+        */
+        CGSPubSubsListener( const TUid aUid,  TInt aKey, 
+                            MGSSettingPSObserver* aObserver );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+    
+    private:    // Data
+    
+        // UID of the monitored item.
+        TUid        iUid;
+        
+        // ID of the monitored item.
+        TInt        iId;
+        
+        // Property to subscribe to.
+        RProperty   iProperty;
+        
+        // The notification interface.
+        MGSSettingPSObserver* iCallback;
+    };
+
+#endif // GSPUBSUBSLISTENER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/Inc/GSSimSecPlugin.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,219 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  View for Device & SIM security plug-in.
+*
+*/
+
+
+#ifndef GSSIMSECPLUGIN_H
+#define GSSIMSECPLUGIN_H
+
+// INCLUDES
+#include "GSSimSecPluginContainer.h"
+#include "GSSimSecPluginModel.h"
+#include "MGSSettingPSObserver.h"
+#include "GSPubSubsListener.h"
+
+#include <aknsettingpage.h>
+#include <ConeResLoader.h>
+#include <gsplugininterface.h>
+#include <gsfwviewuids.h>
+#include <gsbaseview.h>
+#include <secuisecuritysettings.h>
+#include <RSSSettings.h>
+
+// CONSTANTS
+const TInt KMaxStringLength = 80;
+const TUid KGSSimSecPluginUid = { 0x10207438 };
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class CAknViewAppUi;
+class CGSSimSecPluginContainer;
+
+
+// CLASS DECLARATION
+
+/**
+*  CGSSimSecPlugin view class
+*
+*  View class for Sim Security sub-folder
+*/
+class CGSSimSecPlugin : public CGSBaseView,
+                        private MGSSettingPSObserver
+    {
+    public: // Constructors and destructor
+        
+        /**
+        * Symbian OS two-phased constructor
+        * @return GS sim & device security view.
+        */
+        static CGSSimSecPlugin* NewL( TAny* aInitParams );
+        
+        /**
+        * C++ default constructor.
+        */
+        CGSSimSecPlugin();
+
+        /**
+        * Symbian OS default constructor.
+        */
+        void ConstructL();
+
+        /**
+        * Destructor.
+        */
+        ~CGSSimSecPlugin();
+
+    public: // Functions from base classes
+        
+       /**
+        * Returns view id.
+        * @return TUid.
+        */
+        TUid Id() const;
+
+        /**
+        * Handles commands.
+        * @param aCommand Command to be handled.
+        * 
+        */
+        void HandleCommandL( TInt aCommand );
+
+    public: //new
+
+        /**
+        * Updates listbox's item's value.
+        * @param aItemId An item which is updated.
+        * 
+        */
+        void UpdateListBoxL( TInt aItemId );
+        
+        //From CGSBaseView
+        void HandleResourceChangeL( TInt aType );
+
+    public: // From CGSPluginInterface
+
+        /**
+        * @see CGSPluginInterface header file.
+        */
+        void GetCaptionL( TDes& aCaption ) const;
+        
+        /**
+        * @see CGSPluginInterface header file.
+        */
+        TInt PluginProviderCategory() const;
+
+        /**
+        * @see CGSPluginInterface header file.
+        */
+        TBool Visible() const;
+        
+    protected: // From MEikMenuObserver
+
+        void DynInitMenuPaneL( TInt aResourceId, CEikMenuPane* aMenuPane );
+
+    private: // from CAknView
+        /**
+        * Activates the view.
+        * @param aPrevViewId ID of previous view
+        * @param aCustomMessageId customized message ID
+        * @param aCustomMessage sutomized message payload
+        */
+        void DoActivateL( const TVwsViewId& aPrevViewId,
+                          TUid aCustomMessageId,
+                          const TDesC8& aCustomMessage );
+
+    private: // from CGSBaseView
+       
+        void NewContainerL();
+       
+        /**
+        * From CGSBaseView, handles list box selections.
+        * 
+        */
+        void HandleListBoxSelectionL();
+ 
+    private:
+        /**
+        * Callback from MGSSettingPSObserver
+        */
+        void HandleNotifyPSL( const TUid aUid, const TInt& aKey, 
+                                      const TRequestStatus& aStatus );
+      
+    private: //new
+    	
+        /**
+        * Sets Autolock period
+        * 
+        */
+        void SetAutolockTimeL( TInt aPeriod );
+       
+        /**
+        * Set sat operations value (on/off).
+        * 
+        */
+       
+        void SetSatOperationsL();
+       
+        /**
+        * Set sat operations value with setting page(on/off).
+        * 
+        */
+        void SetSatWithSettingPageL();
+       
+        /**
+        * Shows closed user group index query
+        * @param aCugIndex Current Cug index
+        * @param aCugDefault Default CUG index
+        * @return TInt (query result)
+        */
+        TInt CugIndexQueryL( TInt& aCugIndex, TInt& aCugDefault );
+
+        /**
+        * Set closed user group setting
+        * 
+        */
+        void CugModeL();
+       
+        /**
+        * Get CGSSimSecPlugin's ccontainer.
+        */
+        CGSSimSecPluginContainer* Container();
+        
+        
+        TInt SetRemoteLockStatusL( TInt aAutoLockPeriod );
+        
+    private: // Data
+        //for CUG settings
+        RSSSettings        iCugSettings;
+        //to launch SecUI
+        CSecuritySettings* iSecurity;
+        //plugin model.
+        CGSSimSecPluginModel* iModel;
+        //resource loader
+        RConeResourceLoader iResourceLoader;
+        //PubSub object for BT SAP state
+        CGSPubSubsListener* iBtSapListener;
+
+    };
+
+#endif //GSSIMSECPLUGIN_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/Inc/GSSimSecPlugin.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,79 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  contains common definitions for menu id:s
+*
+*/
+
+
+#ifndef GSSIMSECPLUGIN_HRH
+#define GSSIMSECPLUGIN_HRH
+
+// Data query max length
+#define KGSMaxDataLength 21
+
+enum TSimSecMenuCommands
+    {
+    EGSCmdAppOpen = 1,
+    EGSCmdAppHelp,
+    EGSCmdAppChange,
+    EAppCmdChange
+    };
+
+enum TCugPopupIndex
+    {
+    EGSCugNetworkDefault = 0, 
+    EGSCugOn = 1,
+    EGSCugOff = 2
+    };
+
+enum TGSNotes
+    { 
+    EPasswordErrorNote,
+    EPasswordChangedNote,
+    ECugIndexErrorNote
+    };
+
+
+// Device & SIM security
+enum {
+    EGSSettIdPinRequest,
+    EGSSettIdPinCode,
+    EGSSettIdPin2Code,
+    EGSSettIdAutolock,
+    EGSSettIdSecurityCode,
+    EGSSettIdSimChange,
+    EGSSettIdClosedUserGroup,
+    EGSSettIdSatOperations,
+    EGSSettIdTPServer,
+    EGSSettIdUpinRequest,
+    EGSSettIdCodeInUse,
+    EGSSettIdUpinCode,
+    EGSSettIdDevAndSim,
+    EGSSettIdCertManUi,
+    EGSSettIdWlanEapPlugins,
+    EGSSettIdWimSecurity,
+    EGSSettIdTransTracking,
+    EGSSettIdAutoKeyguard,
+    EGSSettIdRemoteLock
+    };
+
+enum TGSListBoxItemVisibility
+    {
+    EGSListBoxItemTypeIsAlwaysVisible = 0,
+    EGSListBoxItemTypeIsDynamic
+    };
+#endif  //GSSIMSECPLUGIN_HRH
+
+//End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/Inc/GSSimSecPlugin.rh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2003-2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Contains common declarations for resources of GS.
+*                The file can be included only in resource file.
+*
+*/
+
+#ifndef GSSIMSEC_RH
+#define GSSIMSEC_RH
+
+
+// Global definitions
+
+
+// ---------------------------------------------------------
+//    sim_sec_feature_array
+//    Defines a structure to contain information about items 
+//    to be able to included in the listbox.
+// ---------------------------------------------------------
+//
+STRUCT SIM_SEC_FEATURE_ARRAY
+    {
+    STRUCT items[];
+    }
+
+// ---------------------------------------------------------
+//    sim_sec_feature
+//    Defines a structure that contains information about 
+//    a single listbox item.
+// ---------------------------------------------------------
+//
+STRUCT SIM_SEC_FEATURE
+    {
+    LTEXT txt = "";    
+    WORD item = -1;
+    BYTE type = EGSListBoxItemTypeIsAlwaysVisible;
+    }
+
+#endif // GSSIMSEC_RH
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/Inc/GSSimSecPluginContainer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,180 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Container for the Display sub-folder
+*
+*/
+
+
+
+#ifndef GSSIMSECCONTAINER_H
+#define GSSIMSECCONTAINER_H
+
+// INCLUDES
+#include <secuisecuritysettings.h>
+#include <e32property.h>
+
+#include <gsbasecontainer.h>
+
+
+// FORWARD DECLARATION
+class CGSListBoxItemTextArray;
+class CGSSimSecPluginModel;
+
+// CLASS DECLARATION
+
+/**
+*  CGSSimSecPluginContainer container class
+*
+*  Container class for SIM security view
+*  @lib GSSimSecPlugin.lib
+*  @since Series 60_3.1
+*/
+class CGSSimSecPluginContainer : public CGSBaseContainer
+    {
+    public: // Constructors and destructor
+        
+        /**
+        * Symbian OS constructor.
+        * @param aRect Listbox's rect.
+        * 
+        */
+        void ConstructL( const TRect& aRect );
+
+        /**
+        * Destructor.
+        */
+        ~CGSSimSecPluginContainer();
+        
+        /**
+        * Constructor
+        */
+        CGSSimSecPluginContainer( CGSSimSecPluginModel* aModel );
+
+   public: // new
+        /**
+        * Updates the listbox items
+        * @param aFeatureId: selected listbox item ID
+        */
+        void UpdateListBoxL( TInt aFeatureId );
+		
+        /**
+        * Retrieves the feature id for the selected item in the listbox
+        * @return listbox item array's current feature.
+        */
+        TInt CurrentFeatureId() const;
+        
+        void HandleResourceChangeL( TInt aType );
+
+   protected: // from CGSBaseContainer
+       /**
+        * Constructs listbox.
+        * @param aResLbxId Resource id for listbox.
+        * 
+        */
+       void ConstructListBoxL( TInt aResLbxId );
+
+   private: //new
+        /**
+        * Creates list box items
+        */   
+        void CreateListBoxItemsL();
+        /**
+        * Creates Code in use item
+        */   
+        void MakeCodeInUseItemL();
+        /**
+        * Creates upin code request list box item
+        */  
+        void MakeUpinRequestItemL();
+        /**
+        * Creates pin code request list box item
+        */  
+        void MakePinRequestItemL();
+        /**
+        * Creates code list box item
+        *
+        * @ param aItemType TInt (code type pin/pin2/security)
+        */  
+        void MakeCodeItemL( const TInt aItemType );
+        /**
+        * Creates autolock list box item
+        */  
+        void MakeAutolockItemL();
+        /**
+        * Creates sim change security list box item
+        */  
+        void MakeSimChangeItemL();
+        /**
+        * Creates closed user group list box item
+        */  
+        void MakeClosedUserGroupItemL();
+        
+        /**
+        * Creates sat operations list box item
+        */  
+        void MakeSatOperationsItemL();
+
+        /**
+        * Creates Trusted provisioning server list box item
+        */  
+        void MakeTPServerItemL();
+        /**
+        * Recreates different pin code related list box items as needed
+        * after switching PIN codes from PIN to UPIN or vice versa.
+        */  
+        void RecreatePinItemsL();
+        
+        void MakeRemoteLockItemL();
+    private:
+        /**
+        * Required for help.
+        * 
+        */
+        void GetHelpContext( TCoeHelpContext& aContext ) const;
+   
+	private: //data
+        //Code in use item's text
+        CDesCArrayFlat* iCodeItems;
+        //UPIN item's text
+        CDesCArrayFlat* iUpinItems;
+        //autolock item's text
+        CDesCArrayFlat* iAutoLockItems;
+        // RemoteLock item's text
+        CDesCArrayFlat* iRemoteLockItems;
+        //PIN item's text
+        CDesCArrayFlat* iPinItems;
+        //security item's text
+        CDesCArrayFlat* iSecurityItems;
+        //SAT item's text
+        CDesCArrayFlat* iSatItems;
+        //items from resource 
+        CDesCArray* iItemArray;
+        //for SecUI 
+        CSecuritySettings* iSecurity;
+        //check if UPIN code is supported
+        TBool iUpinCodeSupported;
+        //check if UPIN code is active
+        TBool iUpinCodeActive;
+        //check if UPIN code is permanently rejected
+        TBool iUpinCodeRejected;
+        //GS listbox model
+		CGSListBoxItemTextArray* iListboxItemArray;
+        //Model pointer. Does not own it, so do not delete this pointer.
+        CGSSimSecPluginModel* iModel;
+
+    };
+
+#endif //GSSIMSECCONTAINER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/Inc/GSSimSecPluginModel.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,121 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Model for Device & SIM security plug-in.
+*
+*/
+
+
+#ifndef GSSIMSECPLUGINMODEL_H
+#define GSSIMSECPLUGINMODEL_H
+
+// INCLUDES
+#include <e32base.h>
+#include <centralrepository.h>
+
+// CONSTANTS
+const TInt KGSBufSize128 = 128;
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DEFINITION
+/**
+*  CGSSimSecPluginModel is the model class of device & sim security plugin.
+*  It provides functions to get and set setting values.
+*  @lib GSSimSecPlugin.lib
+*  @since Series 60_3.1
+
+*/
+class CGSSimSecPluginModel : public CBase
+    {
+    public:  // Constructor and destructor
+        /**
+        * Two-phased constructor
+        */
+        static CGSSimSecPluginModel* NewL();
+
+        /**
+        * Destructor
+        */
+        ~CGSSimSecPluginModel();
+        
+    public:
+        /**
+        * Returns the autolock period time (minutes). 
+        *
+        * @return TInt: period
+        */
+        TInt AutoLockPeriod();
+
+        /**
+        * Sets the autolock period. After this period device is locked.
+        * @param aLockTime TInt (minutes)
+        *
+        * @return ETrue: no errors
+        *         EFalse: an error has occurred
+        */
+        TBool SetAutoLockPeriod( const TInt aLockTime );
+
+        /**
+        * Returns SAT operations sate
+        *
+        * @return TInt 0: SAT operations off
+        *         TInt 1: SAT operations on
+        */
+        TInt SatOperations();
+
+        /**
+        * Sets SAT operations on/off
+        * @param aValue TInt (0 = off 1 =on)
+        *
+        * @return ETrue: no errors
+        *         EFalse: an error has occurred
+        */
+        TBool SetSatOperations( const TInt aValue );
+
+        /**
+        * Checking if SAT operations supported
+        * @return:
+        * 0: not supported
+        * 1: supported
+        */
+        TInt ConfirmSatOperationsSupport();
+
+    private: // Private constructors
+        /**
+        * Default C++ contructor
+        */
+        CGSSimSecPluginModel();
+
+        /**
+        * Symbian OS default constructor
+        * @return void
+        */
+        void ConstructL();
+        
+    private: // data
+        CRepository* iSecurityRepository;
+        CRepository* iPersonalizationRepository;
+    
+    };
+
+
+#endif //GSSIMSECPLUGINMODEL_H
+
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/Inc/MGSSettingPSObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observer interface for indicating publish and subscribe 
+*               setting changes
+*
+*/
+
+
+
+#ifndef MGSSETTINGPSOBSERVER_H
+#define MGSSETTINGPSOBSERVER_H
+
+//  INCLUDES
+#include <e32std.h>
+
+// CLASS DECLARATION
+
+/**
+*  Observer interface for indicating setting changes
+*
+*  @lib GSSimSecPlugin
+*  @since 3.1
+*/
+class MGSSettingPSObserver
+    {
+    public:  // New functions
+
+        /**
+        * Handler for setting changed event
+        * @param aUid uid of setting        
+        * @param aId id of setting
+        * @param aStatus status of completed AO operation
+        */
+        virtual void HandleNotifyPSL( const TUid aUid, const TInt& aKey, 
+                                      const TRequestStatus& aStatus ) = 0;
+    };
+
+#endif // MGSSETTINGPSOBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/Src/GSPubSubsListener.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,155 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Publish and subscribe settings listener.
+*
+*/
+
+
+// INCLUDE FILES
+#include "GSPubSubsListener.h"
+#include "MGSSettingPSObserver.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CGSPubSubsListener::CGSPubSubsListener
+// C++ constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CGSPubSubsListener::CGSPubSubsListener( const TUid aUid, const TInt aKey, 
+                                       MGSSettingPSObserver* aObserver ) 
+    : CActive( CActive::EPriorityStandard )
+    {
+    iUid = aUid;
+    iId = aKey;
+    iCallback = aObserver;
+    }
+
+// -----------------------------------------------------------------------------
+// CGSPubSubsListener::~CGSPubSubsListener
+// Destructor.
+// -----------------------------------------------------------------------------
+//
+CGSPubSubsListener::~CGSPubSubsListener()
+    {
+    Cancel();
+    iProperty.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CGSPubSubsListener::RunL
+// From CActive.
+// -----------------------------------------------------------------------------
+//
+void CGSPubSubsListener::RunL()
+    {
+    const TRequestStatus status( iStatus );
+    StartListening();
+    iCallback->HandleNotifyPSL( iUid, iId, status );
+    }
+
+// -----------------------------------------------------------------------------
+// CGSPubSubsListener::DoCancel
+// From CActive.
+// -----------------------------------------------------------------------------
+//
+void CGSPubSubsListener::DoCancel()
+    {
+    iProperty.Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CGSPubSubsListener::RunError
+// From CActive.
+// -----------------------------------------------------------------------------
+//
+TInt CGSPubSubsListener::RunError( TInt /*aError*/ )
+    {
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CGSPubSubsListener::NewL
+//
+// Symbian OS two phased constructor
+// -----------------------------------------------------------------------------
+//
+CGSPubSubsListener* CGSPubSubsListener::NewL( const TUid aUid, const TInt aKey,
+                                              MGSSettingPSObserver* aObserver )
+    {
+    CGSPubSubsListener* self = new( ELeave ) 
+        CGSPubSubsListener( aUid, aKey, aObserver );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CGSPubSubsListener::StartListening
+// -----------------------------------------------------------------------------
+//
+void CGSPubSubsListener::StartListening() 
+    {
+    iProperty.Subscribe( iStatus );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CGSPubSubsListener::ConstructL
+//
+// Symbian OS default constructor
+// -----------------------------------------------------------------------------
+//
+void CGSPubSubsListener::ConstructL()
+    {
+    CActiveScheduler::Add( this );
+    
+    User::LeaveIfError ( iProperty.Attach( iUid, iId, EOwnerThread ) );
+    StartListening();
+    }
+
+// -----------------------------------------------------------------------------
+// CGSPubSubsListener::Get
+// Read integer value.
+// -----------------------------------------------------------------------------
+//
+TInt CGSPubSubsListener::Get( TInt& aVal )
+    {
+    return iProperty.Get( iUid, iId, aVal );
+    }
+
+// -----------------------------------------------------------------------------
+// CGSPubSubsListener::Get
+// Read binary value.
+// -----------------------------------------------------------------------------
+//
+TInt CGSPubSubsListener::Get( TDes8& aVal )
+    {
+    return iProperty.Get( iUid, iId, aVal );
+    }
+  
+// -----------------------------------------------------------------------------
+// CGSPubSubsListener::Get
+// Read string value.
+// -----------------------------------------------------------------------------
+//      
+TInt CGSPubSubsListener::Get( TDes16& aVal )
+    {
+    return iProperty.Get( iUid, iId, aVal );
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/Src/GSSimSecPlugin.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,806 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  View for Device & SIM Security sub-folder
+*
+*/
+
+
+// INCLUDE FILES
+#include <coeaui.h>
+#include <hlplch.h>             // For HlpLauncher
+#include <bautils.h>
+#include <gulicon.h>
+#include <eikfrlbd.h>
+#include <eiktxlbx.h>
+#include <aknradiobuttonsettingpage.h>
+#include <aknPopup.h>
+#include <aknlists.h>
+#include <RSSSettings.h>
+#include <AknQueryDialog.h>
+#include <aknnotedialog.h>
+#include <aknViewAppUi.h>
+#include <featmgr.h>
+#include <StringLoader.h>
+#include <secui.h>
+#include <secuisecuritysettings.h>
+#include <BTSapDomainPSKeys.h>
+#include <e32property.h>
+
+#include <GSSimSecPluginRsc.rsg>
+#include <gsprivatepluginproviderids.h>
+#include <gsmainview.h>
+#include <gsbasecontainer.h>
+
+#include "GSSimSecPlugin.h"
+#include "GSSimSecPluginContainer.h"
+#include "GSSimSecPlugin.hrh"
+
+
+#ifdef RD_REMOTELOCK
+#include    <RemoteLockSettings.h>  
+#endif // RD_REMOTELOCK
+
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+const TInt KEmptyCugIndex( -100000000 );
+_LIT( KGSSimSecPluginResourceFileName, "z:GSSimSecPluginRsc.rsc" );
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+/**
+* CCugQuery
+* It defines CCugQuery used in closed user group settings
+*/
+class CCugQuery
+    : public CAknNumberQueryDialog
+    {
+    public: // Constructors and destructors
+        /**
+        * C++ constructor.
+        */
+        CCugQuery( TInt& aNumber,const TTone aTone = ENoTone );
+    protected: // From base classes
+        /**
+        * From CCAknNumberQueryDialog Left softkey is allways OK.
+        */
+        void  UpdateLeftSoftKeyL();
+    };
+
+// ============================= LOCAL FUNCTIONS ==============================
+
+// ========================= MEMBER FUNCTIONS =================================
+
+// ---------------------------------------------------------------------------
+// GSSimSecPlugin::NewL()
+// 
+// ---------------------------------------------------------------------------
+CGSSimSecPlugin* CGSSimSecPlugin::NewL( TAny* /*aInitParams*/ )
+    {
+    CGSSimSecPlugin* self = new( ELeave ) CGSSimSecPlugin();
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();    
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// GSSimSecPlugin::CGSSimSecPlugin()
+// 
+// ---------------------------------------------------------------------------
+CGSSimSecPlugin::CGSSimSecPlugin()
+    : iResourceLoader( *iCoeEnv )
+    {    
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::ConstructL()
+// 
+// Symbian OS two-phased constructor
+// ---------------------------------------------------------------------------
+void CGSSimSecPlugin::ConstructL()
+    {
+    FeatureManager::InitializeLibL();
+
+    iModel = CGSSimSecPluginModel::NewL();
+    //PS listener initialization
+    iBtSapListener = CGSPubSubsListener::NewL( 
+                     KPSUidBluetoothSapConnectionState,
+                     KBTSapConnectionState, this );
+
+    iSecurity= CSecuritySettings::NewL();    
+    if(!FeatureManager::FeatureSupported( KFeatureIdFfNoCugSupport ))
+    {    
+    	User::LeaveIfError( iCugSettings.Open() );
+		}
+    // Find the resource file
+    TParse parse;
+    parse.Set( KGSSimSecPluginResourceFileName, 
+               &KDC_RESOURCE_FILES_DIR, NULL );
+    TFileName fileName( parse.FullName() );
+    
+    // Get language of resource file
+    BaflUtils::NearestLanguageFile( iCoeEnv->FsSession(), fileName );
+
+    // Open resource file
+    iResourceLoader.OpenL( fileName );
+    
+    BaseConstructL( R_GS_SIM_SECURITY_VIEW );
+
+    // secui resource file
+    TSecUi::InitializeLibL();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::~CGSSettListSecurityView()
+// 
+// 
+// ---------------------------------------------------------------------------
+CGSSimSecPlugin::~CGSSimSecPlugin()
+    {
+    FeatureManager::UnInitializeLib();
+    // close resource loader
+    iResourceLoader.Close();
+	if(!FeatureManager::FeatureSupported( KFeatureIdFfNoCugSupport ))
+    { 
+    iCugSettings.Close();
+  	}
+    if ( iSecurity )
+        {
+        delete iSecurity;
+        }
+
+    if ( iModel )
+        {
+        delete iModel;
+        }
+    delete iBtSapListener;
+
+    TSecUi::UnInitializeLib();  
+    }
+
+
+// ---------------------------------------------------------------------------
+// TUid CGSSettSimListSecurityView::Id()
+// 
+// 
+// ---------------------------------------------------------------------------
+TUid CGSSimSecPlugin::Id() const
+    {
+    return KGSSimSecPluginUid;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::HandleCommandL()
+// 
+// 
+// ---------------------------------------------------------------------------
+void CGSSimSecPlugin::HandleCommandL( TInt aCommand )
+    {
+    switch ( aCommand )
+        {
+        case EGSCmdAppChange:
+        case EAknSoftkeyChange:
+            {           
+            const TInt currentFeatureId = Container()->CurrentFeatureId();
+
+            if ( currentFeatureId != EGSSettIdSatOperations )
+                {
+                HandleListBoxSelectionL();
+                }
+            else
+                {
+                if(aCommand == EGSCmdAppChange)
+                    SetSatWithSettingPageL();
+                else //user pressed MSK, don't show setting page.
+                    SetSatOperationsL();
+                }
+            }
+            break;
+        case EAknSoftkeyBack:
+            iAppUi->ActivateLocalViewL( KGSSecurityPluginUid );  
+            break;
+        case EAknCmdHelp:
+            {
+            if( FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+                {
+                HlpLauncher::LaunchHelpApplicationL(
+                    iEikonEnv->WsSession(), iAppUi->AppHelpContextL() );
+                }
+            }
+            break;
+        default:
+            iAppUi->HandleCommandL( aCommand );
+            break;
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::UpdateListBoxL
+// 
+// Update the current item in the listbox.
+// ---------------------------------------------------------------------------
+void CGSSimSecPlugin::UpdateListBoxL( TInt aItemId )
+    {
+    Container()->UpdateListBoxL( aItemId );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::DoActivateL(...)
+// 
+// 
+// ---------------------------------------------------------------------------
+void CGSSimSecPlugin::DoActivateL( const TVwsViewId& aPrevViewId, 
+                                   TUid aCustomMessageId, 
+                                   const TDesC8& aCustomMessage )
+    {
+    CGSBaseView::DoActivateL( aPrevViewId, aCustomMessageId, aCustomMessage );    
+    }
+
+
+// ----------------------------------------------------------------------------
+// CGSSimSecPlugin::Container
+// 
+// Return handle to container class.
+// ----------------------------------------------------------------------------
+//
+CGSSimSecPluginContainer* CGSSimSecPlugin::Container()
+    {
+    return static_cast<CGSSimSecPluginContainer*>( iContainer );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::NewContainerL()
+// 
+// Creates new iContainer.
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPlugin::NewContainerL()
+    {
+    iContainer = new( ELeave ) CGSSimSecPluginContainer( iModel );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::HandleListBoxSelectionL()
+// 
+// 
+// ---------------------------------------------------------------------------
+void CGSSimSecPlugin::HandleListBoxSelectionL() 
+    {
+    const TInt currentFeatureId = Container()->CurrentFeatureId();
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    switch ( currentFeatureId )
+        {
+        case EGSSettIdCodeInUse:
+            if(wcdmaSupported || upinSupported)
+                {
+	                if(iSecurity->SwitchPinCodesL())
+	                {
+	                	UpdateListBoxL( currentFeatureId );
+	              	}
+                }       
+            break;
+        case EGSSettIdUpinRequest:
+            if(wcdmaSupported || upinSupported)
+                 {
+                    if(iSecurity->ChangeUPinRequestL())
+                    {            
+                    	UpdateListBoxL( currentFeatureId );
+                    }
+                 }
+            break;
+        case EGSSettIdUpinCode:
+            if(wcdmaSupported || upinSupported)
+              {
+                  iSecurity->ChangeUPinL();
+              }
+            break;
+        case EGSSettIdPinRequest: 
+        		if(iSecurity->ChangePinRequestL())
+            {               
+            	UpdateListBoxL( currentFeatureId );
+            }
+            break;
+        case EGSSettIdPinCode:            
+            iSecurity->ChangePinL();
+            break;
+        case EGSSettIdPin2Code:
+            iSecurity->ChangePin2L();
+            break;
+        case EGSSettIdAutolock:        
+            SetAutolockTimeL( iSecurity->ChangeAutoLockPeriodL( 
+                                         iModel->AutoLockPeriod() ) );
+            break;
+        case EGSSettIdSecurityCode:
+            iSecurity->ChangeSecCodeL();
+            break;
+        case EGSSettIdSimChange:    
+            if(iSecurity->ChangeSimSecurityL())
+            {
+            	UpdateListBoxL( currentFeatureId );
+            }
+            break; 
+            
+#ifdef RD_REMOTELOCK
+        case EGSSettIdRemoteLock:
+            SetRemoteLockStatusL( iModel->AutoLockPeriod() );
+            break;
+            
+#endif                
+        case EGSSettIdClosedUserGroup:
+        	if(!FeatureManager::FeatureSupported( KFeatureIdFfNoCugSupport ))
+    		{        
+	            CugModeL();
+	            UpdateListBoxL( currentFeatureId );
+	          }
+            break;
+        case EGSSettIdSatOperations:
+            SetSatOperationsL();
+            break;
+        default:
+            break;
+        }
+    
+    }
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::SetAutolockTimeL()
+// 
+// 
+// ---------------------------------------------------------------------------
+void CGSSimSecPlugin::SetAutolockTimeL( TInt aPeriod )
+    { 
+    iModel->SetAutoLockPeriod( aPeriod );
+    UpdateListBoxL( EGSSettIdAutolock );
+    }
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::SetSatOperationsL()
+// 
+// 
+// ---------------------------------------------------------------------------
+void CGSSimSecPlugin::SetSatOperationsL()
+    {
+    TInt i = iModel->SatOperations();
+    
+    if ( i == 0 )
+        {
+        iModel->SetSatOperations( 1 );
+        }
+    else
+        {
+        iModel->SetSatOperations( 0 );
+        }
+    UpdateListBoxL( EGSSettIdSatOperations );
+    }
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::SetSatOperationsL()
+// 
+// 
+// ---------------------------------------------------------------------------
+void CGSSimSecPlugin::SetSatWithSettingPageL()
+    {
+    TInt currentItem = iModel->SatOperations();
+
+    CDesCArrayFlat* items =  iCoeEnv->ReadDesC16ArrayResourceL( R_SAT_ARRAY );
+    CleanupStack::PushL( items );
+
+    CAknRadioButtonSettingPage* page = 
+        new( ELeave ) CAknRadioButtonSettingPage( R_SAT_SETTING_PAGE, 
+                                                  currentItem, items );
+
+    if ( page->ExecuteLD( CAknSettingPage::EUpdateWhenChanged ) )            
+        {    
+        iModel->SetSatOperations( currentItem );
+        }
+    
+    CleanupStack::PopAndDestroy( items );
+
+    UpdateListBoxL( EGSSettIdSatOperations );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::CugModeL()
+// 
+// 
+// ---------------------------------------------------------------------------
+void CGSSimSecPlugin::CugModeL()
+    {    
+    TInt cugIndex = 0;
+    TInt currentItem = 0;
+    TInt cugMode = 0;
+    TInt cugDefault;
+    TInt err = KErrNone;
+
+    err = iCugSettings.Get( ESSSettingsDefaultCug, cugDefault );
+    User::LeaveIfError( err );
+
+    
+    if ( iCugSettings.Get( ESSSettingsCug, cugMode ) != KErrNone )
+        {// getting mode was not succesful
+        cugMode = cugDefault;
+        }
+
+    if ( cugMode == cugDefault )
+        {
+        currentItem = EGSCugNetworkDefault;
+        if ( iCugSettings.PreviousCugValue( cugIndex ) != KErrNone )        
+            {
+            cugIndex = 0;
+            }
+        }
+    else
+        {
+        switch ( cugMode )
+            {
+            case ESSSettingsCugSuppress:
+                currentItem = EGSCugOff;
+                if ( iCugSettings.PreviousCugValue( cugIndex ) != KErrNone )
+                    {
+                    cugIndex = 0;
+                    }
+                break;
+            default:
+                currentItem = EGSCugOn;
+                cugIndex = cugMode;
+                break;
+            }
+        }
+
+
+    CDesCArrayFlat* items = iCoeEnv->ReadDesC16ArrayResourceL( R_CUG_LBX );
+    CleanupStack::PushL( items );
+
+    CAknRadioButtonSettingPage* page = 
+        new( ELeave ) CAknRadioButtonSettingPage( R_CUG_SETTING_PAGE, 
+                                                  currentItem, items );
+
+    // call the appropriate cug- methods here
+    if ( page->ExecuteLD( CAknSettingPage::EUpdateWhenChanged ) )    
+        {    
+        
+        switch ( currentItem )
+            {
+            case EGSCugNetworkDefault://cug mode set default, 
+                User::LeaveIfError( iCugSettings.Set( ESSSettingsCug, 
+                                                      cugDefault ) );
+                break;
+            case EGSCugOn: //1, index is queried, if query ok then
+                // set the index and mode
+                if ( CugIndexQueryL( cugIndex, cugDefault )  )
+                    {
+                    if ( iCugSettings.IsValueValidCugIndex( cugIndex ) )
+                        {
+                        User::LeaveIfError( iCugSettings.Set( ESSSettingsCug, 
+                                                              cugIndex ) );
+                        }
+                    else
+                        {
+                        User::LeaveIfError( iCugSettings.Set( ESSSettingsCug, 
+                                                              cugDefault ) );
+                        User::LeaveIfError( iCugSettings.ResetPreviousCugValue() );
+                        }
+                    }
+                break;
+            case EGSCugOff://2, sets cug mode "inactive"
+                User::LeaveIfError( iCugSettings.Set( ESSSettingsCug, 
+                                    ESSSettingsCugSuppress ) );
+                break;
+            default:
+                break;
+            }
+        }
+    CleanupStack::PopAndDestroy( items );
+    return;    
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::CugIndexQueryL()
+// 
+// 
+// ---------------------------------------------------------------------------
+TInt CGSSimSecPlugin::CugIndexQueryL( TInt& aCugIndex, TInt& aCugDefault )
+    {    
+    while ( ETrue )
+        {
+        CCugQuery* dlg = new( ELeave ) CCugQuery( aCugIndex,
+                                       CAknQueryDialog::ENoTone );
+    
+        if ( dlg->ExecuteLD( R_CUG_INDEX ) )
+            {
+            // check content validity (?-32767), 
+            // ui spec concerned only values above limit
+            if( !iCugSettings.IsValueValidCugIndex( aCugIndex )
+                && ( aCugIndex != KEmptyCugIndex )
+                && ( aCugIndex != aCugDefault ) )
+                {
+                CAknNoteDialog* dlg = new ( ELeave ) 
+                    CAknNoteDialog( CAknNoteDialog::EErrorTone, 
+                                    CAknNoteDialog::ELongTimeout );
+                dlg->ExecuteLD( R_CUG_INDEX_ERROR_NOTE );
+                }
+            else //index ok, break
+                {
+                break;
+                }
+            }
+        else // query cancelled
+            {
+            return EFalse;
+            }
+        }
+
+    return ETrue;    
+    }
+
+
+// ---------------------------------------------------------------------------
+// CCugQuery::CCugQuery()
+// 
+// ---------------------------------------------------------------------------
+//
+CCugQuery::CCugQuery( TInt& aNumber, const TTone aTone )
+    : CAknNumberQueryDialog( aNumber, aTone )
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CCugQuery::UpdateLeftSoftKeyL()
+// Left softkey is allways visible
+// ---------------------------------------------------------------------------
+//
+void CCugQuery::UpdateLeftSoftKeyL()
+    {
+    MakeLeftSoftkeyVisible( ETrue );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::HandleResourceChangeL( TInt aType )
+// Updates view layout
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPlugin::HandleResourceChangeL( TInt aType )
+    {
+    if( aType == KAknsMessageSkinChange ||
+        aType == KEikDynamicLayoutVariantSwitch )
+        {
+        //iContainer->HandleResourceChangeL( aType );
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::HandleNotifyPSL
+//
+// Handling PS keys change
+// ---------------------------------------------------------------------------
+//  
+void CGSSimSecPlugin::HandleNotifyPSL( const TUid aUid, const TInt& aKey,
+                                       const TRequestStatus& /* aStatus */ )
+    {
+    if ( aUid == KPSUidBluetoothSapConnectionState && 
+         aKey == KBTSapConnectionState )
+        {
+        Visible();
+        }
+    }
+
+
+// ========================= From CGSPluginInterface ==================
+
+// ----------------------------------------------------------------------------
+// CGSSimSecPlugin::GetCaption
+// 
+// Return application/view caption.
+// ----------------------------------------------------------------------------
+//
+void CGSSimSecPlugin::GetCaptionL( TDes& aCaption ) const
+    {
+    // the resource file is already opened.
+    HBufC* result = StringLoader::LoadL( R_GS_SIM_SECURITY_VIEW_CAPTION );
+    
+    aCaption.Copy( *result );
+    delete result;
+    }
+    
+
+// ----------------------------------------------------------------------------
+// CGSSimSecPlugin::PluginProviderCategory
+// 
+// A means to identify the location of this plug-in in the framework.
+// ----------------------------------------------------------------------------
+//
+TInt CGSSimSecPlugin::PluginProviderCategory() const
+    {
+    //To identify internal plug-ins.
+    return KGSPluginProviderInternal;
+    }
+    
+
+// ----------------------------------------------------------------------------
+// CGSSimSecPlugin::Visible
+// 
+// Provides the visibility status of self to framework.
+// ----------------------------------------------------------------------------
+//    
+TBool CGSSimSecPlugin::Visible() const
+    {
+    TInt btSapConnectionState;
+    TBool visible = ETrue;
+
+    iBtSapListener->Get( btSapConnectionState );
+
+    if ( btSapConnectionState == EBTSapConnected )
+        {
+        visible = EFalse;
+        }
+    
+    return visible;
+    }
+
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPlugin::SetRemoteLockStatusL()
+// 
+// 
+// ---------------------------------------------------------------------------
+TInt CGSSimSecPlugin::SetRemoteLockStatusL( TInt aAutoLockPeriod )
+    {
+    #ifdef RD_REMOTELOCK
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(GS)CGSSettListSimSecurityView::SetRemoteLockStatusL() - Enter" ) );
+    #endif // DEBUG
+
+    TInt retValue( KErrNone );
+    TBool remoteLockStatus( EFalse );
+    TBuf<KRLockMaxLockCodeLength> remoteLockCode;
+
+    CRemoteLockSettings* remoteLockSettings = CRemoteLockSettings::NewLC();
+
+    // Get the current remote lock status 
+    if ( remoteLockSettings->GetEnabled( remoteLockStatus ) )
+        {
+        // Show remote lock setting page
+        retValue = iSecurity->ChangeRemoteLockStatusL( remoteLockStatus, remoteLockCode, aAutoLockPeriod );
+
+        if ( retValue == KErrNone )
+            {
+            if ( remoteLockStatus )
+                {
+                // Set remote lock status
+                if ( remoteLockSettings->SetEnabledL( remoteLockCode ) )
+                    {
+                    // Remote lock status was set successfully
+                    #ifdef _DEBUG
+                    RDebug::Print( _L( "(GS)CGSSettListSimSecurityView::SetRemoteLockStatusL() - Remote lock enabled and code set" ) );
+                    #endif // DEBUG
+                    }
+                else
+                    {
+                    // Failed to enabled remote lock 
+                    retValue = KErrGeneral;
+
+                    #ifdef _DEBUG
+                    RDebug::Print( _L( "(GS)CGSSettListSimSecurityView::SetRemoteLockStatusL() - remoteLockSettings->SetEnabledL failed" ) );
+                    #endif // DEBUG
+                    }
+                }
+            else
+                {
+                // Disable remote lock
+                if ( remoteLockSettings->SetDisabled() )
+                    {
+                    // Remote lock disabled
+                    #ifdef _DEBUG
+                    RDebug::Print( _L( "(GS)CGSSettListSimSecurityView::SetRemoteLockStatusL() - Remote lock disabled" ) );
+                    #endif // DEBUG
+                    }
+                else
+                    {
+                    // Failed to disable remote lock
+                    retValue = KErrGeneral;
+
+                    #ifdef _DEBUG
+                    RDebug::Print( _L( "(GS)CGSSettListSimSecurityView::SetRemoteLockStatusL() - remoteLockSettings->SetDisabled failed" ) );
+                    #endif // DEBUG
+                    }
+                }
+            }
+        else
+            {
+            // User interaction (setting page) failed for some reason
+            #ifdef _DEBUG
+            RDebug::Print( _L( "(GS)CGSSettListSimSecurityView::SetRemoteLockStatusL() - iSecurity->ChangeRemoteLockStatusL failed" ) );
+            #endif // DEBUG
+            }
+        }
+    else
+        {
+        // Failed to retreive the current remote lock status
+        retValue = KErrGeneral;
+
+        #ifdef _DEBUG
+        RDebug::Print( _L( "(GS)CGSSettListSimSecurityView::SetRemoteLockStatusL() - remoteLockSettings->GetEnabled failed" ) );
+        #endif // DEBUG
+        }
+
+    CleanupStack::PopAndDestroy( remoteLockSettings );
+    remoteLockSettings = NULL;
+
+    UpdateListBoxL( EGSSettIdRemoteLock );
+
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(GS)CGSSettListSimSecurityView::SetRemoteLockStatusL() - Exit" ) );
+    #endif // DEBUG
+	return retValue;
+	#else //!RD_REMOTELOCK 
+    return KErrNotSupported;
+    #endif // RD_REMOTELOCK  
+    }
+    
+    
+// ----------------------------------------------------------------------------
+// CGSSimSecPlugin::DynInitMenuPaneL()
+// 
+// Display the dynamic menu
+// ----------------------------------------------------------------------------
+void CGSSimSecPlugin::DynInitMenuPaneL( TInt aResourceId,
+                                          CEikMenuPane* aMenuPane )
+    {
+
+	// show or hide the 'help' menu item when supported
+    if( aResourceId == R_GS_SIM_SEC_MENU_ITEM_HELP )
+        {
+        User::LeaveIfNull( aMenuPane );    
+        if ( FeatureManager::FeatureSupported( KFeatureIdHelp ) )
+            {
+            aMenuPane->SetItemDimmed( EAknCmdHelp, EFalse );
+            }
+        else
+            {
+            aMenuPane->SetItemDimmed( EAknCmdHelp, ETrue );
+            }
+        }
+
+    } 
+// End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/Src/GSSimSecPluginContainer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,943 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Container for the Device & SIM security sub-folder
+*
+*/
+
+
+#include "GSSimSecPluginContainer.h"
+#include "GSSimSecPluginModel.h"
+#include "GSSimSecPlugin.hrh"
+
+#include <aknlists.h>
+#include <etelmm.h>
+#include <RSSSettings.h>
+#include <StringLoader.h>
+#include <featmgr.h>
+#include <csxhelp/cp.hlp.hrh>
+#include <gsfwviewuids.h>
+#include <GSSimSecPluginRsc.rsg>
+#include <gslistbox.h>
+#include <AknsConstants.h>
+#include <secuisecuritysettings.h>
+
+
+#ifdef RD_REMOTELOCK
+#include <RemoteLockSettings.h>
+_LIT( KRemoteLockEmptyItem, " " );
+#endif
+
+#include    <SCPClient.h>                                                  
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+_LIT( CodeItem,"****" );
+_LIT( SecurityCodeItem, "*****" );
+
+const TInt KMaxStringLength = 50;
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================= LOCAL FUNCTIONS ==============================
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer::ConstructL()
+// 
+// Symbian OS two phased constructor
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer::ConstructL( const TRect& aRect )
+    { 
+    iListBox = new( ELeave ) CAknSettingStyleListBox;
+    BaseConstructL( aRect, R_GS_SIM_SECURITY_VIEW_TITLE, R_SIM_SECURITY_LBX );
+    FeatureManager::InitializeLibL();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer::~CGSSettListSecurityContainer()
+// 
+// Destructor 
+// ---------------------------------------------------------------------------
+//
+
+CGSSimSecPluginContainer::~CGSSimSecPluginContainer()
+    {
+    if(iCodeItems)
+        delete iCodeItems;
+    if(iUpinItems)
+        delete iUpinItems;
+    if(iAutoLockItems)
+        delete iAutoLockItems;
+    if(iPinItems)
+        delete iPinItems;
+    if(iSecurityItems)
+        delete iSecurityItems;
+    if(iSatItems)
+        delete iSatItems;
+    if(iSecurity)
+        delete iSecurity;
+    if(iListboxItemArray)
+        delete iListboxItemArray;
+#ifdef RD_REMOTELOCK
+    if(iRemoteLockItems)
+        delete iRemoteLockItems;
+#endif // RD_REMOTELOCK    
+FeatureManager::UnInitializeLib();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer::CGSSimSecPluginContainer()
+// 
+// Constructor
+// ---------------------------------------------------------------------------
+//
+CGSSimSecPluginContainer::CGSSimSecPluginContainer(
+                          CGSSimSecPluginModel* aModel )
+    : iModel ( aModel )
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer::ConstructListBoxL()
+// 
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer::ConstructListBoxL( TInt aResLbxId )
+    {
+    iSecurity= CSecuritySettings::NewL();
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    if(wcdmaSupported || upinSupported)
+        {
+        //check if UPIN code is supported and not rejected
+        TBool resp = iSecurity->IsUpinSupportedL();
+        if( resp )
+            {
+            iUpinCodeSupported = ETrue;
+    
+            //check if UPIN code is active
+            if( iSecurity->IsUpinActive() )
+                {
+                iUpinCodeActive = ETrue;
+                }
+            else
+                {
+                iUpinCodeActive = EFalse;
+                }
+            
+            //Check whether UPIN is blocked
+            resp = iSecurity->IsUpinBlocked();
+    
+            if( !resp )
+                {
+                iUpinCodeRejected = EFalse;
+                }
+            else
+                {
+                iUpinCodeRejected = ETrue;    
+                }
+            }
+        else
+            {
+            iUpinCodeSupported = EFalse;
+            iUpinCodeActive = EFalse;
+            }
+        }
+    
+
+    iListBox->ConstructL( this, EAknListBoxSelectionList );
+    iListboxItemArray = CGSListBoxItemTextArray::NewL( aResLbxId, 
+                        *iListBox, *iCoeEnv );
+    iListBox->Model()->SetItemTextArray( iListboxItemArray );
+    iListBox->Model()->SetOwnershipType( ELbmDoesNotOwnItemArray );
+
+    iAutoLockItems = iCoeEnv->ReadDesC16ArrayResourceL( R_AUTOLOCK_ARRAY );
+
+#ifdef RD_REMOTELOCK
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(GS)CGSSettListSimSecurityContainer::ConstructListBoxL() - Reading R_REMOTELOCK_ARRAY resource" ) );
+    #endif // DEBUG
+
+    iRemoteLockItems = iCoeEnv->ReadDesC16ArrayResourceL( R_REMOTELOCK_ARRAY );
+#endif // RD_REMOTELOCK
+
+
+    if(wcdmaSupported || upinSupported)
+      {
+        iUpinItems = iCoeEnv->ReadDesC16ArrayResourceL( R_UPIN_ARRAY );
+        iCodeItems = iCoeEnv->ReadDesC16ArrayResourceL( R_CODE_ARRAY );
+      }
+    else
+        {
+        iUpinItems = NULL;
+        iCodeItems = NULL;
+        }
+
+    iPinItems = iCoeEnv->ReadDesC16ArrayResourceL( R_PIN_ARRAY );
+    iSecurityItems = iCoeEnv->ReadDesC16ArrayResourceL( R_SECURITY_ARRAY );
+    iSatItems = iCoeEnv->ReadDesC16ArrayResourceL( R_SAT_ARRAY );
+
+    CreateListBoxItemsL();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSettListIdleContainer::CreateListBoxItemsL()
+// 
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer::CreateListBoxItemsL()
+    {
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+
+    if(wcdmaSupported || upinSupported)
+      {
+        if( iUpinCodeSupported && !iUpinCodeRejected )
+            {
+            MakeCodeInUseItemL();
+            }
+    
+        if( iUpinCodeActive )
+            {
+            MakeUpinRequestItemL();
+            MakeCodeItemL( EGSSettIdUpinCode );
+            }
+        else
+            {
+            MakePinRequestItemL();
+            MakeCodeItemL( EGSSettIdPinCode );
+            }
+       }
+    else //not wcdma or upin
+        {   
+            MakePinRequestItemL();
+            MakeCodeItemL( EGSSettIdPinCode );
+        }
+
+    MakeCodeItemL( EGSSettIdPin2Code );
+    MakeAutolockItemL();
+    
+#ifdef RD_REMOTELOCK
+    MakeRemoteLockItemL();
+#endif // RD_REMOTELOCK
+    
+    MakeCodeItemL( EGSSettIdSecurityCode );
+    MakeSimChangeItemL();
+		if(!FeatureManager::FeatureSupported( KFeatureIdFfNoCugSupport ))
+    	{ 
+    		#ifdef _DEBUG
+    		RDebug::Print( _L( "(GS)CGSSettListSimSecurityContainer::CreateListBoxItemsL() CUG supported!" ) );
+    		#endif // DEBUG
+    		MakeClosedUserGroupItemL();
+    	}
+    else
+    {
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(GS)CGSSettListSimSecurityContainer::CreateListBoxItemsL() CUG Not supported!" ) );
+    #endif // DEBUG
+    }
+    
+    TInt support = iModel->ConfirmSatOperationsSupport();
+    
+    if ( support == 1 ) // Confirmation allowed.
+        {
+        MakeSatOperationsItemL();
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CGSSettListIdleContainer::UpdateListBoxL( TInt aFeatureId )
+// 
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer::UpdateListBoxL( TInt aFeatureId )
+    {
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    switch( aFeatureId )
+        {
+        case EGSSettIdCodeInUse:
+            if(wcdmaSupported || upinSupported)
+              {
+                  RecreatePinItemsL();
+              }
+            break;
+        case EGSSettIdUpinRequest:
+            if(wcdmaSupported || upinSupported)
+              {
+                  MakeUpinRequestItemL();
+              }
+            break;
+        case EGSSettIdUpinCode:
+            if(wcdmaSupported || upinSupported)
+              {
+                  MakeCodeItemL( EGSSettIdUpinCode );
+              }
+            break;
+        case EGSSettIdPinRequest:
+            MakePinRequestItemL();
+            break;
+        case EGSSettIdPinCode:
+            MakeCodeItemL( EGSSettIdPinCode );
+            break;
+        case EGSSettIdPin2Code:
+            MakeCodeItemL( EGSSettIdPin2Code );
+            break;
+        case EGSSettIdAutolock:
+            MakeAutolockItemL();
+            break;
+        case EGSSettIdSecurityCode:
+            MakeCodeItemL( EGSSettIdSecurityCode );
+            break;
+        case EGSSettIdSimChange:
+            MakeSimChangeItemL();
+            break;
+            
+    #ifdef RD_REMOTELOCK
+        case EGSSettIdRemoteLock:
+            MakeRemoteLockItemL();
+            break;
+    #endif // RD_REMOTELOCK    
+        case EGSSettIdClosedUserGroup:
+        		if(!FeatureManager::FeatureSupported( KFeatureIdFfNoCugSupport ))
+    				{ 
+            	MakeClosedUserGroupItemL();
+            }
+            break;
+        case EGSSettIdSatOperations:
+            MakeSatOperationsItemL();
+            break;
+        default:
+            return;
+        }
+    
+    iListBox->HandleItemAdditionL();
+    }
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer::MakeCodeItemL()
+// 
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer::MakeCodeItemL( const TInt aItemType )
+    {
+    HBufC* dynamicText = HBufC::NewLC( KGSBufSize128 );
+    TPtr ptrBuffer ( dynamicText->Des() );
+    
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+
+    if(wcdmaSupported || upinSupported)
+      {
+        iUpinCodeSupported = iSecurity->IsUpinSupportedL();
+        iUpinCodeActive = iSecurity->IsUpinActive(); 
+        iUpinCodeRejected = iSecurity->IsUpinBlocked();
+      }
+    else
+      {
+        iUpinCodeSupported = EFalse;
+        iUpinCodeActive = EFalse; 
+        iUpinCodeRejected = EFalse;
+      }
+
+    switch ( aItemType )
+        {
+        case EGSSettIdUpinCode:
+            if( iUpinCodeSupported && !iUpinCodeRejected && iUpinCodeActive )
+                {
+                ptrBuffer =  CodeItem;
+                iListboxItemArray->SetDynamicTextL( EGSSettIdUpinCode, ptrBuffer );
+                iListboxItemArray->SetItemVisibilityL( EGSSettIdUpinCode,
+                                   CGSListBoxItemTextArray::EVisible );
+                }
+            else
+                {
+                iListboxItemArray->SetItemVisibilityL( EGSSettIdUpinCode,
+                                   CGSListBoxItemTextArray::EInvisible );
+                }
+            break;
+        case EGSSettIdPin2Code:
+            ptrBuffer =  CodeItem;
+            iListboxItemArray->SetDynamicTextL( EGSSettIdPin2Code, ptrBuffer );
+            iListboxItemArray->SetItemVisibilityL( EGSSettIdPin2Code, 
+                               CGSListBoxItemTextArray::EVisible );
+            break;
+        case EGSSettIdSecurityCode:
+            ptrBuffer =  SecurityCodeItem;
+            iListboxItemArray->SetDynamicTextL( EGSSettIdSecurityCode, 
+                                                ptrBuffer );
+        if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))
+        {
+        
+            {                                                      
+            // Check the code change policy from the SCP server.
+            TInt allowChange = 1;
+            
+            RSCPClient scpClient;
+            TInt ret = scpClient.Connect();
+            if ( ret == KErrNone )
+                {                                
+                TBuf<KSCPMaxIntLength> policyBuf;
+                policyBuf.Zero();
+                if ( scpClient.GetParamValue( ESCPCodeChangePolicy, policyBuf ) == KErrNone )
+                    {
+                    TLex lex( policyBuf );
+                    lex.Val( allowChange );
+                    #if defined(_DEBUG)
+                        RDebug::Print(_L("(GS)CGSSettListSimSecurityContainer::\
+                            MakeCodeInUseItemL(): Policy retrieved: %d"), allowChange );
+                    #endif //DEBUG                    
+                    }
+                else
+                    {
+                    #if defined(_DEBUG)
+                       RDebug::Print(_L("(GS)CGSSettListSimSecurityContainer::\
+                            MakeCodeInUseItemL(): ERROR: Failed to retrieve the policy value") );
+                    #endif //DEBUG                                                      
+                    }
+                scpClient.Close();
+                }
+            else
+                {
+                #if defined(_DEBUG)
+                    RDebug::Print(_L("(GS)CGSSettListSimSecurityContainer::MakeCodeInUseItemL(): \
+                        ERROR: Failed to connect to SCP") );
+                #endif //DEBUG                                  
+                }
+            
+            if ( allowChange == 1 )
+                {            
+                #if defined(_DEBUG)
+                    RDebug::Print(_L("(GS)CGSSettListSimSecurityContainer::MakeCodeInUseItemL(): \
+                        Code change allowed"));
+                #endif //DEBUG                                        
+        
+                iListboxItemArray->SetItemVisibilityL( EGSSettIdSecurityCode, 
+		        CGSListBoxItemTextArray::EVisible );		        				
+                }
+            else
+                {
+                #if defined(_DEBUG)
+                    RDebug::Print(_L("(GS)CGSSettListSimSecurityContainer::MakeCodeInUseItemL():\
+                        Code change disallowed"));
+                #endif //DEBUG
+                
+                iListboxItemArray->SetItemVisibilityL( EGSSettIdSecurityCode, 
+    		        CGSListBoxItemTextArray::EInvisible );
+                }
+            }
+            
+      }  
+      else
+      {      
+        
+            iListboxItemArray->SetItemVisibilityL( EGSSettIdSecurityCode, 
+                               CGSListBoxItemTextArray::EVisible );
+		                		        
+	}
+            break;
+        case EGSSettIdPinCode:
+        default:
+            if( !iUpinCodeSupported || iUpinCodeRejected || !iUpinCodeActive )
+                {
+                ptrBuffer =  CodeItem;
+                iListboxItemArray->SetDynamicTextL( EGSSettIdPinCode, 
+                                                    ptrBuffer );
+                iListboxItemArray->SetItemVisibilityL( EGSSettIdPinCode, 
+                                   CGSListBoxItemTextArray::EVisible );
+                }
+            else
+                {
+                iListboxItemArray->SetItemVisibilityL( EGSSettIdPinCode, 
+                                   CGSListBoxItemTextArray::EInvisible );
+                }
+            break;
+        }
+    CleanupStack::PopAndDestroy( dynamicText );
+    
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer::MakeAutolockItemL()
+// 
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer::MakeAutolockItemL()
+    {
+    HBufC* dynamicText = HBufC::NewLC( KGSBufSize128 );
+    TPtr ptrBuffer ( dynamicText->Des() );
+
+    TInt period = iModel->AutoLockPeriod();
+    
+    switch ( period )
+        {
+        case 0:
+            ptrBuffer = ( *iAutoLockItems )[ 0 ];
+            break;
+        case 1:
+            {
+            TBuf<KGSBufSize128> tempString;
+            StringLoader::Format( tempString, 
+                                ( ( *iAutoLockItems )[1] ),
+                                  -1, // no index in the key string
+                                  period );
+            ptrBuffer = tempString;
+            }
+            break;
+        default:
+            {
+            TBuf<KGSBufSize128> tempString;
+            StringLoader::Format( tempString, 
+                                ( ( *iAutoLockItems )[2] ),
+                                  -1, // no index in the key string
+                                  period );
+            ptrBuffer = tempString;
+            }
+            break;
+        }
+    iListboxItemArray->SetDynamicTextL( EGSSettIdAutolock, ptrBuffer );
+    CleanupStack::PopAndDestroy( dynamicText );
+    iListboxItemArray->SetItemVisibilityL( EGSSettIdAutolock, 
+                       CGSListBoxItemTextArray::EVisible );
+    }
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer::MakeSimChangeItemL()
+// 
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer::MakeSimChangeItemL()
+    {
+    HBufC* dynamicText = HBufC::NewLC( KGSBufSize128 );
+    TPtr ptrBuffer ( dynamicText->Des() );
+   
+    if ( iSecurity->IsLockEnabledL( RMobilePhone::ELockPhoneToICC ) )
+        {
+        ptrBuffer = ( *iSecurityItems )[0];
+        }
+    else
+        {
+        ptrBuffer = ( *iSecurityItems )[1];
+        }
+
+    iListboxItemArray->SetDynamicTextL( EGSSettIdSimChange, ptrBuffer );
+    CleanupStack::PopAndDestroy( dynamicText );
+    iListboxItemArray->SetItemVisibilityL( EGSSettIdSimChange, 
+                       CGSListBoxItemTextArray::EVisible );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer:: MakePinRequestItemL()
+// 
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer:: MakePinRequestItemL()
+    {
+    HBufC* dynamicText = HBufC::NewLC( KGSBufSize128 );
+    TPtr ptrBuffer ( dynamicText->Des() );
+
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    if(wcdmaSupported || upinSupported)
+      {
+        iUpinCodeSupported = iSecurity->IsUpinSupportedL();
+        iUpinCodeActive = iSecurity->IsUpinActive(); 
+        iUpinCodeRejected = iSecurity->IsUpinBlocked();
+      }
+    else
+        {
+         iUpinCodeSupported = EFalse;
+         iUpinCodeActive = EFalse; 
+         iUpinCodeRejected = EFalse;       
+        }
+
+    if( !iUpinCodeSupported || !iUpinCodeActive || iUpinCodeRejected )
+        {
+        if ( iSecurity->IsLockEnabledL( RMobilePhone::ELockICC ) )
+            {
+            ptrBuffer = ( *iPinItems )[0];
+            }
+        else
+            {
+            ptrBuffer = ( *iPinItems )[1];
+            }   
+
+        iListboxItemArray->SetDynamicTextL( EGSSettIdPinRequest, ptrBuffer );
+        iListboxItemArray->SetItemVisibilityL( EGSSettIdPinRequest, 
+                           CGSListBoxItemTextArray::EVisible );
+        }
+    else
+        {
+        iListboxItemArray->SetItemVisibilityL( EGSSettIdPinRequest, 
+                           CGSListBoxItemTextArray::EInvisible );
+        }
+    CleanupStack::PopAndDestroy( dynamicText );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer:: MakeUpinRequestItemL()
+// 
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer:: MakeUpinRequestItemL()
+    {
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    if(wcdmaSupported || upinSupported)
+      {   
+        HBufC* dynamicText = HBufC::NewLC( KGSBufSize128 );
+        TPtr ptrBuffer ( dynamicText->Des() );
+    
+        iUpinCodeSupported = iSecurity->IsUpinSupportedL();
+        iUpinCodeActive = iSecurity->IsUpinActive();
+        iUpinCodeRejected = iSecurity->IsUpinBlocked();
+    
+    
+        if( iUpinCodeSupported && !iUpinCodeRejected && iUpinCodeActive )
+            {
+        
+            if ( iSecurity->IsLockEnabledL( RMobilePhone::ELockUniversalPin ) )
+                {
+                ptrBuffer = ( *iPinItems )[0];
+                }
+            else
+                {
+                ptrBuffer = ( *iPinItems )[1];
+                }
+    
+            iListboxItemArray->SetDynamicTextL( EGSSettIdUpinRequest, ptrBuffer );
+            iListboxItemArray->SetItemVisibilityL( EGSSettIdUpinRequest, 
+                               CGSListBoxItemTextArray::EVisible );
+            }
+        else
+            {
+            iListboxItemArray->SetItemVisibilityL( EGSSettIdUpinRequest,
+                               CGSListBoxItemTextArray::EInvisible );
+            }
+        
+        CleanupStack::PopAndDestroy( dynamicText );
+      }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer:: MakeCodeInUseItemL()
+// 
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer:: MakeCodeInUseItemL()
+    {
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    if(wcdmaSupported || upinSupported)
+      {
+        HBufC* dynamicText = HBufC::NewLC( KGSBufSize128 );
+        TPtr ptrBuffer ( dynamicText->Des() );
+        iUpinCodeSupported = iSecurity->IsUpinSupportedL();
+        iUpinCodeRejected = iSecurity->IsUpinBlocked();
+        if( iUpinCodeSupported && !iUpinCodeRejected )
+            {
+            if ( !iSecurity->IsUpinActive() )
+                {
+                ptrBuffer = ( *iCodeItems )[0];
+                }
+            else
+                {
+                ptrBuffer = ( *iCodeItems )[1];
+                }
+    
+            iListboxItemArray->SetDynamicTextL( EGSSettIdCodeInUse, ptrBuffer );
+            iListboxItemArray->SetItemVisibilityL( EGSSettIdCodeInUse, 
+                               CGSListBoxItemTextArray::EVisible );
+            }
+        else
+            {
+    
+             iListboxItemArray->SetItemVisibilityL( EGSSettIdCodeInUse, 
+                                CGSListBoxItemTextArray::EInvisible );
+            }
+        
+        CleanupStack::PopAndDestroy( dynamicText );
+      }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer:: MakeClosedUserGroupItemL()
+// 
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer::MakeClosedUserGroupItemL()
+    {
+    HBufC* dynamicText = HBufC::NewLC( KGSBufSize128 );
+    TPtr ptrBuffer ( dynamicText->Des() );
+
+    TInt cugMode = 0;
+    TInt cugDefault;
+    TInt err = KErrNone;
+
+    RSSSettings cugSettings;
+    User::LeaveIfError( cugSettings.Open() );
+
+    err = cugSettings.Get( ESSSettingsDefaultCug, cugDefault );
+    User::LeaveIfError( err );
+
+    if ( cugSettings.Get( ESSSettingsCug , cugMode ) != KErrNone )
+        {// getting mode was not succesful
+        cugMode = cugDefault;
+        }
+    
+    TBuf<KMaxStringLength> string;
+
+    if ( cugMode == cugDefault )
+        {
+        StringLoader::Load( string, R_CUG_NETWORK_DEFAULT );
+        ptrBuffer = string;
+        }
+    else
+        {
+        switch ( cugMode )
+            {
+            case ESSSettingsCugSuppress:
+                StringLoader::Load( string, R_CUG_OFF );
+                ptrBuffer = string;    
+                break;
+            default:
+                StringLoader::Load( string, R_CUG_ON );
+                ptrBuffer = string;    
+                break;
+            }
+        }
+    
+    cugSettings.Close();
+    
+    iListboxItemArray->SetDynamicTextL( EGSSettIdClosedUserGroup, ptrBuffer );
+    iListboxItemArray->SetItemVisibilityL( EGSSettIdClosedUserGroup, 
+                       CGSListBoxItemTextArray::EVisible );
+    CleanupStack::PopAndDestroy( dynamicText );
+
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer:: MakeSatOperationsItemL()
+// 
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer::MakeSatOperationsItemL()
+    {
+    HBufC* dynamicText = HBufC::NewLC( KGSBufSize128 );
+    TPtr ptrBuffer ( dynamicText->Des() );
+
+    TInt satOperation = iModel->SatOperations();
+        
+    if ( satOperation == 1 )
+        {
+        ptrBuffer = ( *iSatItems )[1];
+        }
+    else
+        {
+        ptrBuffer = ( *iSatItems )[0];
+        }
+
+    iListboxItemArray->SetDynamicTextL( EGSSettIdSatOperations, ptrBuffer );
+    iListboxItemArray->SetItemVisibilityL( EGSSettIdSatOperations, 
+                       CGSListBoxItemTextArray::EVisible );
+    CleanupStack::PopAndDestroy( dynamicText );
+
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer::CurrentFeatureId()
+//  
+// ---------------------------------------------------------------------------
+//
+TInt CGSSimSecPluginContainer::CurrentFeatureId() const
+    {
+    return iListboxItemArray->CurrentFeature( );
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer::GetHelpContext() const
+// Gets Help 
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer::GetHelpContext( TCoeHelpContext& aContext ) const
+    {
+    aContext.iMajor = KUidGS;
+    aContext.iContext = KSET_HLP_SECURITY_DEVICE_SIM;
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSettListIdleContainer::RecreatePinItemsL()
+// 
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer::RecreatePinItemsL()
+    {
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    if(wcdmaSupported || upinSupported)
+      {
+        //check if UPIN code is supported and not rejected
+        if( iSecurity->IsUpinSupportedL() )
+            {
+            iUpinCodeSupported = ETrue;
+    
+            //check if UPIN code is active
+            if( iSecurity->IsUpinActive() )
+                {
+                iUpinCodeActive = ETrue;
+                }
+            else
+                {
+                iUpinCodeActive = EFalse;
+                }
+            
+            //Check whether UPIN is blocked
+    
+            if( !iSecurity->IsUpinBlocked() )
+                {
+                iUpinCodeRejected = EFalse;
+                }
+            else
+                {
+                iUpinCodeRejected = ETrue;
+                }
+        }
+        else
+            {
+            iUpinCodeSupported = EFalse;
+            iUpinCodeActive = EFalse;
+            }
+    
+        MakeCodeInUseItemL();
+        MakeUpinRequestItemL();
+        MakeCodeItemL( EGSSettIdUpinCode );
+        MakePinRequestItemL();
+        MakeCodeItemL( EGSSettIdPinCode );
+      }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer::HandleResourceChangeL()
+// 
+// Updates view layout 
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer::HandleResourceChangeL( TInt aType )
+    {
+    if( aType == KAknsMessageSkinChange ||
+        aType == KEikDynamicLayoutVariantSwitch )
+        {
+        TRect mainPaneRect;
+        AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::EMainPane, 
+                                           mainPaneRect );
+        SetRect( mainPaneRect );
+        DrawNow();
+        }
+    }
+    
+    
+
+// ---------------------------------------------------------------------------
+// CGSSimSecPluginContainer::MakeRemoteLockItemL()
+// 
+//  
+// ---------------------------------------------------------------------------
+//
+void CGSSimSecPluginContainer::MakeRemoteLockItemL()
+    {
+    #ifdef RD_REMOTELOCK
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(SECUI)CGSSimSecPluginContainer::MakeRemoteLockItemL() - Enter" ) );
+    #endif // DEBUG
+
+    HBufC* statusItemText = HBufC::NewLC( KGSBufSize128 );
+    TPtr ptrRemoteLockStatus( statusItemText->Des() );
+    TBool remoteLockStatus( EFalse );
+    CRemoteLockSettings* remoteLockSettings = CRemoteLockSettings::NewLC();
+
+    if ( remoteLockSettings->GetEnabled( remoteLockStatus ) )
+        {
+        if ( remoteLockStatus )
+            {
+            // Remote lock enabled
+            ptrRemoteLockStatus = (*iRemoteLockItems)[0];
+            }
+        else
+            {
+            // Remote lock disabled
+            ptrRemoteLockStatus = (*iRemoteLockItems)[1];
+            }
+        }
+    else
+        {
+        // Failed to get remote lock status
+        // Undefined situation. Display empty item
+        ptrRemoteLockStatus = KRemoteLockEmptyItem;
+        }
+
+    CleanupStack::PopAndDestroy( remoteLockSettings );
+    remoteLockSettings = NULL;
+
+    // Remote Lock item
+	iListboxItemArray->SetDynamicTextL( EGSSettIdRemoteLock, ptrRemoteLockStatus );
+    CleanupStack::PopAndDestroy( statusItemText );
+	iListboxItemArray->SetItemVisibilityL( EGSSettIdRemoteLock, CGSListBoxItemTextArray::EVisible );
+
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(SECUI)CGSSimSecPluginContainer::MakeRemoteLockItemL() - Exit" ) );
+    #endif // DEBUG
+	#endif // RD_REMOTELOCK
+    return;
+    }
+    
+    
+//End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/Src/GSSimSecPluginImplementationTable.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,61 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM proxy table for this plugin
+*
+*/
+
+
+// System includes
+#include <e32std.h>
+#include <ecom/implementationproxy.h>
+
+// User includes
+#include "GSSimSecPlugin.h"
+
+// Constants
+const TImplementationProxy KGSSimSecPluginImplementationTable[] = 
+	{
+	IMPLEMENTATION_PROXY_ENTRY( 0x10207439,	CGSSimSecPlugin::NewL )
+	};
+
+
+// ---------------------------------------------------------------------------
+// ImplementationGroupProxy
+// Gate/factory function
+//
+// ---------------------------------------------------------------------------
+//
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( 
+    TInt& aTableCount )
+	{
+	aTableCount = sizeof( KGSSimSecPluginImplementationTable ) 
+        / sizeof( TImplementationProxy );
+	return KGSSimSecPluginImplementationTable;
+	}
+
+
+// ---------------------------------------------------------------------------
+// E32Dll
+// EKA1 entry point
+//
+// ---------------------------------------------------------------------------
+//
+#ifndef EKA2
+GLDEF_C TInt E32Dll( TDllReason /*aReason*/ )
+	{
+	return( KErrNone );
+	}
+#endif // EKA2
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/Src/GSSimSecPluginModel.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,184 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Model for Device & SIM security plug-in.
+*
+*/
+
+
+// INCLUDES
+#include "GSSimSecPluginModel.h"
+
+#include <settingsinternalcrkeys.h>
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+const TInt KGSSettingOff = 0;
+// default value for autolock period
+const TInt KGSDefaultAutoLockTime = 0;
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// ============================= LOCAL FUNCTIONS ==============================
+
+// ========================= MEMBER FUNCTIONS =================================
+
+// ----------------------------------------------------------------------------
+// CGSSimSecPluginModel::NewL
+// 
+// Symbian OS two-phased constructor
+// ----------------------------------------------------------------------------
+//
+CGSSimSecPluginModel* CGSSimSecPluginModel::NewL()
+    {
+    CGSSimSecPluginModel* self = new( ELeave ) CGSSimSecPluginModel;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+
+// ----------------------------------------------------------------------------
+// CGSSimSecPluginModel::CGSSimSecPluginModel
+// 
+// 
+// C++ default constructor can NOT contain any code, that might leave.
+// ----------------------------------------------------------------------------
+//
+CGSSimSecPluginModel::CGSSimSecPluginModel()
+    {
+    
+    }
+
+
+// ----------------------------------------------------------------------------
+// CGSSimSecPluginModel::ConstructL
+// 
+// Symbian OS default constructor can leave.
+// ----------------------------------------------------------------------------
+//
+void CGSSimSecPluginModel::ConstructL()
+    {
+    iSecurityRepository = CRepository::NewL( KCRUidSecuritySettings );
+    iPersonalizationRepository = 
+        CRepository::NewL( KCRUidPersonalizationSettings );
+    }
+
+
+// ----------------------------------------------------------------------------
+// CGSSimSecPluginModel::~CGSSimSecPluginModel
+// 
+// Destructor
+// ----------------------------------------------------------------------------
+//
+CGSSimSecPluginModel::~CGSSimSecPluginModel()
+    {
+    delete iSecurityRepository;
+    iSecurityRepository = NULL;
+
+    delete iPersonalizationRepository;
+    iPersonalizationRepository = NULL;
+    }
+
+
+// ----------------------------------------------------------------------------
+// CGSSimSecPluginModel::AutoLockPeriod()
+// 
+// Reads Autolock period from .ini file and returns it
+// ----------------------------------------------------------------------------
+//
+TInt CGSSimSecPluginModel::AutoLockPeriod()
+    {
+    TInt period = KGSSettingOff;
+    
+    if ( iSecurityRepository->
+         Get( KSettingsAutoLockTime, period ) != KErrNone )
+            {
+            period = KGSDefaultAutoLockTime;
+            iSecurityRepository->Set( KSettingsAutoLockTime, period );
+            }
+    
+    return period;
+    }
+            
+// ----------------------------------------------------------------------------
+// CGSSimSecPluginModel::SetAutoLockPeriod
+// 
+// Writes Autolock period time to Cenrep
+// ----------------------------------------------------------------------------
+//
+TBool CGSSimSecPluginModel::SetAutoLockPeriod( TInt aLockTime )
+    {
+    TInt ret = iSecurityRepository->Set( KSettingsAutoLockTime, aLockTime );
+    
+    return ret;
+    }
+
+// ----------------------------------------------------------------------------
+// CGSSimSecPluginModel::SatOperations()
+// 
+// Reads SatOperations value from .ini file and returns it
+// ----------------------------------------------------------------------------
+//
+TInt CGSSimSecPluginModel::SatOperations()
+    {
+    TInt value = KGSSettingOff;
+    
+    iPersonalizationRepository->Get( KSettingsConfirmSatOperations, value );
+    
+    return value;
+    }
+
+
+// ----------------------------------------------------------------------------
+// CGSSimSecPluginModel::SetSatOperations
+// 
+// Write user changes to the .ini file
+// ----------------------------------------------------------------------------
+//
+TBool CGSSimSecPluginModel::SetSatOperations( TInt aValue )
+    {
+    TInt ret = iPersonalizationRepository->
+            Set( KSettingsConfirmSatOperations, aValue );
+    
+    return ret;
+    }
+
+
+// ----------------------------------------------------------------------------
+// CGSSimSecPluginModel::ConfirmSatOperationsSupport
+// 
+// Get Confirm Sat Operations supported value
+// ----------------------------------------------------------------------------
+//
+TInt CGSSimSecPluginModel::ConfirmSatOperationsSupport()
+    {
+    TInt ret = 0;
+    iPersonalizationRepository->
+        Get( KSettingsConfirmSatOperationsSupported, ret );
+    
+    return ret;
+    }
+  
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/GSSimSecPlugin/loc/gssecurity.loc	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,233 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Localization strings for Device & SIM Security view
+*
+*/
+
+
+//-------------------------------------------------------------
+// security view
+//-------------------------------------------------------------
+
+//d: Command in general settings security folder, opens Device & Sim security view
+//l: list_setting_pane_t1
+//w:
+//r:3.0
+#define qtn_set_dev_sim_security "Device & Sim security"
+
+//d:Text in title pane
+//d:Device and SIM Security view
+//l:title_pane_t2/opt9
+//w:
+//r: 3.1
+#define qtn_set_title_security_phone_and_sim "Phone and SIM"
+
+//-------------------------------------------------------------
+// device & sim security view
+//-------------------------------------------------------------
+//d:Code in use setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//w:
+//r:3.0
+#define qtn_set_code_in_use "Code in use"
+
+
+//d: pin code request setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//w:
+//r:3.0
+#define text_pin_code_cntrl "PIN code request"
+
+//d: Upin code request setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//w:
+//r:3.0
+#define qtn_set_upin_code_req "UPIN code request"
+
+
+//d: sim change security setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//w:
+//r:3.0
+#define qtn_set_sim_change_sec "SIM change security"
+
+//d: atulock period setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//w:
+//r:3.0
+#define qtn_set_autolock "Autolock period"
+
+//d: security code setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//w:
+//r:3.0
+#define qtn_set_sec_code "Security code"
+
+//d:Number query: autolock period time in minutes.
+//l:popup_query_data_window
+//w:
+//r:3.0
+#define qtn_set_autolock_define_time "Autolock period time (min)"
+
+//d: pin code setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//w:
+//r:3.0
+#define text_pin_change "PIN code"
+
+//d: upin code setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//w:
+//r:3.0
+#define qtn_set_upin_code "UPIN code"
+
+//d: pin2 code setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//w:
+//r:3.0
+#define text_pin2_change "PIN2 code"
+
+//d: closed user group setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//w:
+//r:3.0
+#define text_closed_user_groups "Closed user group"
+
+//d: item, network default, to closed user group popup list
+//l: list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define text_cug_default "Network default"
+
+//d: item, on,  to closed user group popup list
+//l: list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define text_cug_group "On"
+
+//d: item, off, to closed user group popup list
+//l: list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define text_cug_suppress "Off"
+
+//d: text to number query asking for cug index
+//l: popup_query_data_window
+//w:
+//r:3.0
+#define text_give_group_number "Group number:"
+
+//d: text to cug error note when entered index is too large
+//l: popup_note_window
+//w:
+//r:3.0
+#define text_cug_error "Value too large"		
+	
+//d:sat operations setting item in device & sim security settings folder
+//l:list_setting_pane_t1
+//w:
+//r:3.0
+#define text_simatk_setting "Confirm SAT operations"
+
+//d:list item in pin code request setting page
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define text_pin_code_off "Off"
+
+//d:list item in pin code request setting page
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define text_pin_code_on  "On"
+
+//d:list item in code in use setting page
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define qtn_set_pin "PIN"
+
+//d:list item in code in use setting page
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define qtn_set_upin "UPIN"
+
+//d:list item in sim change security setting page
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define qtn_set_sim_change_sec_off "Off"
+
+//d:list item in sim change security setting page
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define qtn_set_sim_change_sec_on "On"
+
+//d:List item in autolock period setting page
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define qtn_set_autolock_off "Autolock off"
+
+//d:List item in autolock period setting page
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define qtn_set_autolock_defined "User defined"
+
+//d:Autolock period settings (plural) item edit - setting selection data, %N is number 2-999
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define qtn_set_autolock_value_min "%N minutes"
+
+//d:Autolock period settings (singular) item edit - setting selection data, %N is number 1
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define qtn_set_autolock_min_one "%N minute"
+
+//d:Confirm SAT operations value on
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define text_simatk_notes_on "Asked"
+
+//d:Confirm SAT operations value off
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.0
+#define text_simatk_notes_off "Not asked"
+
+//d: Remote lock setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//w:
+//r:3.2
+#define qtn_set_remotelock_status "Allow remote lock"
+
+//d:Remote lock setting state in remote lock setting item in device & sim security settings folder
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.2
+#define qtn_set_remotelock_off "No"
+
+//d:Remote lock setting state in remote lock setting item in device & sim security settings folder
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.2
+#define qtn_set_remotelock_on  "Yes"
+
+//End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Inc/SecUiAutoLockSettingPage.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,72 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Autolock period settingpage     
+*
+*
+*/
+
+
+#ifndef     __CAUTOLOCKSETTINGPAHGE_H
+#define     __CAUTOLOCKSETTINGPAHGE_H
+
+#include    <aknradiobuttonsettingpage.h>
+#include    <eikmobs.h>
+
+class CAutoLockSettingPage : public CAknRadioButtonSettingPage
+	{
+	public:
+		/**
+		* C++ default constructor.
+		*/
+		CAutoLockSettingPage(TInt aResourceId, TInt& aCurrentSelectionItem, CDesCArrayFlat* aItemArray, TInt& aAutoLockValue);
+		/**
+		* Symbian OS constructor.
+		*/
+		void ConstructL();
+		/**
+		* Setmaximum value for autolock period. Used in TARM.
+		*/
+		void SetPeriodMaximumValue(TInt aMaximumValue);
+		
+	protected:
+		/**
+		* Destructor.
+		*/
+		~CAutoLockSettingPage();
+		/**
+		* Process ui commands
+		* from CAknRadioButtonSettingPage
+		* @param aCommandId TInt 
+		*/
+		void ProcessCommandL(TInt aCommandId);
+		/**
+    	* From CAknRadioButtonSettingPage 
+    	* Handles AutoLockSettingPage's PointerEvent 
+    	*    
+    	* @param aPointerEvent PointerEvent to be handled
+    	*/     
+    	void HandlePointerEventL(const TPointerEvent& aPointerEvent);
+    	
+	private: // data
+		CEikButtonGroupContainer* iPopoutCba;
+		TInt& iAutoLockValue;
+		TInt iMaximum;
+		TInt iOriginalIndex;
+		TInt iPrevSelectionItem;
+
+	};
+
+#endif 
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Inc/SecUiCodeQueryControl.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Provides editor clearing method for CodeQueryDialog
+*               and CodeRequestQueryDialog.
+*
+*
+*/
+
+
+
+
+#ifndef __SECUICODEQUERYCONTROL__
+#define __SECUICODEQUERYCONTROL__
+
+#include <aknQueryControl.h>
+
+class CCodeQueryControl : public CAknQueryControl
+	{
+	public://new functions
+		/**
+		* Clears the secret editor
+		* 
+		*/
+		void ResetEditorL();
+		/**
+		* Plays sounds
+		* 
+		* @param aSid TInt 
+		*/
+		void PlaySound(TInt aSid);
+		/**
+		* Checks if there is an emergency number in the input field.
+		*  
+		*/
+		TBool IsEmergencyNumber();
+		/**
+		* Checks if there is an emergency call support flag is on.
+		*  
+		*/
+		TBool IsEmergencyCallSupportOn();
+	};
+
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Inc/SecUiLockObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,88 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Obsererver for Set System Locked event  
+*
+*
+*/
+
+
+#ifndef     __SECUILOCKOBSERVER_H
+#define     __SECUILOCKOBSERVER_H
+
+#include <e32svr.h>
+#include <e32property.h>
+#include "secui.hrh"
+
+class CCodeQueryDialog;
+
+
+NONSHARABLE_CLASS(CSecUiLockObserver): public CActive
+    {
+    public:
+		/**
+        * Creates instance of the CLockObserver class.
+        *
+		* @param aDialog (pointer to code dialog)
+		* @return Returns the instance just created.
+        */
+        static CSecUiLockObserver* NewL(CCodeQueryDialog* aDialog, TInt aType  = ESecUiDeviceLockObserver);
+		/**
+        * Destructor.
+        */
+		~CSecUiLockObserver();
+		/**
+        * Stops listenig PubSub events.
+        */
+		void StopObserver(); 
+		/**
+        * Starts listenig PubSub events.
+        */
+		void StartObserver();
+		/**
+        * Sets the dialog's address.
+        */
+		void SetAddress(CCodeQueryDialog* aDialog);    
+	private:
+        /**
+        * Starts asynchronic listening KUidAutolockStatus event
+        *
+		* @return KErrNone: if no errors
+        * @return KErrInUse: if already listening
+		*/
+		TInt Start();            
+    private: // constructors
+		/**
+        * C++ default constructor.
+		*
+		* @param aDialog (pointer to code dialog)
+        */
+        CSecUiLockObserver(CCodeQueryDialog* aDialog, TInt aType);
+		 /**
+        * Symbian OS constructor.
+        */
+        void ConstructL();
+    private: // from CActive
+         /** @see CActive::RunL() */
+		void RunL();
+		/** @see CActive::DoCancel() */
+        void DoCancel();
+    private: // data
+    	CCodeQueryDialog*      iDialog; //not owned!
+        RProperty            iProperty;
+        TBool				 iSubscribedToEvent;
+        TInt                 iType; //Type of the observer
+    };
+
+#endif 
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Inc/SecUiObsStartter.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Provides api for starting SecurityObserver
+*
+*
+*/
+
+
+#ifndef     __SECUIOBSSTARTTER_H__
+#define     __SECUIOBSSTARTTER_H__
+
+class TObsStarter 
+	{
+	public:
+		/**
+		* Launches SecurityObserver.exe. 
+		* StartObserver() is called from startup app.
+		*/
+		IMPORT_C static void StartObserverL();
+	};
+
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Inc/SecUiRemoteLockSettingPage.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,89 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  RemoteLock pass phrase setting page
+*
+*
+*/
+
+
+#ifndef __SECUIREMOTELOCKSETTINGPAGE_H__
+#define __SECUIREMOTELOCKSETTINGPAGE_H__
+
+#include <aknradiobuttonsettingpage.h>
+#include <eikmobs.h>
+
+
+
+// LOCAL CONSTANTS
+const TInt KRemoteLockSettingItemOn  = 0;
+const TInt KRemoteLockSettingItemOff = 1;
+
+
+
+// CLASS DECLARATIONS
+
+/** 
+* CRemoteLockSettingPage
+*/
+NONSHARABLE_CLASS(CRemoteLockSettingPage) : public CAknRadioButtonSettingPage
+	{
+	public:
+		/**
+		* C++ default constructor.
+		*/
+		CRemoteLockSettingPage( TInt aResourceId, TInt& aCurrentSelectionItem, CDesCArrayFlat* aItemArray );
+
+		/**
+		* Symbian OS constructor.
+		*/
+		void ConstructL();
+
+	protected:
+		/**
+		* Destructor.
+		*/
+		~CRemoteLockSettingPage();
+
+		/**
+		* Process ui commands
+		* from CAknRadioButtonSettingPage
+		* @param aCommandId TInt 
+		*/
+		void ProcessCommandL( TInt aCommandId );
+			/**
+    	* From CAknRadioButtonSettingPage 
+    	* Handles AutoLockSettingPage's PointerEvent 
+    	*    
+    	* @param aPointerEvent PointerEvent to be handled
+    	*/     
+    	void HandlePointerEventL(const TPointerEvent& aPointerEvent);
+
+	private: // data
+
+		CEikButtonGroupContainer* iPopoutCba;
+
+        /** Remote lock status */
+		TInt& iRemoteLockStatus;
+		TInt iPrevSelectionItem;
+	};
+
+
+
+#endif 
+
+
+
+// End of file
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Inc/SecUiSystemLock.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,74 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  System Lock interface
+*
+*/
+
+
+#ifndef     __SECUISYSTEMLOCK_H
+#define     __SECUISYSTEMLOCK_H
+
+//  INCLUDES
+
+#include    <e32base.h>
+#include <e32property.h>
+#include <etelmm.h>
+#include	<rmmcustomapi.h>
+
+//  CLASS DEFINITIONS 
+class  CSystemLock : public CActive
+    {
+    public:
+       /**
+        * Creates instance of the CSystemLock class.
+        *
+		* @return Returns the instance just created.
+        */
+		IMPORT_C static CSystemLock* NewL();
+		/**
+        * Destructor.
+        */
+        IMPORT_C ~CSystemLock();
+    public:
+         /**
+		* Sets the device as locked
+		*/
+		IMPORT_C void SetLockedL();
+	private:
+		/**
+		* C++ default constructor.
+		*/
+		CSystemLock();
+		/**
+		* Symbian OS constructor.
+		*/
+		void ConstructL();
+	private: // from CActive
+        /** @see CActive::RunL() */
+		void RunL();
+		/** @see CActive::DoCancel() */
+        void DoCancel();
+	private:  // data
+		/*****************************************************
+		*	Series 60 Customer / ETel
+		*	Series 60  ETel API
+		*****************************************************/
+		RTelServer			iServer;
+		RMobilePhone		iPhone;
+        RProperty           iProperty;
+		RMmCustomAPI		iCustomPhone;
+	};
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Inc/SecUiWait.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*    
+*
+*/
+
+
+#ifndef     __SECUIWAIT_H
+#define     __SECUIWAIT_H
+
+//  INCLUDES
+
+#include    <e32base.h>
+#include    <eikappui.h>
+#include    <coecntrl.h>
+//  CLASS DEFINITIONS 
+class  CWait : public CActive
+    {
+     public:
+       /**
+        * Creates instance of the CWait class.
+        *
+        * @return Returns the instance just created.
+        */
+        static CWait* NewL();
+        /**
+        * Destructor.
+        */
+        ~CWait();
+    public:
+        /**
+        * Starts waiting for aReqStatus. 
+        */
+        TInt WaitForRequestL();
+    public:
+        /**
+        * Sets active request type. 
+        */
+        void SetRequestType(TInt aRequestType);
+    public:
+        /**
+        * Gets active request type. 
+        */
+        TInt GetRequestType();
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CWait();
+        /**
+        * Symbian OS constructor.
+        */
+        void ConstructL();
+    private: // from CActive
+        /** @see CActive::RunL() */
+        void RunL();
+        /** @see CActive::DoCancel() */
+        void DoCancel();
+        RTimer iTimer;
+        CActiveSchedulerWait iWait;
+        // Used if there is a need to cancel an active request;
+        // namely in situations where destructor is called when Wait
+        // is active.
+        TInt iRequestType;
+    };
+
+
+// CWaitAbsorbingControl, absorbs all the key presses.
+class CWaitAbsorbingControl : public CCoeControl
+    {
+    public:
+        static CWaitAbsorbingControl* NewLC();
+        virtual ~CWaitAbsorbingControl();
+    private:
+        virtual TKeyResponse OfferKeyEventL(const TKeyEvent& /*aKeyEvent*/,TEventCode /*aType*/);
+    private:
+        CWaitAbsorbingControl();
+        void ConstructL();
+    private: // Data
+         CEikAppUi*  iAppUi;
+
+
+    };
+
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Src/SecUi.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,185 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Provides initialization and uninitialization for
+*               secui resource file.
+*
+*
+*/
+
+
+#include <e32std.h>
+#include <eikenv.h>
+#include <bautils.h>
+#include "secui.h"
+#include 	<data_caging_path_literals.hrh>
+
+_LIT(KDirAndFile,"z:SecUi.rsc");
+
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// TSecUi::InitializeLibL()
+// Initializes SecUi resource file
+// ----------------------------------------------------------
+//
+EXPORT_C void TSecUi::InitializeLibL()
+	{
+	if (Dll::Tls()!=NULL)
+    {//Secui has been initialized already; increase client count.
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI): InitializeLibL: Secui has been initialized already"));
+        #endif
+        TSecUi* instance=(TSecUi*) Dll::Tls();
+        instance->IncreaseClientCount();
+        return;
+    }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI): InitializeLibL: First initialization"));
+    #endif
+	TSecUi* self = new (ELeave) TSecUi();
+	CleanupStack::PushL(self);
+	self->ConstructL();
+    self->IncreaseClientCount();
+	Dll::SetTls(self);
+	CleanupStack::Pop();
+	}
+//
+// ----------------------------------------------------------
+// TSecUi::UnInitializeLib()
+// Uninitializes SecUi resource file
+// ----------------------------------------------------------
+//
+EXPORT_C void TSecUi::UnInitializeLib()
+	{
+    if (Dll::Tls()==NULL)
+        return;
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI): UnInitializeLibL"));
+    #endif
+	TSecUi* instance=(TSecUi*) Dll::Tls();
+    instance->DecreaseClientCount();
+    //only delete the lib is there are no clients using it
+    if(instance->CanBeFreed())
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI): UnInitializeLibL: Last uninitialize"));
+        #endif
+	    delete instance;
+	    Dll::SetTls(NULL);
+        }
+	}
+
+//
+// ----------------------------------------------------------
+// TSecUi::TSecUi()
+// C++ default constructor
+// ----------------------------------------------------------
+//
+TSecUi::TSecUi()
+	{
+	
+	}
+//
+// ----------------------------------------------------------
+// TSecUi::TSecUi()
+// Destructor
+// ----------------------------------------------------------
+//
+TSecUi::~TSecUi()
+	{
+	if (iResourceFileOffset >= 0)
+		{
+		CEikonEnv::Static()->DeleteResourceFile(iResourceFileOffset);
+		}
+	}
+//
+// ----------------------------------------------------------
+// TSecUi::ConstructL()
+// Symbian OS default constructor
+// ----------------------------------------------------------
+//
+void TSecUi::ConstructL()
+	{
+	iResourceFileOffset = CCoeEnv::Static()->AddResourceFileL(ResourceFileName());
+    iClientCount = 0;
+	}
+//
+// ----------------------------------------------------------
+// TSecUi::ResourceFileName
+// Returns the resource file name of SecurityUI dll.
+// ----------------------------------------------------------
+//
+TFileName TSecUi::ResourceFileName()
+	{
+	
+	TParse parse;
+    parse.Set(KDirAndFile, &KDC_RESOURCE_FILES_DIR, NULL); 
+	TFileName resourceFileName(parse.FullName());
+	BaflUtils::NearestLanguageFile(CCoeEnv::Static()->FsSession(), resourceFileName);
+	return resourceFileName;
+	
+	}
+
+// -----------------------------------------------------------------------------
+// TSecUi::CanBeFreed()
+// -----------------------------------------------------------------------------
+//
+TBool TSecUi::CanBeFreed()
+    {
+	if (iClientCount <= 0)
+	{
+        #if defined(_DEBUG)
+		RDebug::Print(_L("(SECUI): No clients; Can be freed: clients(%d) "), iClientCount);
+        #endif
+		return ETrue;
+	}
+	else
+	{
+        #if defined(_DEBUG)
+		RDebug::Print(_L("(SECUI): Can NOT be freed: clients(%d) "), iClientCount);
+		#endif
+        return EFalse;
+	}
+    }
+
+// -----------------------------------------------------------------------------
+// TSecUi::IncreaseClientCount()
+// -----------------------------------------------------------------------------
+//
+void TSecUi::IncreaseClientCount()
+    {
+	++iClientCount;
+    #if defined(_DEBUG)
+	RDebug::Print(_L("(SECUI): IncreaseClientCount, clients now(%d) "), iClientCount);
+    #endif
+    }
+
+// -----------------------------------------------------------------------------
+// TSecUi::DecreaseClientCount()
+// -----------------------------------------------------------------------------
+//
+
+void TSecUi::DecreaseClientCount()
+    {
+	--iClientCount;
+    #if defined(_DEBUG)
+	RDebug::Print(_L("(SECUI): DecreaseClientCount, clients now(%d) "), iClientCount);
+    #endif
+    }
+
+	
+// End of file
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Src/SecUiAutoLockSettingPage.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,244 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Autolock period settingpage
+*
+*
+*/
+
+#include <eikmenub.h>
+#include <SecUi.rsg>
+#include <e32base.h>
+#include <AknQueryDialog.h>
+#include "SecUiAutoLockSettingPage.h"
+#include "secui.hrh"
+#include <featmgr.h>
+/**
+*CAutolockQuery used in autolock period query
+*/
+class CAutolockQuery
+	: public CAknNumberQueryDialog
+	{
+	public: // Constructors and destructors
+		/**
+		* C++ constructor.
+		*/
+		CAutolockQuery(TInt& aNumber,const TTone aTone = ENoTone);
+	protected: // From base classes
+		/**
+		* From CCAknNumberQueryDialog 
+		*/
+		void PreLayoutDynInitL();
+	};
+//
+// ----------------------------------------------------------
+// CAutoLockSettingPage::CAutoLockSettingPage()
+// C++ default constructor
+// ----------------------------------------------------------
+// 
+CAutoLockSettingPage::CAutoLockSettingPage(TInt aResourceId, TInt& aCurrentSelectionItem, CDesCArrayFlat* aItemArray, TInt& aAutoLockValue) : 
+					CAknRadioButtonSettingPage(aResourceId, aCurrentSelectionItem, aItemArray),iAutoLockValue(aAutoLockValue)
+
+	{
+        iOriginalIndex = aCurrentSelectionItem;
+	iPrevSelectionItem = aCurrentSelectionItem;
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoLockSettingPage::ConstructL()
+// Symbian OS default constructor
+// ----------------------------------------------------------
+// 
+void CAutoLockSettingPage::ConstructL()
+	{
+	CAknRadioButtonSettingPage::ConstructL();
+	const TSize screenSize = iCoeEnv->ScreenDevice()->SizeInPixels();
+	iPopoutCba = CEikButtonGroupContainer::NewL(CEikButtonGroupContainer::ECba, CEikButtonGroupContainer::EHorizontal, this, R_AVKON_SOFTKEYS_OK_CANCEL__OK);
+	iPopoutCba->SetBoundingRect(TRect(screenSize));
+	FeatureManager::InitializeLibL();
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoLockSettingPage::CAutoLockSettingPage()
+// Destructor
+// ----------------------------------------------------------
+// 
+CAutoLockSettingPage::~CAutoLockSettingPage()
+	{
+	delete iPopoutCba;
+	FeatureManager::UnInitializeLib();
+	}
+
+//
+// ----------------------------------------------------------
+// CAutoLockSettingPage::ProcessCommandL()
+// 
+// ----------------------------------------------------------
+// 
+void CAutoLockSettingPage::ProcessCommandL(TInt aCommandId)
+	{
+	TInt cur = ListBoxControl()->CurrentItemIndex();
+	// Respond to softkey events
+
+	switch (aCommandId)
+		{
+		case EAknSoftkeySelect:
+		case EAknSoftkeyOk:
+			// autolock off
+			if (cur == 0)
+				{
+				iAutoLockValue = 0;
+				if(iOriginalIndex == 0)
+				    { //User re-selected "Autolock off"; no use in changing lock setting
+				        AttemptExitL(EFalse);
+				    }
+				else
+				    {
+				        AttemptExitL(ETrue);
+				    }
+				
+				}
+			// user defined
+			if (cur == 1)
+				{
+				CAutolockQuery* dlg = new (ELeave) CAutolockQuery(iAutoLockValue);
+				dlg->PrepareLC(R_AUTOLOCK_TIME_QUERY);
+				if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))
+				{
+				//set min and max values from SCP server to the dialog.
+				TInt minimum = 0;
+				if(iMaximum <= 0) //maximum value has not been defined; default value used instead.
+				    iMaximum = 1440;
+				dlg->SetMinimumAndMaximum(minimum, iMaximum);
+			}
+				if(dlg->RunLD())
+					{
+					AttemptExitL(ETrue);
+					}
+				else
+					AttemptExitL(EFalse);
+				}
+			break;
+
+		default:
+			CAknSettingPage::ProcessCommandL(aCommandId);
+			break;
+		}
+
+	}
+//
+// ----------------------------------------------------------
+// CAutoLockSettingPage::SetPeriodMaximumValue()
+// 
+// ----------------------------------------------------------
+// 
+void CAutoLockSettingPage::SetPeriodMaximumValue(TInt aMaximumValue)
+	{
+	if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))
+	{
+		iMaximum = aMaximumValue;
+}
+	}
+	
+//---------------------------------------------------------------------------------------
+// CAutoLockSettingPage::HandlePointerEventL()
+// Passes pointer events to CAknRadioButtonSettingPage
+// 
+//---------------------------------------------------------------------------------------
+//
+
+void CAutoLockSettingPage::HandlePointerEventL(const TPointerEvent& aPointerEvent)
+    {
+    if ( AknLayoutUtils::PenEnabled() )
+        {
+        	TInt cur = ListBoxControl()->CurrentItemIndex();
+         	CAknRadioButtonSettingPage::HandlePointerEventL(aPointerEvent);
+         	//only take into account the "Up" event. Otherwise we'll end up having 2 dialogs.
+         	if(aPointerEvent.iType == TPointerEvent::EButton1Up)
+         	{
+		if(iPrevSelectionItem!=cur)
+			iPrevSelectionItem=cur;
+		else
+         	{
+         	    //only react to the event if the pen is actually inside the dialog.
+         	    if(ListBoxControl()->Rect().Contains(aPointerEvent.iPosition))
+         	        {
+         	            // autolock off
+        				if (cur == 0)
+        					{
+        					    iAutoLockValue = 0;
+        						if(iOriginalIndex == 0)
+                				    { //User re-selected "Autolock off"; no use in changing lock setting
+                				        AttemptExitL(EFalse);
+                				    }
+                				else
+                				    {
+                				        AttemptExitL(ETrue);
+                				    }
+        					}
+        				// user defined
+        				if (cur == 1)
+        					{
+        					CAutolockQuery* dlg = new (ELeave) CAutolockQuery(iAutoLockValue);
+						dlg->PrepareLC(R_AUTOLOCK_TIME_QUERY);
+					if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))
+					{
+        					//set min and max values from SCP server to the dialog.
+        					TInt minimum = 0;			
+				          if(iMaximum <= 0) //maximum value has not been defined; default value used instead.
+				            iMaximum = 1440;        						
+        					dlg->SetMinimumAndMaximum(minimum, iMaximum);
+				}
+        					if(dlg->RunLD())
+        						{
+        						AttemptExitL(ETrue);
+        						}
+        					else
+        						AttemptExitL(EFalse);
+         	        }
+         		
+				}
+		    }
+         	}
+        }
+    }
+//
+// ---------------------------------------------------------
+// CAutolockQuery::CAutolockQuery()
+// 
+// ---------------------------------------------------------
+//
+CAutolockQuery::CAutolockQuery(TInt& aNumber,const TTone aTone)
+	: CAknNumberQueryDialog( aNumber, aTone)
+	{
+	}
+	
+//
+// ---------------------------------------------------------
+// CAutolockQuery::PreLayoutDynInitL()
+// 
+// ---------------------------------------------------------
+//
+void CAutolockQuery::PreLayoutDynInitL()
+	{
+	CAknNumberQueryDialog::PreLayoutDynInitL();
+	if (iNumber == 0)
+		{
+		MakeLeftSoftkeyVisible(EFalse);
+		}
+	}
+    
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Src/SecUiCodeQueryControl.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,105 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Provides editor clearing method for CodeQueryDialog
+*               and CodeRequestQueryDialog.
+*
+*
+*/
+
+#include <aknQueryControl.h>
+#include <aknsoundsystem.h>
+#include <aknappui.h>
+#include <eikenv.h>
+#include <uikon/eiksrvui.h>
+#include <AknEcs.h>
+#include "SecUiCodeQueryControl.h"
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CCodeQueryControl::ResetEditor()
+// Empties editor
+// ----------------------------------------------------------
+//
+void CCodeQueryControl::ResetEditorL()
+	{
+	if (iPinEdwin)
+		{
+		// reset editor
+		iPinEdwin->Reset();
+		// handle event editor empty
+		HandleControlEventL(iPinEdwin,EEventStateChanged);
+		}
+		
+	if (iEcsDetector)
+        {//Reset ECS buffer
+        iEcsDetector->Reset();
+        }
+	}
+//
+// ----------------------------------------------------------
+// CCodeQueryControl::PlaySound()
+// Plays a tone
+// ----------------------------------------------------------
+//
+void CCodeQueryControl::PlaySound(TInt aSid)
+	{ 
+	CAknKeySoundSystem* soundSystem;
+	if (iEikonEnv->AppUi())
+		{
+		soundSystem = static_cast<CAknAppUi*>(iEikonEnv->EikAppUi())->KeySounds();
+		soundSystem->PlaySound(aSid);
+		}
+	}
+//
+// ----------------------------------------------------------
+// CCodeQueryControl::IsEmergencyNumber()
+// Checks if the characters in the input field are emergency numbers.
+// ----------------------------------------------------------
+//
+TBool CCodeQueryControl::IsEmergencyNumber()
+{
+    TBool returnvalue = EFalse;
+    if (iEcsDetector)
+        {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CCodeQueryControl::IsEmergencyNumber() ecs OK"));
+            #endif
+        if(iEcsDetector->State()== CAknEcsDetector::ECompleteMatch)
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CCodeQueryControl::IsEmergencyNumber() Complete match"));
+            #endif
+            returnvalue = ETrue;
+            }
+        }
+    return returnvalue;
+}
+//
+// ----------------------------------------------------------
+// CCodeQueryControl::IsEmergencyNumber()
+// Checks if the characters in the input field are emergency numbers.
+// ----------------------------------------------------------
+//
+TBool CCodeQueryControl::IsEmergencyCallSupportOn()
+{
+	TBool returnvalue = EFalse;
+    if (iEcsDetector)
+    	{
+    		returnvalue = ETrue;
+    	}
+  return returnvalue;
+}
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Src/SecUiCodeQueryDialog.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,507 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Dialog used for code queries.
+*
+*
+*/
+
+#include <AknQueryDialog.h>
+#include "secuicodequerydialog.h"
+#include <eikseced.h>
+#include "SecUiCodeQueryControl.h"
+#include "secui.hrh"
+#include <SecUi.rsg>
+#include <aknsoundsystem.h>
+#include <aknappui.h> 
+#include <AknIncallBubbleNotify.h>
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CCodeQueryDialog::CCodeQueryDialog()
+// C++ constructor
+// ----------------------------------------------------------
+//
+EXPORT_C CCodeQueryDialog::CCodeQueryDialog(TDes& aDataText,TInt aMinLength,TInt aMaxLength,TInt aMode, TBool aIsRemoteLockQuery):
+			CAknTextQueryDialog(aDataText,ENoTone), iMinLength(aMinLength), iMaxLength(aMaxLength), iMode(aMode), iIsRemoteLockQuery(aIsRemoteLockQuery)
+
+	{		
+	}
+//
+// ----------------------------------------------------------
+// CCodeQueryDialog::~CodeQueryDialog()
+// Destructor
+// ----------------------------------------------------------
+//
+CCodeQueryDialog::~CCodeQueryDialog()
+	{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CCodeQueryDialog::~CCodeQueryDialog()"));
+    #endif
+    
+    if ( AknLayoutUtils::PenEnabled() )
+        {
+        TRAP_IGNORE ( SetIncallBubbleAllowedInUsualL( ETrue ) );
+        }
+    
+	if (iFront)
+		{
+		// uncapture keys  
+		if (iMode != ESecUiNone)		
+			{
+			RWindowGroup& groupWin=iCoeEnv->RootWin();
+			groupWin.CancelCaptureKeyUpAndDowns(iAppKey);
+			groupWin.CancelCaptureKeyUpAndDowns(iVoiceKey2);
+			groupWin.CancelCaptureKey(iVoiceKey1);
+			}
+			
+		CAknAppUi* aknappui =static_cast<CAknAppUi*>(iEikonEnv->EikAppUi());
+		
+		if(!iIsRemoteLockQuery)
+		    {
+		    // return normal high-priority in case there are other notifiers active 
+    		// and were are not going to lose foregroung right after following call     
+        	if (!aknappui->IsFullScreenApp())//check that we are autolock and not a "normal" i.e. full screen application.	
+    			iEikonEnv->RootWin().SetOrdinalPosition(0,ECoeWinPriorityAlwaysAtFront); 
+		    }
+		
+		 
+		iEikonEnv->BringForwards(EFalse);	
+		iEikonEnv->EikAppUi()->RemoveFromStack(this);
+		aknappui->KeySounds()->ReleaseContext();
+		aknappui->KeySounds()->PopContext();		
+		iFront = EFalse;
+		}
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CCodeQueryDialog::~CCodeQueryDialog() END"));
+    #endif
+	}
+//
+// ----------------------------------------------------------
+// CCodeQueryDialog::PreLayoutDynInitL()
+// Called by framework before dialog is shown 
+// ----------------------------------------------------------
+//
+void CCodeQueryDialog::PreLayoutDynInitL()
+    {
+    CAknTextQueryDialog::PreLayoutDynInitL();
+    
+    //disable in call bubble.
+    if ( AknLayoutUtils::PenEnabled() )
+        {
+        SetIncallBubbleAllowedInUsualL( EFalse );
+        }
+    
+	SetMaxLength(iMaxLength);
+	// Add this higher than the environment filter, otherwise
+	// we cannot capture keys from the EikSrvUi KeyFilter. 
+	// Used because this query might be called from notifier
+	if (iMode == ESecUiNone)
+		{
+		iEikonEnv->EikAppUi()->AddToStackL(this,ECoeStackPriorityEnvironmentFilter+100,ECoeStackFlagRefusesAllKeys);
+		}
+	else
+		{
+		iEikonEnv->EikAppUi()->AddToStackL(this,ECoeStackPriorityEnvironmentFilter+100,ECoeStackFlagRefusesFocus);
+		}
+	
+	// capture app,voice and end keys if necessary
+	if (iMode != ESecUiNone)		
+		{
+		
+		RWindowGroup& groupWin=iCoeEnv->RootWin();
+		// Capture app key
+		iAppKey = groupWin.CaptureKeyUpAndDowns(EStdKeyApplication0, 0, 0);
+		// capture voice key
+		iVoiceKey1 = groupWin.CaptureKey(EKeySide,0,0);
+		iVoiceKey2 = groupWin.CaptureKeyUpAndDowns(EStdKeyDevice6, 0, 0);
+		}
+    if (!iIsRemoteLockQuery)
+        {
+        MakeLeftSoftkeyVisible(EFalse);
+
+        RWsSession& wsSession = iEikonEnv->WsSession();
+        TInt myWgId = iEikonEnv->RootWin().Identifier();
+
+        TInt wgPrio = wsSession.GetWindowGroupOrdinalPriority(myWgId);
+        // we are already on forgeround, need to update priority differently
+        /*
+         if (wgPrio == ECoeWinPriorityAlwaysAtFront)
+         {
+         iEikonEnv->RootWin().SetOrdinalPosition(0,ECoeWinPriorityAlwaysAtFront+1); 
+         }
+         */
+
+        // this must be done always to keep the reference count in synch  
+        // this does not have any effect if autoforwarding has not been set true (normal application.)
+        iEikonEnv->BringForwards(ETrue, ECoeWinPriorityAlwaysAtFront + 1);
+
+        /// -- Change Window Priority for dialog and CBA 	
+        DrawableWindow()->SetOrdinalPosition(0, ECoeWinPriorityAlwaysAtFront); //
+        ButtonGroupContainer().ButtonGroup()->AsControl()->DrawableWindow()->SetOrdinalPosition(
+                0, ECoeWinPriorityAlwaysAtFront);
+        }
+    	
+	//key sounds
+	static_cast<CAknAppUi*>(iEikonEnv->EikAppUi())->KeySounds()->PushContextL(R_AVKON_DEFAULT_SKEY_LIST);
+	static_cast<CAknAppUi*>(iEikonEnv->EikAppUi())->KeySounds()->BringToForeground();
+	static_cast<CAknAppUi*>(iEikonEnv->EikAppUi())->KeySounds()->LockContext();
+	iFront = ETrue;
+
+	}
+//
+// ---------------------------------------------------------
+// CCodeQueryDialog::OfferKeyEventL
+// called by framework when any key is pressed
+// ---------------------------------------------------------
+//
+TKeyResponse CCodeQueryDialog::OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType)
+	{
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CCodeQueryDialog::OfferKeyEventL"));
+    TInt keycode = aKeyEvent.iCode;
+    RDebug::Print(_L("(SECUI)CCodeQueryDialog::OfferKeyEventL keycode: %d"), keycode);
+    TInt scancode = aKeyEvent.iScanCode;
+    RDebug::Print(_L("(SECUI)CCodeQueryDialog::OfferKeyEventL scancode: %d"), scancode);
+    #endif
+    if(!iIsRemoteLockQuery)
+        {
+        // '#' key 
+    	if( aKeyEvent.iScanCode == EStdKeyHash  && aType == EEventKeyUp)
+    		{ 
+    		TryExitL(EEikBidOk);
+    		return EKeyWasConsumed;
+    		}
+    	
+    	// '*' key
+    	if (aKeyEvent.iCode == '*')
+    		{
+    		return EKeyWasConsumed;
+    		}
+
+        }
+	
+	// app key
+	if (aKeyEvent.iScanCode == EStdKeyApplication0)
+		{
+		if (iMode == ESecUiNone)
+			{
+			TryExitL(EAknSoftkeyCancel);
+			return EKeyWasNotConsumed;	
+			}
+		return EKeyWasConsumed;
+		}
+		
+	// end key
+	if (aKeyEvent.iCode == EKeyPhoneEnd)
+		{
+		#if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CCodeQueryDialog::OfferKeyEventL: EKeyPhoneEnd"));
+        #endif
+		TryExitL(EAknSoftkeyCancel);
+		return EKeyWasConsumed;
+		}
+	if ((aKeyEvent.iScanCode == EStdKeyYes))
+	    {//Since dialler listens to down/up event, 
+	     //have to consume those to prevent it from opening
+	    if(AknLayoutUtils::PenEnabled())
+	       {
+	       CCodeQueryControl* control = STATIC_CAST(CCodeQueryControl*,Control(EGeneralQuery));
+	       if(!control->IsEmergencyCallSupportOn())
+	         { //Only needed in dialogs where there is no emergency call support
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(SECUI)CCodeQueryDialog::OfferKeyEventL: Send down/up event consumed."));
+                #endif
+                return EKeyWasConsumed;
+	         }
+	       }    
+	    }
+	if (aKeyEvent.iCode == EKeyPhoneSend)
+		 {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CCodeQueryDialog::OfferKeyEventL: EKeyPhoneSend"));
+            #endif
+		    if(AknLayoutUtils::PenEnabled())
+		        {
+		        #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CCodeQueryDialog::OfferKeyEventL: pen enabled"));
+            #endif
+	    		 	CCodeQueryControl* control = STATIC_CAST(CCodeQueryControl*,Control(EGeneralQuery));
+	    		 	if(control->IsEmergencyCallSupportOn())
+	    		 	  {
+			    		 	#if defined(_DEBUG)
+		            RDebug::Print(_L("(SECUI)CCodeQueryDialog::OfferKeyEventL: ECS on"));
+		            #endif
+		    		 	if(!control->IsEmergencyNumber())
+		    		 	  {
+		    		 	  	#if defined(_DEBUG)
+			            RDebug::Print(_L("(SECUI)CCodeQueryDialog::OfferKeyEventL: Not E number!"));
+			            #endif
+            			
+		    		 	    ShowWarningNoteL();
+		    		 	 
+		    		 	    #if defined(_DEBUG)
+			            RDebug::Print(_L("(SECUI)CCodeQueryDialog::OfferKeyEventL: send key consumed!"));
+			            #endif
+		    		 	      return EKeyWasConsumed;
+		    		 	  }
+	    		 	  }
+	    		 	else //consume the key to prevent dialler from opening
+	    		 	    {
+                        #if defined(_DEBUG)
+                        RDebug::Print(_L("(SECUI)CCodeQueryDialog::OfferKeyEventL: No ECS. send key consumed!"));
+                        #endif
+	    		 	        return EKeyWasConsumed;
+	    		 	    }
+			      }
+		 }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CCodeQueryDialog::OfferKeyEventL: To AVKON"));
+    #endif
+	return CAknTextQueryDialog::OfferKeyEventL(aKeyEvent,aType);
+	}
+//
+// ---------------------------------------------------------
+// CCodeQueryDialog::NeedToDismissQueryL()
+// Handles '#' key called by CAknTextQueryDialog::OfferKeyEventL()
+// ---------------------------------------------------------
+//
+TBool CCodeQueryDialog::NeedToDismissQueryL(const TKeyEvent& /*aKeyEvent*/)
+	{
+	return EFalse;
+	}
+//
+// ---------------------------------------------------------
+// CCodeQueryDialog::OkToExitL()
+// called by framework when the Softkey is pressed
+// ---------------------------------------------------------
+//
+TBool CCodeQueryDialog::OkToExitL(TInt aButtonId)
+	{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CCodeQueryDialog::OkToExitL:%d"), aButtonId);
+    #endif
+	CCodeQueryControl* control = STATIC_CAST(CCodeQueryControl*,Control(EGeneralQuery));
+	TInt lenght = 0;
+	TBool returnvalue;
+	switch(aButtonId)
+	    {
+	    case EAknSoftkeyOk:
+		    #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CCodeQueryDialog::OkToExitL:EAknSoftkeyOk"));
+            #endif
+            if(control)
+              {
+                lenght = control->GetTextLength();
+              }
+		    if (lenght < iMinLength)
+			    {
+			    #if defined(_DEBUG)
+                RDebug::Print(_L("(SECUI)CCodeQueryDialog::OkToExitL:length < MIN: %d"), lenght);
+                #endif	
+		    	// code was too short -> play error tone & clear editor
+			    if (lenght != 0)
+				    {
+				    #if defined(_DEBUG)
+                    RDebug::Print(_L("(SECUI)CCodeQueryDialog::OkToExitL:length < MIN, Play Sound"));
+                    #endif
+                    if(control)
+                        {
+                        
+			    	    control->PlaySound(EAvkonSIDErrorTone);
+				        #if defined(_DEBUG)
+                        RDebug::Print(_L("(SECUI)CCodeQueryDialog::OkToExitL:length < MIN, Reset Editor"));
+                        #endif
+				        control->ResetEditorL();
+                        }
+				    }
+			    returnvalue = EFalse;
+			    }	
+		    else
+			    {
+			    #if defined(_DEBUG)
+                RDebug::Print(_L("(SECUI)CCodeQueryDialog::OkToExitL:length >= MIN: %d"), lenght);
+                #endif		
+			    returnvalue = CAknTextQueryDialog::OkToExitL(aButtonId);
+			    }
+            break;
+		
+	    case EEikBidCancel: //Also includes EAknSoftkeyCancel as they have the same numerical value
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CCodeQueryDialog::OkToExitL:EEikBidCancel"));
+            #endif       
+            if(iMode != ESecUiNone) //PUK1 code or PIN1 in boot. Must not exit until code has been input.
+                {
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(SECUI)CCodeQueryDialog::OkToExitL:EEikBidCancel: get length."));
+                #endif   
+                if(control)
+                  {
+                    lenght = control->GetTextLength();
+                  }
+                returnvalue = EFalse;
+                if (lenght > 0) //reset editor
+                    {  
+                    #if defined(_DEBUG)
+                    RDebug::Print(_L("(SECUI)CCodeQueryDialog::OkToExitL:EEikBidCancel: length >0."));
+                    #endif              
+                     if (control)
+                       {
+                        #if defined(_DEBUG)
+                        RDebug::Print(_L("(SECUI)CCodeQueryDialog::OkToExitL:EEikBidCancel, reset editor"));
+                        #endif
+                        control->ResetEditorL();
+                       }
+                    }
+                }
+            else
+                returnvalue = ETrue;
+            break;
+        case  ESecUiEmergencyCall: //user has called emergency number from dialog; exit.
+        	#if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CCodeQueryDialog::OkToExitL:Emergency Call"));
+            #endif
+        	returnvalue = ETrue;
+        	break;
+        case EAknSoftkeyEmergencyCall:
+            returnvalue = ETrue;
+            CAknTextQueryDialog::OkToExitL(aButtonId);
+            break;
+	    case ESecUiDeviceLocked: //Dialog was left open when Device lock was activated by timer and must be closed.
+	    	#if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CCodeQueryDialog::OkToExitL:Phone Locked"));
+            #endif
+	    	if(iMode == ESecUiNone)  
+                 returnvalue = ETrue;//Not a PUK1 code query.
+            else
+            	 returnvalue = EFalse;
+	    	break;
+        default:
+        	#if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CCodeQueryDialog::OkToExitL:DEFAULT!"));
+            #endif  
+            if(iMode == ESecUiNone)
+		        returnvalue = ETrue;
+		    else
+                returnvalue = EFalse;
+            break;
+	    }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CCodeQueryDialog::OkToExitL:END: %d"), returnvalue);
+    #endif
+	return returnvalue;
+	}
+//
+// ---------------------------------------------------------
+// CCodeQueryDialog::HandleQueryEditorStateEventL()
+// Gets called when editor sends state event
+// ---------------------------------------------------------
+//
+TBool CCodeQueryDialog::HandleQueryEditorStateEventL(CAknQueryControl* aQueryControl, 
+													TQueryControlEvent aEventType, 
+													TQueryValidationStatus aStatus)
+{
+	
+    if (aEventType == MAknQueryControlObserver::EEmergencyCallAttempted)
+        {
+        TryExitL(ESecUiEmergencyCall);
+        return EFalse;
+        }
+    else
+    	{
+    	return CAknQueryDialog::HandleQueryEditorStateEventL(aQueryControl, aEventType, aStatus );
+    	}
+    
+
+}
+//
+// ---------------------------------------------------------
+// CCodeQueryDialog::TryCancelQueryL()
+// Gets called when a client wishes to cancel the query
+// ---------------------------------------------------------
+//
+void CCodeQueryDialog::TryCancelQueryL(TInt aReason)
+{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CCodeQueryDialog::TryCancelQuery BEGIN"));
+    #endif
+	TryExitL(aReason);
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CCodeQueryDialog::TryCancelQuery END"));
+    #endif
+}
+
+// -----------------------------------------------------------------------------
+// CCodeQueryDialog::CheckIfEntryTextOk()
+// -----------------------------------------------------------------------------
+//
+TBool CCodeQueryDialog::CheckIfEntryTextOk() const
+    {
+	CCodeQueryControl* control = STATIC_CAST(CCodeQueryControl*,Control(EGeneralQuery));
+	if (control)
+	{
+		control->GetText(iDataText);
+	}
+	const TInt textLength = Text().Length();
+	return (textLength <= iMaxLength && textLength >= iMinLength);
+    }
+
+// -----------------------------------------------------------------------------
+// CCTPinQueryDialog::UpdateLeftSoftKeyL()
+// -----------------------------------------------------------------------------
+//
+void CCodeQueryDialog::UpdateLeftSoftKeyL()
+    {
+	CAknTextQueryDialog::UpdateLeftSoftKeyL();
+    if(iIsRemoteLockQuery)
+	    MakeLeftSoftkeyVisible(CheckIfEntryTextOk());
+    }
+// -----------------------------------------------------------------------------
+// CCodeQueryDialog::ShowWarningNoteL()
+// -----------------------------------------------------------------------------
+//
+void CCodeQueryDialog::ShowWarningNoteL()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CCodeQueryDialog::ShowWarningNoteL BEGIN"));
+    #endif
+    
+    CAknNoteDialog* noteDlg = new (ELeave) CAknNoteDialog();
+    noteDlg->PrepareLC(R_EMERGENCY_CALLS_ONLY);
+    noteDlg->SetTimeout(CAknNoteDialog::ELongTimeout);
+    noteDlg->SetTone(CAknNoteDialog::EErrorTone);
+    
+    noteDlg->DrawableWindow()->SetOrdinalPosition(0,ECoeWinPriorityAlwaysAtFront+1); //
+    noteDlg->ButtonGroupContainer().ButtonGroup()->AsControl()->DrawableWindow()->SetOrdinalPosition(0,ECoeWinPriorityAlwaysAtFront+1); 
+    
+    noteDlg->RunLD();
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CCodeQueryDialog::ShowWarningNoteL END"));
+    #endif
+    }
+
+// -----------------------------------------------------------------------------
+// CCodeQueryDialog::SetIncallBubbleAllowedInUsualL()
+// -----------------------------------------------------------------------------
+//
+void CCodeQueryDialog::SetIncallBubbleAllowedInUsualL(TBool aAllowed)
+    {
+    CAknIncallBubble *incallBubble =  CAknIncallBubble::NewL();
+    CleanupStack::PushL(incallBubble);
+    incallBubble->SetIncallBubbleAllowedInUsualL( aAllowed );
+    CleanupStack::PopAndDestroy();
+    }
+
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Src/SecUiLockObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,271 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Obsererver for Set System Locked event  
+*
+*
+*/
+
+
+#include    <e32property.h>
+#include	<PSVariables.h>
+#include	<coreapplicationuisdomainpskeys.h>
+#include <ctsydomainpskeys.h>
+#include    <securityuisprivatepskeys.h>
+#include "secuicodequerydialog.h"
+#include "secui.hrh"
+#include "SecUiLockObserver.h"
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CSecUiLockObserver::NewL()
+// Constructs a new entry with given values.
+// ----------------------------------------------------------
+//
+CSecUiLockObserver* CSecUiLockObserver::NewL(CCodeQueryDialog* aDialog, TInt aType)
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::NewL() BEGIN"));
+    #endif
+    CSecUiLockObserver* self = new (ELeave) CSecUiLockObserver(aDialog, aType);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop();
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::NewL() END"));
+    #endif
+    return self;
+    }
+//
+// ----------------------------------------------------------
+// CSecUiLockObserver::CSecUiLockObserver()
+// Destructor
+// ----------------------------------------------------------
+//
+CSecUiLockObserver::~CSecUiLockObserver()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::~CSecUiLockObserver"));
+    #endif
+    Cancel();
+    }
+//
+// ----------------------------------------------------------
+// CSecUiLockObserver::Start()
+// Starts listening an event 
+// ----------------------------------------------------------
+//
+TInt CSecUiLockObserver::Start()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::Start() BEGIN"));
+    #endif
+    if (IsActive())
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::Start() In use!!!"));
+    #endif
+    return KErrInUse;
+    }
+        
+    iStatus = KRequestPending;
+    
+    switch(iType)
+        {
+            case ESecUiDeviceLockObserver:
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(SECUI)CSecUiLockObserver::Start() Device Lock Observer"));
+                #endif
+                iProperty.Attach(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus); 
+                break;
+            
+            case ESecUiRequestStateObserver:
+                    #if defined(_DEBUG)
+                    RDebug::Print(_L("(SECUI)CSecUiLockObserver::Start() Request State Observer"));
+                    #endif
+                    iProperty.Attach(KPSUidSecurityUIs, KSecurityUIsQueryRequestCancel); 
+                break;
+            case ESecUiCallStateObserver:
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(SECUI)CSecUiLockObserver::Start() Call State Observer"));
+                #endif
+                iProperty.Attach(KPSUidCtsyCallInformation, KCTsyCallState); 
+                break;
+            default:
+                break;
+        }
+    
+    iProperty.Subscribe(iStatus);
+    SetActive();
+    iSubscribedToEvent = ETrue;
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::Start() END"));
+    #endif
+    return KErrNone;
+    }
+//
+// ----------------------------------------------------------
+// CLockObserver::CLockObserver()
+// C++ constructor
+// ----------------------------------------------------------
+// 
+CSecUiLockObserver::CSecUiLockObserver(CCodeQueryDialog* aDialog, TInt aType) : CActive(0), iDialog(aDialog), iSubscribedToEvent(EFalse), iType(aType)
+	{                            
+    }
+//
+// ----------------------------------------------------------
+// CSecUiLockObserver::ConstructL()
+// Symbian OS default constructor
+// ----------------------------------------------------------
+// 
+void CSecUiLockObserver::ConstructL()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::ConstructL() BEGIN"));
+    #endif
+    // Add this active object to the scheduler.
+	CActiveScheduler::Add(this);
+	// Begin obsering PubSub event  
+	Start();
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::ConstructL() END"));
+    #endif	
+    }
+//
+// ----------------------------------------------------------
+// CSecUiLockObserver::RunL()
+// Called by Active Scheduler
+// ----------------------------------------------------------
+// 
+void CSecUiLockObserver::RunL()
+	{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::RunL() BEGIN"));
+    #endif
+    
+    switch(iType)
+        {
+            case ESecUiDeviceLockObserver:
+                 TInt autolockState;
+                 iProperty.Get( autolockState );
+                 if (autolockState > EAutolockOff)
+                    {
+                    #if defined(_DEBUG)
+                    RDebug::Print(_L("(SECUI)CSecUiLockObserver::RunL() TryCancelQueryL Device Lock"));
+                    #endif
+                	iDialog->TryCancelQueryL(ESecUiDeviceLocked);
+                	iSubscribedToEvent = EFalse;
+                    }
+                break;
+            
+            case ESecUiRequestStateObserver:
+                 TInt requestState;
+                 iProperty.Get( requestState );
+                 if(requestState == ESecurityUIsQueryRequestCanceled)
+                    {
+                     #if defined(_DEBUG)
+                    RDebug::Print(_L("(SECUI)CSecUiLockObserver::RunL() TryCancelQueryL Req Canceled"));
+                    #endif
+                	iDialog->TryCancelQueryL(EEikBidCancel);
+                	iSubscribedToEvent = EFalse;   
+                    }
+                break;
+            case ESecUiCallStateObserver:
+                TInt callState;
+                iProperty.Get( callState );
+                if(callState > EPSCTsyCallStateNone)
+                    {
+                     #if defined(_DEBUG)
+                    RDebug::Print(_L("(SECUI)CSecUiLockObserver::RunL() TryCancelQueryL Active Call"));
+                    #endif
+                	iDialog->TryCancelQueryL(EEikBidCancel);
+                	iSubscribedToEvent = EFalse;   
+                    }
+                break;
+            default:
+                break;
+        }
+
+   
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::RunL() END"));
+    #endif
+	}
+//
+// ----------------------------------------------------------
+// CSecUiLockObserver::DoCancel()
+// Cancels event listening
+// ----------------------------------------------------------
+// 
+void CSecUiLockObserver::DoCancel()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::DoCancel() BEGIN"));
+    #endif
+    if(iSubscribedToEvent)
+    	iProperty.Cancel();
+    iStatus = KErrNone;
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::DoCancel() END"));
+    #endif
+    }
+//
+// ----------------------------------------------------------
+// CSecUiLockObserver::StopObserver()
+// Cancels event listening
+// ----------------------------------------------------------
+//     
+void CSecUiLockObserver::StopObserver()
+	{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::StopObserver() BEGIN"));
+    #endif
+    Cancel();
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::StopObserver() END"));
+    #endif
+    }
+//
+// ----------------------------------------------------------
+// CSecUiLockObserver::StartObserver()
+// Start event listening
+// ----------------------------------------------------------
+//     
+void CSecUiLockObserver::StartObserver()
+	{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::StartObserver() BEGIN"));
+    #endif
+    Start();
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::StartObserver() END"));
+    #endif
+    }
+//
+// ----------------------------------------------------------
+// CSecUiLockObserver::SetAddress()
+// Start event listening
+// ----------------------------------------------------------
+//  
+void CSecUiLockObserver::SetAddress(CCodeQueryDialog* aDialog)
+{
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::SetAddress() BEGIN"));
+    #endif
+	iDialog = aDialog;
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecUiLockObserver::SetAddress() END"));
+    #endif
+}
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Src/SecUiManualSecuritySettings.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,609 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Provides api for changing security settings via PhoneApp
+*     
+*
+*/
+
+
+#include <rmmcustomapi.h>
+#include <SecUi.rsg>
+#include "secuimanualsecuritysettings.h"
+#include <exterror.h>
+#include "SecUiWait.h"
+#include <mmtsy_names.h>
+    /*****************************************************
+    *    Series 60 Customer / TSY
+    *    Needs customer TSY implementation
+    *****************************************************/
+//  LOCAL CONSTANTS AND MACROS  
+
+
+
+_LIT(Operator,"1");
+_LIT(Gid1,"2");
+_LIT(Gid2,"3");
+_LIT(Imsi,"4");
+_LIT(Operator_Gid1,"5");
+_LIT(Operator_Gid2,"6");
+_LIT(GlobalUnlock, "7");
+
+const TInt KTriesToConnectServer( 2 );
+const TInt KTimeBeforeRetryingServerConnection( 50000 );
+const TInt PhoneIndex( 0 );
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CManualSecuritySettings::NewL()
+// Constructs a new entry with given values.
+// ----------------------------------------------------------
+//
+EXPORT_C CManualSecuritySettings* CManualSecuritySettings::NewL()
+    {
+    CManualSecuritySettings* self = new (ELeave) CManualSecuritySettings();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+//
+// ----------------------------------------------------------
+// CManualSecuritySettings::CManualSecuritySettings()
+// constructor
+// ----------------------------------------------------------
+//
+CManualSecuritySettings::CManualSecuritySettings()
+    {
+    }
+
+//
+// ----------------------------------------------------------
+// CManualSecuritySettings::ConstructL()
+// Symbian OS constructor.
+// ----------------------------------------------------------
+//
+void CManualSecuritySettings::ConstructL()
+    {
+    
+    iWait = CWait::NewL();
+    
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    /*****************************************************
+    *    Series 60 Customer / TSY
+    *    Needs customer TSY implementation
+    *****************************************************/
+    TInt err( KErrGeneral );
+    TInt thisTry( 0 );
+    RTelServer::TPhoneInfo PhoneInfo;
+    /* All server connections are tried to be made KTriesToConnectServer times because occasional
+    fails on connections are possible, at least on some servers */
+
+    // connect ETel server
+    while ( ( err = iServer.Connect() ) != KErrNone && ( thisTry++ ) <= KTriesToConnectServer )
+        {
+        User::After( KTimeBeforeRetryingServerConnection );
+        }
+    User::LeaveIfError( err );
+
+    // load TSY
+    err = iServer.LoadPhoneModule( KMmTsyModuleName );
+    if ( err != KErrAlreadyExists )
+        {
+        // May also return KErrAlreadyExists if something else
+        // has already loaded the TSY module. And that is
+        // not an error.
+        User::LeaveIfError( err );
+        }
+
+    // open phones
+    User::LeaveIfError(iServer.SetExtendedErrorGranularity(RTelServer::EErrorExtended));
+    User::LeaveIfError(iServer.GetPhoneInfo(PhoneIndex, PhoneInfo));
+    User::LeaveIfError(iPhone.Open(iServer,PhoneInfo.iName));
+    User::LeaveIfError(iCustomPhone.Open(iPhone));
+    }
+//
+// ----------------------------------------------------------
+// CManualSecuritySettings::~CManualSecuritySettings()
+// Destructor
+// ----------------------------------------------------------
+//
+EXPORT_C CManualSecuritySettings::~CManualSecuritySettings()
+    {    
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    /*****************************************************
+    *    Series 60 Customer / TSY
+    *    Needs customer TSY implementation
+    *****************************************************/
+	#if defined(_DEBUG)
+	RDebug::Print(_L("(SECUI)CManualSecuritySettings::~CManualSecuritySettings()"));
+	#endif
+    // Cancel active requests
+    if(iWait->IsActive())
+    {
+        #if defined(_DEBUG)
+	    RDebug::Print(_L("(SECUI)CManualSecuritySettings::~CManualSecuritySettings() CANCEL REQ"));
+	    #endif
+        iPhone.CancelAsyncRequest(iWait->GetRequestType());
+    }
+    // close phone
+    if (iPhone.SubSessionHandle())
+        iPhone.Close();
+    // close custom phone
+    if (iCustomPhone.SubSessionHandle())
+        iCustomPhone.Close();
+    //close ETel connection
+    if (iServer.Handle())
+        {
+        iServer.UnloadPhoneModule(KMmTsyModuleName);
+        iServer.Close();
+        }
+    delete iNote;
+    delete iWait;
+	#if defined(_DEBUG)
+	RDebug::Print(_L("(SECUI)CManualSecuritySettings::~CManualSecuritySettings() END"));
+	#endif  
+    }
+
+//
+// ----------------------------------------------------------
+// CManualSecuritySettings::ChangePinL()
+// Changes pin
+// ----------------------------------------------------------
+//
+EXPORT_C TBool CManualSecuritySettings::ChangePinL(TPin aPin,const TDesC& aOld,const TDesC& aNew,const TDesC& aVerifyNew )
+    {    
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CManualSecuritySettings::ChangePinL()"));
+    #endif        
+    if (aPin == EPin1)
+        {
+		#if defined(_DEBUG)
+		RDebug::Print(_L("(SECUI)CManualSecuritySettings::ChangePinL() PIN1"));
+		#endif        
+        RMobilePhone::TMobilePhoneLock lockType;
+        RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;
+        RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
+
+
+        lockType = RMobilePhone::ELockICC;
+        // check if pin code is enabled...
+        // The following is required, since the new multimode Etel is asynchronous
+        // rather than synchronous.
+    
+		#if defined(_DEBUG)
+		RDebug::Print(_L("(SECUI)CManualSecuritySettings::ChangePinL() GetLockInfo"));
+		#endif
+
+        iWait->SetRequestType(EMobilePhoneGetLockInfo);
+        iPhone.GetLockInfo(iWait->iStatus, lockType, lockInfoPkg);
+        TInt res = iWait->WaitForRequestL();
+         
+        if (res != KErrNone)
+            return EFalse;
+        // if pin is disabled -> pin code change is not allowed
+        if (lockInfo.iSetting == RMobilePhone::ELockSetDisabled)
+            {    
+            ShowResultNoteL(CAknNoteDialog::EErrorTone,R_PIN_NOT_ALLOWED);
+            return EFalse;
+            }
+        }
+    
+	#if defined(_DEBUG)
+	RDebug::Print(_L("(SECUI)CManualSecuritySettings::ChangePinL() CompareF"));
+	#endif
+    if (aNew.CompareF(aVerifyNew) != 0)     
+        {
+        // codes do not match note 
+        ShowResultNoteL(CAknNoteDialog::EErrorTone,R_CODES_DONT_MATCH);
+        return EFalse;
+        }
+    
+
+    RMobilePhone::TMobilePhoneSecurityCode secCodeType;
+    if (aPin == EPin1)
+        {
+        secCodeType = RMobilePhone::ESecurityCodePin1;
+        }
+    else
+        {
+        secCodeType = RMobilePhone::ESecurityCodePin2;
+        }
+
+    RMobilePhone::TMobilePhonePasswordChangeV1 aChange;
+    aChange.iOldPassword = aOld;
+    aChange.iNewPassword = aNew;
+
+	#if defined(_DEBUG)
+	RDebug::Print(_L("(SECUI)CManualSecuritySettings::ChangePinL() ChangeSecurityCode"));
+	#endif
+    iWait->SetRequestType(EMobilePhoneChangeSecurityCode);
+    iPhone.ChangeSecurityCode(iWait->iStatus,secCodeType,aChange);
+    TInt res = iWait->WaitForRequestL();
+    
+	#if defined(_DEBUG)
+	RDebug::Print(_L("(SECUI)CManualSecuritySettings::ChangePinL() ChangeSecurityCode RES: %d"), res);
+	#endif
+
+    switch(res)
+        {        
+        case KErrNone:
+            if (aPin == EPin1)
+                {
+                ShowResultNoteL(CAknNoteDialog::EConfirmationTone,R_PIN_CODE_CHANGED_NOTE);
+                }
+            else
+                {
+                ShowResultNoteL(CAknNoteDialog::EConfirmationTone,R_PIN2_CODE_CHANGED_NOTE);
+                }
+            return ETrue;
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            if (aPin == EPin1)
+                {
+                ShowResultNoteL(CAknNoteDialog::EErrorTone,R_PIN_BLOCKED_NOTE);
+                }
+            else
+                {
+                iCustomPhone.CheckSecurityCode(iWait->iStatus,RMmCustomAPI::ESecurityCodePuk2);
+                TInt res = iWait->WaitForRequestL();
+                }
+            break;
+        case KErrGsm0707OperationNotAllowed:
+            ShowResultNoteL(CAknNoteDialog::EErrorTone,R_OPERATION_NOT_ALLOWED);
+            break;
+        default:
+            ShowResultNoteL(CAknNoteDialog::EErrorTone,R_CODE_ERROR);
+            break;
+        }
+    
+    return EFalse;
+    }
+//
+// ----------------------------------------------------------
+// CManualSecuritySettings::CancelChangePin()
+// Deletes pin operation note if necessary
+// ----------------------------------------------------------
+//
+EXPORT_C void CManualSecuritySettings::CancelChangePin()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CManualSecuritySettings::CancelChangePin()"));
+    #endif    
+    delete iNote;
+    iNote = NULL;
+    }
+//
+// ----------------------------------------------------------
+// CManualSecuritySettings::UnblockPinL()
+// Unblocks pin 
+// ----------------------------------------------------------
+//    
+EXPORT_C TBool CManualSecuritySettings::UnblockPinL(TPin aPin,const TDesC& aPuk,const TDesC& aNew,const TDesC& aVerifyNew )
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CManualSecuritySettings::UnblockPinL()"));
+    #endif        
+    if (aNew.CompareF(aVerifyNew) != 0)     
+        {
+        // codes do not match note 
+        ShowResultNoteL(CAknNoteDialog::EErrorTone,R_CODES_DONT_MATCH);
+        return EFalse;
+        }
+    
+    RMobilePhone::TMobilePhoneSecurityCode blockCodeType;
+    
+    if (aPin == EPin1)
+        {
+        blockCodeType = RMobilePhone::ESecurityCodePuk1;
+        }
+    else
+        {
+        blockCodeType = RMobilePhone::ESecurityCodePuk2;
+        }
+
+    iWait->SetRequestType(EMobilePhoneVerifySecurityCode);
+    iPhone.VerifySecurityCode(iWait->iStatus, blockCodeType, aNew, aPuk);
+    TInt res = iWait->WaitForRequestL();
+
+    switch(res)
+        {        
+        case KErrNone:
+            if (aPin == EPin1)
+                {
+                ShowResultNoteL(CAknNoteDialog::EConfirmationTone,R_PIN_CODE_CHANGED_NOTE);
+                }
+            else
+                {
+                ShowResultNoteL(CAknNoteDialog::EConfirmationTone,R_PIN2_CODE_CHANGED_NOTE);
+                }
+            return ETrue;
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            if (aPin == EPin2)
+                {
+                ShowResultNoteL(CAknNoteDialog::EErrorTone,R_PIN2_REJECTED);
+                }
+            break;
+        case KErrGsm0707OperationNotAllowed:
+            ShowResultNoteL(CAknNoteDialog::EErrorTone,R_OPERATION_NOT_ALLOWED);
+            break;
+        default:
+            ShowResultNoteL(CAknNoteDialog::EErrorTone,R_CODE_ERROR);
+            break;
+        }
+
+    return EFalse;
+    }
+//
+// ----------------------------------------------------------
+// CManualSecuritySettings::CancelUnblockPin()
+// Deletes unblock pin operation note if necessary
+// ----------------------------------------------------------
+//    
+EXPORT_C void CManualSecuritySettings::CancelUnblockPin()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CManualSecuritySettings::CancelUnblockPinL()"));
+    #endif        
+    delete iNote;
+    iNote = NULL;        
+    }
+//
+// ----------------------------------------------------------
+// CManualSecuritySettings::LockSimL()
+// 
+// ----------------------------------------------------------
+//        
+EXPORT_C TBool CManualSecuritySettings::LockSimL(const TDesC& aLockCode,const TDesC& aType )
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CManualSecuritySettings::LockSimL()"));
+    #endif
+
+    
+    RMmCustomAPI::TLockNumber aLockType;
+    TInt ret = KErrGsm0707IncorrectPassword;
+    TInt length = aLockCode.Length();
+
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CManualSecuritySettings::LockSimL(): Param length: %d"), length);
+    #endif
+
+    if(aLockCode.Length() <= KSimLockMaxPasswordSize)
+    {
+    if (aType.CompareF(Operator) == 0)
+        {
+        aLockType = RMmCustomAPI::EOperator;
+        ret = iCustomPhone.ActivateSimLock( aLockCode,aLockType );
+        }
+
+    if (aType.CompareF(Gid1) == 0)
+        {
+        aLockType = RMmCustomAPI::EGid1;
+        ret = iCustomPhone.ActivateSimLock( aLockCode,aLockType );
+        }
+
+    if (aType.CompareF(Gid2) == 0)
+        {
+        aLockType = RMmCustomAPI::EGid2;
+        ret = iCustomPhone.ActivateSimLock( aLockCode,aLockType );
+        }
+
+    if (aType.CompareF(Imsi) == 0)
+        {
+        aLockType = RMmCustomAPI::EImsi;
+        ret = iCustomPhone.ActivateSimLock( aLockCode,aLockType );
+        }
+
+    if (aType.CompareF(Operator_Gid1) == 0)
+        {    
+        aLockType = RMmCustomAPI::EOperator_Gid1;
+        ret = iCustomPhone.ActivateSimLock( aLockCode,aLockType );
+        }
+
+    if (aType.CompareF(Operator_Gid2) == 0)
+        {
+        aLockType = RMmCustomAPI::EOperator_Gid2;
+        ret = iCustomPhone.ActivateSimLock( aLockCode,aLockType );
+        }
+    }
+
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CManualSecuritySettings::LockSimL() RESULT: %d"), ret);
+    #endif
+    switch (ret)
+        {
+        case KErrNone:
+            ShowResultNoteL(CAknNoteDialog::EConfirmationTone,R_SIM_ON);
+            return ETrue;
+        case KErrAlreadyExists:
+            ShowResultNoteL(CAknNoteDialog::EConfirmationTone,R_SIM_ALLREADY_ON);
+            break;
+        case KErrGeneral:
+        case KErrLocked:
+        case KErrAccessDenied:
+        case KErrNotSupported:
+        case KErrGsm0707OperationNotAllowed:
+            ShowResultNoteL(CAknNoteDialog::EErrorTone,R_SIM_NOT_ALLOWED);
+            break;
+        case KErrArgument:
+        case KErrGsm0707IncorrectPassword:
+            ShowResultNoteL(CAknNoteDialog::EErrorTone,R_CODE_ERROR);
+            break;
+        default:
+            break;
+        }
+
+    return EFalse;
+    }
+
+//
+// ----------------------------------------------------------
+// CManualSecuritySettings::CancelLockSim()
+// 
+// ----------------------------------------------------------
+//        
+EXPORT_C void CManualSecuritySettings::CancelLockSim()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CManualSecuritySettings::CancelLockSimL()"));
+    #endif
+    delete iNote;
+    iNote = NULL;    
+    }    
+//
+// ----------------------------------------------------------
+// CManualSecuritySettings::UnlockSimL()
+// 
+// ----------------------------------------------------------
+//            
+EXPORT_C TBool CManualSecuritySettings::UnlockSimL(const TDesC& aUnlockCode,const TDesC& aType )
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CManualSecuritySettings::UnLockSimL()"));
+    #endif
+    RMmCustomAPI::TLockNumber aLockType;
+    TInt ret = KErrGsm0707IncorrectPassword;
+    TInt length = aUnlockCode.Length();
+
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CManualSecuritySettings::UnLockSimL(): Param length: %d"), length);
+    #endif
+    if(aUnlockCode.Length() <= KSimLockMaxPasswordSize)
+    {
+    if (aType.CompareF(Operator) == 0)
+        {
+        aLockType = RMmCustomAPI::EOperator;
+        ret = iCustomPhone.DeActivateSimLock( aUnlockCode,aLockType );
+        }
+
+    if (aType.CompareF(Gid1) == 0)
+        {
+        aLockType = RMmCustomAPI::EGid1;
+        ret = iCustomPhone.DeActivateSimLock( aUnlockCode,aLockType );
+        }
+
+    if (aType.CompareF(Gid2) == 0)
+        {
+        aLockType = RMmCustomAPI::EGid2;
+        ret = iCustomPhone.DeActivateSimLock( aUnlockCode,aLockType );
+        }
+
+    if (aType.CompareF(Imsi) == 0)
+        {
+        aLockType = RMmCustomAPI::EImsi;
+        ret = iCustomPhone.DeActivateSimLock( aUnlockCode,aLockType );
+        }
+
+    if (aType.CompareF(Operator_Gid1) == 0)
+        {    
+        aLockType = RMmCustomAPI::EOperator_Gid1;
+        ret = iCustomPhone.DeActivateSimLock( aUnlockCode,aLockType );
+        }
+
+    if (aType.CompareF(Operator_Gid2) == 0)
+        {
+        aLockType = RMmCustomAPI::EOperator_Gid2;
+        ret = iCustomPhone.DeActivateSimLock( aUnlockCode,aLockType );
+        }
+    if (aType.CompareF(GlobalUnlock) == 0)
+        {
+        aLockType = RMmCustomAPI::EGlobalUnlock;
+        ret = iCustomPhone.DeActivateSimLock( aUnlockCode,aLockType );
+        }    
+        
+    }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CManualSecuritySettings::UnLockSimL() RESULT: %d"), ret);
+    #endif
+    switch (ret)
+        {
+        case KErrNone:
+            ShowResultNoteL(CAknNoteDialog::EConfirmationTone,R_SIM_OFF);
+            return ETrue;
+        case KErrAlreadyExists:
+            ShowResultNoteL(CAknNoteDialog::EConfirmationTone,R_SIM_ALLREADY_OFF);
+            break;
+        case KErrGeneral:
+        case KErrLocked:
+        case KErrAccessDenied:
+        case KErrGsm0707OperationNotAllowed:
+            ShowResultNoteL(CAknNoteDialog::EErrorTone,R_SIM_NOT_ALLOWED);
+            break;
+        case KErrArgument:
+        case KErrGsm0707IncorrectPassword:
+            ShowResultNoteL(CAknNoteDialog::EErrorTone,R_CODE_ERROR);
+            break;
+        default:
+            break;
+        }
+
+    return EFalse;
+    }
+//
+// ----------------------------------------------------------
+// CManualSecuritySettings::CancelUnlockSim()
+// 
+// ----------------------------------------------------------
+//                
+EXPORT_C void CManualSecuritySettings::CancelUnlockSim()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CManualSecuritySettings::CancelUnLockSimL()"));
+    #endif
+    delete iNote;
+    iNote = NULL;
+    }
+
+//
+// ----------------------------------------------------------
+// CManualSecuritySettings::ShowResultNoteL()
+// Shows settingchange results
+// ----------------------------------------------------------
+//
+void CManualSecuritySettings::ShowResultNoteL(CAknNoteDialog::TTone aTone, TInt aResourceID)
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CManualSecuritySettings::CancelUnLockSimL()"));
+    #endif
+    iNote = new (ELeave) CAknNoteDialog(REINTERPRET_CAST(CEikDialog**,&iNote));
+    iNote->SetTimeout(CAknNoteDialog::ELongTimeout);
+    iNote->SetTone(aTone);
+    iNote->ExecuteLD(aResourceID);
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Src/SecUiObsStartter.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of TObsStarter, which provides api
+*               for starting SecurityObserver.exe
+*
+*
+*/
+
+
+// INCLUDES
+#include <eikdll.h>
+#include <data_caging_path_literals.hrh> 
+
+#include "SecUiObsStartter.h"
+
+
+//  LOCAL CONSTANTS AND MACROS  
+_LIT(ObserverName,"SecurityObserver.exe");
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CObsStartter::StartObserverL()
+// Launches SecurityObserver.exe. StartObserverL() is called from startup.
+// ----------------------------------------------------------
+//
+EXPORT_C void TObsStarter::StartObserverL()
+	{
+	RProcess process; 
+    HBufC* observerPath = HBufC::NewLC(KMaxPath);
+    TPtr ObserverEXE(observerPath->Des());
+    ObserverEXE.Append(_L("Z:"));
+    ObserverEXE.Append(KDC_PROGRAMS_DIR);
+    ObserverEXE.Append(ObserverName);
+
+		TInt err = process.Create( ObserverEXE, KNullDesC );
+		process.Resume();
+		if (err)
+			{
+			// Panic here in order to enter SW
+			// reset mechanism.
+			User::Panic(ObserverEXE,err);
+			}
+    CleanupStack::PopAndDestroy(observerPath);
+	}
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Src/SecUiRemoteLockSettingPage.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,181 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  RemoteLock (on/off) setting page
+*
+*
+*/
+
+#include <aknnotewrappers.h>
+#include <eikmenub.h>
+#include <SecUi.rsg>
+#include <e32base.h>
+
+#include "SecUiRemoteLockSettingPage.h"
+#include "secui.hrh"
+
+
+
+// ----------------------------------------------------------
+// CRemoteLockSettingPage::CRemoteLockSettingPage()
+// C++ default constructor
+// ----------------------------------------------------------
+CRemoteLockSettingPage::CRemoteLockSettingPage( TInt aResourceId, TInt& aCurrentSelectionItem, CDesCArrayFlat* aItemArray )
+: CAknRadioButtonSettingPage( aResourceId, aCurrentSelectionItem, aItemArray ),
+  iRemoteLockStatus( aCurrentSelectionItem )
+    {
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(SecUi)CRemoteLockSettingPage::CRemoteLockSettingPage()" ) );
+    #endif // DEBUG
+    iPrevSelectionItem = aCurrentSelectionItem;
+    }
+
+
+
+// ----------------------------------------------------------
+// CRemoteLockSettingPage::ConstructL()
+// Symbian OS default constructor
+// ----------------------------------------------------------
+void CRemoteLockSettingPage::ConstructL()
+    {
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(SecUi)CRemoteLockSettingPage::ConstructL() - Enter" ) );
+    #endif // DEBUG
+
+    CAknRadioButtonSettingPage::ConstructL();
+    const TSize screenSize = iCoeEnv->ScreenDevice()->SizeInPixels();
+    iPopoutCba = CEikButtonGroupContainer::NewL( CEikButtonGroupContainer::ECba, CEikButtonGroupContainer::EHorizontal, this, R_AVKON_SOFTKEYS_OK_CANCEL__OK );
+    iPopoutCba->SetBoundingRect( TRect( screenSize ) );
+
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(SecUi)CRemoteLockSettingPage::ConstructL() - Exit" ) );
+    #endif // DEBUG
+
+    return;
+    }
+
+
+
+// ----------------------------------------------------------
+// CRemoteLockSettingPage::~CRemoteLockSettingPage()
+// Destructor
+// ----------------------------------------------------------
+CRemoteLockSettingPage::~CRemoteLockSettingPage()
+    {
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(SecUi)CRemoteLockSettingPage::~CRemoteLockSettingPage() - Enter" ) );
+    #endif // DEBUG
+
+    delete iPopoutCba;
+    iPopoutCba = NULL;
+
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(SecUi)CRemoteLockSettingPage::~CRemoteLockSettingPage() - Exit" ) );
+    #endif // DEBUG
+    }
+
+
+
+// ----------------------------------------------------------
+// CRemoteLockSettingPage::ProcessCommandL()
+// 
+// ----------------------------------------------------------
+void CRemoteLockSettingPage::ProcessCommandL( TInt aCommandId )
+    {
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(SecUi)CRemoteLockSettingPage::ProcessCommandL() - Enter" ) );
+    #endif // DEBUG
+
+	TInt currentItem = ListBoxControl()->CurrentItemIndex();
+	// Respond to softkey events
+
+	switch ( aCommandId )
+		{
+		case EAknSoftkeySelect:
+		case EAknSoftkeyOk:
+		    {
+		    switch ( currentItem )
+		        {
+		        case KRemoteLockSettingItemOn: // RemoteLock on
+		            iRemoteLockStatus = KRemoteLockSettingItemOn;
+		            AttemptExitL( ETrue );
+		            break;
+
+		        case KRemoteLockSettingItemOff: // RemoteLock off
+		            iRemoteLockStatus = KRemoteLockSettingItemOff;
+		            AttemptExitL( ETrue );
+		            break;
+
+                default:
+                    // Do nothing
+                    break;
+                }
+			break;
+		    }
+
+		default:
+			CAknSettingPage::ProcessCommandL( aCommandId );
+			break;
+		}
+
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(SecUi)CRemoteLockSettingPage::ProcessCommandL() - Exit" ) );
+    #endif // DEBUG
+
+    return;
+	}
+//---------------------------------------------------------------------------------------
+// CRemoteLockSettingPage::HandlePointerEventL()
+// Passes pointer events to CAknRadioButtonSettingPage
+// 
+//---------------------------------------------------------------------------------------
+//
+
+void CRemoteLockSettingPage::HandlePointerEventL(const TPointerEvent& aPointerEvent)
+    {
+    if ( AknLayoutUtils::PenEnabled() )
+        {       	        	
+            TInt currentItem = ListBoxControl()->CurrentItemIndex();
+            CAknRadioButtonSettingPage::HandlePointerEventL(aPointerEvent);
+            
+    		if(aPointerEvent.iType == TPointerEvent::EButton1Up)
+    		    {
+		    if(iPrevSelectionItem!=currentItem)
+			iPrevSelectionItem=currentItem;
+		    else
+		    {
+    		    switch ( currentItem )
+    		        {
+    		        case KRemoteLockSettingItemOn: // RemoteLock on
+    		            iRemoteLockStatus = KRemoteLockSettingItemOn;
+    		            AttemptExitL( ETrue );
+    		            break;
+
+    		        case KRemoteLockSettingItemOff: // RemoteLock off
+    		            iRemoteLockStatus = KRemoteLockSettingItemOff;
+    		            AttemptExitL( ETrue );
+    		            break;
+
+                    default:
+                        // Do nothing
+                        break;
+                    }
+                    }
+    		    }
+    		    
+        }
+    }
+
+
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Src/SecUiSecurityHandler.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,2249 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Provides api for handling security events.
+*
+*
+*/
+
+
+#include <aknnotedialog.h>
+#include <etelmm.h>
+#include <SecUi.rsg>
+#include <exterror.h>
+#include <textresolver.h>
+
+#ifdef __COVER_DISPLAY
+#include <aknmediatorfacade.h>
+#include <secondarydisplay/SecondaryDisplayStartupAPI.h>
+#endif //__COVER_DISPLAY
+
+#include <centralrepository.h> 
+#include <starterclient.h>     //used for RemoveSplashScreen
+#include <e32property.h>
+#include <PSVariables.h>   // Property values
+#include <coreapplicationuisdomainpskeys.h>
+#include <startupdomainpskeys.h>
+#include <uikon/eiksrvui.h>
+#include <settingsinternalcrkeys.h>
+#include <securityuisprivatepskeys.h>
+#include <AknNotiferAppServerApplication.h>
+
+#include <SCPClient.h>
+#include <securitynotification.h>
+#include "secui.hrh"
+#include "secuisecurityhandler.h"
+#include "secuicodequerydialog.h"
+#include "secuisecuritysettings.h"
+#include "SecUiWait.h"
+#include "SecUiLockObserver.h"
+#ifdef RD_REMOTELOCK
+#include <RemoteLockSettings.h>
+#endif // RD_REMOTELOCK
+#include <StringLoader.h>
+#include <featmgr.h>
+//  LOCAL CONSTANTS AND MACROS
+const TInt KMaxNumberOfPUKAttempts(10);
+const TInt KMaxNumberOfPINAttempts(3);
+const TInt KLastRemainingInputAttempt(1);
+
+const TInt KTriesToConnectServer( 2 );
+const TInt KTimeBeforeRetryingRequest( 50000 );
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CSecurityHandler::CSecurityHandler()
+// C++ constructor
+// ----------------------------------------------------------
+//
+EXPORT_C CSecurityHandler::CSecurityHandler(RMobilePhone& aPhone):
+        iPhone(aPhone), iQueryCanceled(ETrue), iSecurityDlg(NULL), iNoteDlg(NULL) 
+    {
+        TInt result = iCustomPhone.Open(aPhone);
+        TRAP_IGNORE( FeatureManager::InitializeLibL() ); //Shouldn't this panic if FM does not initialise??
+    }
+
+//
+// ----------------------------------------------------------
+// CSecurityHandler::~CSecurityHandler()
+// Destructor
+// ----------------------------------------------------------
+//
+EXPORT_C CSecurityHandler::~CSecurityHandler()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("CSecurityHandler::~CSecurityHandler()"));
+    #endif
+    if ( iDestroyedPtr )
+        {
+        *iDestroyedPtr = ETrue;
+        iDestroyedPtr = NULL;
+        }
+    CancelSecCodeQuery();
+    iCustomPhone.Close();
+    FeatureManager::UnInitializeLib();
+    }
+//
+// ----------------------------------------------------------
+// CSecurityHandler::HandleEventL()
+// Handles different security events
+// ----------------------------------------------------------
+//
+EXPORT_C void CSecurityHandler::HandleEventL(
+    RMobilePhone::TMobilePhoneSecurityEvent aEvent )
+    {
+    TInt result = KErrNone;
+    HandleEventL( aEvent, result );
+    }
+
+//
+// ----------------------------------------------------------
+// CSecurityHandler::HandleEventL()
+// Handles different security events
+// ----------------------------------------------------------
+//
+EXPORT_C void CSecurityHandler::HandleEventL(
+    RMobilePhone::TMobilePhoneSecurityEvent aEvent,
+    TBool aStartup, TInt& aResult )
+    {
+    iStartup = aStartup;
+    HandleEventL( aEvent, aResult );
+    }
+    
+//
+// ----------------------------------------------------------
+// CSecurityHandler::HandleEventL()
+// Handles different security events
+// ----------------------------------------------------------
+//
+EXPORT_C void CSecurityHandler::HandleEventL(
+    RMobilePhone::TMobilePhoneSecurityEvent aEvent, TInt& aResult )
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::HandleEventL()"));
+    RDebug::Print(_L("(SECUI)CSecurityHandler::HandleEventL() EVENT: %d"), aEvent);
+    #endif
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+ 
+    switch(aEvent)
+            {
+            case RMobilePhone::EPin1Required:
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(SECUI)CSecurityHandler::HandleEventL() Pin1Required"));
+                #endif
+                aResult = Pin1RequiredL();
+                break;
+            case RMobilePhone::EPuk1Required:
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(SECUI)CSecurityHandler::HandleEventL() PUK1Required"));
+                #endif
+                ((CAknNotifierAppServerAppUi*)(CEikonEnv::Static())->EikAppUi())->SuppressAppSwitching(ETrue);
+                TRAPD(err,aResult = Puk1RequiredL());
+                ((CAknNotifierAppServerAppUi*)(CEikonEnv::Static())->EikAppUi())->SuppressAppSwitching(EFalse);
+                User::LeaveIfError(err);
+                break;
+            case RMobilePhone::EPin2Required:
+                Pin2RequiredL();
+                break;
+            case RMobilePhone::EPuk2Required:
+                Puk2RequiredL();        
+                break;
+            case RMobilePhone::EUniversalPinRequired:
+                if(wcdmaSupported || upinSupported)
+                   {
+                       aResult = UPinRequiredL();
+                   }
+                else
+                    aResult = KErrNotSupported;
+                break;
+            case RMobilePhone::EUniversalPukRequired:
+                if(wcdmaSupported || upinSupported)
+                   {
+                       aResult = UPukRequiredL();
+                   }
+                else
+                    aResult = KErrNotSupported;
+                break;
+            case RMobilePhone::EPhonePasswordRequired:
+                aResult = PassPhraseRequiredL();
+                break;
+            case RMobilePhone::EICCTerminated:
+                SimLockEventL();
+                break;
+            default:
+                break;
+            }
+    #if defined(_DEBUG)
+    RDebug::Print( _L( "CSecurityHandler::HandleEventL() returning %d." ), aResult );
+    #endif
+    }
+//
+// ----------------------------------------------------------
+// CSecurityHandler::AskSecCodeL()
+// For asking security code e.g in settings
+// ----------------------------------------------------------
+//
+EXPORT_C TBool CSecurityHandler::AskSecCodeL()
+    {        
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::AskSecCodeL()"));
+    #endif
+    // Destructor sets thisDestroyed to ETrue
+    TBool thisDestroyed( EFalse );
+    iDestroyedPtr = &thisDestroyed;
+    
+    iQueryCanceled = EFalse;
+    RMobilePhone::TMobilePassword password;
+    RMobilePhone::TMobilePassword required_fourth;
+        
+    TInt ret = KErrNone;
+    TInt err = KErrNone;
+    TInt status = KErrNone;
+    if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ) &&
+    		FeatureManager::FeatureSupported(KFeatureIdSapDeviceLockEnhancements))
+    {
+        // Connect to the SCP server, and request the code query
+        RSCPClient scpClient;
+        User::LeaveIfError( scpClient.Connect() );
+        CleanupClosePushL( scpClient );      
+        status = scpClient.SecCodeQuery( password, 
+                                      RSCPClient::SCP_OK_CANCEL,
+                                      EFalse,
+                                      0 );         
+                                              
+        if ( status != KErrCancel )
+            {
+            // Set this "true" to indicate that the input wasn't cancelled
+            ret = ETrue;
+            }
+        else
+            {
+            ret = EFalse;
+            }
+        
+        CleanupStack::PopAndDestroy(); //scpClient                       
+  }
+  else
+  {
+    iSecurityDlg = new (ELeave) CCodeQueryDialog (password,SEC_C_SECURITY_CODE_MIN_LENGTH,SEC_C_SECURITY_CODE_MAX_LENGTH,ESecUiNone);
+    #ifdef __COVER_DISPLAY
+    iSecurityDlg->PublishDialogL(SecondaryDisplay::ECmdShowSecurityQuery, SecondaryDisplay::KCatStartup);
+    CAknMediatorFacade* covercl = AknMediatorFacade(iSecurityDlg); // uses MOP, so control provided
+	if (covercl) // returns null if __COVER_DISPLAY is not defined
+    	{
+    	// … -  add data that cover ui is interested in
+    	covercl->BufStream().WriteInt32L(SecondaryDisplay::EShowSecCode);// adds int to additional data to be posted to cover ui
+    	covercl->BufStream().CommitL(); // no more data to send so commit buf
+     	}  
+    #endif //__COVER_DISPLAY
+	    CSecUiLockObserver* deviceLockStatusObserver = CSecUiLockObserver::NewL(iSecurityDlg);
+		CleanupStack::PushL(deviceLockStatusObserver);
+		err =KErrNone;
+	    TRAP(err,ret = iSecurityDlg->ExecuteLD(R_SECURITY_QUERY));
+		CleanupStack::PopAndDestroy(deviceLockStatusObserver);
+  }
+    
+    // check if CSecurityHandler has been "killed"
+    if ( thisDestroyed )
+        {
+        return EFalse;
+        }
+
+    iDestroyedPtr = NULL;
+    iSecurityDlg = NULL;
+
+    if (err != KErrNone)
+        {
+        User::Leave(err);
+        }
+
+    if (ret)
+        {
+        while (!iQueryCanceled)
+            {
+	           if (!FeatureManager::FeatureSupported(KFeatureIdSapDeviceLockEnhancements))
+		           {           
+		                RMobilePhone::TMobilePhoneSecurityCode secCodeType;
+		                secCodeType = RMobilePhone::ESecurityCodePhonePassword;
+		                CWait* wait = CWait::NewL();
+		                iPhone.VerifySecurityCode(wait->iStatus,secCodeType, password, required_fourth);
+		                status = wait->WaitForRequestL();
+		                delete wait;
+		
+		           }
+            
+            switch(status)
+                {        
+                case KErrNone:
+                    {
+                    if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ) &&
+    										!(FeatureManager::FeatureSupported(KFeatureIdSapDeviceLockEnhancements)))
+    								{
+                        RSCPClient scpClient;
+                        User::LeaveIfError( scpClient.Connect() );
+                        CleanupClosePushL( scpClient );
+
+                        TSCPSecCode newCode;
+                        newCode.Copy( password );
+                        scpClient.StoreCode( newCode );
+
+                        CleanupStack::PopAndDestroy(); //scpClient  
+                  	}
+                            	
+                    iQueryCanceled = ETrue;
+                    return ETrue;
+                    }                    
+                case KErrGsmSSPasswordAttemptsViolation:
+                case KErrLocked:
+                    {
+                    iDestroyedPtr = &thisDestroyed;
+                    // security code blocked! 
+                    iNoteDlg = new (ELeave) CAknNoteDialog(REINTERPRET_CAST(CEikDialog**,&iNoteDlg));
+                    iNoteDlg->SetTimeout(CAknNoteDialog::ELongTimeout);
+                    iNoteDlg->SetTone(CAknNoteDialog::EErrorTone);
+                    err =KErrNone;
+                    TRAP(err,iNoteDlg->ExecuteLD(R_SEC_BLOCKED));
+                    
+                    // check if CSecurityHandler has been "killed"
+                    if ( thisDestroyed )
+                        {
+                        return EFalse;
+                        }
+                    
+                    iDestroyedPtr = NULL;
+                    iNoteDlg = NULL;
+
+                    if (err != KErrNone)
+                        {
+                        User::Leave(err);
+                        }
+                    break;
+                    }
+                case KErrGsm0707IncorrectPassword:
+                case KErrAccessDenied:
+                    {    
+                    iDestroyedPtr = &thisDestroyed;
+                    // code was entered erroneusly
+                    iNoteDlg = new (ELeave) CAknNoteDialog(REINTERPRET_CAST(CEikDialog**,&iNoteDlg));
+                    iNoteDlg->SetTimeout(CAknNoteDialog::ELongTimeout);
+                    iNoteDlg->SetTone(CAknNoteDialog::EErrorTone);
+                    err =KErrNone;
+                    TRAP(err,iNoteDlg->ExecuteLD(R_CODE_ERROR));    
+                    
+                    // check if CSecurityHandler has been "killed"
+                    if ( thisDestroyed )
+                        {
+                        return EFalse;
+                        }
+                    
+                    iDestroyedPtr = NULL;
+                    iNoteDlg = NULL;
+                    
+                    if (err != KErrNone)
+                        {
+                        User::Leave(err);
+                        }
+                    break;
+                    }    
+                default:
+                    {
+                    iDestroyedPtr = &thisDestroyed;
+                    err =KErrNone;
+                    TRAP(err,ShowGenericErrorNoteL(status));
+                                        
+                    // check if CSecurityHandler has been "killed"
+                    if ( thisDestroyed )
+                        {
+                        return EFalse;
+                        }
+                    
+                    iDestroyedPtr = NULL;
+                    iNoteDlg = NULL;
+                    
+                    if (err != KErrNone)
+                        {
+                        User::Leave(err);
+                        }    
+                    break;
+                    }
+                }     
+        
+            if (iQueryCanceled)
+                {
+                ret = EFalse;
+                break;
+                }    
+            
+            password = _L("");
+            iDestroyedPtr = &thisDestroyed;
+             if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ) &&
+    						FeatureManager::FeatureSupported(KFeatureIdSapDeviceLockEnhancements))  
+    				{       
+                // Connect to the SCP server, and request the code query
+                RSCPClient scpClient;
+                User::LeaveIfError( scpClient.Connect() );
+                CleanupClosePushL( scpClient );
+                status = scpClient.SecCodeQuery( password, 
+                                      RSCPClient::SCP_OK_CANCEL,
+                                      EFalse,
+                                      0 ); 
+        
+                if ( status != KErrCancel )
+                    {
+                    // Set this "true" to indicate that the input wasn't cancelled
+                    ret = ETrue;
+                    }
+                else
+                    {
+                    ret = EFalse;
+                    }                                
+        
+                CleanupStack::PopAndDestroy(); //scpClient                              
+          }
+          else
+          {
+            iSecurityDlg = new (ELeave) CCodeQueryDialog (password,SEC_C_SECURITY_CODE_MIN_LENGTH,SEC_C_SECURITY_CODE_MAX_LENGTH,ESecUiNone);
+            CSecUiLockObserver* deviceLockStatusObserver = CSecUiLockObserver::NewL(iSecurityDlg);
+						CleanupStack::PushL(deviceLockStatusObserver);
+						err =KErrNone;
+            TRAP(err,ret = iSecurityDlg->ExecuteLD(R_SECURITY_QUERY));         
+						CleanupStack::PopAndDestroy(deviceLockStatusObserver);
+          }
+            
+            // check if CSecurityHandler has been "killed"
+            if ( thisDestroyed )
+                {
+                return EFalse;
+                }
+    
+            iDestroyedPtr = NULL;
+            iSecurityDlg = NULL;
+            
+            if (err != KErrNone)
+                {
+                User::Leave(err);
+                }
+
+            if (!ret)
+                break;
+        } // while
+    }    // if
+
+    iQueryCanceled = ETrue;
+    return ret;
+    }
+//
+// ----------------------------------------------------------
+// CSecurityHandler::CancelSecCodeQuery()    
+// Cancels PIN2 and security code queries
+// ----------------------------------------------------------
+//
+EXPORT_C void CSecurityHandler::CancelSecCodeQuery()                
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::CancelSecCodeQuery()"));
+    #endif
+    if (!iQueryCanceled)
+        {
+        iQueryCanceled = ETrue;
+        if (iSecurityDlg != NULL)
+            {
+            delete iSecurityDlg;
+            }
+        if (iNoteDlg != NULL)
+            {
+            delete iNoteDlg;
+            }
+        iNoteDlg = NULL;
+        iSecurityDlg = NULL;
+        }
+    }
+//
+// ----------------------------------------------------------
+// CSecurityHandler::AskSecCodeInAutoLock()
+// for asking security code in autolock
+// ----------------------------------------------------------
+//
+EXPORT_C TBool CSecurityHandler::AskSecCodeInAutoLockL()
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    
+    #ifdef __WINS__
+    return ETrue;
+    #else
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::AskSecCodeInAutoLockL()"));
+    #endif
+    TInt res;
+    CWait* wait;
+        
+    RMobilePhone::TMobilePhoneLockSetting lockChange(RMobilePhone::ELockSetDisabled);
+    RMobilePhone::TMobilePhoneLock lockType = RMobilePhone::ELockPhoneDevice;
+   
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::AskSecCodeInAutoLockL() get autolock period"));
+    #endif
+
+    // get autolock period from Central Repository.
+    CRepository* repository = CRepository::NewL(KCRUidSecuritySettings);
+    TInt period = 0;
+    res = repository->Get(KSettingsAutoLockTime, period);
+    delete repository;
+
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::AskSecCodeInAutoLockL() autolock period:%d"), res);
+    #endif
+    if (res == KErrNone)
+        {
+        // disable autolock in Domestic OS side too if autolock period is 0.
+        if (period == 0 )
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecurityHandler::AskSecCodeInAutoLockL() Call SetLockSetting"));
+            #endif
+
+#ifdef RD_REMOTELOCK
+
+            // If remote lock is enabled, don't disable the domestic OS device lock
+            // since that would render the RemoteLock useless.
+            // Instead just re-set the DOS lock to enabled which as a side effect
+            // requests the security code from the user.
+
+            TBool remoteLockStatus( EFalse );
+            CRemoteLockSettings* remoteLockSettings = CRemoteLockSettings::NewL();
+
+            if ( remoteLockSettings->GetEnabled( remoteLockStatus ) )
+                {
+                if ( remoteLockStatus )
+                    {
+                    // Remote lock is enabled
+                    #ifdef _DEBUG
+                    RDebug::Print( _L( "(SecUi)CSecurityHandler::AskSecCodeInAutoLockL() - RemoteLock is enabled: lockChange = RMobilePhone::ELockSetEnabled" ) );
+                    #endif // _DEBUG
+
+                    lockChange = RMobilePhone::ELockSetEnabled;
+                    }
+                else
+                    {
+                    // Remote lock is disabled
+                    #ifdef _DEBUG
+                    RDebug::Print( _L( "(SecUi)CSecurityHandler::AskSecCodeInAutoLockL() - RemoteLock is disabled: lockChange = RMobilePhone::ELockSetDisabled" ) );
+                    #endif // _DEBUG
+
+                    lockChange = RMobilePhone::ELockSetDisabled;
+                    }
+                }
+            else
+                {
+                // Failed to get remote lock status
+                #ifdef _DEBUG
+                RDebug::Print( _L( "(SecUi)CSecurityHandler::AskSecCodeInAutoLockL() - Failed to get RemoteLock status" ) );
+                #endif // _DEBUG
+                }
+
+            delete remoteLockSettings;
+            remoteLockSettings = NULL;
+
+#else // not defined RD_REMOTELOCK
+
+                lockChange = RMobilePhone::ELockSetDisabled;
+
+#endif // RD_REMOTELOCK
+
+                wait = CWait::NewL();
+                iPhone.SetLockSetting(wait->iStatus,lockType,lockChange);
+                res = wait->WaitForRequestL();
+                delete wait;
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(SECUI)CSecurityHandler::AskSecCodeInAutoLockL() SetLockSetting RESULT:%d"), res);
+                #endif
+            }
+        else
+            {	// ask security code
+                #if defined(_DEBUG)
+            	RDebug::Print(_L("(SECUI)CSecurityHandler::AskSecCodeInAutoLockL() Ask sec code via notifier"));
+            	#endif
+                RNotifier codeQueryNotifier;
+                User::LeaveIfError(codeQueryNotifier.Connect());
+                CWait* wait = CWait::NewL();
+                CleanupStack::PushL(wait);
+                TInt queryResponse = 0;
+                TPckg<TInt> response(queryResponse);
+                TSecurityNotificationPckg params;
+                params().iEvent = static_cast<TInt>(RMobilePhone::EPhonePasswordRequired);
+                params().iStartup = EFalse;
+                #if defined(_DEBUG)
+    			RDebug::Print(_L("(SECUI)CSecurityHandler::AskSecCodeInAutoLockL() Start Notifier"));
+    			#endif
+                codeQueryNotifier.StartNotifierAndGetResponse(wait->iStatus, KSecurityNotifierUid,params, response);
+                res = wait->WaitForRequestL();
+                CleanupStack::PopAndDestroy(); // wait
+              	#if defined(_DEBUG)
+            	RDebug::Print(_L("(SECUI)CSecurityHandler::AskSecCodeInAutoLockL() results:"));
+            	RDebug::Print(_L("(SECUI)CSecurityHandler::AskSecCodeInAutoLockL() res:%d"), res);
+            	RDebug::Print(_L("(SECUI)CSecurityHandler::AskSecCodeInAutoLockL() queryResponse:%d"), queryResponse);
+            	#endif
+            	if(res == KErrNone)
+                	res = queryResponse;
+            }
+        }
+    else
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecurityHandler::AskSecCodeInAutoLockL() KERRSOMETHING:Call SetLockSetting"));
+        #endif
+
+#ifdef RD_REMOTELOCK
+
+        // If remote lock is enabled, don't disable the domestic OS device lock
+        // since that would render the RemoteLock useless.
+        // Instead just re-set the DOS lock to enabled which as a side effect
+        // requests the security code from the user.
+
+        TBool remoteLockStatus( EFalse );
+        CRemoteLockSettings* remoteLockSettings = CRemoteLockSettings::NewL();
+
+        if ( remoteLockSettings->GetEnabled( remoteLockStatus ) )
+            {
+            if ( remoteLockStatus )
+                {
+                // Remote lock is enabled
+                #ifdef _DEBUG
+                RDebug::Print( _L( "(SecUi)CSecurityHandler::AskSecCodeInAutoLockL() - Failed to get AutoLock status and RemoteLock is enabled: lockChange = RMobilePhone::ELockSetEnabled" ) );
+                #endif // _DEBUG
+
+                lockChange = RMobilePhone::ELockSetEnabled;
+                }
+            else
+                {
+                // Remote lock is disabled
+                #ifdef _DEBUG
+                RDebug::Print( _L( "(SecUi)CSecurityHandler::AskSecCodeInAutoLockL() - Failed to get AutoLock status and RemoteLock is disabled: lockChange = RMobilePhone::ELockSetDisabled" ) );
+                #endif // _DEBUG
+
+                lockChange = RMobilePhone::ELockSetDisabled;
+                }
+            }
+        else
+            {
+            // Failed to get remote lock status
+            #ifdef _DEBUG
+            RDebug::Print( _L( "(SecUi)CSecurityHandler::AskSecCodeInAutoLockL() - Failed to get AutoLock status and failed to get RemoteLock status" ) );
+            #endif // _DEBUG
+            }
+
+        delete remoteLockSettings;
+        remoteLockSettings = NULL;
+
+#else // not defined RD_REMOTELOCK
+
+        // could not get the current autolock time... disable autolock in Domestic OS side.
+        lockChange = RMobilePhone::ELockSetDisabled;
+
+#endif // RD_REMOTELOCK
+
+        wait = CWait::NewL();
+        iPhone.SetLockSetting(wait->iStatus,lockType,lockChange);
+        res = wait->WaitForRequestL();
+        delete wait;
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecurityHandler::AskSecCodeInAutoLockL() KES: SetLockSetting RESULT:%d"), res);
+        #endif
+        }
+        
+    switch (res)
+        {
+        case KErrNone:
+            {
+                return ETrue;
+            }
+
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+        case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            {
+			return AskSecCodeInAutoLockL();
+            }
+        case KErrAbort:
+        case KErrCancel:
+            // user pressed "cancel"
+            return EFalse;
+        default:
+            {
+            return AskSecCodeInAutoLockL();
+            }
+        }
+#endif // WINS
+    }
+//
+// ----------------------------------------------------------
+// CSecurityHandler::PassPhraseRequired()    
+// Handles PassPhraseRequired event
+// ----------------------------------------------------------
+//
+TInt CSecurityHandler::PassPhraseRequiredL()
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL()"));
+    #endif
+    TBool StartUp = iStartup;
+
+    RMobilePhone::TMobilePassword password;
+    RMobilePhone::TMobilePassword required_fourth;
+    TInt status;
+    TInt autolockState;
+    TInt err( KErrGeneral );
+    err = RProperty::Get(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, autolockState);
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL() Autolock Status result: %d"), err);
+    #endif
+    if(!StartUp)
+        User::LeaveIfError( err );
+TBool isConditionSatisfied = EFalse;
+TInt tarmFlag=0;
+if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))
+  	{		
+	TInt tRet = RProperty::Get( KSCPSIDAutolock, SCP_TARM_ADMIN_FLAG_UID, tarmFlag );    
+    
+    if ( tRet != KErrNone )
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL():\
+            Warning: failed to get TARM Admin Flag state"));
+        #endif
+        }
+    else
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL(): TARM flag: %d"), tarmFlag );
+        #endif
+        }       
+ 
+    if ( ( StartUp ) || ( tarmFlag & KSCPFlagResyncQuery ) )
+	    			isConditionSatisfied = ETrue;  
+		}
+		else
+		{
+		    if (StartUp)
+		    isConditionSatisfied = ETrue;  
+		}
+		if (isConditionSatisfied)
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL() Dialog 1"));
+        #endif
+        // Security code at bootup: No "cancel" softkey; Emergency calls enabled.
+      if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ) &&
+    			FeatureManager::FeatureSupported(KFeatureIdSapDeviceLockEnhancements))
+    		{                   	    		    		    		
+            // Connect to the SCP server, and request the code query
+            RSCPClient scpClient;
+            User::LeaveIfError( scpClient.Connect() );
+            CleanupClosePushL( scpClient );
+                
+            status = scpClient.SecCodeQuery( password, 
+                                             RSCPClient::SCP_OK_ETEL,
+                                             ETrue,
+                                             KSCPEtelRequest );              
+            // Note that SecCodeQuery doesn't indicate the return value from the dialog            
+        
+            CleanupStack::PopAndDestroy();  //scpClient                                         
+      }  
+      else
+      {     
+        CCodeQueryDialog* securityDlg = new (ELeave) CCodeQueryDialog (password,SEC_C_SECURITY_CODE_MIN_LENGTH,SEC_C_SECURITY_CODE_MAX_LENGTH,ESecUiCodeEtelReqest);
+        if(AknLayoutUtils::PenEnabled())
+            securityDlg->SetEmergencyCallSupportForCBA( ETrue );
+        else
+            securityDlg->SetEmergencyCallSupport(ETrue);
+        #ifdef __COVER_DISPLAY
+        securityDlg->PublishDialogL(SecondaryDisplay::ECmdShowSecurityQuery, SecondaryDisplay::KCatStartup);
+        CAknMediatorFacade* covercl = AknMediatorFacade(securityDlg); // uses MOP, so control provided 
+		if (covercl) // returns null if __COVER_DISPLAY is not defined
+    		{
+    		// … -  add data that cover ui is interested in
+    		covercl->BufStream().WriteInt32L(SecondaryDisplay::EShowSecCode); // adds int to additional data to be posted to cover ui
+    		covercl->BufStream().CommitL(); // no more data to send so commit buf
+     		}  
+        #endif //__COVER_DISPLAY
+        status = securityDlg->ExecuteLD(R_SECURITY_REQUEST_QUERY);
+			}
+        }
+    else if ( (autolockState > EAutolockOff))    
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL() Dialog 2"));
+        #endif
+            // Autolock is On. Security event came from user pressing "unlock".
+            // Emergency call support must be enabled and there must be a "cancel" softkey.
+         if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ) &&
+    				FeatureManager::FeatureSupported(KFeatureIdSapDeviceLockEnhancements))     
+		    		{                                    
+     	    // Connect to the SCP server, and request the code query
+            RSCPClient scpClient;
+            User::LeaveIfError( scpClient.Connect() );
+            CleanupClosePushL( scpClient );
+              
+            status = scpClient.SecCodeQuery( password, 
+                                             RSCPClient::SCP_OK_CANCEL,
+                                             ETrue,
+                                             KSCPEtelRequest );
+            // Note that SecCodeQuery doesn't indicate the return value from the dialog   
+        
+            CleanupStack::PopAndDestroy(); //scpClient
+		    		}
+			    else
+			    {
+        CCodeQueryDialog* securityDlg = new (ELeave) CCodeQueryDialog (password,SEC_C_SECURITY_CODE_MIN_LENGTH,SEC_C_SECURITY_CODE_MAX_LENGTH,ESecUiNone);
+        if(AknLayoutUtils::PenEnabled())
+            securityDlg->SetEmergencyCallSupportForCBA( ETrue );
+        else
+            securityDlg->SetEmergencyCallSupport(ETrue);
+        #ifdef __COVER_DISPLAY
+        securityDlg->PublishDialogL(SecondaryDisplay::ECmdShowSecurityQuery, SecondaryDisplay::KCatStartup);
+        CAknMediatorFacade* covercl = AknMediatorFacade(securityDlg); // uses MOP, so control provided 
+		if (covercl) // returns null if __COVER_DISPLAY is not defined
+    	{
+    	// … -  add data that cover ui is interested in
+    	covercl->BufStream().WriteInt32L(SecondaryDisplay::EShowSecCode); // adds int to additional data to be posted to cover ui
+    	covercl->BufStream().CommitL(); // no more data to send so commit buf
+     	}  
+        #endif //__COVER_DISPLAY
+        status = securityDlg->ExecuteLD(R_SECURITY_QUERY);
+			     }
+        }
+    else    
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL() Dialog 3"));
+        #endif
+            // Code query due to a setting change; "Cancel" softkey active;
+            // no emergency call support.
+	        if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ) &&
+	    			FeatureManager::FeatureSupported(KFeatureIdSapDeviceLockEnhancements))
+	    		{
+     	    // Connect to the SCP server, and request the code query
+            RSCPClient scpClient;
+            User::LeaveIfError( scpClient.Connect() );
+            CleanupClosePushL( scpClient );
+              
+            status = scpClient.SecCodeQuery( password, 
+                                             RSCPClient::SCP_OK_CANCEL,
+                                             EFalse,
+                                             KSCPEtelRequest );            
+            // Note that SecCodeQuery doesn't indicate the return value from the dialog   
+        
+            CleanupStack::PopAndDestroy(); //scpClient
+			    }
+			    else
+			    {
+        iSecurityDlg = new (ELeave) CCodeQueryDialog (password,SEC_C_SECURITY_CODE_MIN_LENGTH,SEC_C_SECURITY_CODE_MAX_LENGTH,ESecUiNone);
+        #ifdef __COVER_DISPLAY
+        iSecurityDlg->PublishDialogL(SecondaryDisplay::ECmdShowSecurityQuery, SecondaryDisplay::KCatStartup);
+        CAknMediatorFacade* covercl = AknMediatorFacade(iSecurityDlg); // uses MOP, so control provided 
+		if (covercl) // returns null if __COVER_DISPLAY is not defined
+    	{
+    	covercl->BufStream().WriteInt32L(SecondaryDisplay::EShowSecCode); // adds int to additional data to be posted to cover ui
+    	covercl->BufStream().CommitL(); // no more data to send so commit buf
+     	}  
+        #endif //__COVER_DISPLAY
+        // read a flag to see whether the query is SecUi originated.
+        TInt secUiOriginatedQuery(ESecurityUIsETelAPIOriginated);
+        RProperty::Get(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, secUiOriginatedQuery);
+        CSecUiLockObserver* deviceLockStatusObserver = CSecUiLockObserver::NewL(iSecurityDlg);
+        CleanupStack::PushL(deviceLockStatusObserver);
+        CSecUiLockObserver* queryStatusObserver = CSecUiLockObserver::NewL(iSecurityDlg, ESecUiRequestStateObserver);
+        CleanupStack::PushL(queryStatusObserver);
+        CSecUiLockObserver* callStatusObserver = NULL;
+        if(secUiOriginatedQuery == ESecurityUIsSystemLockOriginated)
+            {
+                callStatusObserver = CSecUiLockObserver::NewL(iSecurityDlg, ESecUiCallStateObserver);
+                CleanupStack::PushL(callStatusObserver);
+            }
+        status = iSecurityDlg->ExecuteLD(R_SECURITY_QUERY);
+        
+        if(callStatusObserver == NULL)
+            CleanupStack::PopAndDestroy(2); //deviceLockStatusObserver, queryStatusObserver
+        else
+            CleanupStack::PopAndDestroy(3); //deviceLockStatusObserver, queryStatusObserver, callStatusObserver
+        iSecurityDlg = NULL;
+			      }
+        }
+TBool isCondition = EFalse;		
+if(!FeatureManager::FeatureSupported(KFeatureIdSapDeviceLockEnhancements))
+{
+    if (!status || (status == ESecUiEmergencyCall)  
+        || (status == EAknSoftkeyEmergencyCall) || (status == ESecUiDeviceLocked))
+    isCondition = ETrue;
+}
+else
+{
+    if  ( ( status == KErrCancel ) || (status == ESecUiEmergencyCall)  ||
+         (status == EAknSoftkeyEmergencyCall) || (status == ESecUiDeviceLocked))
+    isCondition = ETrue;
+}
+		if (isCondition)
+        {
+		#if defined(_DEBUG)
+		RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL() DIALOG ERROR"));
+		#endif
+        if (!StartUp)
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL() ABORT CALLED!!!!!!"));
+            #endif
+            iPhone.AbortSecurityCode(RMobilePhone::ESecurityCodePhonePassword);
+            }
+        return KErrCancel;
+        }
+
+    RMobilePhone::TMobilePhoneSecurityCode secCodeType = RMobilePhone::ESecurityCodePhonePassword;
+     CWait* wait = NULL;
+if(!FeatureManager::FeatureSupported(KFeatureIdSapDeviceLockEnhancements))
+{ 
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL() VerifySecurityCode"));
+        #endif
+        wait = CWait::NewL();
+        iPhone.VerifySecurityCode(wait->iStatus,secCodeType, password, required_fourth);
+        status = wait->WaitForRequestL();
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL() VerifySecurityCode STATUS: %d"), status);
+        #endif
+        delete wait;
+  }
+  else
+  {
+		wait = NULL;
+  }
+    
+    TInt returnValue = status;
+    switch(status)
+        {        
+        case KErrNone:
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL() KErrNone"));
+            #endif
+            // code approved 
+            CSecuritySettings::ShowResultNoteL(R_CONFIRMATION_NOTE, CAknNoteDialog::EConfirmationTone);
+        if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw))    
+        {
+                // Unset the admin flag if set
+                if ( tarmFlag & KSCPFlagResyncQuery )
+                    {
+                    TInt tRet = RProperty::Get( KSCPSIDAutolock, SCP_TARM_ADMIN_FLAG_UID, tarmFlag );
+                    
+                    if ( tRet == KErrNone )
+	                    {
+	                    tarmFlag &= ~KSCPFlagResyncQuery;
+	                    tRet = RProperty::Set( KSCPSIDAutolock, SCP_TARM_ADMIN_FLAG_UID, tarmFlag );
+	                    }
+	            
+	                if ( tRet != KErrNone )
+                        {
+                        #if defined(_DEBUG)
+                        RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL():\
+                            FAILED to unset TARM Admin Flag"));
+                        #endif
+                        }                    
+                    }                    	            
+				        if(!FeatureManager::FeatureSupported(KFeatureIdSapDeviceLockEnhancements)) 
+				        {           
+    			RSCPClient scpClient;
+                User::LeaveIfError( scpClient.Connect() );
+                CleanupClosePushL( scpClient );
+                TSCPSecCode newCode;
+                newCode.Copy( password );
+                scpClient.StoreCode( newCode );
+                CleanupStack::PopAndDestroy(); //scpClient
+                }
+
+          }
+        		
+            if (StartUp)
+                {
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL()KErrNone: Startup; get autolock period."));
+                #endif
+
+                // get autolock period from Central Repository.
+                CRepository* repository = CRepository::NewL(KCRUidSecuritySettings);
+                TInt period = 0;
+                TInt res = repository->Get(KSettingsAutoLockTime, period);
+                delete repository;
+  
+     						_LIT_SECURITY_POLICY_PASS(KReadPolicy); 
+								_LIT_SECURITY_POLICY_C1(KWritePolicy, ECapabilityWriteDeviceData);
+    						RProperty::Define(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, RProperty::EInt, KReadPolicy, KWritePolicy);
+                RProperty::Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, EAutolockOff);
+                #if defined(_DEBUG)
+								RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL() EAutolockOff")); 
+								#endif																
+
+                if (res == KErrNone)
+                    {
+                    // disable autolock in Domestic OS side too if autolock period is 0.
+                    if (period == 0 )
+                        {
+#ifdef RD_REMOTELOCK
+                        // If remote lock is enabled, don't disable the domestic OS device lock
+                        // since that would render the RemoteLock useless.
+
+                        TBool remoteLockStatus( EFalse );
+                        CRemoteLockSettings* remoteLockSettings = CRemoteLockSettings::NewL();
+
+                        if ( remoteLockSettings->GetEnabled( remoteLockStatus ) )
+                            {
+                            if ( !remoteLockStatus )
+                                {
+                                // Remote lock is disabled
+                                #ifdef _DEBUG
+                                RDebug::Print( _L( "(SecUi)CSecurityHandler::PassPhraseRequiredL() - Autolock and RemoteLock are disabled -> disable DOS device lock" ) );
+                                #endif // _DEBUG
+
+                                // Disable DOS device lock setting
+                                wait = CWait::NewL();
+                                iCustomPhone.DisablePhoneLock(wait->iStatus,password);
+                                wait->WaitForRequestL();
+                                delete wait;
+                                }
+                            }
+                        else
+                            {
+                            // Failed to get remote lock status
+                            #ifdef _DEBUG
+                            RDebug::Print( _L( "(SecUi)CSecurityHandler::PassPhraseRequiredL() - Autolock is disabled, but failed to get RemoteLock status, so do nothing." ) );
+                            #endif // _DEBUG
+                            }
+
+                        delete remoteLockSettings;
+                        remoteLockSettings = NULL;
+
+#else // not defined RD_REMOTELOCK
+
+                        #if defined(_DEBUG)
+                        RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL()KErrNone: Startup; DisablePhoneLock."));
+                        #endif
+                        wait = CWait::NewL();
+                        iCustomPhone.DisablePhoneLock(wait->iStatus,password);
+                        wait->WaitForRequestL();
+                        #if defined(_DEBUG)
+                        RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL()KErrNone: Startup; DisablePhoneLock completed."));
+                        #endif
+                        delete wait;
+#endif // RD_REMOTELOCK
+                        }
+                    }
+                else
+                    {
+#ifdef RD_REMOTELOCK
+                    // If remote lock is enabled, don't disable the domestic OS device lock
+                    // since that would render the RemoteLock useless.
+
+                    TBool remoteLockStatus( EFalse );
+                    CRemoteLockSettings* remoteLockSettings = CRemoteLockSettings::NewL();
+
+                    if ( remoteLockSettings->GetEnabled( remoteLockStatus ) )
+                        {
+                        if ( !remoteLockStatus )
+                            {
+                            // Remote lock is disabled
+                            #ifdef _DEBUG
+                            RDebug::Print( _L( "(SecUi)CSecurityHandler::PassPhraseRequiredL() - Failed to get Autolock period and RemoteLock is disabled -> disable DOS device lock" ) );
+                            #endif // _DEBUG
+
+                            wait = CWait::NewL();
+                            iCustomPhone.DisablePhoneLock(wait->iStatus,password);
+                            wait->WaitForRequestL();
+                            delete wait;
+                            }
+                        }
+                    else
+                        {
+                        // Failed to get remote lock status
+                        #ifdef _DEBUG
+                        RDebug::Print( _L( "(SecUi)CSecurityHandler::PassPhraseRequiredL() - Failed to get Autolock period and RemoteLock status, so do nothing." ) );
+                        #endif // _DEBUG
+                        }
+
+                    delete remoteLockSettings;
+                    remoteLockSettings = NULL;
+
+#else // not defined RD_REMOTELOCK
+
+                    #if defined(_DEBUG)
+                    RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL()KErrNone: Startup; Could not get autolock period."));
+                    #endif
+                    // could not get the current autolock time... disable autolock in Domestic OS side. 
+                    wait = CWait::NewL();
+                    iCustomPhone.DisablePhoneLock(wait->iStatus,password);
+                    wait->WaitForRequestL();
+                    #if defined(_DEBUG)
+                    RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL()KErrNone: Startup; NO AUTOLOCK PERIOD; DisablePhoneLock completed."));
+                    #endif
+                    delete wait;
+
+#endif // RD_REMOTELOCK
+                    }
+                
+                }
+
+            break;    
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            // security code blocked!
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL() ErrGsmSSPasswordAttemptsViolation"));
+            #endif
+            CSecuritySettings::ShowResultNoteL(R_SEC_BLOCKED, CAknNoteDialog::EErrorTone);
+            break;
+        case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL() KErrGsm0707IncorrectPassword"));
+            #endif
+            CSecuritySettings::ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+            break;
+        default:
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecurityHandler::PassPhraseRequiredL() DEFAULT"));
+            #endif
+            CSecuritySettings::ShowErrorNoteL(status);
+            break;
+        }
+        
+    return returnValue;
+    }
+//
+// ----------------------------------------------------------
+// CSecurityHandler::Pin1Required()    
+// Handles Pin1Required event
+// ----------------------------------------------------------
+//
+TInt CSecurityHandler::Pin1RequiredL()
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    
+    RMobilePhone::TMobilePassword password;
+    RMobilePhone::TMobilePassword required_fourth;
+    RMobilePhone::TMobilePhoneSecurityCode secCodeType = RMobilePhone::ESecurityCodePin1;
+    RMobilePhone::TMobilePhoneSecurityCodeInfoV5 codeInfo;
+    RMobilePhone::TMobilePhoneSecurityCodeInfoV5Pckg codeInfoPkg(codeInfo);
+    TBool StartUp = ETrue;   
+    TInt secUiOriginatedQuery(ESecurityUIsSecUIOriginatedUninitialized);
+    TInt err = KErrNone;
+    TInt res = KErrGeneral;
+    CWait* wait = CWait::NewL();
+    CleanupStack::PushL(wait);
+    
+
+    StartUp = iStartup;
+
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Pin1RequiredL()"));
+    #endif
+
+    if(!StartUp)
+    {
+        // read a flag to see whether the query is SecUi originated.
+        err = RProperty::Get(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, secUiOriginatedQuery);
+        
+    if ( err != KErrNone )
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecurityHandler::Pin1RequiredL():\
+            FAILED to get the SECUI query Flag: %d"), err);
+        #endif
+        }
+    else
+            {
+               #if defined(_DEBUG)
+                RDebug::Print(_L("(SECUI)CSecurityHandler::Pin1RequiredL():\
+                    SECUI query Flag: %d"), secUiOriginatedQuery);
+                #endif 
+            }
+    }  
+    #if defined(_DEBUG)
+    RDebug::Print(_L("CSecurityHandler::Pin1RequiredL() Execute dlg"));
+    #endif
+
+    if(StartUp || (secUiOriginatedQuery != ESecurityUIsSecUIOriginated) || (err != KErrNone))
+    {	
+        iSecurityDlg = new (ELeave) CCodeQueryDialog (password,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiCodeEtelReqest);
+        if(AknLayoutUtils::PenEnabled())
+            iSecurityDlg->SetEmergencyCallSupportForCBA( ETrue );
+        else
+            iSecurityDlg->SetEmergencyCallSupport(ETrue);
+        #ifdef __COVER_DISPLAY
+        iSecurityDlg->PublishDialogL(SecondaryDisplay::ECmdShowSecurityQuery, SecondaryDisplay::KCatStartup);
+        CAknMediatorFacade* covercl = AknMediatorFacade(iSecurityDlg); // uses MOP, so control provided 
+		if (covercl) // returns null if __COVER_DISPLAY is not defined
+    	{
+    	// … -  add data that cover ui is interested in
+    	covercl->BufStream().WriteInt32L(SecondaryDisplay::EShowPIN1); // adds int to additional data to be posted to cover ui
+    	covercl->BufStream().CommitL(); // no more data to send so commit buf
+     	}  
+        #endif //__COVER_DISPLAY
+
+        wait->SetRequestType(EMobilePhoneGetSecurityCodeInfo);
+        iPhone.GetSecurityCodeInfo(wait->iStatus, secCodeType, codeInfoPkg);
+        res = wait->WaitForRequestL();
+        #if defined(_DEBUG)
+        TInt attempts(codeInfo.iRemainingEntryAttempts);
+        RDebug::Print(_L("CSecurityHandler::Pin1RequiredL() Remaining Attempts query status: %d"), res);
+        RDebug::Print(_L("CSecurityHandler::Pin1RequiredL() Remaining Attempts: %d"), attempts);
+        #endif
+        User::LeaveIfError(res);
+        
+        if(codeInfo.iRemainingEntryAttempts == KMaxNumberOfPINAttempts)
+            res = iSecurityDlg->ExecuteLD(R_PIN_REQUEST_QUERY);
+        else if(codeInfo.iRemainingEntryAttempts > KLastRemainingInputAttempt)
+            {
+                HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_REMAINING_PIN_ATTEMPTS, codeInfo.iRemainingEntryAttempts);
+                res = iSecurityDlg->ExecuteLD(R_PIN_REQUEST_QUERY, *queryPrompt);
+                CleanupStack::PopAndDestroy(queryPrompt);
+            }
+        else
+            {
+                HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_FINAL_PIN_ATTEMPT);
+                res = iSecurityDlg->ExecuteLD(R_PIN_REQUEST_QUERY, *queryPrompt);
+                CleanupStack::PopAndDestroy(queryPrompt);   
+            }
+        
+        iSecurityDlg = NULL;
+        #if defined(_DEBUG)
+    	RDebug::Print(_L("CSecurityHandler::Pin1RequiredL() Execute dlg RESULT: %d"), res);
+    	#endif
+        if ((!res) || (res == ESecUiEmergencyCall) || (res == EAknSoftkeyEmergencyCall))
+            { 
+            #if defined(_DEBUG)
+            RDebug::Print(_L("CSecurityHandler::Pin1RequiredL() R_PIN_REQUEST_QUERY CANCEL!"));
+            #endif
+            CleanupStack::PopAndDestroy(wait);   
+            return KErrCancel;
+            }
+    }
+    else
+    {	
+        iSecurityDlg = new (ELeave) CCodeQueryDialog (password,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);
+        #ifdef __COVER_DISPLAY
+        iSecurityDlg->PublishDialogL(SecondaryDisplay::ECmdShowSecurityQuery, SecondaryDisplay::KCatStartup);
+        CAknMediatorFacade* covercl = AknMediatorFacade(iSecurityDlg); // uses MOP, so control provided
+		if (covercl) // returns null if __COVER_DISPLAY is not defined
+    		{
+    		// … -  add data that cover ui is interested in
+    		covercl->BufStream().WriteInt32L(SecondaryDisplay::EShowPIN1); // adds int to additional data to be posted to cover ui
+    		covercl->BufStream().CommitL(); // no more data to send so commit buf
+     		}  
+        #endif //__COVER_DISPLAY
+        
+        wait->SetRequestType(EMobilePhoneGetSecurityCodeInfo);
+        iPhone.GetSecurityCodeInfo(wait->iStatus, secCodeType, codeInfoPkg);
+        res = wait->WaitForRequestL();
+        User::LeaveIfError(res);
+        
+        CSecUiLockObserver* deviceLockStatusObserver = CSecUiLockObserver::NewL(iSecurityDlg);
+        CleanupStack::PushL(deviceLockStatusObserver);
+        CSecUiLockObserver* queryStatusObserver = CSecUiLockObserver::NewL(iSecurityDlg, ESecUiRequestStateObserver);
+        CleanupStack::PushL(queryStatusObserver);
+        
+        if(codeInfo.iRemainingEntryAttempts == KMaxNumberOfPINAttempts)
+            res = iSecurityDlg->ExecuteLD(R_PIN_QUERY);
+        else if(codeInfo.iRemainingEntryAttempts > KLastRemainingInputAttempt)
+            {
+                HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_REMAINING_PIN_ATTEMPTS, codeInfo.iRemainingEntryAttempts );
+                res = iSecurityDlg->ExecuteLD(R_PIN_QUERY, *queryPrompt);
+                CleanupStack::PopAndDestroy(queryPrompt);
+            }
+        else
+            {
+                HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_FINAL_PIN_ATTEMPT);
+                res = iSecurityDlg->ExecuteLD(R_PIN_QUERY, *queryPrompt);
+                CleanupStack::PopAndDestroy(queryPrompt);   
+            }
+        
+        CleanupStack::PopAndDestroy(2); //deviceLockStatusObserver, queryStatusObserver
+        iSecurityDlg = NULL;
+        if( !res || (res == ESecUiDeviceLocked))
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("CSecurityHandler::Pin1RequiredL() R_PIN_QUERY cancel!"));
+            #endif 
+            // cancel code request
+            iPhone.AbortSecurityCode(RMobilePhone::ESecurityCodePin1);
+            CleanupStack::PopAndDestroy(wait);
+            return KErrCancel;
+            }      
+    }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("CSecurityNotifier::Pin1RequiredL()VerifySecurityCode"));
+    #endif
+    iPhone.VerifySecurityCode(wait->iStatus,secCodeType, password, required_fourth);
+    res = wait->WaitForRequestL();
+    CleanupStack::PopAndDestroy(wait); 
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Pin1RequiredL() VerifySecurityCode STATUS: %d"), res);
+    #endif
+    TInt returnValue = res;
+    switch(res)
+        {        
+        case KErrNone:
+            // code approved 
+            #if defined(_DEBUG)
+            RDebug::Print(_L("CSecurityHandler::Pin1RequiredL()code approved "));
+            #endif
+            CSecuritySettings::ShowResultNoteL(R_CONFIRMATION_NOTE, CAknNoteDialog::EConfirmationTone);
+            break;
+        case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            // code was entered erroneously
+            CSecuritySettings::ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+            if(StartUp)
+            {
+            returnValue = Pin1RequiredL();
+            }
+            break;
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            // code blocked; show error note and terminate.
+            // code blocked
+            if(StartUp)
+                CSecuritySettings::ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone); 
+            break;
+        case KErrGsm0707SimWrong:
+            // sim lock active
+            break;
+        default:
+            CSecuritySettings::ShowErrorNoteL(res);        
+            if(StartUp)
+            {        
+            returnValue = Pin1RequiredL();
+            }
+            break;
+        }
+    return returnValue;
+    }
+//
+// ----------------------------------------------------------
+// CSecurityHandler::Puk1Required()
+// Handles Puk1Required event
+// ----------------------------------------------------------
+//
+TInt CSecurityHandler::Puk1RequiredL()
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Puk1RequiredL()"));
+    #endif            
+    RMobilePhone::TMobilePassword aPassword;
+    RMobilePhone::TMobilePassword aNewPassword;
+    RMobilePhone::TMobilePhoneSecurityCodeInfoV5 codeInfo;
+    RMobilePhone::TMobilePhoneSecurityCodeInfoV5Pckg codeInfoPkg(codeInfo);
+    RMobilePhone::TMobilePhoneSecurityCode blockCodeType;
+    blockCodeType = RMobilePhone::ESecurityCodePuk1;
+    CWait* wait = CWait::NewL();
+    CleanupStack::PushL(wait);
+    
+    TBool StartUp(ETrue);
+    StartUp = iStartup;
+
+    TInt res(KErrNone);
+    wait->SetRequestType(EMobilePhoneGetSecurityCodeInfo);
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Puk1RequiredL(): Get Code info"));
+    #endif
+    iPhone.GetSecurityCodeInfo(wait->iStatus, blockCodeType, codeInfoPkg);
+    res = wait->WaitForRequestL();
+    
+    TInt thisTry = 0;
+
+	// If there was a problem (as there might be in case we're dropping off SIM Access Profile); try again a couple of times.
+	while ( res != KErrNone && ( thisTry++ ) <= KTriesToConnectServer )
+        {
+        User::After( KTimeBeforeRetryingRequest );
+        iPhone.GetSecurityCodeInfo(wait->iStatus, blockCodeType, codeInfoPkg);
+        res = wait->WaitForRequestL();
+        }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Puk1RequiredL(): Get Code info result: %d"), res);
+    #endif
+    //If there's still an error we're doomed. Bail out.
+    User::LeaveIfError(res);
+    
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Puk1RequiredL(): Show last note"));
+    #endif
+    //show the last "Code Error" note of PIN verify result here so it won't be left under the PUK1 dialog
+    if(!StartUp && (codeInfo.iRemainingEntryAttempts == KMaxNumberOfPUKAttempts))
+        CSecuritySettings::ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+    
+    // ask PUK code
+    iSecurityDlg = new (ELeave) CCodeQueryDialog (aPassword,SEC_C_PUK_CODE_MIN_LENGTH,SEC_C_PUK_CODE_MAX_LENGTH,ESecUiPukRequired);
+    if(AknLayoutUtils::PenEnabled())
+        iSecurityDlg->SetEmergencyCallSupportForCBA( ETrue );
+    else
+        iSecurityDlg->SetEmergencyCallSupport(ETrue);
+    #ifdef __COVER_DISPLAY
+    iSecurityDlg->PublishDialogL(SecondaryDisplay::ECmdShowSecurityQuery, SecondaryDisplay::KCatStartup);
+    CAknMediatorFacade* covercl = AknMediatorFacade(iSecurityDlg); // uses MOP, so control provided
+	if (covercl) // returns null if __COVER_DISPLAY is not defined
+    	{
+    	// … -  add data that cover ui is interested in
+    	covercl->BufStream().WriteInt32L(SecondaryDisplay::EShowPUK1); // adds int to additional data to be posted to cover ui
+    	covercl->BufStream().CommitL(); // no more data to send so commit buf
+     	}  
+    #endif //__COVER_DISPLAY   
+    
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Puk1RequiredL(): Show dialog"));
+    #endif    
+    if(codeInfo.iRemainingEntryAttempts == KMaxNumberOfPUKAttempts)
+            res = iSecurityDlg->ExecuteLD(R_PUK_REQUEST_QUERY);
+    else if(codeInfo.iRemainingEntryAttempts > KLastRemainingInputAttempt)
+       {
+         HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_REMAINING_PUK_ATTEMPTS, codeInfo.iRemainingEntryAttempts);
+         res = iSecurityDlg->ExecuteLD(R_PUK_REQUEST_QUERY, *queryPrompt);
+         CleanupStack::PopAndDestroy(queryPrompt);
+       }
+    else
+       {
+         HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_FINAL_PUK_ATTEMPT);
+         res = iSecurityDlg->ExecuteLD(R_PUK_REQUEST_QUERY, *queryPrompt);
+         CleanupStack::PopAndDestroy(queryPrompt);   
+       }
+    
+    if((!res) || (res == ESecUiEmergencyCall) || (res == EAknSoftkeyEmergencyCall))
+        {
+        CleanupStack::PopAndDestroy(wait);
+        return KErrCancel;
+        }
+        
+    RMobilePhone::TMobilePassword verifcationPassword;
+    // new pin code query
+    iSecurityDlg = new (ELeave) CCodeQueryDialog (aNewPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiPukRequired);
+    if(AknLayoutUtils::PenEnabled())
+        iSecurityDlg->SetEmergencyCallSupportForCBA( ETrue );
+    else
+        iSecurityDlg->SetEmergencyCallSupport(ETrue);
+    res = iSecurityDlg->ExecuteLD(R_NEW_PIN_CODE_REQUEST_QUERY);
+    if((!res) || (res == ESecUiEmergencyCall) || (res == EAknSoftkeyEmergencyCall))
+        {
+        CleanupStack::PopAndDestroy(wait);    
+        return KErrCancel;
+        }
+  
+    // verification code query
+    iSecurityDlg = new (ELeave) CCodeQueryDialog (verifcationPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiPukRequired);
+    if(AknLayoutUtils::PenEnabled())
+        iSecurityDlg->SetEmergencyCallSupportForCBA( ETrue );
+    else
+        iSecurityDlg->SetEmergencyCallSupport(ETrue);
+    res = iSecurityDlg->ExecuteLD(R_VERIFY_NEW_PIN_CODE_REQUEST_QUERY);
+    if((!res) || (res == ESecUiEmergencyCall) || (res == EAknSoftkeyEmergencyCall))
+        {
+        CleanupStack::PopAndDestroy(wait);
+        return KErrCancel;
+        }
+                            
+    while (aNewPassword.CompareF(verifcationPassword) != 0) 
+        {
+        // codes do not match -> note -> ask new pin and verification codes again  
+        CSecuritySettings::ShowResultNoteL(R_CODES_DONT_MATCH, CAknNoteDialog::EErrorTone);
+        
+        verifcationPassword = _L("");
+        aNewPassword = _L("");
+
+        // new pin code query
+        iSecurityDlg = new (ELeave) CCodeQueryDialog (aNewPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiPukRequired);
+        if(AknLayoutUtils::PenEnabled())
+            iSecurityDlg->SetEmergencyCallSupportForCBA( ETrue );
+        else
+            iSecurityDlg->SetEmergencyCallSupport(ETrue);
+        res = iSecurityDlg->ExecuteLD(R_NEW_PIN_CODE_REQUEST_QUERY);
+        if ((!res) || (res == ESecUiEmergencyCall) || (res == EAknSoftkeyEmergencyCall))
+            {
+            CleanupStack::PopAndDestroy(wait);
+            return KErrCancel;
+            }
+                
+        // verification code query
+        iSecurityDlg = new (ELeave) CCodeQueryDialog (verifcationPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiPukRequired);
+        if(AknLayoutUtils::PenEnabled())
+            iSecurityDlg->SetEmergencyCallSupportForCBA( ETrue );
+        else
+            iSecurityDlg->SetEmergencyCallSupport(ETrue);
+        res = iSecurityDlg->ExecuteLD(R_VERIFY_NEW_PIN_CODE_REQUEST_QUERY);
+    	if((!res) || (res == ESecUiEmergencyCall) || (res == EAknSoftkeyEmergencyCall))
+            {
+            CleanupStack::PopAndDestroy(wait);
+            return KErrCancel;
+            }
+        }            
+        
+    // send code
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Puk1RequiredL(): Verify Code"));
+    #endif
+    iPhone.VerifySecurityCode(wait->iStatus,blockCodeType,aNewPassword,aPassword);
+    res = wait->WaitForRequestL();
+    CleanupStack::PopAndDestroy(wait);
+    
+    TInt returnValue = res;
+    switch(res)
+        {
+        case KErrNone:
+            // code approved -> note
+            CSecuritySettings::ShowResultNoteL(R_PIN_CODE_CHANGED_NOTE, CAknNoteDialog::EConfirmationTone);
+            break;
+           case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            // wrong PUK code -> note -> ask PUK code again        
+            CSecuritySettings::ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+            returnValue = Puk1RequiredL();
+            break;
+        case KErrGsm0707SimWrong:
+            // sim lock active
+            break;
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            // sim card rejected.
+            break;
+        default:
+            CSecuritySettings::ShowErrorNoteL(res);        
+            returnValue = Puk1RequiredL();
+            break;
+        }    
+
+        return returnValue;
+    }
+//
+// ----------------------------------------------------------
+// CSecurityHandler::Pin2Required()
+// Handles Pin2Required event
+// ----------------------------------------------------------
+//    
+void CSecurityHandler::Pin2RequiredL()
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Pin2RequiredL() BEGIN"));
+    #endif
+    RMobilePhone::TMobilePassword password;
+    RMobilePhone::TMobilePassword required_fourth;
+    RMobilePhone::TMobilePhoneSecurityCode secCodeType(RMobilePhone::ESecurityCodePin2);
+    RMobilePhone::TMobilePhoneSecurityCodeInfoV5 codeInfo;
+    RMobilePhone::TMobilePhoneSecurityCodeInfoV5Pckg codeInfoPkg(codeInfo);
+    CWait* wait = CWait::NewL();
+    CleanupStack::PushL(wait);
+    
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Pin2RequiredL(): create dialog"));
+    #endif
+    iSecurityDlg = new (ELeave) CCodeQueryDialog (password,SEC_C_PIN2_CODE_MIN_LENGTH,SEC_C_PIN2_CODE_MAX_LENGTH,ESecUiNone);
+    #ifdef __COVER_DISPLAY
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Pin2RequiredL(): publish dialog"));
+    #endif
+    iSecurityDlg->PublishDialogL(SecondaryDisplay::ECmdShowSecurityQuery, SecondaryDisplay::KCatStartup);
+    CAknMediatorFacade* covercl = AknMediatorFacade(iSecurityDlg); // uses MOP, so control provided 
+	if (covercl) // returns null if __COVER_DISPLAY is not defined
+    	{
+    	// … -  add data that cover ui is interested in
+    	covercl->BufStream().WriteInt32L(SecondaryDisplay::EShowPIN2); // adds int to additional data to be posted to cover ui
+    	covercl->BufStream().CommitL(); // no more data to send so commit buf
+     	}  
+    #endif //__COVER_DISPLAY
+    
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Pin2RequiredL(): get PIN2 info"));
+    #endif
+    
+	wait->SetRequestType(EMobilePhoneGetSecurityCodeInfo);
+    iPhone.GetSecurityCodeInfo(wait->iStatus, secCodeType, codeInfoPkg);
+    TInt ret = wait->WaitForRequestL();
+        
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Pin2RequiredL(): get PIN2 info result: %d"), ret);
+    TInt attempts(codeInfo.iRemainingEntryAttempts);
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Pin2RequiredL(): attempts remaining: %d"), attempts);
+    #endif
+    User::LeaveIfError(ret);
+    
+        CSecUiLockObserver* deviceLockStatusObserver = CSecUiLockObserver::NewL(iSecurityDlg);
+	    CleanupStack::PushL(deviceLockStatusObserver);
+        CSecUiLockObserver* queryStatusObserver = CSecUiLockObserver::NewL(iSecurityDlg, ESecUiRequestStateObserver);
+        CleanupStack::PushL(queryStatusObserver);
+        
+        if(codeInfo.iRemainingEntryAttempts == KMaxNumberOfPINAttempts)
+            ret = iSecurityDlg->ExecuteLD(R_PIN2_QUERY);
+        else if(codeInfo.iRemainingEntryAttempts > KLastRemainingInputAttempt)
+            {
+                HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_REMAINING_PIN2_ATTEMPTS, codeInfo.iRemainingEntryAttempts );
+                ret = iSecurityDlg->ExecuteLD(R_PIN2_QUERY, *queryPrompt);
+                CleanupStack::PopAndDestroy(queryPrompt);
+            }
+        else
+            {
+                HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_FINAL_PIN2_ATTEMPT);
+                ret = iSecurityDlg->ExecuteLD(R_PIN2_QUERY, *queryPrompt);
+                CleanupStack::PopAndDestroy(queryPrompt);   
+            }
+    CleanupStack::PopAndDestroy(2); //deviceLockStatusObserver, queryStatusObserver
+    iSecurityDlg = NULL;
+    if (!ret  || (ret == ESecUiDeviceLocked))
+        {
+        iPhone.AbortSecurityCode(RMobilePhone::ESecurityCodePin2);
+        CleanupStack::PopAndDestroy(wait);
+        return;
+        }
+
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Pin2RequiredL(): Verify Code"));
+    #endif
+    iPhone.VerifySecurityCode(wait->iStatus,secCodeType,password,required_fourth);
+    TInt status = wait->WaitForRequestL();
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Pin2RequiredL(): destroy wait"));
+    #endif
+    CleanupStack::PopAndDestroy(wait);
+
+    switch(status)
+        {        
+        case KErrNone:
+            break;
+        case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            // code was entered erroneously
+            CSecuritySettings::ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);       
+            break;
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            // blocked
+            CSecuritySettings::ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+            break;
+        default:
+            CSecuritySettings::ShowErrorNoteL(status);        
+            break;
+        }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Pin2RequiredL(): END"));
+    #endif
+    }
+//
+// ----------------------------------------------------------
+// CSecurityHandler::Puk2Required()
+// Handles Puk2Required event
+// ----------------------------------------------------------
+//    
+void CSecurityHandler::Puk2RequiredL()
+    {    
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    RMobilePhone::TMobilePassword aPassword;
+    RMobilePhone::TMobilePassword aNewPassword;
+    RMobilePhone::TMobilePassword verifcationPassword;
+    RMobilePhone::TMobilePhoneSecurityCodeInfoV5 codeInfo;
+    RMobilePhone::TMobilePhoneSecurityCodeInfoV5Pckg codeInfoPkg(codeInfo);
+    
+    RMobilePhone::TMobilePhoneSecurityCode blockCodeType;
+    blockCodeType = RMobilePhone::ESecurityCodePuk2;
+    CWait* wait = CWait::NewL();
+    CleanupStack::PushL(wait);
+    
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Puk2RequiredL()"));
+    #endif
+    // ask PUK2
+    iSecurityDlg = new (ELeave) CCodeQueryDialog (aPassword,SEC_C_PUK2_CODE_MIN_LENGTH,SEC_C_PUK2_CODE_MAX_LENGTH,ESecUiNone);
+    #ifdef __COVER_DISPLAY
+    iSecurityDlg->PublishDialogL(SecondaryDisplay::ECmdShowSecurityQuery, SecondaryDisplay::KCatStartup);
+    CAknMediatorFacade* covercl = AknMediatorFacade(iSecurityDlg); // uses MOP, so control provided 
+	if (covercl) // returns null if __COVER_DISPLAY is not defined
+    	{
+    	// … -  add data that cover ui is interested in
+    	covercl->BufStream().WriteInt32L(SecondaryDisplay::EShowPUK2); // adds int to additional data to be posted to cover ui
+    	covercl->BufStream().CommitL(); // no more data to send so commit buf
+     	}  
+    #endif //__COVER_DISPLAY
+    CSecUiLockObserver* deviceLockStatusObserver = CSecUiLockObserver::NewL(iSecurityDlg);
+	CleanupStack::PushL(deviceLockStatusObserver);
+	
+	TInt ret(KErrNone);
+    wait->SetRequestType(EMobilePhoneGetSecurityCodeInfo);
+    iPhone.GetSecurityCodeInfo(wait->iStatus, blockCodeType, codeInfoPkg);
+    ret = wait->WaitForRequestL();
+    User::LeaveIfError(ret);
+        
+    if(codeInfo.iRemainingEntryAttempts == KMaxNumberOfPUKAttempts)
+            ret = iSecurityDlg->ExecuteLD(R_PUK2_REQUEST_QUERY);
+    else if(codeInfo.iRemainingEntryAttempts > KLastRemainingInputAttempt)
+       {
+         HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_REMAINING_PUK2_ATTEMPTS, codeInfo.iRemainingEntryAttempts);
+         ret = iSecurityDlg->ExecuteLD(R_PUK2_REQUEST_QUERY, *queryPrompt);
+         CleanupStack::PopAndDestroy(queryPrompt);
+       }
+    else
+       {
+         HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_FINAL_PUK2_ATTEMPT);
+         ret = iSecurityDlg->ExecuteLD(R_PUK2_REQUEST_QUERY, *queryPrompt);
+         CleanupStack::PopAndDestroy(queryPrompt);   
+       }
+	
+	iSecurityDlg = NULL;
+    if(!ret  || (ret == ESecUiDeviceLocked))
+        {
+        #if defined(_DEBUG)
+    	RDebug::Print(_L("(SECUI)CSecurityHandler::Puk2RequiredL() PUK QUERY CANCEL"));
+    	#endif    
+        // cancel "get security unblock code" request
+        iPhone.AbortSecurityCode(blockCodeType);
+		CleanupStack::PopAndDestroy(2); //wait, deviceLockStatusObserver
+        return;
+        }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Puk2RequiredL() NEW QUERY"));
+    #endif
+    // new pin2 code query
+    iSecurityDlg = new (ELeave) CCodeQueryDialog (aNewPassword,SEC_C_PIN2_CODE_MIN_LENGTH,SEC_C_PIN2_CODE_MAX_LENGTH,ESecUiNone);
+    deviceLockStatusObserver->SetAddress(iSecurityDlg);
+    ret = iSecurityDlg->ExecuteLD(R_NEW_PIN2_CODE_QUERY);
+    if(!ret  || (ret == ESecUiDeviceLocked))
+        {
+        #if defined(_DEBUG)
+    	RDebug::Print(_L("(SECUI)CSecurityHandler::Puk2RequiredL() NEW QUERY CANCEL"));
+    	#endif 
+        // cancel "get security unblock code" request
+        iPhone.AbortSecurityCode(blockCodeType);
+        CleanupStack::PopAndDestroy(2); //wait, deviceLockStatusObserver
+        return;
+        }
+
+     // verification code query
+    iSecurityDlg = new (ELeave) CCodeQueryDialog (verifcationPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);
+    deviceLockStatusObserver->SetAddress(iSecurityDlg);
+    ret = iSecurityDlg->ExecuteLD(R_VERIFY_NEW_PIN2_CODE_QUERY);
+    if (!ret || (ret == ESecUiDeviceLocked))    
+        {
+        #if defined(_DEBUG)
+    	RDebug::Print(_L("(SECUI)CSecurityHandler::Puk2RequiredL() VERIFY QUERY CANCEL"));
+    	#endif 
+        // cancel "get security unblock code" request
+        iPhone.AbortSecurityCode(blockCodeType);
+        CleanupStack::PopAndDestroy(2); //wait, deviceLockStatusObserver
+        return;
+        }
+        
+    while (aNewPassword.CompareF(verifcationPassword) != 0) 
+        {
+        // codes do not match -> note -> ask new pin and verification codes again  
+        CSecuritySettings::ShowResultNoteL(R_CODES_DONT_MATCH, CAknNoteDialog::EErrorTone);
+        
+        verifcationPassword = _L("");
+        aNewPassword = _L("");
+
+        // new pin2 code query
+        iSecurityDlg = new (ELeave) CCodeQueryDialog (aNewPassword,SEC_C_PIN2_CODE_MIN_LENGTH,SEC_C_PIN2_CODE_MAX_LENGTH,ESecUiNone);
+        deviceLockStatusObserver->SetAddress(iSecurityDlg);
+        deviceLockStatusObserver->StartObserver();
+        
+        ret = iSecurityDlg->ExecuteLD(R_NEW_PIN2_CODE_QUERY);
+    
+        if(!ret || (ret == ESecUiDeviceLocked))
+            {
+            // cancel "get security unblock code" request
+            iPhone.AbortSecurityCode(blockCodeType);
+            CleanupStack::PopAndDestroy(2); //wait, deviceLockStatusObserver
+            return;
+            }
+                    
+        // verification code query
+        iSecurityDlg = new (ELeave) CCodeQueryDialog (verifcationPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);
+        deviceLockStatusObserver->SetAddress(iSecurityDlg);
+        deviceLockStatusObserver->StartObserver();
+        ret = iSecurityDlg->ExecuteLD(R_VERIFY_NEW_PIN2_CODE_QUERY);
+        
+        if (!ret || (ret == ESecUiDeviceLocked))    
+            {
+            // cancel "get security unblock code" request
+            iPhone.AbortSecurityCode(blockCodeType);
+            CleanupStack::PopAndDestroy(2); //wait, deviceLockStatusObserver
+            return;
+            }
+        }            
+    CleanupStack::PopAndDestroy(deviceLockStatusObserver);            
+    // send code
+    
+    iPhone.VerifySecurityCode(wait->iStatus,blockCodeType,aNewPassword,aPassword);
+    TInt res = wait->WaitForRequestL();
+    CleanupStack::PopAndDestroy(wait);
+    
+    switch(res)
+        {
+        case KErrNone:
+            // code approved -> note
+            CSecuritySettings::ShowResultNoteL(R_PIN2_CODE_CHANGED_NOTE, CAknNoteDialog::EConfirmationTone);
+            break;
+        case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            // wrong PUK2 code -> note -> ask PUK2 code again        
+            CSecuritySettings::ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+            Puk2RequiredL();
+            break;
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            // Pin2 features blocked permanently!
+            CSecuritySettings::ShowResultNoteL(R_PIN2_REJECTED, CAknNoteDialog::EConfirmationTone);    
+            break;    
+        default:
+            CSecuritySettings::ShowErrorNoteL(res);            
+            Puk2RequiredL();
+            break;
+        }            
+    }
+
+//
+// ----------------------------------------------------------
+// CSecurityHandler::UPinRequiredL()
+// Hendles UniversalPinRequired event
+// ----------------------------------------------------------
+//  
+TInt CSecurityHandler::UPinRequiredL()
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    if(wcdmaSupported || upinSupported)
+       {
+        RMobilePhone::TMobilePassword password;
+        RMobilePhone::TMobilePassword required_fourth;
+        RMobilePhone::TMobilePhoneSecurityCodeInfoV5 codeInfo;
+        RMobilePhone::TMobilePhoneSecurityCodeInfoV5Pckg codeInfoPkg(codeInfo);
+        RMobilePhone::TMobilePhoneSecurityCode secCodeType = RMobilePhone::ESecurityUniversalPin;
+        CWait* wait = CWait::NewL();
+        CleanupStack::PushL(wait);
+        TBool StartUp = ETrue; 
+        TInt secUiOriginatedQuery(ESecurityUIsSecUIOriginatedUninitialized);
+        TInt err = KErrNone;
+        TInt res = KErrGeneral;
+    
+        StartUp = iStartup;
+    
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecurityHandler::UPinRequiredL()"));
+        #endif
+    
+        if(!StartUp)
+        {
+            // read a flag to see whether the query is SecUi originated. 
+            err = RProperty::Get(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, secUiOriginatedQuery);
+        }
+        
+        #if defined(_DEBUG)
+        RDebug::Print(_L("CSecurityHandler::UPinRequiredL() Execute dlg"));
+        #endif 
+        if(StartUp || (secUiOriginatedQuery != ESecurityUIsSecUIOriginated) || (err != KErrNone))
+        {
+            iSecurityDlg = new (ELeave) CCodeQueryDialog (password,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiCodeEtelReqest);
+            if(AknLayoutUtils::PenEnabled())
+                iSecurityDlg->SetEmergencyCallSupportForCBA( ETrue );
+            else
+                iSecurityDlg->SetEmergencyCallSupport(ETrue);
+            #ifdef __COVER_DISPLAY
+            iSecurityDlg->PublishDialogL(SecondaryDisplay::ECmdShowSecurityQuery, SecondaryDisplay::KCatStartup);
+            CAknMediatorFacade* covercl = AknMediatorFacade(iSecurityDlg); // uses MOP, so control provided 
+    		if (covercl) // returns null if __COVER_DISPLAY is not defined
+        		{
+        		// … -  add data that cover ui is interested in
+        		covercl->BufStream().WriteInt32L(SecondaryDisplay::EShowUPIN); // adds int to additional data to be posted to cover ui
+        		covercl->BufStream().CommitL(); // no more data to send so commit buf
+         		}  
+            #endif //__COVER_DISPLAY
+            
+            wait->SetRequestType(EMobilePhoneGetSecurityCodeInfo);
+            iPhone.GetSecurityCodeInfo(wait->iStatus, secCodeType, codeInfoPkg);
+            res = wait->WaitForRequestL();
+            User::LeaveIfError(res);
+            
+            if(codeInfo.iRemainingEntryAttempts == KMaxNumberOfPINAttempts)
+                res = iSecurityDlg->ExecuteLD(R_UPIN_REQUEST_QUERY);
+            else if(codeInfo.iRemainingEntryAttempts > KLastRemainingInputAttempt)
+                {
+                    HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_REMAINING_UPIN_ATTEMPTS, codeInfo.iRemainingEntryAttempts);
+                    res = iSecurityDlg->ExecuteLD(R_UPIN_REQUEST_QUERY, *queryPrompt);
+                    CleanupStack::PopAndDestroy(queryPrompt);
+                }
+            else
+                {
+                    HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_FINAL_UPIN_ATTEMPT);
+                    res = iSecurityDlg->ExecuteLD(R_UPIN_REQUEST_QUERY, *queryPrompt);
+                    CleanupStack::PopAndDestroy(queryPrompt);   
+                }
+            
+            
+            if ((!res) || (res == ESecUiEmergencyCall) || (res == EAknSoftkeyEmergencyCall))
+                { 
+                CleanupStack::PopAndDestroy(wait);   
+                return KErrCancel;
+                }
+        }
+        else
+        {
+            iSecurityDlg = new (ELeave) CCodeQueryDialog (password,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);
+            #ifdef __COVER_DISPLAY
+            iSecurityDlg->PublishDialogL(SecondaryDisplay::ECmdShowSecurityQuery, SecondaryDisplay::KCatStartup);
+            CAknMediatorFacade* covercl = AknMediatorFacade(iSecurityDlg); // uses MOP, so control provided 
+    		if (covercl) // returns null if __COVER_DISPLAY is not defined
+        		{
+        		// … -  add data that cover ui is interested in
+        		covercl->BufStream().WriteInt32L(SecondaryDisplay::EShowUPIN); // adds int to additional data to be posted to cover ui
+        		covercl->BufStream().CommitL(); // no more data to send so commit buf
+         		}  
+            #endif //__COVER_DISPLAY
+            
+    		wait->SetRequestType(EMobilePhoneGetSecurityCodeInfo);
+            iPhone.GetSecurityCodeInfo(wait->iStatus, secCodeType, codeInfoPkg);
+            res = wait->WaitForRequestL();
+            User::LeaveIfError(res);
+            
+            CSecUiLockObserver* deviceLockStatusObserver = CSecUiLockObserver::NewL(iSecurityDlg);
+    		CleanupStack::PushL(deviceLockStatusObserver);
+    		CSecUiLockObserver* queryStatusObserver = CSecUiLockObserver::NewL(iSecurityDlg, ESecUiRequestStateObserver);
+            CleanupStack::PushL(queryStatusObserver);
+            
+            if(codeInfo.iRemainingEntryAttempts == KMaxNumberOfPINAttempts)
+                res = iSecurityDlg->ExecuteLD(R_UPIN_QUERY);
+            else if(codeInfo.iRemainingEntryAttempts > KLastRemainingInputAttempt)
+                {
+                    HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_REMAINING_UPIN_ATTEMPTS, codeInfo.iRemainingEntryAttempts);
+                    res = iSecurityDlg->ExecuteLD(R_UPIN_QUERY, *queryPrompt);
+                    CleanupStack::PopAndDestroy(queryPrompt);
+                }
+            else
+                {
+                    HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_FINAL_UPIN_ATTEMPT);
+                    res = iSecurityDlg->ExecuteLD(R_UPIN_QUERY, *queryPrompt);
+                    CleanupStack::PopAndDestroy(queryPrompt);   
+                }
+    		
+    		CleanupStack::PopAndDestroy(2); //deviceLockStatusObserver, queryStatusObserver
+    		iSecurityDlg = NULL;
+            if( !res || (res == ESecUiDeviceLocked))
+                {
+                // cancel code request
+                CleanupStack::PopAndDestroy(wait);
+                iPhone.AbortSecurityCode(RMobilePhone::ESecurityUniversalPin);
+                return KErrCancel;
+                }      
+        }
+        
+        #if defined(_DEBUG)
+        RDebug::Print(_L("CSecurityNotifier::UPinRequiredL()VerifySecurityCode"));
+        #endif
+        iPhone.VerifySecurityCode(wait->iStatus,secCodeType, password, required_fourth);
+        res = wait->WaitForRequestL();
+        CleanupStack::PopAndDestroy(wait);
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecurityHandler::UPinRequiredL() VerifySecurityCode STATUS: %d"), res);
+        #endif
+        TInt returnValue = res;
+        switch(res)
+            {        
+            case KErrNone:
+                // code approved 
+                #if defined(_DEBUG)
+                RDebug::Print(_L("CSecurityHandler::UPinRequiredL()code approved "));
+                #endif
+                CSecuritySettings::ShowResultNoteL(R_CONFIRMATION_NOTE, CAknNoteDialog::EConfirmationTone);
+                break;
+            case KErrGsm0707IncorrectPassword:
+            case KErrAccessDenied:
+                // code was entered erroneously
+                CSecuritySettings::ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+                if(StartUp)
+                {
+                returnValue = UPinRequiredL();
+                }
+                break;
+            case KErrGsmSSPasswordAttemptsViolation:
+            case KErrLocked:
+                // code blocked; show error note and terminate.
+                if(StartUp)
+                    CSecuritySettings::ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone); 
+                break;
+            case KErrGsm0707SimWrong:
+                // sim lock active
+                break;
+            default:
+                CSecuritySettings::ShowErrorNoteL(res);
+                if(StartUp)
+                {
+                returnValue = UPinRequiredL();
+                }
+                break;
+            }
+    
+        return returnValue;
+       }
+    else
+        return KErrNone;
+    }
+//
+// ----------------------------------------------------------
+// CSecurityHandler::UPukRequiredL()
+// Handles UPukRequired event
+// ----------------------------------------------------------
+//
+TInt CSecurityHandler::UPukRequiredL()
+    {
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    if(wcdmaSupported || upinSupported)
+       {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecurityHandler::UPukRequiredL()"));
+        #endif            
+        RMobilePhone::TMobilePassword aPassword;
+        RMobilePhone::TMobilePassword aNewPassword;
+        RMobilePhone::TMobilePhoneSecurityCodeInfoV5 codeInfo;
+        RMobilePhone::TMobilePhoneSecurityCodeInfoV5Pckg codeInfoPkg(codeInfo);
+    
+        RMobilePhone::TMobilePhoneSecurityCode blockCodeType;
+        blockCodeType = RMobilePhone::ESecurityUniversalPuk;
+        CWait* wait = CWait::NewL();
+        CleanupStack::PushL(wait);
+        
+        TBool StartUp(ETrue);
+        StartUp = iStartup;
+    
+        TInt res(KErrNone);
+        wait->SetRequestType(EMobilePhoneGetSecurityCodeInfo);
+        iPhone.GetSecurityCodeInfo(wait->iStatus, blockCodeType, codeInfoPkg);
+        res = wait->WaitForRequestL();
+        User::LeaveIfError(res);
+        //show last "Code Error" note for UPIN verify result so it won't be left under the PUK1 dialog
+        if(!StartUp && (codeInfo.iRemainingEntryAttempts == KMaxNumberOfPUKAttempts))
+            CSecuritySettings::ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+        
+        // ask UPUK code
+        iSecurityDlg = new (ELeave) CCodeQueryDialog (aPassword,SEC_C_PUK_CODE_MIN_LENGTH,SEC_C_PUK_CODE_MAX_LENGTH,ESecUiPukRequired);
+        if(AknLayoutUtils::PenEnabled())
+            iSecurityDlg->SetEmergencyCallSupportForCBA( ETrue );
+        else
+            iSecurityDlg->SetEmergencyCallSupport(ETrue);
+        #ifdef __COVER_DISPLAY
+        iSecurityDlg->PublishDialogL(SecondaryDisplay::ECmdShowSecurityQuery, SecondaryDisplay::KCatStartup);
+        CAknMediatorFacade* covercl = AknMediatorFacade(iSecurityDlg); // uses MOP, so control provided 
+    		if (covercl) // returns null if __COVER_DISPLAY is not defined
+        		{
+        		// … -  add data that cover ui is interested in
+        		covercl->BufStream().WriteInt32L(SecondaryDisplay::EShowUPUK);// adds int to additional data to be posted to cover ui
+        		covercl->BufStream().CommitL(); // no more data to send so commit buf
+         		}  
+        #endif //__COVER_DISPLAY
+       
+            
+        if(codeInfo.iRemainingEntryAttempts == KMaxNumberOfPUKAttempts)
+                res = iSecurityDlg->ExecuteLD(R_UPUK_REQUEST_QUERY);
+        else if(codeInfo.iRemainingEntryAttempts > KLastRemainingInputAttempt)
+           {
+             HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_REMAINING_UPUK_ATTEMPTS, codeInfo.iRemainingEntryAttempts);
+             res = iSecurityDlg->ExecuteLD(R_UPUK_REQUEST_QUERY, *queryPrompt);
+             CleanupStack::PopAndDestroy(queryPrompt);
+           }
+        else
+           {
+             HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_FINAL_UPUK_ATTEMPT);
+             res = iSecurityDlg->ExecuteLD(R_UPUK_REQUEST_QUERY, *queryPrompt);
+             CleanupStack::PopAndDestroy(queryPrompt);   
+           }
+        
+        if((!res) || (res == ESecUiEmergencyCall) || (res == EAknSoftkeyEmergencyCall))
+            {
+            CleanupStack::PopAndDestroy(wait);
+            return KErrCancel;
+            }
+            
+        RMobilePhone::TMobilePassword verifcationPassword;
+        // new upin code query
+        iSecurityDlg = new (ELeave) CCodeQueryDialog (aNewPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiPukRequired);
+        if(AknLayoutUtils::PenEnabled())
+            iSecurityDlg->SetEmergencyCallSupportForCBA( ETrue );
+        else
+            iSecurityDlg->SetEmergencyCallSupport(ETrue);
+        res = iSecurityDlg->ExecuteLD(R_NEW_UPIN_CODE_REQUEST_QUERY);
+        if((!res) || (res == ESecUiEmergencyCall) || (res == EAknSoftkeyEmergencyCall))
+            {
+            CleanupStack::PopAndDestroy(wait);    
+            return KErrCancel;
+            }
+      
+        // verification code query
+        iSecurityDlg = new (ELeave) CCodeQueryDialog (verifcationPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiPukRequired);
+        if(AknLayoutUtils::PenEnabled())
+            iSecurityDlg->SetEmergencyCallSupportForCBA( ETrue );
+        else
+            iSecurityDlg->SetEmergencyCallSupport(ETrue);
+        res = iSecurityDlg->ExecuteLD(R_VERIFY_NEW_UPIN_CODE_REQUEST_QUERY);
+        if((!res) || (res == ESecUiEmergencyCall) || (res == EAknSoftkeyEmergencyCall))
+            {
+            CleanupStack::PopAndDestroy(wait);
+            return KErrCancel;
+            }
+                                
+        while (aNewPassword.CompareF(verifcationPassword) != 0) 
+            {
+            // codes do not match -> note -> ask new upin and verification codes again  
+            CSecuritySettings::ShowResultNoteL(R_CODES_DONT_MATCH, CAknNoteDialog::EErrorTone);
+            
+            verifcationPassword = _L("");
+            aNewPassword = _L("");
+    
+            // new upin code query
+            iSecurityDlg = new (ELeave) CCodeQueryDialog (aNewPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiPukRequired);
+            if(AknLayoutUtils::PenEnabled())
+                iSecurityDlg->SetEmergencyCallSupportForCBA( ETrue );
+            else
+                iSecurityDlg->SetEmergencyCallSupport(ETrue);
+            res = iSecurityDlg->ExecuteLD(R_NEW_UPIN_CODE_REQUEST_QUERY);
+        	if((!res) || (res == ESecUiEmergencyCall) || (res == EAknSoftkeyEmergencyCall))
+                {
+                CleanupStack::PopAndDestroy(wait);
+                return KErrCancel;
+                }
+                    
+            // verification code query
+            iSecurityDlg = new (ELeave) CCodeQueryDialog (verifcationPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiPukRequired);
+            if(AknLayoutUtils::PenEnabled())
+                iSecurityDlg->SetEmergencyCallSupportForCBA( ETrue );
+            else
+                iSecurityDlg->SetEmergencyCallSupport(ETrue);
+            res = iSecurityDlg->ExecuteLD(R_VERIFY_NEW_UPIN_CODE_REQUEST_QUERY);
+        	if((!res) || (res == ESecUiEmergencyCall) || (res == EAknSoftkeyEmergencyCall))
+                {
+                CleanupStack::PopAndDestroy(wait);
+                return KErrCancel;
+                }
+            }            
+            
+        // send code
+        iPhone.VerifySecurityCode(wait->iStatus,blockCodeType,aNewPassword,aPassword);
+        res = wait->WaitForRequestL();
+        CleanupStack::PopAndDestroy(wait);
+        
+        TInt returnValue = res;
+        switch(res)
+            {
+            case KErrNone:
+                // code approved -> note
+                CSecuritySettings::ShowResultNoteL(R_UPIN_CODE_CHANGED_NOTE, CAknNoteDialog::EConfirmationTone);
+                break;
+            case KErrGsm0707IncorrectPassword:
+            case KErrAccessDenied:
+                // wrong PUK code -> note -> ask UPUK code again        
+                CSecuritySettings::ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+                returnValue = UPukRequiredL();
+                break;
+            case KErrGsm0707SimWrong:
+                // sim lock active
+                break;
+            case KErrGsmSSPasswordAttemptsViolation:
+            case KErrLocked:
+                // sim card rejected.
+                break;
+            default:
+                CSecuritySettings::ShowErrorNoteL(res);        
+                returnValue = UPukRequiredL();
+                break;
+            }   
+    
+        return returnValue;
+       }
+    else
+        return KErrNone;
+    }
+
+//
+// ----------------------------------------------------------
+// CSecurityHandler::SimLockEventL()
+// Shows "SIM restriction on" note
+// ----------------------------------------------------------
+//    
+void CSecurityHandler::SimLockEventL()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("CSecurityHandler::SimLockEventL()"));
+    #endif
+    CSecuritySettings::ShowResultNoteL(R_SIM_ON, CAknNoteDialog::EConfirmationTone);    
+    }
+// ---------------------------------------------------------
+// CSecurityHandler::RemoveSplashScreenL()
+// Removes splash screen
+// ---------------------------------------------------------
+void CSecurityHandler::RemoveSplashScreenL() const
+    {
+
+    }
+
+// ---------------------------------------------------------
+// CSecurityHandler::ShowGenericErrorNoteL(TInt aStatus)
+// Shows a generic error note
+// ---------------------------------------------------------
+
+void CSecurityHandler::ShowGenericErrorNoteL(TInt aStatus)
+    {
+       // Let's create TextResolver instance for error resolving...
+       CTextResolver* textresolver = CTextResolver::NewLC(); 
+       // Resolve the error
+       TPtrC errorstring;
+       errorstring.Set( textresolver->ResolveErrorString( aStatus ) );
+       iNoteDlg = new (ELeave) CAknNoteDialog(REINTERPRET_CAST(CEikDialog**,&iNoteDlg));
+       iNoteDlg->PrepareLC(R_CODE_ERROR);
+       iNoteDlg->SetTextL((TDesC&)errorstring);
+       iNoteDlg->RunDlgLD(CAknNoteDialog::ELongTimeout, CAknNoteDialog::EErrorTone);
+       CleanupStack::PopAndDestroy(textresolver); 
+    }
+                    
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Src/SecUiSecuritySettings.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,2603 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Provides api for changing security settings.
+*
+*
+*/
+
+
+#include <etelmm.h>
+#include <exterror.h>
+#include <textresolver.h>
+#include <SecUi.rsg>
+#include <aknnotedialog.h>
+#include <mmtsy_names.h>
+#include <centralrepository.h> 
+#include <gsmerror.h>
+#include <SCPClient.h>
+#include <StringLoader.h>
+#include <e32property.h>
+#include <PSVariables.h>   // Property values
+#include <securityuisprivatepskeys.h>
+#include <startupdomainpskeys.h>
+#include "secuisecuritysettings.h"
+#include "SecUiAutoLockSettingPage.h"
+#include "secui.hrh"
+#include "secuisecurityhandler.h"
+#include "secuicodequerydialog.h"
+#include "SecUiWait.h"
+
+#ifdef RD_REMOTELOCK
+#include <aknnotewrappers.h>
+#include <StringLoader.h>
+#include <RemoteLockSettings.h>
+#include "SecUiRemoteLockSettingPage.h"
+#endif // RD_REMOTELOCK
+#include <featmgr.h>
+    /*****************************************************
+    *    Series 60 Customer / TSY
+    *    Needs customer TSY implementation
+    *****************************************************/
+//  LOCAL CONSTANTS AND MACROS  
+
+const TInt KTriesToConnectServer( 2 );
+const TInt KTimeBeforeRetryingServerConnection( 50000 );
+const TInt PhoneIndex( 0 );
+
+const TInt KMaxNumberOfPINAttempts(3);
+const TInt KLastRemainingInputAttempt(1);
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CSecuritySettings::NewL()
+// ----------------------------------------------------------
+//
+EXPORT_C CSecuritySettings* CSecuritySettings::NewL()
+    {
+    CSecuritySettings* self = new (ELeave) CSecuritySettings();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(); //self
+    return self;
+    }
+//
+// ----------------------------------------------------------
+// CSecuritySettings::CSecuritySettings()
+// constructor
+// ----------------------------------------------------------
+//
+EXPORT_C CSecuritySettings::CSecuritySettings()
+    {
+    }
+//
+// ----------------------------------------------------------
+// CSecuritySettings::ConstructL()
+// Symbian OS constructor.
+// ----------------------------------------------------------
+//
+EXPORT_C void CSecuritySettings::ConstructL()
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    /*****************************************************
+    *    Series 60 Customer / TSY
+    *    Needs customer TSY implementation
+    *****************************************************/
+
+    TInt err( KErrGeneral );
+    TInt thisTry( 0 );
+    iWait = CWait::NewL();
+    RTelServer::TPhoneInfo PhoneInfo;
+    /* All server connections are tried to be made KTriesToConnectServer times because occasional
+    fails on connections are possible, at least on some servers */
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ConstructL()"));
+    #endif
+    
+    FeatureManager::InitializeLibL();
+    // connect to ETel server
+    while ( ( err = iServer.Connect() ) != KErrNone && ( thisTry++ ) <= KTriesToConnectServer )
+        {
+        User::After( KTimeBeforeRetryingServerConnection );
+        }
+    User::LeaveIfError( err );
+
+    // load TSY
+    err = iServer.LoadPhoneModule( KMmTsyModuleName );
+    if ( err != KErrAlreadyExists )
+        {
+        // May return also KErrAlreadyExists if something else
+        // has already loaded the TSY module. And that is
+        // not an error.
+        User::LeaveIfError( err );
+        }
+
+    // open phones
+    User::LeaveIfError(iServer.SetExtendedErrorGranularity(RTelServer::EErrorExtended));
+    User::LeaveIfError(iServer.GetPhoneInfo(PhoneIndex, PhoneInfo));
+    User::LeaveIfError(iPhone.Open(iServer,PhoneInfo.iName));
+    User::LeaveIfError(iCustomPhone.Open(iPhone));
+
+    iSecurityHandler = new( ELeave ) CSecurityHandler( iPhone );
+    }
+//
+// ----------------------------------------------------------
+// CSecuritySettings::~CSecuritySettings()
+// Destructor
+// ----------------------------------------------------------
+//
+EXPORT_C CSecuritySettings::~CSecuritySettings()
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    /*****************************************************
+    *    Series 60 Customer / TSY
+    *    Needs customer TSY implementation
+    *****************************************************/
+    delete iSecurityHandler;
+
+    // Cancel active requests
+    if(iWait->IsActive())
+    {
+        #if defined(_DEBUG)
+	    RDebug::Print(_L("(SECUI)CManualSecuritySettings::~CSecuritySettings() CANCEL REQ"));
+	    #endif
+        iPhone.CancelAsyncRequest(iWait->GetRequestType());
+        
+        switch(iWait->GetRequestType())
+            {   //inform query that it has beeen canceled
+                case EMobilePhoneSetLockSetting:
+                case EMobilePhoneSetFdnSetting:
+                    RProperty::Set(KPSUidSecurityUIs, KSecurityUIsQueryRequestCancel, ESecurityUIsQueryRequestCanceled);
+                    break;
+                default:
+                    break;
+            }                            
+        
+    }
+    // close phone
+    if (iPhone.SubSessionHandle())
+        iPhone.Close();
+    // close custom phone
+    if (iCustomPhone.SubSessionHandle())
+        iCustomPhone.Close();
+    //close ETel connection
+    if (iServer.Handle())
+        {
+        iServer.UnloadPhoneModule(KMmTsyModuleName);
+        iServer.Close();
+        }
+    delete iWait;
+    FeatureManager::UnInitializeLib();
+    }
+//
+// ----------------------------------------------------------
+// CSecuritySettings::ChangePinL()
+// Changes PIN1
+// ----------------------------------------------------------
+//
+EXPORT_C void CSecuritySettings::ChangePinL()
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    
+    TInt simState;
+    TInt err( KErrGeneral );
+    err = RProperty::Get(KPSUidStartup, KPSSimStatus, simState);
+    User::LeaveIfError( err );
+    TBool simRemoved(simState == ESimNotPresent);
+
+    if ( simRemoved )
+        {
+        ShowResultNoteL(R_INSERT_SIM, CAknNoteDialog::EErrorTone);
+        return;
+        }
+
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ChangePinL()"));
+    #endif    
+    RMobilePhone::TMobilePhoneSecurityCode secCodeType;
+    secCodeType = RMobilePhone::ESecurityCodePin1;
+
+    RMobilePhone::TMobilePassword oldPassword;
+    RMobilePhone::TMobilePassword newPassword;
+    RMobilePhone::TMobilePassword verifcationPassword;
+    RMobilePhone::TMobilePhonePasswordChangeV1 passwords;
+    RMobilePhone::TMobilePhoneSecurityCodeInfoV5 codeInfo;
+    RMobilePhone::TMobilePhoneSecurityCodeInfoV5Pckg codeInfoPkg(codeInfo);
+
+    CCodeQueryDialog* verdlg = new (ELeave) CCodeQueryDialog (verifcationPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);
+    CleanupStack::PushL(verdlg);
+
+    CCodeQueryDialog* newdlg = new (ELeave) CCodeQueryDialog(newPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);
+    CleanupStack::PushL(newdlg);
+
+    CCodeQueryDialog* dlg = new (ELeave) CCodeQueryDialog (oldPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);       
+    CleanupStack::PushL(dlg);
+
+    RMobilePhone::TMobilePhoneLock lockType;
+    RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;
+    
+    lockType = RMobilePhone::ELockICC;
+
+    RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
+    iWait->SetRequestType(EMobilePhoneGetLockInfo);
+    iPhone.GetLockInfo(iWait->iStatus, lockType, lockInfoPkg);
+    TInt res = iWait->WaitForRequestL();
+    User::LeaveIfError(res);
+
+    if (lockInfo.iSetting == RMobilePhone::ELockSetDisabled)
+        {    
+        CleanupStack::PopAndDestroy(3,verdlg);
+        ShowResultNoteL(R_PIN_NOT_ALLOWED, CAknNoteDialog::EErrorTone);
+        return;
+        }
+    
+    CleanupStack::Pop(); // dlg
+    iWait->SetRequestType(EMobilePhoneGetSecurityCodeInfo);
+    iPhone.GetSecurityCodeInfo(iWait->iStatus, secCodeType, codeInfoPkg);
+    res = iWait->WaitForRequestL();
+    User::LeaveIfError(res);
+    // ask pin
+    if(codeInfo.iRemainingEntryAttempts == KMaxNumberOfPINAttempts)
+            res = dlg->ExecuteLD(R_PIN_QUERY);
+    else if(codeInfo.iRemainingEntryAttempts > KLastRemainingInputAttempt)
+       {
+         HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_REMAINING_PIN_ATTEMPTS, codeInfo.iRemainingEntryAttempts);
+         res = dlg->ExecuteLD(R_PIN_QUERY, *queryPrompt);
+         CleanupStack::PopAndDestroy(queryPrompt);
+       }
+    else
+       {
+         HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_FINAL_PIN_ATTEMPT);
+         res = dlg->ExecuteLD(R_PIN_QUERY, *queryPrompt);
+         CleanupStack::PopAndDestroy(queryPrompt);   
+       }  
+    
+      if( !res )
+        {
+        CleanupStack::PopAndDestroy(2,verdlg);
+        return;
+        }      
+    CleanupStack::Pop(); // newdlg
+    // new pin code query
+     if (!(newdlg->ExecuteLD(R_NEW_PIN_CODE_QUERY)))
+        {
+        CleanupStack::PopAndDestroy(verdlg);
+        return;
+        }
+
+    CleanupStack::Pop(); // verdlg
+    // verification code query
+    if (!(verdlg->ExecuteLD(R_VERIFY_NEW_PIN_CODE_QUERY)))
+            return;
+        
+    while (newPassword.CompareF(verifcationPassword) != 0) 
+        {
+        // codes do not match -> note -> ask new pin and verification codes again  
+        ShowResultNoteL(R_CODES_DONT_MATCH, CAknNoteDialog::EErrorTone);
+    
+        newPassword = _L("");
+        verifcationPassword = _L("");
+
+        // new pin code query
+        CCodeQueryDialog* newdlg = new (ELeave) CCodeQueryDialog (newPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);
+        if (!(newdlg->ExecuteLD(R_NEW_PIN_CODE_QUERY)))
+              return;
+        
+        // verification code query
+        CCodeQueryDialog* verdlg = new (ELeave) CCodeQueryDialog (verifcationPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);
+        if (!(verdlg->ExecuteLD(R_VERIFY_NEW_PIN_CODE_QUERY)))
+            return;
+        }            
+        
+    // send code
+    passwords.iOldPassword = oldPassword;
+    passwords.iNewPassword = newPassword;
+    iWait->SetRequestType(EMobilePhoneChangeSecurityCode);
+    iPhone.ChangeSecurityCode(iWait->iStatus, secCodeType, passwords);
+    res = iWait->WaitForRequestL();
+    #if defined(_DEBUG)
+    RDebug::Print( _L("(SECUI)CSecuritySettings::ChangePinL(): RETURN CODE: %d"), res);
+    #endif
+    switch(res)
+        {
+        case KErrNone:
+            {
+            // code changed 
+            ShowResultNoteL(R_PIN_CODE_CHANGED_NOTE, CAknNoteDialog::EConfirmationTone);
+            break;
+            }        
+        case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            {    
+            // code was entered erroneously
+            ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+            ChangePinL();
+            break;
+            }    
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            {
+            // Pin1 blocked! 
+            return;
+            }
+        case KErrGsm0707OperationNotAllowed:
+            {
+            // not allowed with this sim
+            ShowResultNoteL(R_OPERATION_NOT_ALLOWED, CAknNoteDialog::EErrorTone);
+            return;
+            }
+        case KErrAbort:
+            {
+            break;
+            }
+        default:
+            {
+            ShowErrorNoteL(res);
+            ChangePinL();
+            break;
+            }
+        }
+
+    }
+
+//
+// ----------------------------------------------------------
+// CSecuritySettings::ChangeUPinL()
+// Changes Universal PIN
+// ----------------------------------------------------------
+//
+EXPORT_C void CSecuritySettings::ChangeUPinL()
+    {
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    if(wcdmaSupported || upinSupported)
+      {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeUPinL()"));
+        #endif
+        TInt simState;
+        TInt err( KErrGeneral );
+        err = RProperty::Get(KPSUidStartup, KPSSimStatus, simState);
+        User::LeaveIfError( err );
+        TBool simRemoved(simState == ESimNotPresent);
+    
+        if ( simRemoved )
+            {
+            ShowResultNoteL(R_INSERT_SIM, CAknNoteDialog::EErrorTone);
+            return;
+            }
+    
+        RMobilePhone::TMobilePhoneSecurityCode secCodeType;
+        secCodeType = RMobilePhone::ESecurityUniversalPin;
+    
+        RMobilePhone::TMobilePassword oldPassword;
+        RMobilePhone::TMobilePassword newPassword;
+        RMobilePhone::TMobilePassword verifcationPassword;
+        RMobilePhone::TMobilePhonePasswordChangeV1 passwords;
+        RMobilePhone::TMobilePhoneSecurityCodeInfoV5 codeInfo;
+        RMobilePhone::TMobilePhoneSecurityCodeInfoV5Pckg codeInfoPkg(codeInfo);
+    
+        CCodeQueryDialog* verdlg = new (ELeave) CCodeQueryDialog (verifcationPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);
+        CleanupStack::PushL(verdlg);
+    
+        CCodeQueryDialog* newdlg = new (ELeave) CCodeQueryDialog(newPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);
+        CleanupStack::PushL(newdlg);
+    
+        CCodeQueryDialog* dlg = new (ELeave) CCodeQueryDialog (oldPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);       
+        CleanupStack::PushL(dlg);
+    
+        RMobilePhone::TMobilePhoneLock lockType;
+        RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;
+        
+        lockType = RMobilePhone::ELockUniversalPin;
+        
+        RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
+        iWait->SetRequestType(EMobilePhoneGetLockInfo);
+        iPhone.GetLockInfo(iWait->iStatus, lockType, lockInfoPkg);
+        TInt res = iWait->WaitForRequestL();
+        User::LeaveIfError(res);
+    
+        if (lockInfo.iSetting == RMobilePhone::ELockSetDisabled)
+            {    
+            CleanupStack::PopAndDestroy(3,verdlg);
+            ShowResultNoteL(R_UPIN_NOT_ALLOWED, CAknNoteDialog::EErrorTone);
+            return;
+            }
+        
+        CleanupStack::Pop(); // dlg
+        // ask pin
+        iWait->SetRequestType(EMobilePhoneGetSecurityCodeInfo);
+        iPhone.GetSecurityCodeInfo(iWait->iStatus, secCodeType, codeInfoPkg);
+        res = iWait->WaitForRequestL();
+        User::LeaveIfError(res);
+            
+        if(codeInfo.iRemainingEntryAttempts == KMaxNumberOfPINAttempts)
+            res = dlg->ExecuteLD(R_UPIN_QUERY);
+        else if(codeInfo.iRemainingEntryAttempts > KLastRemainingInputAttempt)
+            {
+              HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_REMAINING_UPIN_ATTEMPTS, codeInfo.iRemainingEntryAttempts);
+              res = dlg->ExecuteLD(R_UPIN_QUERY, *queryPrompt);
+              CleanupStack::PopAndDestroy(queryPrompt);
+            }
+        else
+            {
+              HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_FINAL_UPIN_ATTEMPT);
+              res = dlg->ExecuteLD(R_UPIN_QUERY, *queryPrompt);
+              CleanupStack::PopAndDestroy(queryPrompt);   
+            }        
+        
+        
+        
+         if( !res )
+            {
+            CleanupStack::PopAndDestroy(2,verdlg);
+            return;
+            }      
+        CleanupStack::Pop(); // newdlg
+        // new pin code query
+         if (!(newdlg->ExecuteLD(R_NEW_UPIN_CODE_QUERY)))
+            {
+            CleanupStack::PopAndDestroy(verdlg);
+            return;
+            }
+    
+        CleanupStack::Pop(); // verdlg
+        // verification code query
+        if (!(verdlg->ExecuteLD(R_VERIFY_NEW_UPIN_CODE_QUERY)))
+                return;
+            
+        while (newPassword.CompareF(verifcationPassword) != 0) 
+            {
+            // codes do not match -> note -> ask new pin and verification codes again  
+            ShowResultNoteL(R_CODES_DONT_MATCH, CAknNoteDialog::EErrorTone);
+        
+            newPassword = _L("");
+            verifcationPassword = _L("");
+    
+            // new pin code query
+            CCodeQueryDialog* newdlg = new (ELeave) CCodeQueryDialog (newPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);
+            if (!(newdlg->ExecuteLD(R_NEW_UPIN_CODE_QUERY)))
+                  return;
+            
+            // verification code query
+            CCodeQueryDialog* verdlg = new (ELeave) CCodeQueryDialog (verifcationPassword,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);
+            if (!(verdlg->ExecuteLD(R_VERIFY_NEW_UPIN_CODE_QUERY)))
+                return;
+            }            
+            
+        // send code
+        passwords.iOldPassword = oldPassword;
+        passwords.iNewPassword = newPassword;
+        iWait->SetRequestType(EMobilePhoneChangeSecurityCode);
+        iPhone.ChangeSecurityCode(iWait->iStatus, secCodeType, passwords);
+        res = iWait->WaitForRequestL();
+        #if defined(_DEBUG)
+        RDebug::Print( _L("(SECUI)CSecuritySettings::ChangePinL(): RETURN CODE: %d"), res);
+        #endif
+        switch(res)
+            {
+            case KErrNone:
+                {
+                // code changed 
+                ShowResultNoteL(R_UPIN_CODE_CHANGED_NOTE, CAknNoteDialog::EConfirmationTone);
+                break;
+                }        
+            case KErrGsm0707IncorrectPassword:
+            case KErrAccessDenied:
+                {    
+                // code was entered erroneously
+                ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+                ChangeUPinL();
+                break;
+                }    
+            case KErrGsmSSPasswordAttemptsViolation:
+            case KErrLocked:
+                {
+                return;
+                }
+            case KErrGsm0707OperationNotAllowed:
+                {
+                // not allowed with this sim
+                ShowResultNoteL(R_OPERATION_NOT_ALLOWED, CAknNoteDialog::EErrorTone);
+                return;
+                }
+            case KErrAbort:
+                {
+                break;
+                }
+            default:
+                {
+                ShowErrorNoteL(res);
+                ChangeUPinL();
+                break;
+                }
+            }
+      }
+
+    }
+
+//
+// ----------------------------------------------------------
+// CSecuritySettings::ChangePin2L()
+// Changes PIN2
+// ----------------------------------------------------------
+//
+EXPORT_C void CSecuritySettings::ChangePin2L()
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ChangePin2L()"));
+    #endif
+    TInt simState;
+    TInt err( KErrGeneral );
+    err = RProperty::Get(KPSUidStartup, KPSSimStatus, simState);
+    User::LeaveIfError( err );
+    TBool simRemoved(simState == ESimNotPresent);
+
+    if ( simRemoved )
+        {
+        ShowResultNoteL(R_INSERT_SIM, CAknNoteDialog::EErrorTone);
+        return;
+        }
+
+    RMmCustomAPI::TSecurityCodeType secCodeType;
+    RMobilePhone::TMobilePhoneSecurityCode EtelsecCodeType;
+    secCodeType = RMmCustomAPI::ESecurityCodePin2;
+    RMobilePhone::TMobilePassword oldPassword;
+    RMobilePhone::TMobilePassword newPassword;
+    RMobilePhone::TMobilePassword verifcationPassword;
+    RMobilePhone::TMobilePhonePasswordChangeV1 passwords;
+    RMobilePhone::TMobilePhoneSecurityCodeInfoV5 codeInfo;
+    RMobilePhone::TMobilePhoneSecurityCodeInfoV5Pckg codeInfoPkg(codeInfo);
+    
+    // check if pin2 is blocked...
+    TBool isBlocked = EFalse;
+
+    TInt ret = iCustomPhone.IsBlocked(secCodeType,isBlocked);
+    
+    if(isBlocked)
+        return;
+    
+    if (ret != KErrNone)
+        {    
+        switch (ret)
+            {
+            // PIN2 Blocked.
+            case KErrGsm0707SIMPuk2Required:
+                break;
+            case KErrGsmSSPasswordAttemptsViolation:
+            case KErrLocked:
+                // Pin2 features blocked permanently!
+                ShowResultNoteL(R_PIN2_REJECTED, CAknNoteDialog::EConfirmationTone);
+                break;
+            case KErrGsm0707SimNotInserted:
+                // not allowed with this sim
+                ShowResultNoteL(R_OPERATION_NOT_ALLOWED, CAknNoteDialog::EErrorTone);
+                break;
+            default:
+                ShowErrorNoteL(ret);
+                break;
+            }
+        return;
+        }
+    
+    CCodeQueryDialog* verdlg = new (ELeave) CCodeQueryDialog (verifcationPassword,SEC_C_PIN2_CODE_MIN_LENGTH,SEC_C_PIN2_CODE_MAX_LENGTH,ESecUiNone);
+    CleanupStack::PushL(verdlg);
+
+    CCodeQueryDialog* newdlg = new (ELeave) CCodeQueryDialog(newPassword,SEC_C_PIN2_CODE_MIN_LENGTH,SEC_C_PIN2_CODE_MAX_LENGTH,ESecUiNone);    
+    CleanupStack::PushL(newdlg);
+
+    CCodeQueryDialog* dlg = new (ELeave) CCodeQueryDialog (oldPassword,SEC_C_PIN2_CODE_MIN_LENGTH,SEC_C_PIN2_CODE_MAX_LENGTH,ESecUiNone);      
+    CleanupStack::PushL(dlg);
+
+
+    // Security code must be changed to Etel API format
+    // Custom API Pin1 and Pin2 have the same enum values as the Etel ones
+    EtelsecCodeType = (RMobilePhone::TMobilePhoneSecurityCode)secCodeType;
+    #ifndef __WINS__    
+        iWait->SetRequestType(EMobilePhoneGetSecurityCodeInfo);
+        iPhone.GetSecurityCodeInfo(iWait->iStatus, EtelsecCodeType, codeInfoPkg);
+        ret = iWait->WaitForRequestL();
+        User::LeaveIfError(ret);
+    #else
+        codeInfo.iRemainingEntryAttempts = 1;
+    #endif //__WINS__
+
+    if(codeInfo.iRemainingEntryAttempts == KMaxNumberOfPINAttempts)
+            ret = dlg->ExecuteLD(R_PIN2_QUERY);
+    else if(codeInfo.iRemainingEntryAttempts > KLastRemainingInputAttempt)
+       {
+         HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_REMAINING_PIN2_ATTEMPTS, codeInfo.iRemainingEntryAttempts );
+         ret = dlg->ExecuteLD(R_PIN2_QUERY, *queryPrompt);
+         CleanupStack::PopAndDestroy(queryPrompt);
+       }
+    else
+       {
+         HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_FINAL_PIN2_ATTEMPT);
+         ret = dlg->ExecuteLD(R_PIN2_QUERY, *queryPrompt);
+         CleanupStack::PopAndDestroy(queryPrompt);   
+       }
+
+    CleanupStack::Pop(); // dlg
+    if(!ret)
+        {
+        CleanupStack::PopAndDestroy(2,verdlg);
+        return;
+        }
+
+    // new pin code query
+    CleanupStack::Pop(); // newdlg
+    if(!(newdlg->ExecuteLD(R_NEW_PIN2_CODE_QUERY)))
+        {
+        CleanupStack::PopAndDestroy(verdlg);
+        return;
+        }
+
+     // verification code query
+    CleanupStack::Pop(); // verdlg
+    if(!(verdlg->ExecuteLD(R_VERIFY_NEW_PIN2_CODE_QUERY)))
+        {
+        return;
+        }
+
+    while (newPassword.CompareF(verifcationPassword) != 0)     
+        {
+        // codes do not match -> note -> ask new pin and verification codes again  
+        ShowResultNoteL(R_CODES_DONT_MATCH, CAknNoteDialog::EErrorTone);
+
+        newPassword = _L("");
+        verifcationPassword = _L("");
+        
+        // new pin code query
+        CCodeQueryDialog* dlg = new (ELeave) CCodeQueryDialog (newPassword,SEC_C_PIN2_CODE_MIN_LENGTH,SEC_C_PIN2_CODE_MAX_LENGTH,ESecUiNone);
+        if(!(dlg->ExecuteLD(R_NEW_PIN2_CODE_QUERY)))
+            return;
+              
+        // verification code query
+        CCodeQueryDialog* dlg2 = new (ELeave) CCodeQueryDialog (verifcationPassword,SEC_C_PIN2_CODE_MIN_LENGTH,SEC_C_PIN2_CODE_MAX_LENGTH,ESecUiNone);
+          if(!(dlg2->ExecuteLD(R_VERIFY_NEW_PIN2_CODE_QUERY)))
+            return;
+        }        
+    
+
+    passwords.iOldPassword = oldPassword;
+    passwords.iNewPassword = newPassword;
+    iWait->SetRequestType(EMobilePhoneChangeSecurityCode);
+    iPhone.ChangeSecurityCode(iWait->iStatus,EtelsecCodeType,passwords);
+    TInt res = iWait->WaitForRequestL();
+        #if defined(_DEBUG)
+    RDebug::Print( _L("(SECUI)CSecuritySettings::ChangePin2L(): RETURN CODE: %d"), res);
+    #endif
+    switch(res)
+        {
+        case KErrNone:
+            {
+            // code changed 
+            ShowResultNoteL(R_PIN2_CODE_CHANGED_NOTE, CAknNoteDialog::EConfirmationTone);
+            break;
+            }        
+        case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            {    
+            ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+            ChangePin2L();
+            break;
+            }    
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            {
+            // Pin2 blocked!
+            ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+            CSecurityHandler* handler = new(ELeave) CSecurityHandler(iPhone);
+            CleanupStack::PushL(handler); 
+            handler->HandleEventL(RMobilePhone::EPuk2Required);
+            CleanupStack::PopAndDestroy(handler); // handler    
+            return;
+            }
+        case KErrGsm0707OperationNotAllowed:
+            {
+            // not allowed with this sim
+            ShowResultNoteL(R_OPERATION_NOT_ALLOWED, CAknNoteDialog::EErrorTone);
+            return;
+            }
+        case KErrAbort:
+            {
+            break;
+            }
+        default:
+            {
+            ShowErrorNoteL(res);
+            ChangePin2L();
+            break;
+            }
+        }
+     }
+//
+// ----------------------------------------------------------
+// CSecuritySettings::ChangeSecCodeL()
+// Changes security code 
+// ----------------------------------------------------------
+//
+EXPORT_C void CSecuritySettings::ChangeSecCodeL()
+    {  
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeSecCodeL()"));
+    #endif
+    TInt res;
+    RMobilePhone::TMobilePassword newPassword;
+if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ) &&
+		(FeatureManager::FeatureSupported(KFeatureIdSapDeviceLockEnhancements  )))   
+{ 
+    
+    // Connect to the SCP server, and request the code change
+    RSCPClient scpClient;
+    User::LeaveIfError( scpClient.Connect() );
+    CleanupClosePushL( scpClient );
+    res = scpClient.ChangeCodeRequest();
+    CleanupStack::PopAndDestroy(); // scpClient
+    
+}
+else
+{
+         
+    RMobilePhone::TMobilePhoneSecurityCode secCodeType;
+    secCodeType = RMobilePhone::ESecurityCodePhonePassword;
+    RMobilePhone::TMobilePassword oldPassword;
+    RMobilePhone::TMobilePassword verifcationPassword;
+    RMobilePhone::TMobilePassword required_fourth;
+    RMobilePhone::TMobilePhonePasswordChangeV1 passwords;
+
+    CCodeQueryDialog* verdlg = new (ELeave) CCodeQueryDialog (verifcationPassword,SEC_C_SECURITY_CODE_MIN_LENGTH,SEC_C_SECURITY_CODE_CHANGE_MAX_LENGTH,ESecUiNone);
+    CleanupStack::PushL(verdlg);
+
+    CCodeQueryDialog* newdlg = new (ELeave) CCodeQueryDialog(newPassword,SEC_C_SECURITY_CODE_MIN_LENGTH,SEC_C_SECURITY_CODE_CHANGE_MAX_LENGTH,ESecUiNone);
+    CleanupStack::PushL(newdlg);
+
+    CCodeQueryDialog* dlg = new (ELeave) CCodeQueryDialog (oldPassword,SEC_C_SECURITY_CODE_MIN_LENGTH,SEC_C_SECURITY_CODE_MAX_LENGTH,ESecUiNone);
+    CleanupStack::PushL(dlg);
+
+    // ask security code
+    CleanupStack::Pop(); // dlg
+    if (!(dlg->ExecuteLD(R_SECURITY_QUERY)))
+        {
+        CleanupStack::PopAndDestroy(2,verdlg);
+        return;
+        }
+    // new security code query
+    CleanupStack::Pop(); // newdlg
+    if(!(newdlg->ExecuteLD(R_NEW_SECURITY_CODE_QUERY)))
+        {    
+        CleanupStack::PopAndDestroy(verdlg);
+        return;
+        }
+     
+    // verification code query
+    CleanupStack::Pop(); // verdlg
+      if(!(verdlg->ExecuteLD(R_VERIFY_NEW_SECURITY_CODE_QUERY)))
+        {
+        return;
+        }
+
+    while (newPassword.CompareF(verifcationPassword) != 0)         
+        {            
+        // codes do not match -> note -> ask new pin and verification codes again  
+        ShowResultNoteL(R_CODES_DONT_MATCH, CAknNoteDialog::EErrorTone);
+        
+        newPassword = _L("");
+        verifcationPassword = _L("");
+
+        // new pin code query
+        CCodeQueryDialog* dlg = new (ELeave) CCodeQueryDialog (newPassword,SEC_C_SECURITY_CODE_MIN_LENGTH,SEC_C_SECURITY_CODE_CHANGE_MAX_LENGTH,ESecUiNone);
+        if(!(dlg->ExecuteLD(R_NEW_SECURITY_CODE_QUERY)))
+            return;
+          
+        // verification code query
+        CCodeQueryDialog* dlg2 = new (ELeave) CCodeQueryDialog (verifcationPassword,SEC_C_SECURITY_CODE_MIN_LENGTH,SEC_C_SECURITY_CODE_CHANGE_MAX_LENGTH,ESecUiNone);
+          if(!(dlg2->ExecuteLD(R_VERIFY_NEW_SECURITY_CODE_QUERY)))
+            return;    
+        }            
+    iWait->SetRequestType(EMobilePhoneVerifySecurityCode);    
+    // check code
+    iPhone.VerifySecurityCode(iWait->iStatus,secCodeType, oldPassword, required_fourth);
+    res = iWait->WaitForRequestL();
+    #if defined(_DEBUG)
+    RDebug::Print( _L("(SECUI)CSecuritySettings::ChangeSecCode(): CODE VERIFY RESP: %d"), res);
+    #endif
+    // change code 
+    if (res == KErrNone)
+        {
+        passwords.iOldPassword = oldPassword;
+        passwords.iNewPassword = newPassword;
+        iWait->SetRequestType(EMobilePhoneChangeSecurityCode);
+        iPhone.ChangeSecurityCode(iWait->iStatus,secCodeType,passwords);
+        res = iWait->WaitForRequestL();
+        }
+        
+}
+        
+    #if defined(_DEBUG)
+    RDebug::Print( _L("(SECUI)CSecuritySettings::ChangeSecCode(): RETURN CODE: %d"), res);
+    #endif
+    switch(res)
+        {
+        case KErrNone:
+            {
+            // code changed 
+            ShowResultNoteL(R_SECURITY_CODE_CHANGED_NOTE, CAknNoteDialog::EConfirmationTone);
+            if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ) &&
+								!(FeatureManager::FeatureSupported(KFeatureIdSapDeviceLockEnhancements  )))
+						{
+            // Send the changed code to the SCP server. Not used with device lock enhancements.
+            
+            RSCPClient scpClient;
+            TSCPSecCode newCode;
+            newCode.Copy( newPassword );
+            if ( scpClient.Connect() == KErrNone )
+                {
+                scpClient.StoreCode( newCode );
+                scpClient.Close();
+                }                                               
+          }
+                        
+            break;
+            }
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            {
+            ShowResultNoteL(R_SEC_BLOCKED, CAknNoteDialog::EErrorTone);
+            ChangeSecCodeL();
+            break;
+            }
+        case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            {    
+            // code was entered erroneously
+            ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+            ChangeSecCodeL();
+            break;
+            }
+        case KErrAbort:
+            {
+            break;
+            }
+        default:
+            {
+            ShowErrorNoteL(res);
+            ChangeSecCodeL();
+            break;
+            }
+        }
+    }
+//
+// ----------------------------------------------------------
+// CSecuritySettings::ChangeAutoLockPeriodL()
+// Changes autolock period
+// ----------------------------------------------------------
+//
+EXPORT_C TInt CSecuritySettings::ChangeAutoLockPeriodL(TInt aPeriod)
+    {            
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeAutoLockPeriodLXXXX()"));
+    #endif
+    RMobilePhone::TMobilePhoneLockSetting lockChange(RMobilePhone::ELockSetDisabled);
+    RMobilePhone::TMobilePhoneLock lockType = RMobilePhone::ELockPhoneDevice;
+    TInt currentItem = 0;
+    TInt oldPeriod = aPeriod;
+
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeAutoLockPeriodL() ReadDesC16ArrayResourceL"));
+    #endif
+
+
+    CCoeEnv* coeEnv = CCoeEnv::Static();        
+    CDesCArrayFlat* items =  coeEnv->ReadDesC16ArrayResourceL(R_AUTOLOCK_LBX);
+    CleanupStack::PushL(items);
+        
+    if (aPeriod == 0)
+        {
+        currentItem = 0;  // autolock off
+        }
+    else
+        {
+        currentItem = 1;  // user defined
+        }
+    
+
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeAutoLockPeriodL() New autolocksettingpage"));
+    #endif
+    
+    CAutoLockSettingPage* dlg = new (ELeave)CAutoLockSettingPage(R_AUTOLOCK_SETTING_PAGE, currentItem, items, aPeriod);
+    CleanupStack::PushL(dlg);
+    dlg->ConstructL();
+    TInt maxPeriod;
+    if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))
+		{
+    // Retrieve the current autolock period max. value from the SCP server, 
+    // and check that the value the user
+    // selected is ok from the Corporate Policy point of view.
+	RSCPClient scpClient;
+    TInt ret = scpClient.Connect();
+    if ( ret == KErrNone )
+        {       
+        CleanupClosePushL( scpClient );
+        TBuf<KSCPMaxIntLength> maxPeriodBuf;
+        if ( scpClient.GetParamValue( ESCPMaxAutolockPeriod, maxPeriodBuf ) == KErrNone )
+            {
+            TLex lex( maxPeriodBuf );          
+            if ( ( lex.Val( maxPeriod ) == KErrNone ) && ( maxPeriod > 0 ) )
+                {               
+                 dlg->SetPeriodMaximumValue(maxPeriod);
+                }
+            else
+                {
+                   maxPeriod = 0;
+                   dlg->SetPeriodMaximumValue(maxPeriod);     
+                }
+                
+            }
+        else
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeAutoLockPeriodL():\
+                ERROR: Failed to retrieve max period"));
+            #endif            
+            }            
+        }
+    else
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeAutoLockPeriodL():\
+            ERROR: Failed to connect to SCP."));
+        #endif            
+        }
+    CleanupStack::PopAndDestroy(); // scpClient 
+}
+    CleanupStack::Pop(); //dlg
+    if (!dlg->ExecuteLD(CAknSettingPage::EUpdateWhenChanged))
+        {
+        CleanupStack::PopAndDestroy(items);           
+        return oldPeriod;
+        }
+    
+    CleanupStack::PopAndDestroy();    // items
+    
+    if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))
+		{
+    TBool allow = ETrue;               
+               
+    if ((aPeriod == 0) && (maxPeriod > 0))
+       {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeAutoLockPeriodL() \
+        The period: %d is not allowed by TARM; max: %d"),aPeriod, maxPeriod );
+        #endif                
+        allow = EFalse;                                                
+        HBufC* prompt;
+        prompt = StringLoader::LoadLC( R_SECUI_TEXT_AUTOLOCK_MUST_BE_ACTIVE );
+        CAknNoteDialog* noteDlg = new (ELeave) CAknNoteDialog( REINTERPRET_CAST(CEikDialog**,&noteDlg) );
+        noteDlg->PrepareLC( R_CODE_ERROR );
+        noteDlg->SetTextL( *prompt );
+        noteDlg->SetTimeout( CAknNoteDialog::ELongTimeout );
+        noteDlg->SetTone( CAknNoteDialog::EErrorTone );
+        noteDlg->RunLD();                    
+                    
+        CleanupStack::PopAndDestroy( prompt );                      
+        }          
+        
+    if ( !allow ) 
+        {
+         return ChangeAutoLockPeriodL( oldPeriod );
+        }                       
+  }
+
+    if (aPeriod == 0)
+        {
+        
+        #ifdef RD_REMOTELOCK
+
+        // If remote lock is enabled, don't disable the domestic OS device lock
+        // since that would render the RemoteLock useless.
+        // Instead just re-set the DOS lock to enabled which as a side effect
+        // requests the security code from the user.
+
+        TBool remoteLockStatus( EFalse );
+        CRemoteLockSettings* remoteLockSettings = CRemoteLockSettings::NewL();
+
+        if ( remoteLockSettings->GetEnabled( remoteLockStatus ) )
+            {
+            if ( remoteLockStatus )
+                {
+                // Remote lock is enabled
+                #ifdef _DEBUG
+                RDebug::Print( _L( "(SecUi)CSecuritySettings::ChangeAutoLockPeriodL() - RemoteLock is enabled: lockChange = RMobilePhone::ELockSetEnabled" ) );
+                #endif // _DEBUG
+
+                lockChange = RMobilePhone::ELockSetEnabled;
+                }
+            else
+                {
+                // Remote lock is disabled
+                #ifdef _DEBUG
+                RDebug::Print( _L( "(SecUi)CSecuritySettings::ChangeAutoLockPeriodL() - RemoteLock is disabled: lockChange = RMobilePhone::ELockSetDisabled" ) );
+                #endif // _DEBUG
+
+                lockChange = RMobilePhone::ELockSetDisabled;
+                }
+            }
+        else
+            {
+            // Failed to get remote lock status
+            #ifdef _DEBUG
+            RDebug::Print( _L( "(SecUi)CSecuritySettings::ChangeAutoLockPeriodL() - Failed to get RemoteLock status" ) );
+            #endif // _DEBUG
+            }
+
+        delete remoteLockSettings;
+        remoteLockSettings = NULL;
+
+        #else // not defined RD_REMOTELOCK
+
+        lockChange = RMobilePhone::ELockSetDisabled;
+
+        #endif // RD_REMOTELOCK
+        }
+    else
+        {
+        lockChange = RMobilePhone::ELockSetEnabled;
+        }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeAutoLockPeriodL() SetLockSetting"));
+    #endif
+        iWait->SetRequestType(EMobilePhoneSetLockSetting);
+        RProperty::Set(KPSUidSecurityUIs, KSecurityUIsQueryRequestCancel, ESecurityUIsQueryRequestOk);
+        iPhone.SetLockSetting(iWait->iStatus,lockType,lockChange);
+        TInt status = iWait->WaitForRequestL();
+        #if defined(_DEBUG)
+        RDebug::Print( _L("(SECUI)CSecuritySettings::ChangeAutoLockPeriodL(): RETURN CODE: %d"), status);
+        #endif
+        switch(status)
+        {
+        case KErrNone:
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeAutoLockPeriodL() KErrNone"));
+            #endif
+            break;
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeAutoLockPeriodL() PasswordAttemptsViolation"));
+            #endif
+            return ChangeAutoLockPeriodL(oldPeriod);
+        case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeAutoLockPeriodL() IncorrectPassword"));
+            #endif
+            // code was entered erroneously
+            return ChangeAutoLockPeriodL(oldPeriod);
+        case KErrAbort:
+            // User pressed "cancel" in the code query dialog.
+            return oldPeriod;
+        default:
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeAutoLockPeriodL() default"));
+            #endif            
+            return ChangeAutoLockPeriodL(oldPeriod);
+        }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeAutoLockPeriodL() END"));
+    #endif
+    return aPeriod; 
+    }
+
+
+
+//
+// ----------------------------------------------------------
+// CSecuritySettings::ChangeRemoteLockStatusL()
+// Changes remote lock status (on/off)
+// ----------------------------------------------------------
+//
+EXPORT_C TInt CSecuritySettings::ChangeRemoteLockStatusL( TBool& aRemoteLockStatus, TDes& aRemoteLockCode, TInt aAutoLockPeriod )
+    {
+   #ifdef RD_REMOTELOCK
+    TInt retValue( KErrNone );
+
+    #ifdef _DEBUG
+    RDebug::Print(_L("(SecUi)CSecuritySettings::ChangeRemoteLockStatusL() - Enter, aRemoteLockStatus == %d, aAutoLockPeriod == %d" ), aRemoteLockStatus, aAutoLockPeriod );
+    #endif // _DEBUG
+
+    CCoeEnv* coeEnv       = CCoeEnv::Static();        
+    CDesCArrayFlat* items = coeEnv->ReadDesC16ArrayResourceL( R_REMOTELOCK_LBX );
+    CleanupStack::PushL( items );
+
+    // Store the current remote lock setting 
+    TInt previousItem( 0 );
+    TInt currentItem(  0 );
+
+    if ( aRemoteLockStatus )
+        {
+        previousItem = KRemoteLockSettingItemOn;
+        currentItem  = KRemoteLockSettingItemOn;
+        }
+    else
+        {
+        previousItem = KRemoteLockSettingItemOff;
+        currentItem  = KRemoteLockSettingItemOff;
+        }
+
+    // Create Remote Lock setting page for user to enable or disable remote locking 
+    CRemoteLockSettingPage* remoteLockSettingPage = new( ELeave ) CRemoteLockSettingPage( R_REMOTELOCK_SETTING_PAGE, currentItem, items );
+
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(SecUi)CSecuritySettings::ChangeRemoteLockStatusL() - Executing CRemoteLockSettingPage dialog" ) );
+    #endif // _DEBUG
+
+    // Execute the remote lock enable/disable dialog
+    TBool ret = remoteLockSettingPage->ExecuteLD( CAknSettingPage::EUpdateWhenChanged );
+
+    // Setting page list box items (texts) no longer needed
+    CleanupStack::PopAndDestroy( items );
+
+    if ( ret )
+        {
+        if ( currentItem == KRemoteLockSettingItemOn )
+            {
+            #ifdef _DEBUG
+            RDebug::Print( _L( "(SecUi)CSecuritySettings::ChangeRemoteLockStatusL() - Remote lock status set to ON" ) );
+            #endif // _DEBUG
+
+            aRemoteLockStatus = ETrue;
+
+            // If user wishes to enable remote lock
+            // a new remote lock code is required.
+            // RemoteLockCodeQueryL also 
+            retValue = RemoteLockCodeQueryL( aRemoteLockCode );
+            }
+        else if ( currentItem == KRemoteLockSettingItemOff )
+            {
+            #ifdef _DEBUG
+            RDebug::Print( _L( "(SecUi)CSecuritySettings::ChangeRemoteLockStatusL() - Remote lock status set to OFF" ) );
+            #endif // _DEBUG
+
+            aRemoteLockStatus = EFalse;
+            retValue          = KErrNone;
+
+            // Check whether the status was already off
+            // If not don't make the user enter the security code
+            // (which occurs when setting the DOS lock setting) for no reason.
+            if ( currentItem != previousItem )
+                {
+                // Check whether AutoLock is enabled (timeout value greater 
+                // than zero) or not. If AutoLock is enabled the domestic OS 
+                // device lock should be left enabled.
+                if ( aAutoLockPeriod == 0 )
+                    {
+                    // Disable lock setting from domestic OS
+                    retValue = RemoteLockSetLockSettingL( EFalse );
+                    }
+                else
+                    {
+                    // If AutoLock is enabled, don't disable the DOS device lock
+                    // Re-set (enable) the domestic OS device lock because as a 
+                    // side effect it requires the security code from the user
+                    retValue = RemoteLockSetLockSettingL( ETrue );
+                    }
+                }
+            }
+        else
+            {
+            // This should never happen. But if it does don't change anything
+            retValue = KErrUnknown;
+            }
+        }
+    else
+        {
+        // Something went wrong with the RemoteLockSettingPage dialog 
+        retValue = KErrGeneral;
+
+        #ifdef _DEBUG
+        RDebug::Print( _L( "(SecUi)CSecuritySettings::ChangeRemoteLockStatusL() - CRemoteLockSettingPage::ExecuteLD() failed" ) );
+        #endif // _DEBUG
+        }
+
+    #ifdef _DEBUG
+    RDebug::Print(_L("(SecUi)CSecuritySettings::ChangeRemoteLockStatusL() - Exit" ) );
+    #endif
+
+    return retValue;
+    #else //! RD_REMOTELOCK
+    return KErrNotSupported;
+    #endif //RD_REMOTELOCK
+    }
+//
+// ----------------------------------------------------------
+// CSecuritySettings::RemoteLockCodeQueryL()
+// Pops up remote lock code query. Requires user to enter a new remote lock 
+// code twice and if they match enables the domestic OS device lock (which as 
+// a side effect pops up security code query).
+// ----------------------------------------------------------
+//
+TInt CSecuritySettings::RemoteLockCodeQueryL( TDes& aRemoteLockCode )
+    {
+    #ifdef RD_REMOTELOCK
+    TInt retValue( KErrNone );
+
+    #ifdef _DEBUG
+    RDebug::Print(_L("(SecUi)CSecuritySettings::ChangeRemoteLockCodeL() - Enter" ) );
+    #endif // _DEBUG
+
+    // Clear the remote lock code buffer
+    aRemoteLockCode.Zero();
+
+    // ----- Remote lock code query -------------------------------------------
+
+    // Execute Remote Lock code query
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(SecUi)CSecuritySettings::ChangeRemoteLockCodeL() - Executing remote lock code query" ) );
+    #endif // _DEBUG
+
+    // Load the query prompt from resources
+    CCodeQueryDialog* codeQuery = new( ELeave ) CCodeQueryDialog( aRemoteLockCode, SEC_REMOTELOCK_CODE_MIN_LENGTH,SEC_REMOTELOCK_CODE_MAX_LENGTH, ESecUiNone, ETrue );
+    TInt buttonId = codeQuery->ExecuteLD( R_REMOTELOCK_CODE_QUERY );
+    if ( buttonId == EEikBidOk )
+        {
+            // Ok was pressed and the remote lock code seems fine
+            retValue = KErrNone;
+        }
+    else
+        {
+        // User pressed Cancel
+        // Set the code length to zero leaving no trash for possible retry
+        aRemoteLockCode.Zero();
+        retValue = KErrAbort;
+        }
+
+    if ( retValue != KErrNone )
+        {
+        #ifdef _DEBUG
+        RDebug::Print(_L("(SecUi)CSecuritySettings::ChangeRemoteLockCodeL() - Exit, Remote lock code error" ) );
+        #endif // _DEBUG
+
+        // Can't continue beyond this 
+        return retValue;
+        }
+
+    // ----- Remote lock code confirm query -----------------------------------
+
+    // Confirm the code by asking it again
+    #ifdef _DEBUG
+    RDebug::Print( _L( "(SecUi)CSecuritySettings::ChangeRemoteLockCodeL() - Executing remote lock code verify query" ) );
+    #endif // _DEBUG
+
+    // Buffer for the confirmation code
+    TBuf<KRLockMaxLockCodeLength> confirmCode;
+
+    // Load the confirmation query prompt from resources
+    CCodeQueryDialog* codeConfirmQuery = new( ELeave ) CCodeQueryDialog( confirmCode, SEC_REMOTELOCK_CODE_MIN_LENGTH, SEC_REMOTELOCK_CODE_MAX_LENGTH, ESecUiNone, ETrue );
+    buttonId = codeConfirmQuery->ExecuteLD( R_VERIFY_REMOTELOCK_CODE_QUERY);
+
+
+   if ( buttonId == EEikBidOk )
+        {
+        // Compare codes. Compare returns zero if descriptors have
+        // the same length and the same content
+        while ( (aRemoteLockCode.CompareF( confirmCode ) != 0) && (buttonId == EEikBidOk))
+            {
+                //Codes didn't match; zero the bufffers and show the dialog again
+                aRemoteLockCode.Zero();
+                confirmCode.Zero();
+                // Codes don't match. Notify user
+                ShowResultNoteL( R_REMOTELOCK_CODES_DONT_MATCH, CAknNoteDialog::EErrorTone );
+                codeQuery = new( ELeave ) CCodeQueryDialog( aRemoteLockCode, SEC_REMOTELOCK_CODE_MIN_LENGTH,SEC_REMOTELOCK_CODE_MAX_LENGTH, ESecUiNone, ETrue );
+                buttonId = codeQuery->ExecuteLD( R_REMOTELOCK_CODE_QUERY );
+                //Unless user pressed Cancel show the verification query
+                if(buttonId == EEikBidOk)
+                    {
+                        codeConfirmQuery = new( ELeave ) CCodeQueryDialog( confirmCode, SEC_REMOTELOCK_CODE_MIN_LENGTH, SEC_REMOTELOCK_CODE_MAX_LENGTH, ESecUiNone, ETrue );
+                        buttonId = codeConfirmQuery->ExecuteLD( R_VERIFY_REMOTELOCK_CODE_QUERY);
+                    }
+                
+            } 
+        //User pressed cancel        
+        if(buttonId != EEikBidOk)
+            {
+              // Set the code length to zero leaving no trash for possible retry
+              // Report error and let the user try again 
+              aRemoteLockCode.Zero();
+              confirmCode.Zero();
+              retValue = KErrAbort; 
+            }
+        else
+            {
+            // Codes match
+            confirmCode.Zero();
+
+            // ----- Check against security code ------------------------------
+            
+            // Check that the new remote lock code doesn't match the security 
+            // code of the device.
+
+            RMobilePhone::TMobilePhoneSecurityCode secCodeType;
+            secCodeType = RMobilePhone::ESecurityCodePhonePassword;
+            RMobilePhone::TMobilePassword securityCode;
+            RMobilePhone::TMobilePassword unblockCode;  // Required here only as a dummy parameter 
+
+            if ( aRemoteLockCode.Length() <= RMobilePhone::KMaxMobilePasswordSize )
+                {
+                securityCode = aRemoteLockCode;
+                iWait->SetRequestType( EMobilePhoneVerifySecurityCode );
+                iPhone.VerifySecurityCode( iWait->iStatus, secCodeType, securityCode, unblockCode );
+                TInt res = iWait->WaitForRequestL();
+                // The remote lock code matches the security code 
+                // and that is not allowed
+                while ( (res == KErrNone) && (buttonId == EEikBidOk))
+                    {
+                    #ifdef _DEBUG
+                    RDebug::Print(_L("(SecUi)CSecuritySettings::ChangeRemoteLockCodeL() - Unacceptable remote lock code" ) );
+                    #endif // _DEBUG
+                    aRemoteLockCode.Zero();
+                    confirmCode.Zero();
+                    
+					ShowResultNoteL( R_REMOTELOCK_INVALID_CODE, CAknNoteDialog::EErrorTone );
+					
+					codeQuery = new( ELeave ) CCodeQueryDialog( aRemoteLockCode, SEC_REMOTELOCK_CODE_MIN_LENGTH,SEC_REMOTELOCK_CODE_MAX_LENGTH, ESecUiNone, ETrue );
+                    buttonId = codeQuery->ExecuteLD( R_REMOTELOCK_CODE_QUERY );
+                    //Unless user pressed Cancel show the verification query
+                    if(buttonId == EEikBidOk)
+                        {
+                            codeConfirmQuery = new( ELeave ) CCodeQueryDialog( confirmCode, SEC_REMOTELOCK_CODE_MIN_LENGTH, SEC_REMOTELOCK_CODE_MAX_LENGTH, ESecUiNone, ETrue );
+                            buttonId = codeConfirmQuery->ExecuteLD( R_VERIFY_REMOTELOCK_CODE_QUERY);
+                            
+                            // Compare codes. Compare returns zero if descriptors have
+                            // the same length and the same content
+                            while ( (aRemoteLockCode.CompareF( confirmCode ) != 0) && (buttonId == EEikBidOk))
+                                {
+                                    //Codes didn't match; zero the bufffers and show the dialog again
+                                    aRemoteLockCode.Zero();
+                                    confirmCode.Zero();
+                                    // Codes don't match. Notify user
+                                    ShowResultNoteL( R_REMOTELOCK_CODES_DONT_MATCH, CAknNoteDialog::EErrorTone );
+                                    codeQuery = new( ELeave ) CCodeQueryDialog( aRemoteLockCode, SEC_REMOTELOCK_CODE_MIN_LENGTH,SEC_REMOTELOCK_CODE_MAX_LENGTH, ESecUiNone, ETrue );
+                                    buttonId = codeQuery->ExecuteLD( R_REMOTELOCK_CODE_QUERY );
+                                    //Unless user pressed Cancel show the verification query
+                                    if(buttonId == EEikBidOk)
+                                        {
+                                            codeConfirmQuery = new( ELeave ) CCodeQueryDialog( confirmCode, SEC_REMOTELOCK_CODE_MIN_LENGTH, SEC_REMOTELOCK_CODE_MAX_LENGTH, ESecUiNone, ETrue );
+                                            buttonId = codeConfirmQuery->ExecuteLD( R_VERIFY_REMOTELOCK_CODE_QUERY);
+                                        }
+                
+                                } 
+                            //User pressed cancel        
+                            if(buttonId != EEikBidOk)
+                                {
+                                  // Set the code length to zero leaving no trash for possible retry
+                                  // Report error and let the user try again 
+                                  aRemoteLockCode.Zero();
+                                  confirmCode.Zero();
+                                  retValue = KErrAbort; 
+                                }
+                            else //Check against security code
+                                {
+                                    securityCode = aRemoteLockCode;
+                                    iWait->SetRequestType( EMobilePhoneVerifySecurityCode );
+                                    iPhone.VerifySecurityCode( iWait->iStatus, secCodeType, securityCode, unblockCode );
+                                    res = iWait->WaitForRequestL();
+                                }
+                        }
+					
+                    }
+               //User pressed cancel        
+               if(buttonId != EEikBidOk)
+                    {
+                      // Set the code length to zero leaving no trash for possible retry
+                      // Report error and let the user try again 
+                      aRemoteLockCode.Zero();
+                      confirmCode.Zero();
+                      retValue = KErrAbort; 
+                    }
+                }
+
+            // ----- Enable DOS device lock (Security code query) -------------
+
+            if ( retValue == KErrNone )
+                {
+                // Enable lock setting in domestic OS. It is safe to enable the 
+                // lock setting since RemoteLock API requires remote locking to
+                // be enabled when changing or setting the remote lock message.
+                retValue = RemoteLockSetLockSettingL( ETrue );
+                }
+            }
+        }
+    else //User pressed Cancel
+        {
+        // Set the code length to zero leaving no trash for possible retry
+        aRemoteLockCode.Zero();
+        confirmCode.Zero();
+        retValue = KErrAbort;
+        }
+
+    #ifdef _DEBUG
+    RDebug::Print(_L("(SecUi)CSecuritySettings::ChangeRemoteLockCodeL() - Exit" ) );
+    #endif // _DEBUG
+
+    return retValue;
+    #else //! RD_REMOTELOCK
+    return KErrNotSupported;
+    #endif //RD_REMOTELOCK
+    }
+//
+// ----------------------------------------------------------
+// CSecuritySettings::RemoteLockSetLockSettingL()
+// Changes lock setting in domestic OS. Changing the domestic OS lock setting
+// requires user to enter the security code.
+// ----------------------------------------------------------
+//
+TInt CSecuritySettings::RemoteLockSetLockSettingL( TBool aLockSetting )
+    {
+    #ifdef RD_REMOTELOCK
+    TInt retValue( KErrNone );
+
+    #ifdef _DEBUG
+    RDebug::Print(_L("(SecUi)CSecuritySettings::RemoteLockSetLockSettingL( %d ) - Enter" ), aLockSetting );
+    #endif // _DEBUG
+
+    RMobilePhone::TMobilePhoneLockSetting lockSetting = RMobilePhone::ELockSetEnabled;
+    RMobilePhone::TMobilePhoneLock        lockType    = RMobilePhone::ELockPhoneDevice;
+
+    if ( aLockSetting )
+        {
+        lockSetting = RMobilePhone::ELockSetEnabled;
+        }
+    else
+        {
+        lockSetting = RMobilePhone::ELockSetDisabled;
+        }
+
+    iWait->SetRequestType( EMobilePhoneSetLockSetting );
+    RProperty::Set(KPSUidSecurityUIs, KSecurityUIsQueryRequestCancel, ESecurityUIsQueryRequestOk);
+    iPhone.SetLockSetting( iWait->iStatus, lockType, lockSetting );
+
+    // Wait for code verify to complete
+    retValue = iWait->WaitForRequestL();
+
+    switch( retValue )
+        {
+        case KErrNone:
+            #ifdef _DEBUG
+            RDebug::Print( _L( "(SecUi)CSecuritySettings::RemoteLockSetLockSettingL() - EMobilePhoneSetLockSetting request returned KErrNone" ) );
+            #endif // _DEBUG
+            break;
+
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            #ifdef _DEBUG
+            RDebug::Print( _L( "(SecUi)CSecuritySettings::RemoteLockSetLockSettingL() - EMobilePhoneSetLockSetting request returned KErrLocked" ) );
+            #endif // _DEBUG
+            //Error note is shown in CSecurityHandler::PassPhraseRequired()
+            break;
+
+        case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            #ifdef _DEBUG
+            RDebug::Print( _L( "(SecUi)CSecuritySettings::RemoteLockSetLockSettingL() - EMobilePhoneSetLockSetting request returned KErrAccessDenied" ) );
+            #endif // _DEBUG
+            // Security code was entered erroneously
+            //Error note is shown in CSecurityHandler::PassPhraseRequired()
+            break;
+
+        case KErrAbort:
+            #ifdef _DEBUG
+            RDebug::Print( _L( "(SecUi)CSecuritySettings::RemoteLockSetLockSettingL() - EMobilePhoneSetLockSetting request returned KErrAbort" ) );
+            #endif // _DEBUG
+            break;
+
+        default:
+            #ifdef _DEBUG
+            RDebug::Print( _L( "(SecUi)CSecuritySettings::RemoteLockSetLockSettingL() - EMobilePhoneSetLockSetting request returned: %d"), retValue );
+            #endif // _DEBUG
+            break;
+        }
+
+    #ifdef _DEBUG
+    RDebug::Print(_L("(SecUi)CSecuritySettings::RemoteLockSetLockSettingL() - Exit" ) );
+    #endif // _DEBUG
+
+    return retValue;
+    #else //! RD_REMOTELOCK
+    return KErrNotSupported;
+    #endif //RD_REMOTELOCK
+    }
+
+
+
+//
+// ----------------------------------------------------------
+// CSecuritySettings::ChangeSimSecurityL()
+// Changes SIM security
+// ----------------------------------------------------------
+//
+EXPORT_C TBool CSecuritySettings::ChangeSimSecurityL()
+    {    
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeSimSecurityL()"));
+    #endif
+
+    RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;
+    RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
+    RMobilePhone::TMobilePhoneLock lockType = RMobilePhone::ELockPhoneToICC;
+    RMobilePhone::TMobilePhoneLockSetting lockChangeSetting;
+    CCoeEnv* coeEnv = CCoeEnv::Static();
+    CDesCArrayFlat* items = coeEnv->ReadDesC16ArrayResourceL(R_SECURITY_LBX);
+    CleanupStack::PushL(items);
+                        
+    //get lock info
+    iWait->SetRequestType(EMobilePhoneGetLockInfo);
+    iPhone.GetLockInfo(iWait->iStatus, lockType, lockInfoPkg);
+    TInt status = iWait->WaitForRequestL();
+    User::LeaveIfError(status);
+    TInt currentItem = 0;
+
+    if (lockInfo.iSetting == RMobilePhone::ELockSetDisabled)
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeSimSecurityL()lockInfo: ELockSetDisabled"));
+        #endif
+        currentItem = 1;  // off
+        }
+                        
+    TInt oldItem = currentItem;
+
+    CAknRadioButtonSettingPage* dlg = new (ELeave)CAknRadioButtonSettingPage(R_SECURITY_SETTING_PAGE, currentItem, items);
+    CleanupStack::PushL(dlg);
+    
+
+    CleanupStack::Pop(); // dlg
+    if ( !(dlg->ExecuteLD(CAknSettingPage::EUpdateWhenChanged)) || oldItem==currentItem )
+        {
+        CleanupStack::PopAndDestroy();    // items
+        return EFalse;
+        }    
+
+
+
+    if (currentItem == 1)
+        {
+        lockChangeSetting = RMobilePhone::ELockSetDisabled;
+        }
+    else
+        {
+        lockChangeSetting = RMobilePhone::ELockSetEnabled;
+        }
+
+    CleanupStack::PopAndDestroy();    // items 
+    
+    iWait->SetRequestType(EMobilePhoneSetLockSetting);
+    RProperty::Set(KPSUidSecurityUIs, KSecurityUIsQueryRequestCancel, ESecurityUIsQueryRequestOk);
+    iPhone.SetLockSetting(iWait->iStatus,lockType,lockChangeSetting);
+    status = iWait->WaitForRequestL();
+
+    #if defined(_DEBUG)
+    RDebug::Print( _L("(SECUI)CSecuritySettings::ChangeSimSecurityL(): RETURN CODE: %d"), status);
+    #endif        
+    switch(status)
+        {
+        case KErrNone:
+            {
+            break;
+            }        
+        case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            {    
+            // code was entered erroneously
+            return ChangeSimSecurityL();
+            }    
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            {
+            return ChangeSimSecurityL();
+            }
+        case KErrAbort:
+            {
+            return EFalse;
+            }
+        default:
+            {
+            ShowErrorNoteL(status);
+            return ChangeSimSecurityL();
+            }
+        }
+    
+    return ETrue;
+    }
+//
+// ----------------------------------------------------------
+// CSecuritySettings::ChangePinRequestL()
+// Changes PIN1 request
+// ----------------------------------------------------------
+//
+EXPORT_C TBool CSecuritySettings::ChangePinRequestL()
+    {    
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ChangePinRequestL()"));
+    #endif      
+    TInt simState;
+    TInt err( KErrGeneral );
+    err = RProperty::Get(KPSUidStartup, KPSSimStatus, simState);
+    User::LeaveIfError( err );
+    TBool simRemoved(simState == ESimNotPresent);
+
+    if ( simRemoved )
+        {
+        ShowResultNoteL(R_INSERT_SIM, CAknNoteDialog::EErrorTone);
+        return EFalse;;
+        }
+
+    RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;
+    RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
+    RMobilePhone::TMobilePhoneLock lockType = RMobilePhone::ELockICC;
+
+    RMobilePhone::TMobilePhoneLockSetting lockChangeSetting;
+    
+    CCoeEnv* coeEnv = CCoeEnv::Static();
+    CDesCArrayFlat* items = coeEnv->ReadDesC16ArrayResourceL(R_PIN_LBX);
+    CleanupStack::PushL(items);
+                        
+    //get lock info
+    iWait->SetRequestType(EMobilePhoneGetLockInfo);
+    iPhone.GetLockInfo(iWait->iStatus, lockType, lockInfoPkg);
+    TInt status = iWait->WaitForRequestL();
+    User::LeaveIfError(status);                    
+    TInt currentItem = 0;
+
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ChangePinRequestL() GetLockInfo"));
+    #endif
+
+    if (lockInfo.iSetting == RMobilePhone::ELockSetDisabled)
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::ChangePinRequestL() lockInfo: ELockSetDisabled"));
+        #endif
+        currentItem = 1;  // off
+        }
+                        
+    TInt oldItem = currentItem;
+
+    CAknRadioButtonSettingPage* dlg = new (ELeave)CAknRadioButtonSettingPage(R_PIN_SETTING_PAGE, currentItem, items);
+    CleanupStack::PushL(dlg);
+    
+
+    CleanupStack::Pop(); // dlg
+    if ( !(dlg->ExecuteLD(CAknSettingPage::EUpdateWhenChanged)) || oldItem==currentItem )
+        {
+        CleanupStack::PopAndDestroy();    // items
+        return EFalse;
+        }    
+
+
+    if (currentItem == 1)
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::ChangePinRequestL() currentItem: ELockSetDisabled"));
+        #endif
+        lockChangeSetting = RMobilePhone::ELockSetDisabled;
+        }
+    else
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::ChangePinRequestL() currentItem: ELockSetEnabled"));
+        #endif
+        lockChangeSetting = RMobilePhone::ELockSetEnabled;
+        }
+
+    CleanupStack::PopAndDestroy();    // items 
+
+    // Raise a flag to indicate that the PIN
+    // request coming from ETEL has originated from SecUi and not from Engine.
+    TInt tRet = RProperty::Set(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsSecUIOriginated);
+    if ( tRet != KErrNone )
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::ChangePinRequestL():\
+            FAILED to set the SECUI query Flag: %d"), tRet);
+        #endif
+        }
+    // Change the lock setting
+    iWait->SetRequestType(EMobilePhoneSetLockSetting);
+    RProperty::Set(KPSUidSecurityUIs, KSecurityUIsQueryRequestCancel, ESecurityUIsQueryRequestOk);
+    iPhone.SetLockSetting(iWait->iStatus,lockType,lockChangeSetting);
+    status = iWait->WaitForRequestL();
+    #if defined(_DEBUG)
+    RDebug::Print( _L("(SECUI)CSecuritySettings::ChangePinRequestL(): RETURN CODE: %d"), status);
+    #endif
+
+    // Lower the flag                             
+    RProperty::Set(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsETelAPIOriginated);
+
+    switch(status)
+        {
+        case KErrNone:
+            {
+            break;
+            }
+        case KErrGsm0707OperationNotAllowed:
+            {
+            // not allowed with this sim
+            ShowResultNoteL(R_OPERATION_NOT_ALLOWED, CAknNoteDialog::EErrorTone);
+            return EFalse;
+            }
+        case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            {    
+            // code was entered erroneously
+            return ChangePinRequestL();
+            }    
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            {
+            return ETrue;
+            }
+        case KErrAbort:
+            {
+            return EFalse;
+            }
+        default:
+            {
+            return ChangePinRequestL();
+            }
+        }
+    
+    return ETrue;
+    }
+
+//
+// ----------------------------------------------------------
+// CSecuritySettings::ChangeUPinRequestL()
+// Changes UPIN request on/off
+// ----------------------------------------------------------
+//
+EXPORT_C TBool CSecuritySettings::ChangeUPinRequestL()
+    {
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    if(wcdmaSupported || upinSupported)
+      {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeUPinRequestL()"));
+        #endif
+        
+        TInt simState;
+        TInt err( KErrGeneral );
+        err = RProperty::Get(KPSUidStartup, KPSSimStatus, simState);
+        User::LeaveIfError( err );
+        TBool simRemoved(simState == ESimNotPresent);
+    
+        if ( simRemoved )
+            {
+            ShowResultNoteL(R_INSERT_SIM, CAknNoteDialog::EErrorTone);
+            return EFalse;
+            }
+    
+        RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;
+        RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
+        RMobilePhone::TMobilePhoneLock lockType = RMobilePhone::ELockUniversalPin;
+    
+        RMobilePhone::TMobilePhoneLockSetting lockChangeSetting = RMobilePhone::ELockSetDisabled;
+        
+        CCoeEnv* coeEnv = CCoeEnv::Static();
+        CDesCArrayFlat* items = coeEnv->ReadDesC16ArrayResourceL(R_UPIN_LBX);
+        CleanupStack::PushL(items);
+                            
+        //get lock info
+        iWait->SetRequestType(EMobilePhoneGetLockInfo);
+        iPhone.GetLockInfo(iWait->iStatus, lockType, lockInfoPkg);
+        TInt status = iWait->WaitForRequestL();
+        User::LeaveIfError(status);                    
+        TInt currentItem = 0;
+    
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeUPinRequestL() GetLockInfo"));
+        #endif
+    
+        if (lockInfo.iSetting == RMobilePhone::ELockSetDisabled)
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::ChangeUPinRequestL() lockInfo: ELockSetDisabled"));
+            #endif
+            currentItem = 1;  // off
+            }
+                            
+        TInt oldItem = currentItem;
+    
+        CAknRadioButtonSettingPage* dlg = new (ELeave)CAknRadioButtonSettingPage(R_UPIN_SETTING_PAGE, currentItem, items);
+        CleanupStack::PushL(dlg);
+        
+    
+        CleanupStack::Pop(); // dlg
+        if ( !(dlg->ExecuteLD(CAknSettingPage::EUpdateWhenChanged)) || oldItem==currentItem )
+            {
+            CleanupStack::PopAndDestroy();    // items
+            return EFalse;
+            }    
+    
+    
+       if (currentItem == 1)
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::ChangePinRequestL() currentItem: ELockSetDisabled"));
+            #endif
+            lockChangeSetting = RMobilePhone::ELockSetDisabled;
+            }
+        else
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::ChangePinRequestL() currentItem: ELockSetEnabled"));
+            #endif
+            lockChangeSetting = RMobilePhone::ELockSetEnabled;
+            }
+    
+        CleanupStack::PopAndDestroy();    // items 
+    
+        // Raise a flag to indicate that the UPIN
+        // request coming from ETEL has originated from SecUi and not from Engine.
+        RProperty::Set(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsSecUIOriginated);                              
+        // Change the lock setting
+        iWait->SetRequestType(EMobilePhoneSetLockSetting);
+        RProperty::Set(KPSUidSecurityUIs, KSecurityUIsQueryRequestCancel, ESecurityUIsQueryRequestOk);
+        iPhone.SetLockSetting(iWait->iStatus,lockType,lockChangeSetting);
+        status = iWait->WaitForRequestL();
+        #if defined(_DEBUG)
+        RDebug::Print( _L("(SECUI)CSecuritySettings::ChangeUPinRequestL(): RETURN CODE: %d"), status);
+        #endif
+    
+        // Lower the flag                           
+        RProperty::Set(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsETelAPIOriginated);
+        
+        switch(status)
+            {
+            case KErrNone:
+                {
+                break;
+                }
+            case KErrGsm0707OperationNotAllowed:
+                {
+                // not allowed with this sim
+                ShowResultNoteL(R_OPERATION_NOT_ALLOWED, CAknNoteDialog::EErrorTone);
+                return EFalse;
+                }
+            case KErrGsm0707IncorrectPassword:
+            case KErrAccessDenied:
+                {    
+                // code was entered erroneously
+                return ChangeUPinRequestL();
+                }    
+            case KErrGsmSSPasswordAttemptsViolation:
+            case KErrLocked:
+                {
+                return EFalse;
+                }
+            case KErrAbort:
+                {
+                return EFalse;
+                }
+            default:
+                {
+                ShowErrorNoteL(status);
+                return ChangeUPinRequestL();
+                }
+            }
+        
+        return ETrue;
+      }
+    else
+        return EFalse;
+
+    }
+
+//
+// ----------------------------------------------------------
+// CSecuritySettings::SwitchPinCodesL()
+// Changes the pin code currently in use (PIN/UPIN)
+// ----------------------------------------------------------
+//
+EXPORT_C TBool CSecuritySettings::SwitchPinCodesL()
+    { 
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    if(wcdmaSupported || upinSupported)
+      {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::SwitchPinCodesL()"));
+        #endif 
+    
+        // If we are in simless offline mode the PIN codes can't obviously be switched
+        TInt simState;
+        TInt err( KErrGeneral );
+        err = RProperty::Get(KPSUidStartup, KPSSimStatus, simState);    
+        User::LeaveIfError( err );
+        TBool simRemoved(simState == ESimNotPresent);
+    
+        if ( simRemoved )
+            {
+            ShowResultNoteL(R_INSERT_SIM, CAknNoteDialog::EErrorTone);
+            return EFalse;
+            }
+    
+       
+        RMobilePhone::TMobilePhoneLock lockType = RMobilePhone::ELockUniversalPin;
+        RMobilePhone::TMobilePhoneLockSetting lockChangeSetting = RMobilePhone::ELockReplaced;                       
+        RMobilePhone::TMobilePhoneSecurityCode activeCode;
+     
+        iCustomPhone.GetActivePin(activeCode);
+    
+        RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;    
+        RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::SwitchPinCodesL() GetLockInfo"));
+        #endif    
+        iWait->SetRequestType(EMobilePhoneGetLockInfo);
+    
+        if (activeCode == RMobilePhone::ESecurityUniversalPin)
+            {
+             lockType = RMobilePhone::ELockUniversalPin;
+             iPhone.GetLockInfo(iWait->iStatus, lockType, lockInfoPkg);
+             TInt res = iWait->WaitForRequestL();
+             User::LeaveIfError(res);
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::SwitchPinCodesL() Lock Info got: UPIN"));
+            #endif 
+            }
+        else
+            {
+             lockType = RMobilePhone::ELockICC;
+             iPhone.GetLockInfo(iWait->iStatus, lockType, lockInfoPkg);
+             TInt res = iWait->WaitForRequestL();
+             User::LeaveIfError(res);
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::SwitchPinCodesL() Lock Info got: PIN"));
+            #endif 
+            }
+    
+        // code request must be ON to change active code.
+        if (lockInfo.iSetting == RMobilePhone::ELockSetDisabled)
+           {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::SwitchPinCodesL() CODE REQ NOT ON."));
+            #endif
+            if (activeCode == RMobilePhone::ESecurityUniversalPin)
+                {
+                ShowResultNoteL(R_UPIN_NOT_ALLOWED, CAknNoteDialog::EErrorTone);
+                }
+            else
+                {
+                ShowResultNoteL(R_PIN_NOT_ALLOWED, CAknNoteDialog::EErrorTone);
+                }
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::SwitchPinCodesL() CODE REQ NOT ON NOTE END."));
+            #endif 
+            return EFalse;
+            }
+    
+        
+        
+        CCoeEnv* coeEnv = CCoeEnv::Static();
+        CDesCArrayFlat* items = coeEnv->ReadDesC16ArrayResourceL(R_CODE_LBX);
+        CleanupStack::PushL(items);
+    
+        iCustomPhone.GetActivePin(activeCode);
+        TInt currentItem = 0;
+    
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::SwitchPinCodesL() GetLockInfo"));
+        #endif
+    
+        if (activeCode == RMobilePhone::ESecurityUniversalPin)
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::SwitchPinCodesL() active code: UPIN"));
+            #endif
+            currentItem = 1;  // UPIN
+            }
+                            
+        TInt oldItem = currentItem;
+    
+        CAknRadioButtonSettingPage* dlg = new (ELeave)CAknRadioButtonSettingPage(R_CODE_IN_USE_SETTING_PAGE, currentItem, items);
+        CleanupStack::PushL(dlg);
+        
+    
+        CleanupStack::Pop(); // dlg
+        if ( !(dlg->ExecuteLD(CAknSettingPage::EUpdateWhenChanged)) || oldItem==currentItem )
+            {
+            CleanupStack::PopAndDestroy();    // items
+            return EFalse;
+            }    
+    
+    
+       if (currentItem == 1)
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::SwitchPinCodesL() currentItem: UPIN"));
+            #endif
+            lockType = RMobilePhone::ELockUniversalPin;
+            }
+        else
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::SwitchPinCodesL() currentItem: PIN1"));
+            #endif
+            lockType = RMobilePhone::ELockICC;
+            }
+    
+        CleanupStack::PopAndDestroy();    // items 
+    
+        // Raise a flag to indicate that the code
+        // request coming from ETEL has originated from SecUi and not from Engine.
+        RProperty::Set(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsSecUIOriginated);                           
+        // Change the lock setting
+        iWait->SetRequestType(EMobilePhoneSetLockSetting);
+        RProperty::Set(KPSUidSecurityUIs, KSecurityUIsQueryRequestCancel, ESecurityUIsQueryRequestOk);
+        iPhone.SetLockSetting(iWait->iStatus,lockType,lockChangeSetting);
+        TInt status = iWait->WaitForRequestL();
+        #if defined(_DEBUG)
+        RDebug::Print( _L("(SECUI)CSecuritySettings::SwitchPinCodesL(): RETURN CODE: %d"), status);
+        #endif
+        // Lower the flag                            
+        RProperty::Set(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsETelAPIOriginated);
+        
+        switch(status)
+            {
+            case KErrNone:
+                {
+                break;
+                }
+            case KErrGsm0707OperationNotAllowed:
+                {
+                // not allowed with this sim
+                ShowResultNoteL(R_OPERATION_NOT_ALLOWED, CAknNoteDialog::EErrorTone);
+                return EFalse;
+                }
+            case KErrGsm0707IncorrectPassword:
+            case KErrAccessDenied:
+                {    
+                // code was entered erroneously
+                return SwitchPinCodesL();
+                }    
+            case KErrGsmSSPasswordAttemptsViolation:
+            case KErrLocked:
+                {
+                return EFalse;
+                }
+            case KErrAbort:
+                {
+                return EFalse;
+                }
+            default:
+                {
+                ShowErrorNoteL(status);
+                return SwitchPinCodesL();
+                }
+            }
+        
+        return ETrue;
+      }
+    else
+        return EFalse;
+    }
+
+//
+// ----------------------------------------------------------
+// CSecuritySettings::IsLockEnabledL()
+// Return is lock enabled/disabled
+// ----------------------------------------------------------
+//
+EXPORT_C TBool CSecuritySettings::IsLockEnabledL(RMobilePhone::TMobilePhoneLock aLockType)
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::IsLockEnabledL()"));
+    #endif
+    #ifdef __WINS__
+
+    return EFalse;
+
+    #else  //WINS
+
+    RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;
+    
+    //get lock info
+    RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
+    iWait->SetRequestType(EMobilePhoneGetLockInfo);
+    iPhone.GetLockInfo(iWait->iStatus, aLockType, lockInfoPkg);
+    TInt res = iWait->WaitForRequestL();
+
+    if (res != KErrNone)
+        return ETrue;
+
+     //lock is enabled return true
+    if (lockInfo.iSetting == RMobilePhone::ELockSetEnabled)
+        {
+        return ETrue;                        
+        }
+
+    // lock is disabled return false
+    return EFalse;
+        
+    #endif 
+
+    }
+//
+// ----------------------------------------------------------
+// CSecuritySettings::AskSecCodeL()
+// For asking security code e.g in settings
+// ----------------------------------------------------------
+//
+EXPORT_C TBool CSecuritySettings::AskSecCodeL()
+    {
+    return iSecurityHandler->AskSecCodeL();
+    }
+//
+// ----------------------------------------------------------
+// CSecuritySettings::AskPin2L()
+// Asks PIN2
+// ----------------------------------------------------------
+//    
+EXPORT_C TBool CSecuritySettings::AskPin2L()
+    {    
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::AskPin2L()"));
+    #endif
+    TInt ret = 0;
+    // check if pin2 is blocked...
+    RMmCustomAPI::TSecurityCodeType secCodeType = RMmCustomAPI::ESecurityCodePin2;
+    RMobilePhone::TMobilePhoneSecurityCode etelsecCodeType(RMobilePhone::ESecurityCodePin2);
+    RMobilePhone::TMobilePhoneSecurityCodeInfoV5 codeInfo;
+    RMobilePhone::TMobilePhoneSecurityCodeInfoV5Pckg codeInfoPkg(codeInfo);
+    TBool isBlocked = EFalse;
+    //Check whether PIN2 is blocked
+    ret = iCustomPhone.IsBlocked(secCodeType,isBlocked);
+    
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::AskPin2L() IsBlocked return value: %d"), ret);
+    #endif
+    if(isBlocked)
+        return EFalse;
+    
+    if (ret != KErrNone)
+        {    
+        switch (ret)
+            {
+			// PIN2 Blocked.
+            case KErrGsm0707SIMPuk2Required:
+                break;
+            case KErrGsmSSPasswordAttemptsViolation:
+            case KErrLocked:
+                // Pin2 features blocked permanently!
+                ShowResultNoteL(R_PIN2_REJECTED, CAknNoteDialog::EConfirmationTone);
+                break;
+            case KErrGsm0707SimNotInserted:
+                // not allowed with this sim
+                ShowResultNoteL(R_OPERATION_NOT_ALLOWED, CAknNoteDialog::EErrorTone);
+                break;
+            default:
+                ShowErrorNoteL(ret);
+                break;
+            }
+        return EFalse;
+        }
+    iWait->SetRequestType(EMobilePhoneGetSecurityCodeInfo);
+    iPhone.GetSecurityCodeInfo(iWait->iStatus, etelsecCodeType, codeInfoPkg);
+    ret = iWait->WaitForRequestL();
+        
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Pin2RequiredL(): get PIN2 info result: %d"), ret);
+    TInt attempts(codeInfo.iRemainingEntryAttempts);
+    RDebug::Print(_L("(SECUI)CSecurityHandler::Pin2RequiredL(): attempts remaining: %d"), attempts);
+    #endif
+    User::LeaveIfError(ret);
+    
+    // ask pin2 code  
+    RMobilePhone::TMobilePassword password;
+    CCodeQueryDialog* dlg = new (ELeave) CCodeQueryDialog (password,SEC_C_PIN_CODE_MIN_LENGTH,SEC_C_PIN_CODE_MAX_LENGTH,ESecUiNone);  
+    if(codeInfo.iRemainingEntryAttempts == KMaxNumberOfPINAttempts)
+            ret = dlg->ExecuteLD(R_PIN2_QUERY);
+    else if(codeInfo.iRemainingEntryAttempts > KLastRemainingInputAttempt)
+            {
+                HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_REMAINING_PIN2_ATTEMPTS, codeInfo.iRemainingEntryAttempts );
+                ret = dlg->ExecuteLD(R_PIN2_QUERY, *queryPrompt);
+                CleanupStack::PopAndDestroy(queryPrompt);
+            }
+    else
+            {
+                HBufC* queryPrompt = StringLoader::LoadLC(R_SECUI_FINAL_PIN2_ATTEMPT);
+                ret = dlg->ExecuteLD(R_PIN2_QUERY, *queryPrompt);
+                CleanupStack::PopAndDestroy(queryPrompt);   
+            } 
+       
+    if (!ret)
+        {
+		#if defined(_DEBUG)
+		RDebug::Print(_L("(SECUI)CSecuritySettings::AskPin2L(): Cancel pressed"));
+		#endif
+        return EFalse;
+        }
+    
+    // verify code
+    RMobilePhone::TMobilePassword required_fourth;
+    iWait->SetRequestType(EMobilePhoneVerifySecurityCode);
+    iPhone.VerifySecurityCode(iWait->iStatus,etelsecCodeType, password, required_fourth);
+    TInt res = iWait->WaitForRequestL();
+
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::AskPin2L() VerifySecurityCode return value: %d"), res);
+    #endif
+
+    switch(res)
+        {        
+        case KErrNone:
+            break;
+        case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            // code was entered erroneously
+            ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+            return    AskPin2L();    
+        case KErrGsm0707OperationNotAllowed:
+            // not allowed with this sim
+            ShowResultNoteL(R_OPERATION_NOT_ALLOWED, CAknNoteDialog::EErrorTone);
+            return EFalse;
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            // code was blocked
+            ShowResultNoteL(R_CODE_ERROR, CAknNoteDialog::EErrorTone);
+            return EFalse;        
+        default:
+            ShowErrorNoteL(res);
+            return    AskPin2L();
+        }
+
+    return ETrue;
+    }
+//
+// ----------------------------------------------------------
+// CSecuritySettings::SetFdnModeL()
+// Activates or deactivates Fixed Dialling Numbers (FDN) mode.  
+// ----------------------------------------------------------
+//
+EXPORT_C void CSecuritySettings::SetFdnModeL()
+    {    
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::SetFdnModeL()"));
+    #endif
+    RMmCustomAPI::TSecurityCodeType secCodeType = RMmCustomAPI::ESecurityCodePin2;
+    
+    TBool isBlocked = EFalse;
+    TInt ret = iCustomPhone.IsBlocked(secCodeType,isBlocked);
+    
+    if(isBlocked)
+        return;
+    
+    if (ret != KErrNone)
+        {    
+        switch (ret)
+            {
+             // PIN2 Blocked.
+            case KErrGsm0707SIMPuk2Required:
+                break;
+            case KErrGsmSSPasswordAttemptsViolation:
+            case KErrLocked:
+                // Pin2 features blocked permanently!
+                ShowResultNoteL(R_PIN2_REJECTED, CAknNoteDialog::EConfirmationTone);
+                break;
+            case KErrGsm0707SimNotInserted:
+                // not allowed with this sim
+                ShowResultNoteL(R_OPERATION_NOT_ALLOWED, CAknNoteDialog::EErrorTone);    
+                break;
+            default:
+                ShowErrorNoteL(ret);
+                break;
+            }
+        return;
+        }
+
+    
+    TInt status = KErrNone;
+
+    RMobilePhone::TMobilePhoneFdnStatus fdnMode;
+    RMobilePhone::TMobilePhoneFdnSetting fdnSet;
+                    
+    iPhone.GetFdnStatus(fdnMode);
+    
+    if (fdnMode == RMobilePhone::EFdnActive)
+        {
+        fdnSet = RMobilePhone::EFdnSetOff;
+        }
+    else
+        {
+        fdnSet = RMobilePhone::EFdnSetOn;   
+        }
+        
+      // Change the FDN setting
+    iWait->SetRequestType(EMobilePhoneSetFdnSetting);
+    RProperty::Set(KPSUidSecurityUIs, KSecurityUIsQueryRequestCancel, ESecurityUIsQueryRequestOk);
+    iPhone.SetFdnSetting(iWait->iStatus, fdnSet);
+    status = iWait->WaitForRequestL();
+
+    #if defined(_DEBUG)
+    RDebug::Print( _L("(SECUI)CSecuritySettings::SetFdnModeL(): RETURN CODE: %d"), status);
+    #endif
+    switch(status)
+        {        
+        case KErrNone:
+            break;
+        case KErrGsm0707IncorrectPassword:
+        case KErrAccessDenied:
+            // code was entered erroneously
+            SetFdnModeL();
+            break;
+        case KErrGsmSSPasswordAttemptsViolation:
+        case KErrLocked:
+            break;
+        case KErrAbort:
+            break;
+        case KErrGsm0707OperationNotAllowed:
+            // not allowed with this sim
+            ShowResultNoteL(R_OPERATION_NOT_ALLOWED, CAknNoteDialog::EErrorTone);
+            break;
+        default:
+            ShowErrorNoteL(status);
+            break;
+        }    
+  }
+//
+// ----------------------------------------------------------
+// CSecuritySettings::GetFndMode()
+// Retrieves the current Fixed Dialling Numbers mode
+// ----------------------------------------------------------
+//
+EXPORT_C TInt CSecuritySettings::GetFdnMode (RMobilePhone::TMobilePhoneFdnStatus& aFdnMode)
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::GetFdnMode()"));
+    #endif
+    return iPhone.GetFdnStatus(aFdnMode);
+    }
+
+//
+// ----------------------------------------------------------
+// CSecuritySettings::ShowErrorNoteL()
+// Shows error note
+// ----------------------------------------------------------
+//
+void CSecuritySettings::ShowErrorNoteL(TInt aError)
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ShowErrorNoteL()"));
+    #endif
+    // Let's create TextResolver instance for error resolving...
+    CTextResolver* textresolver = CTextResolver::NewLC(); 
+    // Resolve the error
+    TPtrC errorstring;
+    errorstring.Set( textresolver->ResolveErrorString( aError ) );
+    CAknNoteDialog* noteDlg = new (ELeave) CAknNoteDialog(REINTERPRET_CAST(CEikDialog**,&noteDlg));
+    noteDlg->PrepareLC(R_CODE_ERROR);
+    noteDlg->SetTextL((TDesC&)errorstring);
+    noteDlg->SetTimeout(CAknNoteDialog::ELongTimeout);
+    noteDlg->SetTone(CAknNoteDialog::EErrorTone);
+    noteDlg->RunLD();
+    CleanupStack::PopAndDestroy(); // resolver    
+    }
+
+//
+// ----------------------------------------------------------
+// CSecuritySettings::ShowResultNoteL()
+// Shows result note
+// ----------------------------------------------------------
+//
+void CSecuritySettings::ShowResultNoteL(TInt aResourceID, CAknNoteDialog::TTone aTone)
+    {  
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ShowResultNoteL()"));
+    RDebug::Print(_L("(SECUI)CSecuritySettings::ShowResultNoteL() Resource ID: %d"), aResourceID);
+    #endif
+    CAknNoteDialog* noteDlg = new (ELeave) CAknNoteDialog(REINTERPRET_CAST(CEikDialog**,&noteDlg));
+    noteDlg->SetTimeout(CAknNoteDialog::ELongTimeout);
+    noteDlg->SetTone(aTone);
+    noteDlg->ExecuteLD(aResourceID);
+    }
+
+//
+// ----------------------------------------------------------
+// CSecuritySettings::IsUpinSupportedL()
+// Return is UPIN supported
+// ----------------------------------------------------------
+//
+EXPORT_C TBool CSecuritySettings::IsUpinSupportedL()
+{
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    if(wcdmaSupported || upinSupported)
+      {
+    	#if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinSupported() BEGIN"));
+        #endif
+        #ifdef __WINS__
+    
+        return EFalse;
+    
+        #else  //WINS
+    
+        RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;
+        
+        //get lock info
+        RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
+        iWait->SetRequestType(EMobilePhoneGetLockInfo);
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinSupported() GetLockInfo"));
+        #endif
+        iPhone.GetLockInfo(iWait->iStatus, RMobilePhone::ELockUniversalPin, lockInfoPkg);
+        TInt res = iWait->WaitForRequestL();
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinSupported() GetLockInfo DONE"));
+        #endif
+        if ((res == KErrNotSupported) || (res == KErrGsmInvalidParameter))
+        {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinSupported(): NOT SUPPORTED"));
+            #endif
+            return EFalse;
+        }
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinSupported(): SUPPORTED: %d"), res);
+        #endif
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinSupported() END"));
+        #endif
+        return ETrue;
+            
+        #endif //WINS
+      }
+    else
+        return EFalse;
+}
+//
+// ----------------------------------------------------------
+// CSecuritySettings::IsCodeBlocked()
+// Return is a code blocked
+// ----------------------------------------------------------
+//
+EXPORT_C TBool CSecuritySettings::IsUpinBlocked()
+{
+TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    if(wcdmaSupported || upinSupported)
+      {
+    #ifdef __WINS__
+        return EFalse;
+    #else//__WINS__
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinBlocked() BEGIN"));
+        #endif
+    	RMmCustomAPI::TSecurityCodeType secCodeType;
+        secCodeType = RMmCustomAPI::ESecurityUniversalPin;
+        TBool isBlocked = EFalse;
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinBlocked() IsBlocked"));
+        #endif
+        TInt ret = iCustomPhone.IsBlocked(secCodeType,isBlocked);
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinBlocked() DONE.RETURN: %d"), ret);
+        #endif
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinBlocked():isblocked: %d"), isBlocked);
+        #endif
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinBlocked() END"));
+        #endif
+        return isBlocked;
+    #endif //__WINS__
+      }
+    else
+        return EFalse;
+}
+//
+// ----------------------------------------------------------
+// CSecuritySettings::GetActivePinCode()
+// Return the code active in current application (PIN/UPIN)
+// ----------------------------------------------------------
+//
+EXPORT_C TBool CSecuritySettings::IsUpinActive()
+{
+    TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+    TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+    if(wcdmaSupported || upinSupported)
+      {
+        #ifdef __WINS__
+        return EFalse;
+        #else//__WINS__
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinActive() BEGIN"));
+        #endif
+    	RMobilePhone::TMobilePhoneSecurityCode activePin;
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinActive() GetActivePin"));
+        #endif
+        iCustomPhone.GetActivePin(activePin);
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinActive() GetActivePin DONE"));
+        #endif
+    	if(activePin == RMobilePhone::ESecurityUniversalPin)
+        {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinActive(): UPIN ACTIVE"));
+            #endif
+    		return ETrue;
+        }
+         #if defined(_DEBUG)
+         RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinActive(): UPIN NOT ACTIVE"));
+         #endif
+         #if defined(_DEBUG)
+         RDebug::Print(_L("(SECUI)CSecuritySettings::IsUpinActive(): END"));
+         #endif
+    	return EFalse;
+        #endif //__WINS__
+      }
+    else
+        return EFalse;
+}
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Src/SecUiSystemLock.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,306 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  System Lock interface
+*
+*
+*/
+
+
+#include    <e32property.h>
+#include    <PSVariables.h>   // Property values
+#include    <coreapplicationuisdomainpskeys.h>
+#include    "SecUiSystemLock.h"
+#include    <eikenv.h>
+#include    <AknNotifierController.h>
+#include    <rmmcustomapi.h>
+#include    "secuisecuritysettings.h"
+#include    "SecUiWait.h"
+#include    <mmtsy_names.h>
+#include 	<e32property.h>
+#include <ctsydomainpskeys.h>
+#include    <securityuisprivatepskeys.h>
+    /*****************************************************
+    *    Series 60 Customer / TSY
+    *    Needs customer TSY implementation
+    *****************************************************/
+//  LOCAL CONSTANTS AND MACROS  
+
+const TInt KTriesToConnectServer( 2 );
+const TInt KTimeBeforeRetryingServerConnection( 50000 );
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CSystemLock::NewL()    
+// 
+// ----------------------------------------------------------
+// 
+EXPORT_C CSystemLock* CSystemLock::NewL()
+    {
+    CSystemLock* self = new(ELeave) CSystemLock();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+//
+// ----------------------------------------------------------
+// CSystemLock::ConstructL()    
+// 
+// ----------------------------------------------------------
+// 
+void CSystemLock::ConstructL()    
+    {    
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    /*****************************************************
+    *    Series 60 Customer / TSY
+    *    Needs customer TSY implementation
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSystemLock::ConstructL()"));
+    #endif
+    TInt err( KErrGeneral );
+    TInt thisTry( 0 );
+    
+    /* All server connections are tried to be made KTiesToConnectServer times because occasional
+    fails on connections are possible, at least on some servers */
+    thisTry = 0;
+
+    // connect to ETel server
+    while ( ( err = iServer.Connect() ) != KErrNone && ( thisTry++ ) <= KTriesToConnectServer )
+        {
+        User::After( KTimeBeforeRetryingServerConnection );
+        }
+    User::LeaveIfError( err );
+
+    // load TSY
+    err = iServer.LoadPhoneModule( KMmTsyModuleName );
+    if ( err != KErrAlreadyExists )
+        {
+        // May also return KErrAlreadyExists if something else
+        // has already loaded the TSY module. And that is
+        // not an error.
+        User::LeaveIfError( err );
+        }
+
+    // open phones
+    User::LeaveIfError(iPhone.Open(iServer, KMmTsyPhoneName));
+    CActiveScheduler::Add(this);            
+    }    
+// ----------------------------------------------------------
+// CSystemLock::CSystemLock()
+// C++ constructor
+// ----------------------------------------------------------
+// 
+CSystemLock::CSystemLock() : CActive(0)                    
+    {    
+    }
+//
+// ----------------------------------------------------------
+// CSystemLock::CSystemLock()
+// Destructor
+// ----------------------------------------------------------
+//
+EXPORT_C CSystemLock::~CSystemLock()
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    /*****************************************************
+    *    Series 60 Customer / TSY
+    *    Needs customer TSY implementation
+    *****************************************************/
+
+    Cancel();
+   
+     // close phone
+    if (iPhone.SubSessionHandle())
+        iPhone.Close();
+    //close ETel connection
+    if (iServer.Handle())
+        {
+        iServer.UnloadPhoneModule(KMmTsyModuleName);
+        iServer.Close();
+        }
+    }
+//
+// ----------------------------------------------------------
+// CSystemLock::SetLockedL()
+// Activates system lock 
+// ----------------------------------------------------------
+//
+EXPORT_C void CSystemLock::SetLockedL()
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSystemLock::SetLockedL()"));
+    #endif
+    // close fast-swap window
+    CEikonEnv::Static()->DismissTaskList();
+
+#ifdef __WINS__
+    // can not verify security code in emulator ---> lock system 
+#ifdef RD_REMOTELOCK
+		iProperty.Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, EManualLocked);
+#else// !RD_REMOTELOCK
+        iProperty.Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, EAutolockOn);
+#endif//RD_REMOTELOCK
+#else //__WINS__
+
+    if(IsActive())
+        return;
+
+
+    RMobilePhone::TMobilePhoneLock lockType = RMobilePhone::ELockPhoneDevice;
+    RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;
+    RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
+    RMobilePhone::TMobilePhoneLockSetting lockChange(RMobilePhone::ELockSetDisabled);
+    CWait* wait = CWait::NewL();
+    CleanupStack::PushL( wait );
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSystemLock::SetLockedL() GetLockInfo"));
+    #endif
+    iPhone.GetLockInfo(wait->iStatus, lockType, lockInfoPkg);
+    if (wait->WaitForRequestL() == KErrNone)
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSystemLock::SetLockedL() KErrNone"));
+        #endif
+        if (lockInfo.iSetting == RMobilePhone::ELockSetDisabled)
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSystemLock::SetLockedL() ELockSetDisabled"));
+            #endif
+            // ask code
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSystemLock::SetLockedL() SetLockSetting"));
+            #endif
+            //iCustomPhone.CheckSecurityCode(iStatus, RMmCustomAPI::ESecurityCodePassPhrase);
+            lockChange = RMobilePhone::ELockSetEnabled;
+            RProperty::Set(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsSystemLockOriginated);
+            iPhone.SetLockSetting(iStatus, lockType, lockChange);
+            SetActive();
+            }        
+        else
+            {
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSystemLock::SetLockedL() Lock System"));
+            #endif
+ // lock system 
+#ifdef RD_REMOTELOCK
+		iProperty.Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, EManualLocked);
+#else// !RD_REMOTELOCK
+        iProperty.Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, EAutolockOn);
+#endif //RD_REMOTELOCK
+
+            #if defined(_DEBUG)
+            RDebug::Print(_L("(SECUI)CSystemLock::SetLockedL() Lock System OK"));
+            #endif
+            }
+        }
+    else
+        {
+        // ask code 
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECUI)CSystemLock::SetLockedL() ask code (SLS) "));
+        #endif
+        lockChange = RMobilePhone::ELockSetEnabled;
+        RProperty::Set(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsSystemLockOriginated);
+        iPhone.SetLockSetting(iStatus, lockType, lockChange);
+        SetActive();
+        }
+    CleanupStack::PopAndDestroy();
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSystemLock::SetLockedL() END"));
+    #endif // DEBUG
+    #endif // WINS
+    }
+//
+// ----------------------------------------------------------
+// CSystemLock::RunL()
+// Handles query result
+// ----------------------------------------------------------
+// 
+void CSystemLock::RunL()
+    {    
+    #if defined(_DEBUG)
+    TInt status(iStatus.Int());
+    RDebug::Print(_L("(SECUI)CSystemLock::RunL(): %d"), status);
+    #endif
+    //lower the flag
+    RProperty::Set(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsETelAPIOriginated);
+    if    (iStatus == KErrNone)
+        {
+        	TInt callState;
+        	RProperty::Get(KPSUidCtsyCallInformation, KCTsyCallState, callState);
+    		//If there is ann ongoing call, phone is not locked.
+    	    if (callState == EPSCTsyCallStateNone)
+    		{
+    			#if defined(_DEBUG)
+        		RDebug::Print(_L("(SECUI)CSystemLock::RunL() KErrNone"));
+        		#endif
+        		// clear notifiers
+        		AknNotifierController::HideAllNotifications(ETrue);
+        		// query approved -> lock system  
+			#ifdef RD_REMOTELOCK
+				iProperty.Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, EManualLocked);
+			#else// !RD_REMOTELOCK
+        		iProperty.Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, EAutolockOn);
+        	#endif//RD_REMOTELOCK
+        		AknNotifierController::HideAllNotifications(EFalse);
+    		}
+        }
+    else if((iStatus != KErrCancel) && (iStatus != KErrAbort))
+        {   //Code error or something like that. Show the dialog again.
+            #if defined(_DEBUG)
+        	RDebug::Print(_L("(SECUI)CSystemLock::RunL() Code Error"));
+        	#endif
+            SetLockedL();
+        }
+    else
+        {
+          //User canceled the dialog; do nothing...
+        }
+        
+        
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSystemLock::RunL() END"));
+    #endif
+    }
+//
+// ----------------------------------------------------------
+// CSecObsNotify::StartNotifier
+// Cancels code request
+// ----------------------------------------------------------
+//
+void CSystemLock::DoCancel()
+    {
+    /*****************************************************
+    *    Series 60 Customer / ETel
+    *    Series 60  ETel API
+    *****************************************************/
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECUI)CSystemLock::DoCancel"));
+    #endif
+    iPhone.CancelAsyncRequest(EMobilePhoneSetLockSetting);
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/Src/SecUiWait.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,167 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*    
+*
+*/
+
+
+
+#include    <e32base.h>
+#include    <eikenv.h>
+#include    <eikappui.h>
+#include    "SecUiWait.h"
+
+
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CWait::NewL()    
+// 
+// ----------------------------------------------------------
+// 
+CWait* CWait::NewL()
+    {
+    CWait* self = new(ELeave) CWait();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+//
+// ----------------------------------------------------------
+// CWait::ConstructL()    
+// 
+// ----------------------------------------------------------
+// 
+void CWait::ConstructL()    
+    {    
+    CActiveScheduler::Add(this);            
+    }    
+//
+// ----------------------------------------------------------
+// CWait::CWait()
+// 
+// ----------------------------------------------------------
+//
+CWait::CWait() : CActive(0)
+    { 
+    }
+//
+// ----------------------------------------------------------
+// CWait::~CWait()
+// Destructor
+// ----------------------------------------------------------
+//
+CWait::~CWait()
+    {
+		Cancel();
+    }
+//
+// ----------------------------------------------------------
+// CWait::WaitForRequestL()
+// 
+// ----------------------------------------------------------
+//
+TInt CWait::WaitForRequestL()
+    {    
+    CWaitAbsorbingControl* absorbing = CWaitAbsorbingControl::NewLC();
+    SetActive();
+    iWait.Start();
+    CleanupStack::PopAndDestroy(absorbing);
+    return iStatus.Int();
+    }
+//
+// ----------------------------------------------------------
+// CWait::RunL()
+// 
+// ----------------------------------------------------------
+// 
+void CWait::RunL()
+    {        
+    if(iWait.IsStarted())        
+        iWait.AsyncStop();
+    }
+//
+// ----------------------------------------------------------
+// CWait::DoCancel()
+// Cancels code request
+// ----------------------------------------------------------
+//
+void CWait::DoCancel()
+    {
+    if(iWait.IsStarted())
+        iWait.AsyncStop();
+    }
+
+//
+// ----------------------------------------------------------
+// CWait::SetRequestType
+// Sets active request type
+// ----------------------------------------------------------
+//
+void CWait::SetRequestType(TInt aRequestType)
+{
+    iRequestType = aRequestType;
+}
+
+//
+// ----------------------------------------------------------
+// CWait::GetRequestType
+// Gets active request type
+// ----------------------------------------------------------
+//
+TInt CWait::GetRequestType()
+{
+    return iRequestType;
+}
+//
+// class CWaitAbsorbingControl
+//
+CWaitAbsorbingControl::CWaitAbsorbingControl()
+    {
+    }
+
+CWaitAbsorbingControl::~CWaitAbsorbingControl()
+    {
+    if (iCoeEnv && iAppUi)
+        iAppUi->RemoveFromStack(this);
+    }
+
+CWaitAbsorbingControl* CWaitAbsorbingControl::NewLC()
+    {
+    CWaitAbsorbingControl* self= new(ELeave) CWaitAbsorbingControl();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    return self;
+    }
+
+void CWaitAbsorbingControl::ConstructL()
+    {
+    CreateWindowL();
+    SetExtent(TPoint(0,0), TSize(0,0));
+    ActivateL();
+    SetPointerCapture(ETrue);
+    ClaimPointerGrab(ETrue);
+    iAppUi=iEikonEnv->EikAppUi();
+    iAppUi->AddToStackL(this, ECoeStackPriorityEnvironmentFilter);
+    }
+
+TKeyResponse CWaitAbsorbingControl::OfferKeyEventL(const TKeyEvent& /*aKeyEvent*/,TEventCode /*aType*/)
+    {
+    return EKeyWasConsumed;
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/group/SecUi.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,128 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Makefile
+*
+*
+*
+*/
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET  secui.dll
+TARGETTYPE  dll
+UID 0x1000006C 0x100058ED
+VENDORID VID_DEFAULT
+CAPABILITY CAP_GENERAL_DLL
+
+SOURCEPATH .
+
+SOURCEPATH ../Data
+
+START RESOURCE SecUi.rss
+HEADER
+TARGETPATH   RESOURCE_FILES_DIR  
+LANGUAGE_IDS
+END
+
+USERINCLUDE . ../Inc
+
+MW_LAYER_SYSTEMINCLUDE ../../../inc 
+
+
+#ifdef __PROTOCOL_CDMA
+
+    SOURCEPATH ../Cdma/Src
+    SOURCE  SecUiSecuritySettingsCdma.cpp
+    SOURCE  SecUiSecurityHandlerCdma.cpp
+    SOURCE  SecUiObsStartterCdma.cpp
+    SOURCE  SecUiAutoLockSettingPageCdma.cpp
+    SOURCE  SecUiSystemLockCdma.cpp
+
+    SOURCEPATH ../Src
+    SOURCE  SecUi.cpp
+    SOURCE  SecUiCodeQueryDialog.cpp
+    SOURCE  SecUiCodeQueryControl.cpp
+    SOURCE  SecUiManualSecuritySettings.cpp
+    SOURCE  SecUiWait.cpp
+
+
+    library EUSER.LIB BAFL.LIB CONE.LIB
+    library EIKCORE.LIB EIKCOCTL.LIB
+    library avkon.lib  eikdlg.lib 
+    library etel.lib etelmm.lib
+    library eikctl.lib 
+    library ws32.lib commonengine.lib
+    library efsrv.lib 
+	LIBRARY centralrepository.lib
+	LIBRARY aknNotifierWrapper.lib
+    library customapi.lib
+    library securityclient.lib  //Security Engine
+    library apparc.lib //For starting application in secuiobsstartter
+
+   LIBRARY SCPClient.lib // SCP server
+
+#else //If GSM:
+
+
+    SOURCEPATH ../Src
+
+    SOURCE  ../Src/SecUi.cpp
+    SOURCE  ../Src/SecUiCodeQueryDialog.cpp
+    SOURCE  ../Src/SecUiSecuritySettings.cpp
+    SOURCE  ../Src/SecUiSecurityHandler.cpp
+    SOURCE  ../Src/SecUiCodeQueryControl.cpp
+    SOURCE  ../Src/SecUiAutoLockSettingPage.cpp
+    SOURCE  ../Src/SecUiObsStartter.cpp
+    SOURCE  ../Src/SecUiManualSecuritySettings.cpp
+    SOURCE  ../Src/SecUiSystemLock.cpp
+    SOURCE  ../Src/SecUiWait.cpp
+    SOURCE  ../Src/SecUiLockObserver.cpp
+#ifdef RD_REMOTELOCK
+    SOURCE  ../Src/SecUiRemoteLockSettingPage.cpp
+#endif    
+
+    library     euser.lib bafl.lib cone.lib
+    library     eikcore.lib eikcoctl.lib
+    library     avkon.lib  eikdlg.lib 
+    library     etel.lib etelmm.lib
+    library     eikctl.lib 
+    library     ws32.lib commonengine.lib
+    library     efsrv.lib 
+    library     eiksrvui.lib
+    library     customapi.lib
+    LIBRARY     starterclient.lib       //use of Starter to remove splash screen
+    library     sysutil.lib
+    library     estor.lib
+
+#ifdef RD_REMOTELOCK
+    library     rlocksettings.lib 
+#endif    
+
+
+   LIBRARY      scpclient.lib // SCP server         
+	LIBRARY centralrepository.lib
+	LIBRARY aknnotifierwrapper.lib
+#endif //__PROTOCOL_CDMA
+
+// Modified by build team
+#if defined(WINSCW)
+    DEFFILE ../BWinsCw/SECUI_EKA2.def
+#endif
+LIBRARY                 featmgr.lib
+LIBRARY aknnotify.lib
+
+SMPSAFE
+
+// end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information for the Security UI
+*		
+*
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+default
+
+
+PRJ_EXPORTS
+//SecUi iby files
+../rom/SecUi.iby CORE_MW_LAYER_IBY_EXPORT_PATH(secui.iby)
+../rom/SecUiResources.iby LANGUAGE_MW_LAYER_IBY_EXPORT_PATH(secuiresources.iby)
+//Sim Sec Plugin iby files
+../rom/GSSimSecPlugin.iby CORE_MW_LAYER_IBY_EXPORT_PATH(gssimsecplugin.iby)
+../rom/GSSimSecPluginResources.iby LANGUAGE_MW_LAYER_IBY_EXPORT_PATH(gssimsecpluginresources.iby)
+//localisation files
+../loc/SecUi.loc MW_LAYER_LOC_EXPORT_PATH(secui.loc)
+../GSSimSecPlugin/loc/gssecurity.loc MW_LAYER_LOC_EXPORT_PATH(gssecurity.loc)
+//ADO internal APIs
+../Inc/SecUiSystemLock.h MW_LAYER_PLATFORM_EXPORT_PATH(secuisystemlock.h)
+
+PRJ_MMPFILES
+
+../group/SecUi.mmp
+//SIM security plugin for General Settings
+../GSSimSecPlugin/GSSimSecPlugin.mmp
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/loc/SecUi.loc	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,600 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Localization for Code queries, Insert Sim Card Note,
+*               System reboot note, Security view (in settings),
+*               Sim & Device security view (in settings) and
+*               SIM locking notes.
+*
+*
+*/
+
+
+// LOCALISATION STRINGS
+
+//d:Query requesting universal pin code
+//l:popup_query_data_window
+//
+#define qtn_enter_upin "UPIN code"
+
+//d:Query requesting universal puk code
+//l:popup_query_data_window
+//
+#define qtn_enter_upuk "UPIN blocked. Enter UPUK code"
+
+//d:Query requesting new upin code
+//l:popup_query_data_window
+//
+#define qtn_set_new_upin "New UPIN code"
+
+//d:Query requesting to verify new upin code
+//l:popup_query_data_window
+//
+#define qtn_verify_new_upin "Verify new UPIN code"
+
+//d:Query requesting pin code
+//l:popup_query_data_window
+//
+#define text_pin "Enter PIN code"
+
+//d:Query requesting pin2 code
+//l:popup_query_data_window
+//
+#define text_pin2 "Enter PIN2 code"
+
+//d:Query requesting puk code
+//l:popup_query_data_window
+//
+#define qtn_simcd_enter_puk "SIM Card blocked. Enter PUK code"
+
+//d:Query requesting puk2 code
+//l:popup_query_data_window
+//
+#define qtn_simcd_enter_puk2 "PIN2 code blocked. Enter PUK2 code"
+
+//d:Query requesting security code
+//l:popup_query_data_window
+//
+#define qtn_set_enter_sec_code "Enter Security code"
+
+//d:Note code accepted. Shown after right code.
+//l:popup_note_window
+//
+#define text_code_accepted "Code accepted"
+
+//d:Note code error. Shown after wrong code.
+//l:popup_note_window
+//
+#define text_code_error "Code error"
+
+//d:Query requesting new pin code
+//l:popup_query_data_window
+//
+#define text_new_pin "Enter new PIN code"
+
+//d:Query requesting new pin2 code
+//l:popup_query_data_window
+//
+#define text_new_pin2 "Enter new PIN2 code"
+
+//d:Query requesting to verify new pin code
+//l:popup_query_data_window
+//
+#define text_verify_pin "Verify new PIN code"
+
+//d:Query requesting to verify new pin2 code
+//l:popup_query_data_window
+//
+#define text_verify_pin2 "Verify new PIN2 code"
+
+//d:Note code changed. Shown after pin code has been changed.
+//l:popup_note_window
+//
+#define text_pin_changed "PIN code changed"
+
+
+//d:Note code changed. Shown after upin code has been changed.
+//l:popup_note_window
+//
+#define qtn_set_upin_changed "UPIN code changed"
+
+
+//d:Note code changed. Shown after pin2 code has been changed.
+//l:popup_note_window
+//
+#define text_pin2_changed "PIN2 code changed"
+
+//d:Note codes don't match. Shown after new and verify codes do not match.
+//l:popup_note_window
+//
+#define text_codes_do_not_match "Codes do not match"
+
+//d:Error note set pin request. Shown if user tries to change pin code when pin request is off.  
+//l:popup_note_window
+//
+#define text_pin_code_cntrl_set "Set PIN code request on"
+
+//d:Error note set upin request. Shown if user tries to change upin code when upin request is off.  
+//l:popup_note_window
+//
+#define qtn_set_upin_on "Set UPIN code request on"
+
+//d:Note upin rejected. Shown after UPIN code has been blocked.
+//l:popup_note_window
+//
+#define qtn_error_upin_rejected "UPIN code rejected"
+
+//d:Query requesting to enter new security code. Shown when changing code.
+//l:popup_query_data_window
+//
+#define qtn_set_new_sec_code "Enter new Security code"
+
+//d:Query requesting to verify security code. Shown when changing code.
+//l:popup_query_data_window
+//
+#define qtn_set_verify_sec_code "Verify new Security code"
+
+//d:Note code changed. Shown after security code has been changed.
+//l:popup_note_window
+//
+#define qtn_set_new_sec_code_changed "Security code changed"
+
+//d:Note Pin2 rejected. Shown after PUK2 code has been blocked.
+//l:popup_note_window
+//
+#define text_pin2_rejected "PIN2 code rejected"
+
+//d:Note Security code blocked. Shown after Security code has been entered incorrectly 5 times.
+//d:Code is ublocked after five minutes.
+//l:popup_note_window
+//
+#define qtn_set_sec_code_error_wait "Code error. Wait five minutes and try again."
+
+//d:Note that user chosen USIM (line) has been activated. Shown together with the line name. For example: "Operator X activated". 
+//l:popup_note_window
+//
+#define qtn_conf_usim_activated "activated"
+
+//d:Header line of the popup menu where different USIM applications are selected from.
+//l: list_single_pane_t1_cp2
+//
+#define qtn_set_select_line "Select line:"
+
+//d:Remaining attempts to enter correct PIN1 code.
+//l:popup_query_data_window
+//w:
+//r:3.2
+#define qtn_simcd_attempt_count_pin "%N attempts remaining. Enter PIN code:"
+
+//d:Remaining attempts to enter correct PIN2 code.
+//l:popup_query_data_window
+//w:
+//r:3.2
+#define qtn_simcd_attempt_count_pin2 "%N attempts remaining. Enter PIN2 code:"
+
+//d:Remaining attempts to enter correct UPIN code.
+//l:popup_query_data_window
+//w:
+//r:3.2
+#define qtn_simcd_attempt_count_upin "%N attempts remaining. Enter UPIN code:"
+
+//d:Remaining attempts to enter correct PUK1 code.
+//l:popup_query_data_window
+//w:
+//r:3.2
+#define qtn_simcd_attempt_count_puk "%N attempts remaining. Enter PUK code:"
+
+//d:Remaining attempts to enter correct PUK2 code.
+//l:popup_query_data_window
+//w:
+//r:3.2
+#define qtn_simcd_attempt_count_puk2 "%N attempts remaining. Enter PUK2 code:"
+
+//d:Remaining attempts to enter correct UPUK code.
+//l:popup_query_data_window
+//w:
+//r:3.2
+#define qtn_simcd_attempt_count_upuk "%N attempts remaining. Enter UPUK code:"
+
+//d:Final attempt to enter correct PIN1 code.
+//l:popup_query_data_window
+//w:
+//r:3.2
+#define qtn_simcd_final_attempt_pin "Final attempt. Enter PIN code:"
+
+//d:Final attempt to enter correct PIN2 code.
+//l:popup_query_data_window
+//w:
+//r:3.2
+#define qtn_simcd_final_attempt_pin2 "Final attempt. Enter PIN2 code:"
+
+//d:Final attempt to enter correct UPIN code.
+//l:popup_query_data_window
+//w:
+//r:3.2
+#define qtn_simcd_final_attempt_upin "Final attempt. Enter UPIN code:"
+
+//d:Final attempt to enter correct PUK1 code.
+//l:popup_query_data_window
+//w:
+//r:3.2
+#define qtn_simcd_final_attempt_puk "Final attempt. Enter PUK code:"
+
+//d:Final attempt to enter correct PUK2 code.
+//l:popup_query_data_window
+//w:
+//r:3.2
+#define qtn_simcd_final_attempt_puk2 "Final attempt. Enter PUK2 code:"
+
+//d:Final attempt to enter correct UPUK code.
+//l:popup_query_data_window
+//w:
+//r:3.2
+#define qtn_simcd_final_attempt_upuk "Final attempt. Enter UPUK code:"
+
+
+//-------------------------------------------------------------
+// GENERAL SETTINGS
+
+//-------------------------------------------------------------
+// security view
+//-------------------------------------------------------------
+
+//d: title for security settings folder (in general settings)
+//l: title_pane_t2/opt9
+//
+#define qtn_set_title_settings_security "Security settings"
+
+//d: Command in general settings security folder, opens Device & Sim security view
+//l: list_setting_pane_t1
+//
+#define qtn_set_dev_sim_security "Device & Sim security"
+
+//d: Command in general settings security folder, opens Wims view
+//l: list_setting_pane_t1
+//
+#define qtn_set_wim_security "Security module"
+
+//d: Command in general settings security folder, opens Certificate management view
+//l: list_setting_pane_t1
+//
+#define qtn_set_certmanui_security "Certificate management"
+                
+
+//-------------------------------------------------------------
+// device & sim security view
+//-------------------------------------------------------------
+//d:Code in use setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//
+#define qtn_set_code_in_use "Code in use"
+
+
+//d: pin code request setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//
+#define text_pin_code_cntrl "PIN code request"
+
+//d: Upin code request setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//
+#define qtn_set_upin_code_req "UPIN code request"
+
+
+//d: sim change security setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//
+#define qtn_set_sim_change_sec "SIM change security"
+
+//d: atulock period setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//
+#define qtn_set_autolock "Autolock period"
+
+//d: security code setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//
+#define qtn_set_sec_code "Security code"
+
+//d:Number query: autolock period time in minutes.
+//l:popup_query_data_window
+//
+#define qtn_set_autolock_define_time "Autolock period time (min)"
+
+//d: pin code setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//
+#define text_pin_change "PIN code"
+
+//d: upin code setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//
+#define qtn_set_upin_code "UPIN code"
+
+//d: pin2 code setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//
+#define text_pin2_change "PIN2 code"
+
+//d: fixed dialings setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//
+#define text_menu_fdn "Fixed dialing"
+
+//d:list item in fixed dialing setting page
+//l:list_set_graphic_pane_t1
+//
+#define text_fdn_off "Off"
+
+//d:list item in fixed dialing setting page
+//l:list_set_graphic_pane_t1
+//
+#define text_fdn_on "On"
+
+//d: closed user group setting item in device & sim security settings folder
+//l: list_setting_pane_t1
+//
+#define text_closed_user_groups "Closed user group"
+
+//d: item, network default, to closed user group popup list
+//l: list_set_graphic_pane_t1
+#define text_cug_default "Network default"
+
+//d: item, on,  to closed user group popup list
+//l: list_set_graphic_pane_t1
+#define text_cug_group "On"
+
+//d: item, off, to closed user group popup list
+//l: list_set_graphic_pane_t1
+#define text_cug_suppress "Off"
+
+//d: text to number query asking for cug index
+//l: popup_query_data_window
+#define text_give_group_number "Group number:"
+
+//d: text to cug error note when entered index is too large
+//l: popup_note_window
+#define text_cug_error "Value too large"		
+	
+//d:sat operations setting item in device & sim security settings folder
+//l:list_setting_pane_t1
+//
+#define text_simatk_setting "Confirm SAT operations"
+
+//d:list item in pin code request setting page
+//l:list_set_graphic_pane_t1
+//
+#define text_pin_code_off "Off"
+
+//d:list item in pin code request setting page
+//l:list_set_graphic_pane_t1
+//
+#define text_pin_code_on  "On"
+
+//d:list item in code in use setting page
+//l:list_set_graphic_pane_t1
+//
+#define qtn_set_pin "PIN"
+
+//d:list item in code in use setting page
+//l:list_set_graphic_pane_t1
+//
+#define qtn_set_upin "UPIN"
+
+//d:list item in sim change security setting page
+//l:list_set_graphic_pane_t1
+//
+#define qtn_set_sim_change_sec_off "Off"
+
+//d:list item in sim change security setting page
+//l:list_set_graphic_pane_t1
+//
+#define qtn_set_sim_change_sec_on "On"
+
+//d:List item in autolock period setting page
+//l:list_set_graphic_pane_t1
+//
+#define qtn_set_autolock_off "Autolock off"
+
+//d:List item in autolock period setting page
+//l:list_set_graphic_pane_t1
+//
+#define qtn_set_autolock_defined "User defined"
+
+//d:Autolock period settings (plural) item edit - setting selection data, %U is number 2-999
+//l:list_set_graphic_pane_t1
+//
+#define qtn_set_autolock_value_min "%U minutes"
+
+//d:Autolock period settings (singular) item edit - setting selection data, %U is number 1
+//l:list_set_graphic_pane_t1
+//
+#define qtn_set_autolock_min_one "%U minute"
+
+//d:Confirm SAT operations value on
+//l:list_set_graphic_pane_t1
+//
+#define text_simatk_notes_on "Asked"
+
+//d:Confirm SAT operations value off
+//l:list_set_graphic_pane_t1
+//
+#define text_simatk_notes_off "Not asked"
+
+//d: Command in general settings security folder, Updates bootstrap values
+//l: list_setting_pane_t1
+//
+#define qtn_op_set_trusted_prov_server "Trusted provisioning server"
+
+//d: Confirmation note for Trusted provisioning server
+//l: popup_note_window
+//
+#define qtn_op_set_conf_change_trustser "Reset Trusted provisioning server settings?"
+
+//d: Information note for Trusted prov server. Displayed after the changes are successful
+//l: popup_note_window
+//
+#define qtn_op_restore_bootstrap_ok "Bootstrap restored"
+
+//d: Information note for Trusted prov server. Displayed if there are no changes to be done
+//l: popup_note_window
+//
+#define qtn_op_set_conf_noserver "Nothing to be restored."
+
+//-------------------------------------------------------------
+// Network view
+//-------------------------------------------------------------
+
+//d:Line in use item in General Settings network settings folder
+//l: list_setting_pane_t1
+//
+#define qtn_set_line "Line in use"
+
+
+//-------------------------------------------------------------
+// Sim locking notes
+//-------------------------------------------------------------
+
+//d:Shown when SIM lock is closed from the keybad
+//l:popup_note_window
+//
+#define text_sim_lock_closed "SIM restriction on"
+
+//d:Shown when SIM lock is closed from the keybad with wrong code
+//l:popup_note_window
+//
+#define text_sim_lock_error "Code error"
+
+//d:Shown when SIM lock is closed from the keybad, but the lock is already closed
+//l:popup_note_window
+//
+#define text_sim_lock_already_closed "SIM was already restricted"
+
+//d:Shown when SIM lock is closed from the keybad, but the lock cannot be closed
+//l:popup_note_window
+//
+#define text_sim_lock_not_done "Not allowed"
+
+//d:Shown when SIM lock is opened from the keybad
+//l:popup_note_window
+//
+#define text_sim_lock_opened "SIM restriction off"
+
+//d:Shown when SIM lock is opened from the keybad, but the lock is already open
+//l:popup_note_window
+//
+#define text_sim_lock_already_open "SIM was not restricted"
+
+//-------------------------------------------------------------
+// CDMA Specific Strings
+//-------------------------------------------------------------
+
+//d:CDMA List item in autolock period setting page
+//l:list_set_graphic_pane_t1
+//
+#define qtn_set_lock_on_power_up_only "On Power-up only"
+
+//d:CDMA List item in autolock period setting page
+//l:list_set_graphic_pane_t1
+//
+#define qtn_set_timed_and_on_power_up "Timed & power-up"
+
+//d:CDMA Query requesting SPC code
+//l:popup_query_data_window
+//
+#define qtn_cdma_nam_prg_serv_prg_code "Service Programming Code"
+
+//d:CDMA Query requesting to enter new SPC code. Shown when changing code.
+//l:popup_query_data_window
+//
+#define qtn_set_new_spc_code "New SPC code"
+
+//d:CDMA Query requesting to verify SPC code. Shown when changing code.
+//l:popup_query_data_window
+//
+#define qtn_set_verify_spc_code "Verify SPC code"
+
+//d:CDMA Note code changed. Shown after security code has been changed.
+//l:popup_note_window
+//
+#define qtn_set_new_spc_code_changed "Service Programming code changed"
+
+//-------------------------------------------------------------
+// TARM Specific Strings
+//-------------------------------------------------------------
+//d: An error note text, which informs the user that autolock cannot be disabled
+//l:popup_note_window
+//w:
+//r:3.1
+//
+#define qtn_set_autolock_must_be_active "Cannot disable autolock"
+
+//-------------------------------------------------------------
+// Remotelock Specific Strings
+//-------------------------------------------------------------
+//d: Remote lock setting page header
+//l: list_setting_pane_t1
+//w:
+//r:3.2
+#define qtn_set_remotelock_status "Allow remote lock"
+
+//d:Remote lock setting state choice in remote lock radio buton dialog.
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.2
+#define qtn_set_remotelock_off "No"
+
+//d:Remote lock setting state choice in remote lock radio buton dialog.
+//l:list_set_graphic_pane_t1
+//w:
+//r:3.2
+#define qtn_set_remotelock_on  "Yes"
+
+//d:Query for requesting remote lock message
+//l:popup_query_data_window
+//w:
+//r:3.2
+#define qtn_set_remotelock_code_prompt "New remote lock message:"
+
+//d:Query for verifying remote lock message
+//l:popup_query_data_window
+//w:
+//r:3.2
+#define qtn_set_remotelock_code_confirm_prompt "Verify remote lock message:"
+
+//d:Note codes don't match. Shown if new and verify remote lock messages do not match..
+//l:popup_note_window
+//w:
+//r:3.2
+#define qtn_set_remotelock_note_code_error "Messages do not match"
+
+//d:Note invalid message. Shown if remote lock message is the same as current security code.
+//l:popup_note_window
+//w:
+//r:3.2
+#define qtn_set_remotelock_note_invalid_code "Lock code and remote lock message must not be the same"
+
+//d:Note Energency calls only. 
+//d:Shown when user presses send key in a touch dialog with emergenncy call support.
+//l:popup_note_window
+//w:
+//r:5.0
+#define qtn_emerg_emergency_only  "Emergency calls only"
+
+// end of file
+
+
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/rom/GSSimSecPlugin.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,28 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  GSAccsPlugin ROM files.
+*
+*/
+
+#ifndef GSSIMSECPLUGIN_IBY
+#define GSSIMSECPLUGIN_IBY
+
+    #ifdef RD_GS_RENOVATION
+
+        ECOM_PLUGIN( GSSimSecPlugin.dll, 10207438.rsc )
+
+    #endif // RD_GS_RENOVATION
+
+#endif // GSSIMSECPLUGIN_IBY
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/rom/GSSimSecPluginResources.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,28 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  GSSecurityPlugin ROM resources.
+*
+*/
+
+#ifndef GSSIMSECPLUGINRESOURCES_IBY
+#define GSSIMSECPLUGINRESOURCES_IBY
+
+    #ifdef RD_GS_RENOVATION
+
+        data=DATAZ_\RESOURCE_FILES_DIR\GSSimSecPluginRsc.rsc     RESOURCE_FILES_DIR\GSSimSecPluginRsc.rsc
+
+    #endif // RD_GS_RENOVATION
+
+#endif // GSSIMSECPLUGINRESOURCES_IBY
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/rom/SecUi.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef __SECUI_IBY__
+#define __SECUI_IBY__
+
+//Secui
+file=ABI_DIR\BUILD_DIR\SecUi.dll                        SHARED_LIB_DIR\SecUi.dll
+
+//Security Notifier
+file=ABI_DIR\BUILD_DIR\SecurityNotifier.dll             SHARED_LIB_DIR\SecurityNotifier.dll
+
+//Notifier wrapper
+ECOM_PLUGIN(Securitynotifierwrapper.dll,102071FA.rsc)
+
+//Security Observer
+#ifndef RD_STARTUP_CHANGE
+
+file=ABI_DIR\BUILD_DIR\SecurityObserver.exe             PROGRAMS_DIR\SecurityObserver.exe
+
+#endif //RD_STARTUP_CHANGE
+
+#endif//__SECUI_IBY__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/SecUi/rom/SecUiResources.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef __SECUI_RESOURCES_IBY__
+#define __SECUI_RESOURCES_IBY__
+
+//Resource file(s) for SecUi
+
+data=DATAZ_\RESOURCE_FILES_DIR\SecUi.rsc                             RESOURCE_FILES_DIR\SecUi.rsc
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securitynotifier/BWinsCw/SecurityNotifierU.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?NotifierArray@@YAPAV?$CArrayPtr@VMEikSrvNotifierBase2@@@@XZ @ 1 NONAME ; class CArrayPtr<class MEikSrvNotifierBase2> * NotifierArray(void)_E32Dll=__E32Dll	; Entry point for emulation
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securitynotifier/BWinsCw/SecurityNotifierUU.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?NotifierArray@@YAPAV?$CArrayPtr@VMEikSrvNotifierBase2@@@@XZ @ 1 NONAME ; class CArrayPtr<class MEikSrvNotifierBase2> * NotifierArray(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securitynotifier/Bmarm/SECURITYNOTIFIERU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	NotifierArray__Fv @ 1 NONAME R3UNUSED ; NotifierArray(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securitynotifier/Bwins/SECURITYNOTIFIERU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?NotifierArray@@YAPAV?$CArrayPtr@VMEikSrvNotifierBase@@@@XZ @ 1 NONAME ; class CArrayPtr<class MEikSrvNotifierBase> * __cdecl NotifierArray(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securitynotifier/EABI/SecurityNotifierU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,5 @@
+EXPORTS
+	_Z13NotifierArrayv @ 1 NONAME
+	_ZTI17CSecurityNotifier @ 2 NONAME ; #<TI>#
+	_ZTV17CSecurityNotifier @ 3 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securitynotifier/Group/102071FA.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource registry info file
+*    
+*
+*
+*/
+
+
+#include <ecom/registryinfo.rh>
+#include <uikon.hrh>
+
+RESOURCE REGISTRY_INFO theInfo
+{
+	dll_uid = 0x102071FA;
+	interfaces =
+	{
+	INTERFACE_INFO
+		{
+		interface_uid = KUikonUidPluginInterfaceNotifiers;
+		implementations =
+				{
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x102071FA;
+					version_no = 1;
+					display_name = "TTNOTIFY2V2 Plugin 1";
+					default_data = "TTNOTIFY2V2";
+					opaque_data	 = "0";
+					}
+				};
+		}
+	};
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securitynotifier/Group/Securitynotifier.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2000 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Notifier plug-in for Security application
+*               (KUidNotifierPlugIn is 0x10005522)
+*
+*/
+
+#include <platform_paths.hrh>
+
+TARGET          securitynotifier.dll
+TARGETTYPE      dll
+UID		0x101fdfae 0x10005987
+
+VENDORID VID_DEFAULT
+CAPABILITY CAP_GENERAL_DLL
+
+SOURCEPATH	../Src
+SOURCE          SecurityNotifier.cpp
+  
+USERINCLUDE     ../Inc  
+MW_LAYER_SYSTEMINCLUDE ../../../inc
+
+
+
+LANG SC
+
+LIBRARY euser.lib    
+LIBRARY eiksrv.lib
+LIBRARY secui.lib
+LIBRARY etel.lib
+LIBRARY etelmm.lib
+LIBRARY commonengine.lib
+LIBRARY	ws32.lib
+LIBRARY	cone.lib
+LIBRARY	sysutil.lib
+LIBRARY centralrepository.lib
+LIBRARY eikcore.lib
+LIBRARY scpclient.lib // SCP server
+
+#if defined(WINSCW)
+DEFFILE ../BWinsCw/SecurityNotifierU.def
+#endif
+LIBRARY                 featmgr.lib
+
+SMPSAFE
+
+//End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securitynotifier/Group/Securitynotifierappserver_reg.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Registration file for Securitynotifierappserver
+*
+*/
+
+#include <appinfo.rh>
+
+UID2 KUidAppRegistrationResourceFile
+UID3 0x102071FB  //  UID
+
+RESOURCE APP_REGISTRATION_INFO
+    {
+    app_file = "Securitynotifierappserver";
+    hidden = KAppIsHidden;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securitynotifier/Group/Securitynotifierwrapper.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Makefile
+*
+*
+*
+*/
+
+#include <platform_paths.hrh>
+
+TARGET         		securitynotifierwrapper.dll
+CAPABILITY 		CAP_ECOM_PLUGIN
+TARGETTYPE 		PLUGIN 
+
+UID			0x10009D8D 0x102071FA
+
+
+USERINCLUDE		../Inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+LANG            	SC
+SOURCEPATH		../Src
+SOURCE  		Securitynotifierwrapper.cpp
+
+SOURCEPATH		. 
+START RESOURCE 102071FA.rss 
+#ifdef SYMBIAN_SECURE_ECOM 
+TARGET 			securitynotifierwrapper.rsc
+#endif 
+END
+
+
+LIBRARY 		ecom.lib
+LIBRARY		    	aknnotifierwrapper.lib
+LIBRARY 		euser.lib
+
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securitynotifier/Group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,31 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*	 This file provides the information required for building the
+*        whole of a SecurityNotifier application.
+*
+*
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS 
+
+PRJ_MMPFILES
+../Group/Securitynotifier.mmp
+../Group/Securitynotifierwrapper.mmp
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securitynotifier/Inc/SecurityNotifier.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,133 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*   Notifier class for Security code dialogs. Notifier calls appropriate
+*   dialog to be opened from SecUi.
+*
+*/
+
+#ifndef     __SECURITYNOTIFIER_H
+#define     __SECURITYNOTIFIER_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <eiknotapi.h>
+#include <etelmm.h>
+#include <securitynotification.h>
+
+
+// CONSTANTS
+
+const TUid KSecurityNotifierChannel = {0x1000598F};
+const TUid KSecurityNotifierAppServerUid = {0x102071FB};
+
+IMPORT_C CArrayPtr<MEikSrvNotifierBase2>* NotifierArray();   // Notifier array (entry point)
+
+
+// CLASS DECLARATION
+
+/**
+*  CSecurityNotifier class
+*
+*
+*/
+class CSecurityNotifier : public CActive,public MEikSrvNotifierBase2
+    {
+    public:
+        /**
+        * Creates instance of the CSecurityNotifier class.
+        *
+        * @return Returns the MEikSrvNotifierBase2 instance just created.
+        */
+        static MEikSrvNotifierBase2* NewL();
+        /**
+        * Destructor.
+        */
+        ~CSecurityNotifier();
+    public: // from MEikSrvNotifierBase2
+        /**
+        * Called when all resources allocated by notifiers should be freed.
+        */
+        void Release();
+        /**
+        * From MEikSrvNotifierBase2 - method for registering the EikSrv plugin
+        *
+        * @return TNotifierInfo - struct containing the plugin priorities etc.
+        */
+        TNotifierInfo RegisterL();
+         /**
+        * From MEikSrvNotifierBase2 - method for getting the notifier info
+        *
+        * @return TNotifierInfo - struct containing the plugin priorities etc.
+        */
+        TNotifierInfo Info() const;
+         /**
+        * From MEikSrvNotifierBase2 - method for starting the plugin. Synchronous version
+        * @param aBuffer - buffer containing the parameters for the plugin, packaged in TPckg<SAknSoftNotificationParams>
+        * @return TPtrC8 - return value to the client, this method will return KNullDesC
+        */
+        TPtrC8 StartL(const TDesC8& aBuffer);
+        /**
+        * From MEikSrvNotifierBase2 - method for starting the plugin. Asynchronous version.
+        * @param aBuffer - buffer containing parameters for the plugin, packaged in TPckg<SAknSoftNotificationParams>
+        * @param aReturnVal - return value of any type. Not used in this case.
+        * @param aMessage - RMessage to notify that the execution has ended
+        */
+        void StartL(const TDesC8& aBuffer,TInt aReturnVal, const RMessagePtr2& aMessage);
+        /**
+        * From MEikSrvNotifierBase2 - method for cancelling the plugin execution.
+        */
+        void Cancel();
+         /**
+        * From MEikSrvNotifierBase2 - method for updating the plugin while execution is in progress
+        * @param aBuffer - buffer containing parameters for the plugin, packaged in TPckg<SAknSoftNotificationParams>
+        * @return not used, return KNullDesC
+        */
+        TPtrC8 UpdateL(const TDesC8& /*aBuffer*/);
+    public: // From CActive
+        /** @see CActive::RunL() */
+        void RunL();
+        /** @see CActive::DoCancel() */
+        void DoCancel();
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CSecurityNotifier();
+        /**
+        * Initialize parameters and jumps to RunL
+        * @param aBuffer - buffer containing parameters for the plugin, packaged in TPckg<SAknSoftNotificationParams>
+        * @param aReturnVal - return value of any type. Not used in this case.
+        * @param aMessage - RMessage to notify that the execution has ended
+        */
+        void GetParamsL(const TDesC8& aBuffer, TInt aReturnVal, const RMessagePtr2& aMessage);
+    private: // data
+        TNotifierInfo   iInfo;
+	/*****************************************************
+	*	Series 60 Customer / ETel
+	*	Series 60  ETel API
+	*****************************************************/
+        RTelServer      iServer;
+		RMobilePhone	iPhone;
+		RMobilePhone::TMobilePhoneSecurityEvent iEvent;
+    protected:
+        RMessagePtr2    iMessage;               // Received message
+        TInt            iReturnVal;             // Return value
+        TBool           iStartup;               // System state: true means we are in the middle of a boot.
+    };
+
+#endif
+
+// end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securitynotifier/Src/SecurityNotifier.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,477 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*   SecurityNotifier implementation. Notifier calls appropriate
+*   dialog to be opened from SecUi.
+*
+*/
+
+
+#include "SecurityNotifier.h"
+#include <e32std.h>
+#include <secui.h>
+#include <secuisecurityhandler.h>
+#include <e32property.h>
+#include <securityuisprivatepskeys.h>
+#include <eikenv.h>
+#include <startupdomainpskeys.h>
+#include <mmtsy_names.h>
+#include <securitynotification.h>
+#include <AknQueryDialog.h>
+#include <featmgr.h>
+#include <SCPClient.h>
+
+//  LOCAL CONSTANTS AND MACROS
+	/*****************************************************
+	*	Series 60 Customer / TSY
+	*	Needs customer TSY implementation
+	*****************************************************/
+
+const TInt KTriesToConnectServer( 2 );
+const TInt KTimeBeforeRetryingServerConnection( 50000 );
+const TInt PhoneIndex( 0 );
+const TInt KDelayPeriod(200000);
+
+
+// ================= EXPORTED FUNCTIONS ====================
+
+// ---------------------------------------------------------
+//
+// Lib main entry point: Creates an notifiers array.
+//
+// ---------------------------------------------------------
+EXPORT_C CArrayPtr<MEikSrvNotifierBase2>* NotifierArray()
+    {
+    CArrayPtrFlat<MEikSrvNotifierBase2>* array = new CArrayPtrFlat<MEikSrvNotifierBase2>(1);
+
+    if (array)
+        {
+        TRAPD(err,
+            {
+            MEikSrvNotifierBase2* securityNotifier = CSecurityNotifier::NewL();
+            CleanupStack::PushL(securityNotifier);
+            array->AppendL(securityNotifier);
+            CleanupStack::Pop(securityNotifier);
+            });
+
+        if (err)
+            {
+            TInt count = array->Count();
+            while (count--)
+                (*array)[count]->Release();
+            delete array;
+            array = NULL;
+            }
+        }
+
+    return (array);
+    }
+
+// ================= LOCAL FUNCTIONS =======================
+
+TBool IsAdminCall()
+    {
+    TBool isAdminCall = EFalse;
+ if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))
+    {
+    RSCPClient scpClient;
+    if ( scpClient.Connect() == KErrNone )
+        {
+        if ( scpClient.QueryAdminCmd( ESCPCommandLockPhone ) )
+            {
+            #if defined(_DEBUG)
+        	RDebug::Print(_L("CSecObsNotify::SCP admin command, no action required"));
+	        #endif
+
+	        isAdminCall = ETrue;
+            }
+
+        scpClient.Close();
+        }
+   }
+    return isAdminCall;
+    }
+
+
+// ================= CSecurityNotifier =======================
+//
+// ----------------------------------------------------------
+// CSecurityNotifier::NewL()
+// Create new CSecurityNotifier object.
+// ----------------------------------------------------------
+//
+MEikSrvNotifierBase2* CSecurityNotifier::NewL()
+    {
+    MEikSrvNotifierBase2* self = new(ELeave) CSecurityNotifier;
+    return self;
+    }
+//
+// ----------------------------------------------------------
+//  CSecurityNotifier::CSecurityNotifier()
+//  Default constructor: Sets the active object's priority and
+//  puts itself to the active scheduler stack.
+// ----------------------------------------------------------
+//
+CSecurityNotifier::CSecurityNotifier(): CActive(EPriorityStandard)
+    {
+    CActiveScheduler::Add(this);
+    TRAP_IGNORE( FeatureManager::InitializeLibL() );
+    }
+//
+// ----------------------------------------------------------
+// CSecurityNotifier::~CSecurityNotifier()
+// Destructor
+// ----------------------------------------------------------
+//
+CSecurityNotifier::~CSecurityNotifier()
+    {
+    	FeatureManager::UnInitializeLib();
+    }
+//
+// ----------------------------------------------------------
+// CSecurityNotifier::Release()
+// Called when all resources allocated by notifiers should be freed.
+// ----------------------------------------------------------
+//
+void CSecurityNotifier::Release()
+    {
+    delete this;
+    }
+//
+// ----------------------------------------------------------
+// CSecurityNotifier::Release()
+// This function is called once when DLL is loaded.
+// Adds CSecurityNotifier resource file to the list maintained by CCoeEnv.
+// ----------------------------------------------------------
+//
+MEikSrvNotifierBase2::TNotifierInfo CSecurityNotifier::RegisterL()
+    {
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECURITYNOTIFIER)CSecurityNotifier::RegisterL()"));
+	#endif
+    iInfo.iUid = KSecurityNotifierUid;
+    iInfo.iChannel = KSecurityNotifierChannel;
+    iInfo.iPriority = ENotifierPriorityHigh;
+    return iInfo;
+    }
+//
+// ----------------------------------------------------------
+// CSecurityNotifier::Info()
+// Info
+// ----------------------------------------------------------
+//
+MEikSrvNotifierBase2::TNotifierInfo CSecurityNotifier::Info() const
+    {
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECURITYNOTIFIER)CSecurityNotifier::Info()"));
+	#endif
+    return iInfo;
+    }
+
+//
+// ----------------------------------------------------------
+// CSecurityNotifier::StartL()
+// Will be called by the manager to start the notifier. The contents of
+// the buffer are passed unchanged from the RNotifier call, and can be used
+// by the notifier implementation.
+// ----------------------------------------------------------
+//
+TPtrC8 CSecurityNotifier::StartL(const TDesC8& /*aBuffer*/)
+    {
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECURITYNOTIFIER)CSecurityNotifier::StartL()"));
+	#endif
+    TPtrC8 ret(KNullDesC8);
+    return (ret);
+    }
+//
+// ----------------------------------------------------------
+// CSecurityNotifier::StartL()
+// Asynchronic notifier launch.
+// ----------------------------------------------------------
+//
+void CSecurityNotifier::StartL(const TDesC8& aBuffer, TInt aReturnVal,const RMessagePtr2& aMessage)
+    {
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECURITYNOTIFIER)CSecurityNotifier::StartL2()"));
+	#endif
+    TRAPD(err, GetParamsL(aBuffer, aReturnVal, aMessage));
+    if (err)
+        {
+        aMessage.Complete(err);
+        User::Leave(err);
+        }
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECURITYNOTIFIER)CSecurityNotifier::StartL2() Start BEGIN"));
+    #endif
+    }
+//
+// ----------------------------------------------------------
+// CSecurityNotifier::GetParamsL()
+// Initialize parameters and jump to RunL
+// ----------------------------------------------------------
+//
+void CSecurityNotifier::GetParamsL(const TDesC8& aBuffer, TInt aReturnVal, const RMessagePtr2& aMessage)
+    {
+	/*****************************************************
+	*	Series 60 Customer / ETel
+	*	Series 60  ETel API
+	*****************************************************/
+    iMessage = aMessage;
+    iReturnVal = aReturnVal;
+    TBool skipQuery = EFalse; // In some cases the query is handled by some other entity and SecurityNotifier should skip it.
+
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECURITYNOTIFIER)CSecurityNotifier::GetParamsL() Start BEGIN"));
+    #endif
+    
+
+    TSecurityNotificationPckg pckg;
+    pckg.Copy( aBuffer );
+    iStartup = pckg().iStartup;
+    iEvent = static_cast<RMobilePhone::TMobilePhoneSecurityEvent>(pckg().iEvent);
+    
+
+if(FeatureManager::FeatureSupported(KFeatureIdSapTerminalControlFw ))
+		{
+    if(iEvent == RMobilePhone::EPhonePasswordRequired)
+        {
+            skipQuery = IsAdminCall(); // SCP handles the call.
+        }
+}
+
+    if ( skipQuery )
+        {
+        iMessage.Write( iReturnVal, TPckgBuf<TInt>( KErrNone ) );
+        iMessage.Complete( KErrNone );
+        }
+    else
+        {
+        // Call SetActive() so RunL() will be called by the active scheduler
+        SetActive();
+        iStatus = KRequestPending;
+        TRequestStatus* stat = &iStatus;
+	    #if defined(_DEBUG)
+        RDebug::Print(_L("CSecurityNotifier::GetParamsL() End"));
+        #endif
+        User::RequestComplete(stat, KErrNone); // jump to RunL
+        }
+    }
+//
+// ----------------------------------------------------------
+// CSecurityNotifier::RunL()
+// Show query
+// ----------------------------------------------------------
+void CSecurityNotifier::RunL()
+    {
+	/*****************************************************
+	*	Series 60 Customer / ETel
+	*	Series 60  ETel API
+	*****************************************************/
+	/*****************************************************
+	*	Series 60 Customer / TSY
+	*	Needs customer TSY implementation
+	*****************************************************/
+
+    TInt err( KErrGeneral );
+    TInt thisTry( 0 );
+	RTelServer::TPhoneInfo PhoneInfo;
+	#if defined(_DEBUG)
+    RDebug::Print(_L("CSecurityNotifier::RunL() Start"));
+    #endif
+    /*All server connections are tried to be made KTriesToConnectServer times because occasional
+    fails on connections are possible, at least on some servers*/
+
+    // connect to ETel server
+	#if defined(_DEBUG)
+    RDebug::Print(_L("CSecurityNotifier::RunL() connect to ETel server"));
+    #endif
+    while ( ( err = iServer.Connect() ) != KErrNone && ( thisTry++ ) <= KTriesToConnectServer )
+        {
+        User::After( KTimeBeforeRetryingServerConnection );
+        }
+    User::LeaveIfError( err );
+
+    thisTry = 0;
+
+    // load TSY
+	#if defined(_DEBUG)
+    RDebug::Print(_L("CSecurityNotifier::RunL() load TSY"));
+    #endif
+    err = iServer.LoadPhoneModule( KMmTsyModuleName );
+    if ( err != KErrAlreadyExists )
+        {
+        // may also return KErrAlreadyExists if something
+        // else has already loaded the TSY module. And that is
+        // not an error.
+        User::LeaveIfError( err );
+        }
+
+    // open phones
+	#if defined(_DEBUG)
+    RDebug::Print(_L("CSecurityNotifier::RunL() open phones"));
+    #endif
+    User::LeaveIfError(iServer.SetExtendedErrorGranularity(RTelServer::EErrorExtended));
+	User::LeaveIfError(iServer.GetPhoneInfo(PhoneIndex, PhoneInfo));
+    User::LeaveIfError(iPhone.Open(iServer,PhoneInfo.iName));
+    RProperty Property;
+    CleanupClosePushL( Property );
+    err = Property.Set(KPSUidStartup, KStartupSecurityCodeQueryStatus, ESecurityQueryActive);
+    User::LeaveIfError( err );
+
+    // initialize security ui
+	#if defined(_DEBUG)
+    RDebug::Print(_L("CSecurityNotifier::RunL() initialize security ui"));
+    #endif
+    CSecurityHandler* handler = new(ELeave) CSecurityHandler(iPhone);
+    CleanupStack::PushL(handler);
+    TSecUi::InitializeLibL();
+    
+    TBool StartUp = iStartup;
+
+    TInt secUiOriginatedQuery(ESecurityUIsSecUIOriginated);
+    err = KErrNone;
+    if(!StartUp)
+    {
+        err = Property.Get(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, secUiOriginatedQuery);
+    }
+    
+    // handle event
+    TInt result = KErrNone;
+    //Bring the window group to foreground
+    ( CEikonEnv::Static() )->BringForwards(ETrue);
+    
+    TRAPD( error, handler->HandleEventL( iEvent, iStartup, result ) );
+
+   
+    // if something went wrong cancel the code request
+    if (error)
+        {
+		#if defined(_DEBUG)
+		RDebug::Print(_L("CSecurityNotifier::RunL() ERROR: %d"), error);
+		#endif
+		TBool wcdmaSupported(FeatureManager::FeatureSupported( KFeatureIdProtocolWcdma ));
+		TBool upinSupported(FeatureManager::FeatureSupported( KFeatureIdUpin ));
+        switch (iEvent)
+            {
+            case RMobilePhone::EUniversalPinRequired:
+                if(wcdmaSupported || upinSupported)
+                  {
+                   iPhone.AbortSecurityCode(RMobilePhone::ESecurityUniversalPin);
+                  }
+                break;
+            case RMobilePhone::EUniversalPukRequired:
+                if(wcdmaSupported || upinSupported)
+                  {
+                   iPhone.AbortSecurityCode(RMobilePhone::ESecurityUniversalPuk);
+                  }
+                break;
+			case RMobilePhone::EPin1Required:
+                iPhone.AbortSecurityCode(RMobilePhone::ESecurityCodePin1);
+                break;
+			case RMobilePhone::EPuk1Required:
+                iPhone.AbortSecurityCode(RMobilePhone::ESecurityCodePuk1);
+                break;
+			case RMobilePhone::EPin2Required:
+                iPhone.AbortSecurityCode(RMobilePhone::ESecurityCodePin2);
+                break;
+			case RMobilePhone::EPuk2Required:
+                iPhone.AbortSecurityCode(RMobilePhone::ESecurityCodePuk2);
+                break;
+			case RMobilePhone::EPhonePasswordRequired:
+                iPhone.AbortSecurityCode(RMobilePhone::ESecurityCodePhonePassword);
+                break;
+            default:
+                break;
+            }
+        }
+
+    // uninitialize security ui
+    CleanupStack::PopAndDestroy(handler); // handler
+    TSecUi::UnInitializeLib();
+    Property.Set(KPSUidStartup, KStartupSecurityCodeQueryStatus, ESecurityQueryNotActive);
+    CleanupStack::PopAndDestroy( &Property );
+
+    //close ETel connection
+    if (iServer.Handle())
+        {
+        iPhone.Close();
+        iServer.UnloadPhoneModule(KMmTsyModuleName);
+        iServer.Close();
+        }
+
+    User::LeaveIfError(error);
+
+    // Complete message and free resources
+    iMessage.Write( iReturnVal, TPckgBuf<TInt>( result ) );
+    iMessage.Complete(KErrNone);
+    iReturnVal = KErrNone;
+    //Leave the window group to foreground for a short time to absorb key presses so that autolock has time to activate.
+    if(!StartUp)
+		User::After(KDelayPeriod);
+	( CEikonEnv::Static() )->BringForwards(EFalse);
+	#if defined(_DEBUG)
+    RDebug::Print(_L("CSecurityNotifier::RunL() End"));
+    #endif
+    }
+
+// ----------------------------------------------------------
+// This method will be called by framework (CActive)
+// if active object is still active.
+// Does nothing here.
+// ----------------------------------------------------------
+//
+void CSecurityNotifier::DoCancel()
+    {
+    }
+//
+// ----------------------------------------------------------
+//  CSecurityNotifier::Cancel()
+//  Will be called by the manager to stop the notifier. Nothing happens when
+//  a call to cancel is made on a notifier that hasn't started.
+// ----------------------------------------------------------
+//
+void CSecurityNotifier::Cancel()
+    {
+    }
+//
+// ----------------------------------------------------------
+//  CSecurityNotifier::UpdateL()
+//  Will be called by the manager to update an already started  notifier.
+//  The contents of the buffer are passed unchanged from the RNotifier call,
+//  and can be used by the notifier implementation
+//  Nothing happens when a call to update is made on a notifier that hasn't started.
+// ----------------------------------------------------------
+//
+TPtrC8 CSecurityNotifier::UpdateL(const TDesC8& /*aBuffer*/)
+    {
+    return TPtrC8();
+    }
+//
+// ----------------------------------------------------------
+// CE32Dll()
+// DLL entry point
+// ----------------------------------------------------------
+//
+
+#ifndef EKA2
+
+GLDEF_C TInt E32Dll( TDllReason /*aReason*/)
+    {
+    return KErrNone;
+    }
+
+#endif
+
+// end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securitynotifier/Src/Securitynotifierwrapper.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,91 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Securitynotifierwrapper acts as a proxy between
+*               clients and Securitynotifierappserver. 
+*
+*/
+
+
+#include <ecom/implementationproxy.h>
+
+#include <AknNotifierWrapper.h> // link against aknnotifierwrapper.lib
+
+#define KMyNotifierUid TUid::Uid(0x10005988) //  uid
+#define KMyPriority TInt(MEikSrvNotifierBase2::ENotifierPriorityHigh)
+#define KMyAppServerUid TUid::Uid(0x102071FB)
+ 
+void CleanupArray(TAny* aArray)
+    {
+    CArrayPtrFlat<MEikSrvNotifierBase2>*     
+        subjects=static_cast<CArrayPtrFlat<MEikSrvNotifierBase2>*>(aArray);
+    TInt lastInd = subjects->Count()-1;
+    for (TInt i=lastInd; i >= 0; i--)
+        subjects->At(i)->Release();	    	    
+    delete subjects;
+    }
+
+CArrayPtr<MEikSrvNotifierBase2>* DoCreateNotifierArrayL()
+    {
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECURITYNOTIFIER)WRAPPER DoCreateNotifierArrayL BEGIN"));
+	#endif
+    CArrayPtrFlat<MEikSrvNotifierBase2>* subjects=
+        new (ELeave)CArrayPtrFlat<MEikSrvNotifierBase2>(3);
+    
+    CleanupStack::PushL(TCleanupItem(CleanupArray, subjects));
+
+    // Create Wrappers
+
+    // Session owning notifier(if default implementation is enough)
+    CAknCommonNotifierWrapper* master = 
+        CAknCommonNotifierWrapper::NewL( KMyNotifierUid,
+                                   KMyNotifierUid,
+                                   KMyPriority,
+                                   _L("SecurityNotifier.dll"),
+                                   1, // we don't use synch reply
+                                   ETrue); // preload library once app server is up and running 
+	  	
+	   
+    subjects->AppendL( master );
+    CleanupStack::Pop();	// array cleanup
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECURITYNOTIFIER)WRAPPER DoCreateNotifierArrayL END"));
+	#endif
+    
+    return(subjects);
+    }
+
+
+CArrayPtr<MEikSrvNotifierBase2>* NotifierArray()
+    // old Lib main entry point
+    {
+    CArrayPtr<MEikSrvNotifierBase2>* array = 0;
+    TRAP_IGNORE(array = DoCreateNotifierArrayL()); 	
+    return array;
+    }
+
+const TImplementationProxy ImplementationTable[] =
+	{
+#ifdef __EABI__
+	{{0x102071fa},(TFuncPtr)NotifierArray}
+#else
+	{{0x102071fa},NotifierArray}
+#endif
+	};
+
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+	{
+	aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy) ;
+	return ImplementationTable;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securityobserver/Bmarm/SECURITYOBSERVERU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securityobserver/Bwins/SECURITYOBSERVERU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?WinsMain@@YAHPAX@Z @ 1 NONAME ; int __cdecl WinsMain(void *)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securityobserver/EABI/SecurityObserverU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,10 @@
+EXPORTS
+	_ZTI13CSecObsNotify @ 1 NONAME ; #<TI>#
+	_ZTI14CPhoneObserver @ 2 NONAME ; #<TI>#
+	_ZTI16CSimLockObserver @ 3 NONAME ; #<TI>#
+	_ZTI17CSecurityObserver @ 4 NONAME ; #<TI>#
+	_ZTV13CSecObsNotify @ 5 NONAME ; #<VT>#
+	_ZTV14CPhoneObserver @ 6 NONAME ; #<VT>#
+	_ZTV16CSimLockObserver @ 7 NONAME ; #<VT>#
+	_ZTV17CSecurityObserver @ 8 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securityobserver/Group/SecurityObserver.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2000 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observer for ETel security events. Uses SecurityNotifier
+*               which calls appropriate dialog to be opened from SecUi.
+*
+*/
+
+
+
+TARGET        SecurityObserver.exe
+
+TARGETTYPE		exexp
+UID						0x10005D30 0x10000938
+
+CAPABILITY      CAP_SERVER
+VENDORID        VID_DEFAULT
+
+TARGETPATH      /system/programs
+
+SOURCEPATH	    	../src
+SOURCE          	SecurityObserver.cpp 
+SOURCE			SecObsNotify.cpp 
+SOURCE			SecPhoneObserver.cpp
+SOURCE			SecSimLockObserver.cpp
+
+USERINCLUDE     ../inc  
+SYSTEMINCLUDE   /epoc32/include /epoc32/include/oem
+SYSTEMINCLUDE ../../inc // subsystem headers
+SYSTEMINCLUDE ../../../inc // ado headers
+
+
+LIBRARY	euser.lib etel.lib  
+LIBRARY ETELMM.LIB
+LIBRARY SysUtil.lib
+
+#ifdef __SAP_TERMINAL_CONTROL_FW
+LIBRARY SCPClient.lib
+#endif //__SAP_TERMINAL_CONTROL_FW
+
+SMPSAFE
+
+//End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securityobserver/Group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*    This file provides the information required for building the
+*    whole of a SecurityObserver application.
+*
+*
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+default
+
+PRJ_EXPORTS
+
+#ifndef RD_STARTUP_CHANGE
+../inc/SecurityObserver.h  MW_LAYER_SOURCE_PATH(systemswservices/inc/SecurityOserver.h)
+#endif //RD_STARTUP_CHANGE
+
+PRJ_MMPFILES
+#ifndef RD_STARTUP_CHANGE
+../group/Securityobserver.mmp
+#endif //RD_STARTUP_CHANGE
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securityobserver/Inc/SecObsNotify.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,85 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*		CSecObsNotify - starts and cancels notifier plug-ins. 
+*
+*
+*/
+
+
+#ifndef     __SECOBSNOTIFY_H
+#define     __SECOBSNOTIFY_H
+
+//  INCLUDES
+#include    <e32base.h>
+#include    <e32property.h>
+#include "SecPhoneObserver.h"
+#include "SecurityObserver.hrh"
+
+class CSecurityObserver;
+
+//  CLASS DEFINITIONS
+class   CSecObsNotify : public CActive
+    {
+    public:
+        /**
+        * Creates instance of the CSecObsNotify class.
+        *
+        * @param aObserver CSecurityObserver* pointer to securityobserver
+        * @return Returns the instance just created.
+        */
+        static CSecObsNotify* NewL(CSecurityObserver* aObserver);
+        /**
+        * Destructor.
+        */
+        ~CSecObsNotify();
+    public:
+        /**
+        * Starts given notifier asyncronously
+        *
+        * @param aNotifierToStart TSecurityNotifier
+        */
+        void StartNotifier(TSecurityNotifier aNotifierToStart);
+        /**
+        * Cancels active notifier.
+        */
+        void CancelActiveNotifier();
+    private:
+        /**
+        * C++ default constructor.
+        *
+        * @param aObserver CSecurityObserver* pointer to securityobserver
+        */
+        CSecObsNotify(CSecurityObserver* aObserver);
+        /**
+        * Symbian OS constructor.
+        */
+        void ConstructL();
+    private: // from CActive
+        /** @see CActive::RunL() */
+        void RunL();
+        /** @see CActive::DoCancel() */
+        void DoCancel();
+    private: // data
+        RNotifier iNotifier;
+        RProperty iProperty;
+        CPhoneObserver* iPhoneObserver;
+        TBuf8<1> iDummy;
+        CSecurityObserver* iObserver;
+        TSecurityNotifier iActiveNotifier;
+        TSecurityNotifier iPendingNotifier;
+   };
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securityobserver/Inc/SecPhoneObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,86 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observer for phone events. Used to re-active
+*               code query after emergency call
+*
+*
+*/
+
+#ifndef     __SECPHONEOBSERVER_H
+#define     __SECPHONEOBSERVER_H
+
+#include <e32svr.h>
+#include    <e32property.h>
+#include "SecurityObserver.hrh"
+
+class CSecObsNotify;
+class CSecurityObserver;
+
+class   CPhoneObserver: public CActive
+    {
+    public:
+        /**
+        * Creates instance of the CPhoneObserve class.
+        *
+        * @param aNotifierController CSecObsNotify* pointer to launch differend security
+        *  notifiers
+        * @param aObserver CSecurityObserver* pointer to securityobserver
+        * @return Returns the instance just created.
+        */
+        static CPhoneObserver* NewL(CSecObsNotify* aNotifierController,CSecurityObserver* aObserver);
+        /**
+        * Destructor.
+        */
+        ~CPhoneObserver();
+    public:
+        /**
+        * Starts asynchronic listening of KUidCurrentCall event
+        *
+        * @param aNotifier TSecurityNotifier: notifier which is activated when call has ended
+        * @return KErrNone: if no errors
+        * @return KErrInUse: if already listening
+        */
+        TInt Start(TSecurityNotifier aNotifier);
+        /**
+        * Stops asynchronic listening of KUidCurrentCall event
+        */
+        void Stop();
+    private: // constructors
+        /**
+        * C++ default constructor.
+        *
+        * @param aNotifierController CSecObsNotify* pointer to launch differend security
+        *  notifiers
+        * @param aObserver CSecurityObserver* pointer to securityobserver
+        */
+        CPhoneObserver(CSecObsNotify* aNotifierController,CSecurityObserver* aObserver);
+        /**
+        * Symbian OS constructor.
+        */
+        void ConstructL();
+    private: // from CActive
+        /** @see CActive::RunL() */
+        void RunL();
+        /** @see CActive::DoCancel() */
+        void DoCancel();
+    private: // data
+        CSecObsNotify*       iNotifierController; // not owned !
+        CSecurityObserver*   iObserver; //not owned !
+        TSecurityNotifier    iNotifier;
+        RProperty            iProperty;
+    };
+
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securityobserver/Inc/SecSimLockObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,79 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observer for Sim Locking events.
+*               Shows "Sim restriction on" note if necessary.
+*
+*
+*/
+
+#ifndef     __SECSIMLOCKOBSERVER_H
+#define     __SECSIMLOCKOBSERVER_H
+
+#include <e32svr.h>
+#include    <e32property.h>
+
+class CSecObsNotify;
+
+class   CSimLockObserver: public CActive
+    {
+    public:
+        /* Creates instance of the CSimLockObserve class.
+        *
+        * @param aNotifierController CSecObsNotify* pointer to launch differend security
+        *  notifiers
+        * @return Returns the instance just created.
+        */
+        static CSimLockObserver* NewL(CSecObsNotify* aNotifierController);
+        /**
+        * Destructor.
+        */
+        ~CSimLockObserver();
+    public:
+        /**
+        * Starts asynchronic listening of Sim lock events
+        *
+        * @return KErrNone: if no errors
+        * @return KErrInUse: if already listening
+        */
+        TInt Start();
+        /**
+        * Stops asynchronic listening of Sim lock events
+        *
+        */
+        void Stop();
+    private: // constructors
+        /**
+        * C++ default constructor.
+        *
+        * @param aNotifierController CSecObsNotify* pointer to launch differend security
+        *  notifiers
+        */
+        CSimLockObserver(CSecObsNotify* aNotifierController);
+        /**
+        * Symbian OS constructor.
+        */
+        void ConstructL();
+    private: // from CActive
+        /** @see CActive::RunL() */
+        void RunL();
+        /** @see CActive::DoCancel() */
+        void DoCancel();
+    private:  //data
+        CSecObsNotify*       iNotifierController; // not owned !
+        RProperty            iProperty;
+    };
+
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securityobserver/Inc/SecurityObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,134 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observer for ETel security events. Uses SecurityNotifier
+*               which calls appropriate dialog to be opened from SecUi.
+*
+*
+*/
+
+
+#ifndef     __SECURITYOBSERVER_H_
+#define     __SECURITYOBSERVER_H_
+
+//  INCLUDES
+
+#include <e32base.h>
+#include <etelmm.h>
+#include    <e32property.h>
+#include "SecObsNotify.h"
+#include "SecurityObserver.hrh"
+#include "SecSimLockObserver.h"
+
+class CSecurityObserver : public CActive
+    {
+    public:
+        /**
+        * Creates instance of the CSecurityObserver class.
+        *
+        * @return Returns the instance just created.
+        */
+        static  CSecurityObserver* NewL();
+        /**
+        * Destructor.
+        */
+        ~CSecurityObserver();
+    public:
+        /**
+        * Starts asynchronic listening security events
+        *
+        */
+        void StartListen();
+        /**
+        * Is pin1 required or not
+        *
+        * @return ETrue: required
+        *         EFalse: not required
+        */
+        inline TBool IsPin1Required() const;
+        /**
+        * Is puk1 required or not
+        *
+        * @return ETrue: required
+        *         EFalse: not required
+        */
+        inline TBool IsPuk1Required() const;
+        /**
+        * Is security code required or not
+        *
+        * @return ETrue: required
+        *         EFalse: not required
+        */
+        inline TBool IsPassPhraseRequired() const;
+        /**
+        * Is UPIN code required or not
+        *
+        * @return ETrue: required
+        *         EFalse: not required
+        */
+        inline TBool IsUPinRequired() const;
+
+        //inline TBool CSecurityObserver::IsUSimAppPinRequired() const
+        /**
+        * Is UPUK code required or not
+        *
+        * @return ETrue: required
+        *         EFalse: not required
+        */
+        inline TBool IsUPukRequired() const;
+    protected:
+        /**
+        * Symbian OS constructor.
+        */
+        void ConstructL();
+        /**
+        * C++ default constructor.
+        */
+        CSecurityObserver();
+    private:    //  from CActive
+        /** @see CActive::RunL() */
+        void DoCancel();
+        /** @see CActive::RunL() */
+        void RunL();
+    private:  // data
+	/*****************************************************
+	*	Series 60 Customer / ETel
+	*	Series 60  ETel API
+	*****************************************************/
+        RTelServer       iServer;
+		RMobilePhone	iPhone;
+		CSecObsNotify* iNotifierController;
+        CSimLockObserver* iSimLockObserver;
+		RMobilePhone::TMobilePhoneSecurityEvent iEvent;
+        RProperty iProperty;
+        TBool iPin1Required;
+        TBool iPuk1Required;
+        TBool iPassPhraseRequired;
+        TBool iUPinRequired;
+        TBool iUPukRequired;
+        TBool iUSimAppPinRequired;
+        };
+
+    inline TBool CSecurityObserver::IsPin1Required() const
+        {return iPin1Required;}
+    inline TBool CSecurityObserver::IsPuk1Required() const
+        {return iPuk1Required;}
+    inline TBool CSecurityObserver::IsPassPhraseRequired() const
+        {return iPassPhraseRequired;}
+    inline TBool CSecurityObserver::IsUPinRequired() const
+        {return iUPinRequired;}
+    inline TBool CSecurityObserver::IsUPukRequired() const
+        {return iUPukRequired;}
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securityobserver/Inc/SecurityObserver.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  SecurityObserver resource header
+*
+*/
+
+
+#ifndef SECURITYOBSERVER_HRH
+#define SECURITYOBSERVER_HRH
+
+enum TSecurityNotifier
+    {
+    ESecurityNotifierNone,
+    ESecurityNotifierPin1,
+    ESecurityNotifierPuk1,
+    ESecurityNotifierPin2,
+    ESecurityNotifierPuk2,
+    ESecurityNotifierSecurityCode,
+    ESecuritySimLockRestrictionOn,
+	ESecurityNotifierUSIMAppPin,
+	ESecurityNotifierSecondUSIMAppPin,
+	ESecurityNotifierUPin,
+	ESecurityNotifierUPuk
+    };
+
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securityobserver/Src/SecObsNotify.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,392 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*       CSecObsNotify - starts and cancels notifier plug-ins.
+*       Handles PIN/PIN2/PUK/PUK2/... notifiers
+*
+*/
+
+
+//  Include Files
+#include    "SecObsNotify.h"
+#include    "SecurityObserver.h"
+#include    <SecurityNotifier.h>
+
+#ifndef RD_STARTUP_CHANGE
+#include    <SysStartup.h>
+#endif //RD_STARTUP_CHANGE
+
+#include    "SecurityObserver.hrh"
+
+#ifdef __SAP_TERMINAL_CONTROL_FW
+#include <SCPClient.h>
+#endif //__SAP_TERMINAL_CONTROL_FW
+
+//===========================================================
+//  MEMBER FUNCTIONS
+//===========================================================
+//
+// ----------------------------------------------------------
+// CSecObsNotify::NewL()
+// Constructs a new entry with given values.
+// ----------------------------------------------------------
+//
+CSecObsNotify* CSecObsNotify::NewL(CSecurityObserver* aObserver)
+    {
+    CSecObsNotify* self = new(ELeave) CSecObsNotify(aObserver);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+//
+// ----------------------------------------------------------
+// CSecObsNotify::~CSecObsNotify
+// C++ destructor.
+// ----------------------------------------------------------
+//
+CSecObsNotify::~CSecObsNotify()
+    {
+    Cancel();
+    delete iPhoneObserver;
+    }
+//
+// ----------------------------------------------------------
+// CSecObsNotify::CSecObsNotify
+// C++ constructor
+// ----------------------------------------------------------
+//
+CSecObsNotify::CSecObsNotify(CSecurityObserver* aObserver) : CActive(0),
+                                 iObserver(aObserver),
+                                 iActiveNotifier(ESecurityNotifierNone),
+                                 iPendingNotifier(ESecurityNotifierNone)
+    {
+    }
+//
+// ----------------------------------------------------------
+// CSecObsNotify::ConstructL
+// Adds this active object to the scheduler.
+// ----------------------------------------------------------
+//
+void CSecObsNotify::ConstructL()
+    {
+    // Add this active object to the scheduler.
+    CActiveScheduler::Add(this);
+    iPhoneObserver = CPhoneObserver::NewL(this,iObserver);
+    }
+
+//
+// ----------------------------------------------------------
+// CSecObsNotify::RunL
+//
+// ----------------------------------------------------------
+//
+void CSecObsNotify::RunL()
+    {
+    #if defined(_DEBUG)
+	RDebug::Print(_L("CSecObsNotify::RunL()"));
+	#endif
+#ifndef RD_STARTUP_CHANGE
+
+#if defined(__PROTOCOL_WCDMA) || defined(__UPIN) 
+    if (iActiveNotifier == ESecurityNotifierUPin)
+        {
+        if (iObserver->IsUPinRequired() && !iObserver->IsUPukRequired() && SysStartup::State() != ESWStateNormal)
+            {
+            iPhoneObserver->Stop();
+            iPhoneObserver->Start(iActiveNotifier);
+            }
+        }
+  
+#endif //__PROTOCOL_WCDMA || __UPIN
+    if (iActiveNotifier == ESecurityNotifierPin1)
+        {
+        if (iObserver->IsPin1Required() && !iObserver->IsPuk1Required() && SysStartup::State() != ESWStateNormal)
+            {
+            iPhoneObserver->Stop();
+            iPhoneObserver->Start(iActiveNotifier);
+            }
+        }
+#endif // RD_STARTUP_CHANGE    
+
+    if (iActiveNotifier == ESecurityNotifierPuk1)
+        {
+        if (iObserver->IsPuk1Required())
+            {
+            iPhoneObserver->Stop();
+            iPhoneObserver->Start(iActiveNotifier);
+            }
+        }
+    #if defined(__PROTOCOL_WCDMA) || defined(__UPIN)
+    if (iActiveNotifier == ESecurityNotifierUPuk)
+        {
+        if (iObserver->IsUPukRequired())
+            {
+            iPhoneObserver->Stop();
+            iPhoneObserver->Start(iActiveNotifier);
+            }
+        }
+    #endif //__PROTOCOL_WCDMA || __UPIN
+
+#ifndef RD_STARTUP_CHANGE
+
+    if (iActiveNotifier == ESecurityNotifierSecurityCode)
+        {
+        #if defined(_DEBUG)
+	    RDebug::Print(_L("CSecObsNotify::RunL(): ESecurityNotifierSecurityCode"));
+	    #endif
+        if (iObserver->IsPassPhraseRequired() && SysStartup::State() != ESWStateNormal)
+            {
+            #if defined(_DEBUG)
+	        RDebug::Print(_L("CSecObsNotify::RunL(): ESecurityNotifierSecurityCode: IF"));
+	        #endif
+            iPhoneObserver->Stop();
+            iPhoneObserver->Start(iActiveNotifier);
+            #if defined(_DEBUG)
+	        RDebug::Print(_L("CSecObsNotify::RunL(): ESecurityNotifierSecurityCode: IF: END"));
+	        #endif
+            }
+        }
+#endif // RD_STARTUP_CHANGE 
+
+    CancelActiveNotifier();
+
+    if (iPendingNotifier != ESecurityNotifierNone)
+        {
+        #if defined(_DEBUG)
+	    RDebug::Print(_L("CSecObsNotify::RunL(): start pending notifier"));
+	    #endif
+        // previous notifier cancelled and we have pending notifier
+        StartNotifier(iPendingNotifier);
+
+#ifndef RD_STARTUP_CHANGE
+        #if defined(__PROTOCOL_WCDMA) || defined(__UPIN)
+        if(((iPendingNotifier == ESecurityNotifierPuk1) || (iPendingNotifier == ESecurityNotifierUPuk)) && iObserver->IsPassPhraseRequired())
+        #else
+        if((iPendingNotifier == ESecurityNotifierPuk1) && iObserver->IsPassPhraseRequired())
+        #endif //__PROTOCOL_WCDMA || __UPIN
+            { 
+            //PUK code query has been written in top of Sec code query in boot;
+            //it arrived before PIN code event was completed and Sec code event
+            //could be moved from pending to active. Putting sec code event
+            //back to pending event.
+            iPendingNotifier=ESecurityNotifierSecurityCode;
+            }
+        else
+            {
+            iPendingNotifier=ESecurityNotifierNone;
+            }
+#else // RD_STARTUP_CHANGE
+        iPendingNotifier=ESecurityNotifierNone;
+#endif // RD_STARTUP_CHANGE     
+        }
+  
+    }
+//
+// ----------------------------------------------------------
+// CSecObsNotify::CancelActiveNotifier
+// Cancels notifier
+// ----------------------------------------------------------
+//
+void CSecObsNotify::CancelActiveNotifier()
+    {
+    if (iActiveNotifier != ESecurityNotifierNone)
+        {
+        iNotifier.CancelNotifier(KSecurityNotifierUid);
+        iNotifier.Close();
+        iActiveNotifier=ESecurityNotifierNone;
+        }
+    }
+//
+// ----------------------------------------------------------
+// CSecObsNotify::StartNotifier
+// Starts given notifier asyncronously
+// ----------------------------------------------------------
+//
+void CSecObsNotify::StartNotifier( TSecurityNotifier aNotifierToStart )
+    {
+    #if defined(_DEBUG)
+	RDebug::Print(_L("CSecObsNotify::StartNotifier"));
+	#endif
+	    
+    #ifdef __SAP_TERMINAL_CONTROL_FW
+    // Check with the SCP Server whether this notification request resulted from an admin command,
+    // we're only interested in the security code events
+    if ( aNotifierToStart == ESecurityNotifierSecurityCode )        
+        {        
+        TBool isNormalCall = ETrue;
+        
+        RSCPClient SCPClient;
+        if ( SCPClient.Connect() == KErrNone )
+            {
+            if ( SCPClient.QueryAdminCmd( ESCPCommandLockPhone ) )
+                {
+                #if defined(_DEBUG)
+        	    RDebug::Print(_L("CSecObsNotify::SCP admin command, no action required"));
+	            #endif
+	    
+	            isNormalCall = EFalse;
+                }
+            
+            SCPClient.Close();            
+            }
+        
+        if ( !isNormalCall )
+            {
+            // Nothing further to be done in this method
+            return;
+            }
+        }
+    #endif //__SAP_TERMINAL_CONTROL_FW  
+    	
+    if(IsActive())
+        {
+        #if defined(_DEBUG)
+	    RDebug::Print(_L("CSecObsNotify::StartNotifier IsActive"));
+	    #endif
+        
+        if (iActiveNotifier != ESecurityNotifierNone)
+            {
+                #if defined(_DEBUG)
+	            RDebug::Print(_L("CSecObsNotify::StartNotifier: iActiveNotifier != ESecurityNotifierNone"));
+	            #endif
+                iPendingNotifier = aNotifierToStart; // to be started when previous has ended
+                return;
+            }
+
+        }
+    #if defined(_DEBUG)
+	RDebug::Print(_L("CSecObsNotify::StartNotifier: SWITCH"));
+	#endif
+	TInt err = KErrNone;
+    switch (aNotifierToStart)
+        {
+        #if defined(__PROTOCOL_WCDMA) || defined(__UPIN)
+        case ESecurityNotifierUPin:
+            {
+            #if defined(_DEBUG)
+	        RDebug::Print(_L("CSecObsNotify::StartNotifier: UPin"));
+	        #endif
+            err = iNotifier.Connect();
+            if(err == KErrNone)
+            	iNotifier.StartNotifierAndGetResponse(iStatus, KSecurityNotifierUid, KUPinRequired,iDummy);
+            break;
+            }
+        case ESecurityNotifierUPuk:
+            {
+            #if defined(_DEBUG)
+	        RDebug::Print(_L("CSecObsNotify::StartNotifier: UPuk"));
+	        #endif
+	        err = iNotifier.Connect();
+            if(err == KErrNone)
+            	iNotifier.StartNotifierAndGetResponse(iStatus, KSecurityNotifierUid, KUPukRequired,iDummy);
+            break;
+            }
+        #endif //__PROTOCOL_WCDMA
+        case ESecurityNotifierPin1:
+            {
+            #if defined(_DEBUG)
+	        RDebug::Print(_L("CSecObsNotify::StartNotifier: Pin1"));
+	        #endif
+            err = iNotifier.Connect();
+            if(err == KErrNone)
+            	iNotifier.StartNotifierAndGetResponse(iStatus, KSecurityNotifierUid, KPin1Required,iDummy);
+            break;
+            }
+        case ESecurityNotifierPuk1:
+            {
+            #if defined(_DEBUG)
+	        RDebug::Print(_L("CSecObsNotify::StartNotifier: Puk1"));
+	        #endif
+            err = iNotifier.Connect();
+            if(err == KErrNone)
+            	iNotifier.StartNotifierAndGetResponse(iStatus, KSecurityNotifierUid, KPuk1Required,iDummy);
+            break;
+            }
+        case ESecurityNotifierPin2:
+            {
+            #if defined(_DEBUG)
+	        RDebug::Print(_L("CSecObsNotify::StartNotifier: Pin2"));
+	        #endif
+            err = iNotifier.Connect();
+            if(err == KErrNone)
+            	iNotifier.StartNotifierAndGetResponse(iStatus, KSecurityNotifierUid, KPin2Required,iDummy);
+            break;
+            }
+        case ESecurityNotifierPuk2:
+            {
+            #if defined(_DEBUG)
+	        RDebug::Print(_L("CSecObsNotify::StartNotifier: Puk2"));
+	        #endif
+            err = iNotifier.Connect();
+            if(err == KErrNone)
+            	iNotifier.StartNotifierAndGetResponse(iStatus, KSecurityNotifierUid, KPuk2Required,iDummy);
+            break;
+            }
+        case ESecurityNotifierSecurityCode:
+            {
+            #if defined(_DEBUG)
+	        RDebug::Print(_L("CSecObsNotify::StartNotifier: Security Code"));
+	        #endif
+            #if defined(_DEBUG)
+	        RDebug::Print(_L("CSecObsNotify::StartNotifier ESecurityNotifierSecurityCode"));
+	        #endif
+            err = iNotifier.Connect();
+            if(err == KErrNone)
+            	iNotifier.StartNotifierAndGetResponse(iStatus, KSecurityNotifierUid, KPassPhraseRequired,iDummy);
+            #if defined(_DEBUG)
+	        RDebug::Print(_L("CSecObsNotify::StartNotifier SEC: StartNotifierAndGetResponse"));
+	        #endif
+            break;
+            }
+        case ESecuritySimLockRestrictionOn:
+            {
+            #if defined(_DEBUG)
+	        RDebug::Print(_L("CSecObsNotify::StartNotifier: Sim Lock"));
+	        #endif
+            err = iNotifier.Connect();
+            if(err == KErrNone)
+            	iNotifier.StartNotifierAndGetResponse(iStatus, KSecurityNotifierUid, KSimTerminated,iDummy);
+			break;
+            }
+        default:
+            iActiveNotifier = ESecurityNotifierNone;
+            return;
+        }
+    if (err != KErrNone)
+    {
+    	_LIT(panicCategory, "SecObsNotify PANIC");
+    	TInt reason(1);
+    	User::Panic(panicCategory, reason); 	
+    }
+    
+    iActiveNotifier = aNotifierToStart;
+    #if defined(_DEBUG)
+	RDebug::Print(_L("CSecObsNotify::StartNotifier SetActive"));
+	#endif
+    SetActive();
+    }
+
+//
+// ----------------------------------------------------------
+// CSecObsNotify::StartNotifier
+// Close open notifier
+// ----------------------------------------------------------
+//
+void CSecObsNotify::DoCancel()
+    {
+    CancelActiveNotifier();
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securityobserver/Src/SecPhoneObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,198 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observer for phone events. Used to re-active
+*               code query after emergency call
+*
+*
+*/
+
+
+#include    "SecPhoneObserver.h"
+
+#ifndef RD_STARTUP_CHANGE
+#include    <SysStartup.h>
+#endif //RD_STARTUP_CHANGE
+
+#include    <PSVariables.h>   // Property values
+#include    <TelephonyInternalPSKeys.h>
+#include    "SecObsNotify.h"
+#include    "SecurityObserver.h"
+#include    "SecurityObserver.hrh"
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CPhoneObserver::NewL()
+// Constructs a new entry with given values.
+// ----------------------------------------------------------
+//
+CPhoneObserver* CPhoneObserver::NewL(CSecObsNotify* aNotifierController,CSecurityObserver* aObserver)
+    {
+    CPhoneObserver* self = new (ELeave) CPhoneObserver(aNotifierController,aObserver);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+//
+// ----------------------------------------------------------
+// CPhoneObserver::CPhoneObserver()
+// Destructor
+// ----------------------------------------------------------
+//
+CPhoneObserver::~CPhoneObserver()
+    {
+    Cancel();
+    }
+//
+// ----------------------------------------------------------
+// CPhoneObserver::Start()
+// Starts listening KUidCurrentCall event
+// ----------------------------------------------------------
+//
+TInt CPhoneObserver::Start(TSecurityNotifier aNotifier)
+    {
+    if (IsActive())
+        return KErrInUse;
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECURITYOBSERVER) CPhoneObserver::Start"));
+    #endif
+    iNotifier = aNotifier;
+    iStatus = KRequestPending;
+    iProperty.Attach(KPSUidTelephonyCallHandling, KTelephonyCallState); 
+    iProperty.Subscribe(iStatus);
+    SetActive();
+    #if defined(_DEBUG)
+    RDebug::Print(_L("(SECURITYOBSERVER) CPhoneObserver::Start Observer active"));
+    #endif
+    return KErrNone;
+    }
+
+//
+// ----------------------------------------------------------
+// CPhoneObserver::Start()
+// Stops listening KUidCurrentCall event
+// ----------------------------------------------------------
+//
+void CPhoneObserver::Stop()
+    {
+    Cancel();
+    }
+//
+// ----------------------------------------------------------
+// CPhoneObserver::CPhoneObserver()
+// C++ constructor
+// ----------------------------------------------------------
+//
+CPhoneObserver::CPhoneObserver(CSecObsNotify* aNotifierController,CSecurityObserver* aObserver) :
+                                                                    CActive(0)
+                                                                    ,iNotifierController(aNotifierController)
+                                                                    ,iObserver(aObserver)
+    {
+    }
+//
+// ----------------------------------------------------------
+// CPhoneObserver::ConstructL()
+// Symbian OS default constructor
+// ----------------------------------------------------------
+//
+void CPhoneObserver::ConstructL()
+    {
+    // Add this active object to the scheduler.
+    CActiveScheduler::Add(this);
+    }
+//
+// ----------------------------------------------------------
+// CPhoneObserver::RunL()
+//
+// ----------------------------------------------------------
+//
+void CPhoneObserver::RunL()
+    {
+    TInt callState;
+    iProperty.Get(KPSUidTelephonyCallHandling, KTelephonyCallState, callState);
+    if (callState == EPSTelephonyCallStateNone)
+        {
+        
+        switch (iNotifier)
+            {
+#if defined(__PROTOCOL_WCDMA) || defined(__UPIN)
+#ifndef RD_STARTUP_CHANGE
+            case ESecurityNotifierUPin:
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(SECURITYOBSERVER) CPhoneObserver::RunL() UPIN"));
+                #endif
+                if (iObserver->IsUPinRequired() && !iObserver->IsUPukRequired())
+                    iNotifierController->StartNotifier(iNotifier);
+                break;
+#endif //RD_STARTUP_CHANGE
+            case ESecurityNotifierUPuk:
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(SECURITYOBSERVER) CPhoneObserver::RunL() UPUK"));
+                #endif
+                if (iObserver->IsUPukRequired())
+                    iNotifierController->StartNotifier(iNotifier);
+                break;
+#endif //__PROTOCOL_WCDMA
+
+#ifndef RD_STARTUP_CHANGE
+            case ESecurityNotifierPin1:
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(SECURITYOBSERVER) CPhoneObserver::RunL() PIN1"));
+                #endif
+                if (iObserver->IsPin1Required() && !iObserver->IsPuk1Required())
+                    iNotifierController->StartNotifier(iNotifier);
+                break;
+#endif //RD_STARTUP_CHANGE
+            case ESecurityNotifierPuk1:
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(SECURITYOBSERVER) CPhoneObserver::RunL() PUK1"));
+                #endif
+                if (iObserver->IsPuk1Required())
+                    iNotifierController->StartNotifier(iNotifier);
+                break;
+#ifndef RD_STARTUP_CHANGE
+            case ESecurityNotifierSecurityCode:
+                #if defined(_DEBUG)
+                RDebug::Print(_L("(SECURITYOBSERVER) CPhoneObserver::RunL() Sec Code"));
+                #endif
+                if (iObserver->IsPassPhraseRequired() && SysStartup::State() != ESWStateNormal)
+                    iNotifierController->StartNotifier(iNotifier);
+                break;
+#endif //RD_STARTUP_CHANGE
+            default:
+                break;
+            }
+        }
+    else
+        {
+        #if defined(_DEBUG)
+        RDebug::Print(_L("(SECURITYOBSERVER) CPhoneObserver::RunL() Call Active"));
+        #endif
+        // Continue observing system agent event
+        Start(iNotifier);
+        }
+    }
+//
+// ----------------------------------------------------------
+// CValueObserver::DoCancel()
+// Cancels event listening
+// ----------------------------------------------------------
+//
+void CPhoneObserver::DoCancel()
+    {
+    iProperty.Cancel();
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securityobserver/Src/SecSimLockObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,148 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observer for Sim Locking events.
+*               Shows "Sim restriction on" note if necessary.
+*
+*
+*/
+
+
+#include    "SecSimLockObserver.h"
+
+#ifndef RD_STARTUP_CHANGE
+#include    <PSVariables.h>   // Property values
+#else //RD_STARTUP_CHANGE
+#include    <StartupDomainPSKeys.h>
+#endif //RD_STARTUP_CHANGE 
+
+#include    "SecObsNotify.h"
+#include    "SecurityObserver.hrh"
+
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CSimLockObserver::NewL()
+// Constructs a new entry with given values.
+// ----------------------------------------------------------
+//
+CSimLockObserver* CSimLockObserver::NewL(CSecObsNotify* aNotifierController)
+    {
+    CSimLockObserver* self = new (ELeave) CSimLockObserver(aNotifierController);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+//
+// ----------------------------------------------------------
+// CSimLockObserver::CSimLockObserver()
+// Destructor
+// ----------------------------------------------------------
+//
+CSimLockObserver::~CSimLockObserver()
+    {
+    Cancel();
+    }
+//
+// ----------------------------------------------------------
+// CSimLockObserver::Start()
+// Starts listening event
+// ----------------------------------------------------------
+//
+TInt CSimLockObserver::Start()
+    {
+    if (IsActive())
+        return KErrInUse;
+    iStatus = KRequestPending;
+#ifndef RD_STARTUP_CHANGE
+    iProperty.Attach(KUidSystemCategory, KPSUidSimLockStatusValue); 
+#else //RD_STARTUP_CHANGE
+    iProperty.Attach(KPSUidStartup, KStartupSimLockStatus); 
+#endif //RD_STARTUP_CHANGE   
+    iProperty.Subscribe(iStatus);
+    SetActive();
+    return KErrNone;
+    }
+
+//
+// ----------------------------------------------------------
+// CSimLockObserver::Stopt()
+// Stops listening event
+// ----------------------------------------------------------
+//
+void CSimLockObserver::Stop()
+    {
+    Cancel();
+    }
+//
+// ----------------------------------------------------------
+// CCSimLockObserver::CSimLockObserver()
+// C++ constructor
+// ----------------------------------------------------------
+//
+CSimLockObserver::CSimLockObserver(CSecObsNotify* aNotifierController) :
+                                    CActive(0)
+                                    ,iNotifierController(aNotifierController)
+    {
+
+    }
+//
+// ----------------------------------------------------------
+// CSimLockObserver::ConstructL()
+// Symbian OS default constructor
+// ----------------------------------------------------------
+//
+void CSimLockObserver::ConstructL()
+    {
+    // Add this active object to the scheduler.
+    CActiveScheduler::Add(this);
+    }
+//
+// ----------------------------------------------------------
+// CPhoneObserver::RunL()
+//
+// ----------------------------------------------------------
+//
+void CSimLockObserver::RunL()
+    {
+    // Show "Sim restriction on" note
+    TInt simLockStatus;
+#ifndef RD_STARTUP_CHANGE
+    iProperty.Get(KUidSystemCategory, KPSUidSimLockStatusValue, simLockStatus);
+    if (simLockStatus == EPSSimLockRestrictionOn)
+#else //RD_STARTUP_CHANGE
+    iProperty.Get(KPSUidStartup, KStartupSimLockStatus, simLockStatus);
+    if (simLockStatus == ESimLockRestrictionOn)
+#endif //RD_STARTUP_CHANGE   
+        {
+        iNotifierController->StartNotifier(ESecuritySimLockRestrictionOn);
+        }
+    else
+        {
+        // Continue observing system agent event
+        Start();
+        }
+    }
+//
+// ----------------------------------------------------------
+// CSimLockObserver::DoCancel()
+// Cancels event listening
+// ----------------------------------------------------------
+//
+void CSimLockObserver::DoCancel()
+    {
+    iProperty.Cancel();
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/Securityobserver/Src/SecurityObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,513 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observer for ETel security events. Uses SecurityNotifier
+*               which calls appropriate dialog to be opened from SecUi.
+*
+*
+*/
+
+#include <w32std.h>
+#include <e32std.h>
+#include <coedef.h>
+
+#include <e32base.h>
+#include <etelmm.h>
+#include <eiksrv.h>
+#include    <e32property.h>
+#include    <PSVariables.h>   // Property values
+#include <CoreApplicationUIsPrivatePSKeys.h>
+#include <SecurityNotifier.h>
+#include <MmTsy_names.h>
+#include "SecurityObserver.h"
+#include "SecObsNotify.h"
+#include "SecurityObserver.hrh"
+
+
+//  LOCAL CONSTANTS AND MACROS
+	/*****************************************************
+	*	Series 60 Customer / TSY
+	*	Needs customer TSY implementation
+	*****************************************************/
+
+_LIT(SecObserver,"SecurityObserver");
+
+const TInt KTriesToConnectServer( 2 );
+const TInt KTimeBeforeRetryingServerConnection( 50000 );
+const TInt PhoneIndex( 0 );
+
+// LOCAL FUNCTION PROTOTYPES
+LOCAL_C void StartL();
+
+
+//===================== LOCAL FUNCTIONS ====================
+//
+//----------------------------------------------------------
+// E32Main
+//----------------------------------------------------------
+//
+GLDEF_C TInt E32Main()
+    {
+    __UHEAP_MARK;
+    CTrapCleanup* theCleanup = CTrapCleanup::New();
+    TRAPD(ret,StartL());
+    delete theCleanup;
+    __UHEAP_MARKEND;
+    if (ret)
+        {
+        // Panic here in order to enter SW
+        // reset mechanism.
+        User::Panic(SecObserver,ret);
+        }
+    return(KErrNone);
+    }
+
+#if defined(__WINS__)
+EXPORT_C TInt WinsMain(TAny *)
+    {
+    E32Main();
+    return KErrNone;
+    }
+#endif  // __WINS__
+
+//
+//----------------------------------------------------------
+// StartL() SecurityObserver starter.
+//----------------------------------------------------------
+//
+LOCAL_C void StartL()
+    {
+    __UHEAP_MARK;
+
+    #if defined(_DEBUG)
+    RDebug::Print(_L("Starting SecurityObsever"));
+    #endif
+
+
+#ifdef __WINS__
+
+	// do nothing...
+
+#else  // __WINS__
+	TInt simStatus;
+#ifndef RD_STARTUP_CHANGE
+    RProperty property;
+    for(;;)
+	{	
+        property.Get(KUidSystemCategory, KPSUidSimCStatusValue, simStatus);
+        if	(simStatus > EPSCSimInitWait)
+            break;
+        User::After(100000);
+	}
+#endif //RD_STARTUP_CHANGE
+#endif  // __WINS__
+	// rename thread to "SecurityObserver"
+    User::RenameThread(SecObserver);
+	
+	//Initialise the PubSub variable used to distinguish between code requests 
+	//originated from DOS and SecUi
+	_LIT_SECURITY_POLICY_PASS(KReadPolicy); 
+	_LIT_SECURITY_POLICY_C1(KWritePolicy, ECapabilityWriteDeviceData);   
+    TInt pSresult = RProperty::Define(KPSUidCoreApplicationUIs, KCoreAppUIsSecUIOriginatedQuery, RProperty::EInt, KReadPolicy, KWritePolicy);    
+ 	RProperty::Set(KPSUidCoreApplicationUIs, KCoreAppUIsSecUIOriginatedQuery, ECoreAppUIsETelAPIOriginated);
+    #if defined(_DEBUG)
+    RDebug::Print(_L("SecurityObsever PS Define result:´%d"), pSresult);
+	#endif
+	
+    // Install active scheduler
+	CActiveScheduler* theScheduler = new (ELeave) CActiveScheduler();
+	CleanupStack::PushL(theScheduler);
+	CActiveScheduler::Install(theScheduler);
+
+	// Start Observer 
+    CSecurityObserver * theObserver = CSecurityObserver::NewL();
+    CleanupStack::PushL(theObserver);
+
+	#if defined(_DEBUG)
+    RDebug::Print(_L("SecurityObsever has been started"));
+	#endif
+
+    // Run the scheduler
+    CActiveScheduler::Start();
+   
+	
+
+
+    CleanupStack::PopAndDestroy(2);//theScheduler and theObserver
+
+    __UHEAP_MARKEND;
+    }
+// ================= MEMBER FUNCTIONS =======================
+//
+// ----------------------------------------------------------
+// CSecurityObserver::NewL()
+// Constructs a new entry.
+// ----------------------------------------------------------
+//
+CSecurityObserver* CSecurityObserver::NewL()
+    {
+    CSecurityObserver* self = new (ELeave) CSecurityObserver();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+//
+// ----------------------------------------------------------
+// CSecurityObserver::ConstructL()
+// Symbian OS constructor
+// ----------------------------------------------------------
+//
+void CSecurityObserver::ConstructL()
+    {
+	/*****************************************************
+	*	Series 60 Customer / ETel
+	*	Series 60  ETel API
+	*****************************************************/
+	/*****************************************************
+	*	Series 60 Customer / TSY
+	*	Needs customer TSY implementation
+	*****************************************************/
+	TInt err( KErrGeneral );
+    TInt thisTry( 0 );
+    RTelServer::TPhoneInfo PhoneInfo;
+	//connect to ETel
+
+	thisTry = 0;
+
+	// connect to ETel server
+	while ( ( err = iServer.Connect() ) != KErrNone && ( thisTry++ ) <= KTriesToConnectServer )
+        {
+        User::After( KTimeBeforeRetryingServerConnection );
+        }
+    User::LeaveIfError( err );
+
+    // load TSY
+    err = iServer.LoadPhoneModule( KMmTsyModuleName );
+    if ( err != KErrAlreadyExists )
+        {
+        // may return also KErrAlreadyExists if some other
+        // is already loaded the tsy module. And that is
+        // not an error.
+        User::LeaveIfError( err );
+        }
+
+	// open phone
+	User::LeaveIfError(iServer.GetPhoneInfo(PhoneIndex, PhoneInfo));
+	User::LeaveIfError(iPhone.Open(iServer,PhoneInfo.iName));
+
+	//  Add this active object to the scheduler.
+	CActiveScheduler::Add(this);
+ 
+	//start notifier controller
+	iNotifierController = CSecObsNotify::NewL(this);
+
+	//Sim lock observer
+	iSimLockObserver = CSimLockObserver::NewL(iNotifierController);
+			
+	
+	#if defined(_DEBUG)
+    RDebug::Print(_L("SecurityObsever: Checking sim lock status"));
+	#endif
+
+	// check sim lock state at startup
+#ifndef RD_STARTUP_CHANGE
+    TInt ret2;
+    iProperty.Get(KUidSystemCategory, KPSUidSimLockStatusValue, ret2);
+
+    	if (ret2 == EPSSimLockRestrictionOn)
+		{
+		iNotifierController->StartNotifier(ESecuritySimLockRestrictionOn);
+		}
+	else
+		{
+		// start observing sim lock events
+		iSimLockObserver->Start();
+		}
+#else //RD_STARTUP_CHANGE
+        iSimLockObserver->Start();
+#endif //RD_STARTUP_CHANGE
+
+	#if defined(_DEBUG)
+    RDebug::Print(_L("SecurityObsever: Checking sim status"));
+	#endif
+
+#ifndef RD_STARTUP_CHANGE
+	// check sim state at startup
+	TInt simStatus;
+	iProperty.Get(KUidSystemCategory, KPSUidSimCStatusValue, simStatus);
+	
+	switch (simStatus)
+		{
+#if defined(__PROTOCOL_WCDMA) || defined(__UPIN)
+        case EPSCSimUPinVerifyRequired:
+            #if defined(_DEBUG)
+			RDebug::Print(_L("SecurityObsever: UPin required "));
+		    #endif
+	
+			iUPinRequired = ETrue;
+			iNotifierController->StartNotifier(ESecurityNotifierUPin);
+			// set the first notification request to ETel active
+			StartListen();
+			return;
+#endif //__PROTOCOL_WCDMA
+        case EPSCSimPinVerifyRequired:
+			#if defined(_DEBUG)
+			RDebug::Print(_L("SecurityObsever: Pin required "));
+			#endif
+	
+			iPin1Required = ETrue;
+			iNotifierController->StartNotifier(ESecurityNotifierPin1);
+			// set the first notification request to ETel active
+			StartListen();
+			return;
+        case EPSCSimBlocked:
+			#if defined(_DEBUG)
+			RDebug::Print(_L("SecurityObsever: Puk required "));
+			#endif
+
+			iPuk1Required = ETrue;
+			iNotifierController->StartNotifier(ESecurityNotifierPuk1);
+			// set the first notification request to ETel active
+			StartListen();
+			return;
+#if defined(__PROTOCOL_WCDMA) || defined(__UPIN)
+        case EPSCSimUPinBlocked:
+			#if defined(_DEBUG)
+			RDebug::Print(_L("SecurityObsever: UPuk required "));
+			#endif
+
+			iUPukRequired = ETrue;
+			iNotifierController->StartNotifier(ESecurityNotifierUPuk);
+			// set the first notification request to ETel active
+			StartListen();
+			return;
+#endif //__PROTOCOL_WCDMA
+		default:
+			break;
+		}
+
+#ifndef __WINS__
+	// check if security code is needed at startup
+    for (;;)
+		{		
+		iProperty.Get(KUidSystemCategory, KPSUidSecurityCodeStatusValue, ret2);
+		if (ret2 == EPSSecurityCodeRequired)
+			{
+			iPassPhraseRequired = ETrue;
+			iNotifierController->StartNotifier(ESecurityNotifierSecurityCode);	
+			break;	
+			}
+		if (ret2 == EPSSecurityCodeNotRequired)
+			{
+			break;
+			}
+		User::After(100000);
+		}
+#endif  // __WINS__
+
+
+	#if defined(_DEBUG)
+    RDebug::Print(_L("SecurityObsever: No Pin/Puk required. Start listening security events"));
+	#endif
+#endif //RD_STARTUP_CHANGE
+	// set the first notification request to ETel active
+	StartListen();
+	}
+	
+//
+// ----------------------------------------------------------
+// CSecurityObserver::CSecurityObserver()
+// C++ constructor
+// ----------------------------------------------------------
+// 
+
+CSecurityObserver::CSecurityObserver(): CActive(0),iPin1Required(EFalse)
+										,iPuk1Required(EFalse)
+										,iPassPhraseRequired(EFalse)
+    {
+    }
+
+//
+// ----------------------------------------------------------
+// CSecurityObserver::~CSecurityObserver()
+// C++ destructor. Stops observing ETel events and closes ETel connection.
+// ----------------------------------------------------------
+//
+CSecurityObserver::~CSecurityObserver()
+    {
+	/*****************************************************
+	*	Series 60 Customer / ETel
+	*	Series 60  ETel API
+	*****************************************************/
+	/*****************************************************
+	*	Series 60 Customer / TSY
+	*	Needs customer TSY implementation
+	*****************************************************/
+    //  Call DoCancel() if iActive
+    Cancel();
+
+    if (iServer.Handle())
+        {
+        iPhone.Close();           
+        iServer.UnloadPhoneModule(KMmTsyModuleName);
+        iServer.Close();
+        }
+
+	delete iSimLockObserver;
+	iSimLockObserver = NULL;
+	delete iNotifierController; 
+	iNotifierController = NULL;
+	}
+//
+// ----------------------------------------------------------
+// CSecurityObserver::StartListen()
+// Starts observing ETel security events
+// ----------------------------------------------------------
+//
+void CSecurityObserver::StartListen()
+    {
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECURITYOBSERVER)CSecurityObsever::StartListen()"));
+	#endif
+	if (!IsActive())
+		{    		
+		iPhone.NotifySecurityEvent(iStatus, iEvent);
+		SetActive();
+		}
+	}
+//
+// ----------------------------------------------------------
+// CSecurityObserver::RunL()
+// Handles security events received from ETel.
+// ----------------------------------------------------------
+// 
+void CSecurityObserver::RunL()
+    {
+	/*****************************************************
+	*	Series 60 Customer / ETel
+	*	Series 60  ETel API
+	*****************************************************/
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECURITYOBSERVER)CSecurityObsever::RunL()"));
+	#endif
+    if  (iStatus != KErrNone)
+        return;
+		
+	switch(iEvent)
+		{
+        #if defined(__PROTOCOL_WCDMA) || defined(__UPIN)
+        case RMobilePhone::EUniversalPinRequired:            
+            
+	   	   	#if defined(_DEBUG)
+	    	RDebug::Print(_L("SecurityObsever: Handling EUniversalPinRequired event"));
+			#endif
+		  
+			iUPinRequired = ETrue;
+		    iNotifierController->StartNotifier(ESecurityNotifierUPin);
+            break;
+       case RMobilePhone::EUniversalPukRequired:
+
+		    #if defined(_DEBUG)
+			RDebug::Print(_L("SecurityObsever: Handling EUniversalPukRequired event"));
+			#endif
+		  
+            iUPukRequired = ETrue;
+		    iNotifierController->StartNotifier(ESecurityNotifierUPuk);
+            break;
+       #endif //__PROTOCOL_WCDMA        
+       case RMobilePhone::EPin1Required:            
+            
+		   	#if defined(_DEBUG)
+			RDebug::Print(_L("SecurityObsever: Handling EPin1Required event"));
+			#endif
+		  
+			iPin1Required = ETrue;
+		    iNotifierController->StartNotifier(ESecurityNotifierPin1);
+            break;
+       case RMobilePhone::EPuk1Required:
+
+		    #if defined(_DEBUG)
+			RDebug::Print(_L("SecurityObsever: Handling EPuk1Required event"));
+			#endif
+		  
+            iPuk1Required = ETrue;
+		    iNotifierController->StartNotifier(ESecurityNotifierPuk1);
+            break;
+       case RMobilePhone::EPin2Required:
+
+			#if defined(_DEBUG)
+			RDebug::Print(_L("SecurityObsever: Handling EPin2Required event"));
+			#endif
+
+			iNotifierController->StartNotifier(ESecurityNotifierPin2);
+            break;
+       case RMobilePhone::EPuk2Required:
+			
+			#if defined(_DEBUG)
+			RDebug::Print(_L("SecurityObsever: Handling EPuk2Required event"));
+			#endif
+		   
+			iNotifierController->StartNotifier(ESecurityNotifierPuk2);
+            break;
+       case RMobilePhone::EPhonePasswordRequired:
+
+			#if defined(_DEBUG)
+			RDebug::Print(_L("SecurityObsever: Handling EPhonePasswordRequired event"));
+			#endif
+
+		    iPassPhraseRequired = ETrue;
+		    iNotifierController->StartNotifier(ESecurityNotifierSecurityCode);
+            break;
+       #if defined(__PROTOCOL_WCDMA) || defined(__UPIN)
+       case RMobilePhone::EUniversalPinVerified:
+			iUPinRequired = EFalse;
+		    break;
+	   case RMobilePhone::EUniversalPukVerified:
+		    iUPukRequired = EFalse;
+		    break;
+       #endif //__PROTOCOL_WCDMA
+	   case RMobilePhone::EPin1Verified:
+			iPin1Required = EFalse;
+		    break;
+	   case RMobilePhone::EPuk1Verified:
+		    iPuk1Required = EFalse;
+		    break;
+	   case RMobilePhone::EPhonePasswordVerified:
+		    iPassPhraseRequired = EFalse;
+		    break;
+	   default:
+			break;
+		}	
+	StartListen();
+	}
+//
+// ----------------------------------------------------------
+// CSecurityObserver::DoCancel()
+// Stops observing ETel events.
+// ----------------------------------------------------------
+// 
+void CSecurityObserver::DoCancel()
+    {
+	/*****************************************************
+	*	Series 60 Customer / ETel
+	*	Series 60  ETel API
+	*****************************************************/
+	#if defined(_DEBUG)
+    RDebug::Print(_L("(SECURITYOBSERVER)CSecurityObsever::DoCancel()"));
+	#endif
+	iPhone.CancelAsyncRequest(EMobilePhoneNotifySecurityEvent);
+	}
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+
+#include "../keylockpolicyapi/group/bld.inf"
+#include "../Autolock/group/bld.inf"
+#include "../SecUi/group/bld.inf"
+#include "../Securitynotifier/Group/bld.inf"
+#include "../Securityobserver/Group/bld.inf"
+#include "../lockclient/group/bld.inf"
+#include "../lockapp/group/bld.inf"
+
+PRJ_TESTMMPFILES
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/keylockpolicyapi/bwins/keylockpolicyapiu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,15 @@
+EXPORTS
+	??1CKeyLockPolicyApi@@UAE@XZ @ 1 NONAME ; CKeyLockPolicyApi::~CKeyLockPolicyApi(void)
+	?AddKeyCombination@CKeyLockPolicyApi@@QAEHKK@Z @ 2 NONAME ; int CKeyLockPolicyApi::AddKeyCombination(unsigned long, unsigned long)
+	?ClearKeycombinations@CKeyLockPolicyApi@@QAEHXZ @ 3 NONAME ; int CKeyLockPolicyApi::ClearKeycombinations(void)
+	?DisableKeyguardFeature@CKeyLockPolicyApi@@QAEHXZ @ 4 NONAME ; int CKeyLockPolicyApi::DisableKeyguardFeature(void)
+	?EnableKeyguardFeature@CKeyLockPolicyApi@@QAEHXZ @ 5 NONAME ; int CKeyLockPolicyApi::EnableKeyguardFeature(void)
+	?GetKeyCombination@CKeyLockPolicyApi@@QAEHHAAK0@Z @ 6 NONAME ; int CKeyLockPolicyApi::GetKeyCombination(int, unsigned long &, unsigned long &)
+	?GetLastPrimaryKey@CKeyLockPolicyApi@@QAEIXZ @ 7 NONAME ; unsigned int CKeyLockPolicyApi::GetLastPrimaryKey(void)
+	?HandleKeyEventL@CKeyLockPolicyApi@@QAEHABUTKeyEvent@@W4TEventCode@@@Z @ 8 NONAME ; int CKeyLockPolicyApi::HandleKeyEventL(struct TKeyEvent const &, enum TEventCode)
+	?HasConfiguration@CKeyLockPolicyApi@@QAEHXZ @ 9 NONAME ; int CKeyLockPolicyApi::HasConfiguration(void)
+	?KeyguardAllowed@CKeyLockPolicyApi@@SAHXZ @ 10 NONAME ; int CKeyLockPolicyApi::KeyguardAllowed(void)
+	?NewL@CKeyLockPolicyApi@@SAPAV1@W4TLockPolicyType@@@Z @ 11 NONAME ; class CKeyLockPolicyApi * CKeyLockPolicyApi::NewL(enum TLockPolicyType)
+	?PrimaryKeyPressed@CKeyLockPolicyApi@@QAEHXZ @ 12 NONAME ; int CKeyLockPolicyApi::PrimaryKeyPressed(void)
+	?RemoveKeyCombination@CKeyLockPolicyApi@@QAEHKK@Z @ 13 NONAME ; int CKeyLockPolicyApi::RemoveKeyCombination(unsigned long, unsigned long)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/keylockpolicyapi/eabi/keylockpolicyapiu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,21 @@
+EXPORTS
+	_ZN17CKeyLockPolicyApi15HandleKeyEventLERK9TKeyEvent10TEventCode @ 1 NONAME
+	_ZN17CKeyLockPolicyApi15KeyguardAllowedEv @ 2 NONAME
+	_ZN17CKeyLockPolicyApi16HasConfigurationEv @ 3 NONAME
+	_ZN17CKeyLockPolicyApi17AddKeyCombinationEmm @ 4 NONAME
+	_ZN17CKeyLockPolicyApi17GetKeyCombinationEiRmS0_ @ 5 NONAME
+	_ZN17CKeyLockPolicyApi17GetLastPrimaryKeyEv @ 6 NONAME
+	_ZN17CKeyLockPolicyApi17PrimaryKeyPressedEv @ 7 NONAME
+	_ZN17CKeyLockPolicyApi20ClearKeycombinationsEv @ 8 NONAME
+	_ZN17CKeyLockPolicyApi20RemoveKeyCombinationEmm @ 9 NONAME
+	_ZN17CKeyLockPolicyApi21EnableKeyguardFeatureEv @ 10 NONAME
+	_ZN17CKeyLockPolicyApi22DisableKeyguardFeatureEv @ 11 NONAME
+	_ZN17CKeyLockPolicyApi4NewLE15TLockPolicyType @ 12 NONAME
+	_ZN17CKeyLockPolicyApiD0Ev @ 13 NONAME
+	_ZN17CKeyLockPolicyApiD1Ev @ 14 NONAME
+	_ZN17CKeyLockPolicyApiD2Ev @ 15 NONAME
+	_ZTI17CKeyLockPolicyApi @ 16 NONAME ; #<TI>#
+	_ZTI21CKeyLockPolicyApiImpl @ 17 NONAME ; #<TI>#
+	_ZTV17CKeyLockPolicyApi @ 18 NONAME ; #<VT>#
+	_ZTV21CKeyLockPolicyApiImpl @ 19 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/keylockpolicyapi/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,28 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Keylock policy component offers a configuration support for keyguard
+ *
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+../rom/keylockpolicyapi.iby CORE_MW_LAYER_IBY_EXPORT_PATH(keylockpolicyapi.iby)
+
+PRJ_MMPFILES
+keylockpolicyapi.mmp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/keylockpolicyapi/group/keylockpolicyapi.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Keylock policy component offers a configuration support for keyguard
+ *
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          keylockpolicyapi.dll
+TARGETTYPE      DLL
+UID             0x1000008d 0x2000B1AA
+CAPABILITY      CAP_GENERAL_DLL
+
+VENDORID        0x70000001
+
+USERINCLUDE     ../inc
+
+// This is a SYSTEMINCLUDE macro containing the middleware layer specific include directories
+MW_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          keylockpolicyapi.cpp
+SOURCE          keylockpolicyapiimpl.cpp
+
+LIBRARY         euser.lib
+LIBRARY         efsrv.lib
+LIBRARY         centralrepository.lib
+LIBRARY         cenrepnotifhandler.lib
+
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/keylockpolicyapi/inc/gendebug.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,164 @@
+/*
+* Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  generic debug header file for project KeylockPolicyApi
+*
+*/
+
+
+#ifndef GENDEBUG_H
+#define GENDEBUG_H
+
+#include <e32svr.h>
+
+/** @file gendebug.h
+	@brief Common helper file for debugging.
+
+	The file contains methods for adding traces and hardcoded breakpoint.
+
+	@page page1 A documentation for general helper module for doing debugging and tracing.
+
+	@subsection subsec1 This subsection describes the usage of hardcoded breakpoints.
+
+	Hardcoded breakpoints are usefull for allowing the execution to stop in right places
+	without bringing the OS down like using general assertions would do. Hardcoded breakpoints
+	must be used together with debugger. The hardcoded breakpoints are used by inserting
+	macro _DBG_MUST_BREAK into source code.
+
+	@note This feature has not been implemented yet.
+
+	@subsection subsec2 This subsection describes the usage of trace utilities.
+
+	Tracing is the most important way of doing HW level debugging (after looking the source of course).
+	Most of times users don't have access to debuggers and doing debugging in the field can be greatly
+	improved if there are great variety of configurable traces available.
+
+	In order to use the macro in kernel space, ALWAYS_KERNEL must be defined in the MMP-file of the module.
+
+	To use static tracing the module using these utilities must have defined DEBUG_LEVEL (this is integer constant) in
+	MMP-file. This constant defines the bit-mask for the set of traces, which are put into code at the compile time. See
+	the macro definitions for details.
+
+	The other way to do tracing is to use run-time tracing, which requires from user to put class member variable iDbgLevel
+	into their class. This variable is used the same way as the static flag by using bit-mask to define enabled traces. See
+	the macro definitions for details.
+*/
+
+/// @todo Implement this after checking the ARM manual
+#if defined(_DEBUG)
+#define _DBG_MUST_BREAK
+#else
+#define _DBG_MUST_BREAK
+#endif
+
+/** Critical trace-level is used when system is about to down very soon because of critical error.
+	In most cases this trace level can be replaced by using assert with trace but in some cases
+	more information can be provided by using this debug level
+*/
+#define CRIT_LEVEL				0x00000001
+
+/** Serious trace-level is used when something bad and unexpected has happened but system might be
+	able to recover. In another words, software is not going to bring system forcefully down but
+	that's exactly what might happen due to an error.
+*/
+#define SERIOUS_LEVEL			0x00000002
+
+/* Error level is used to trace various errors, which are due to legal errors in normal operation. */
+#define ERROR_LEVEL				0x00000004
+
+/* Warning level is used to trace various warning, which are due to abnormal behaviour. */
+#define WARNING_LEVEL			0x00000008
+
+/* Info level is used to trace all general information. */
+#define INFO_LEVEL				0x00000010
+
+/* User definable trace level. This comment and definition should be replaced by the real usage. */
+#define USER_DEFINED_1			0x000010000
+/* User definable trace level. This comment and definition should be replaced by the real usage. */
+#define USER_DEFINED_2			0x000020000
+/* User definable trace level. This comment and definition should be replaced by the real usage. */
+#define USER_DEFINED_3			0x000040000
+/* User definable trace level. This comment and definition should be replaced by the real usage. */
+#define USER_DEFINED_4			0x000080000
+/* User definable trace level. This comment and definition should be replaced by the real usage. */
+#define USER_DEFINED_5			0x000100000
+/* User definable trace level. This comment and definition should be replaced by the real usage. */
+#define USER_DEFINED_6			0x000200000
+/* User definable trace level. This comment and definition should be replaced by the real usage. */
+#define USER_DEFINED_7			0x000400000
+/* User definable trace level. This comment and definition should be replaced by the real usage. */
+#define USER_DEFINED_8			0x000800000
+
+#define DEVICE_1_MASK			0x0000f000
+#define DEVICE_2_MASK			0x000f0000
+#define DEVICE_3_MASK			0x00f00000
+#define DEVICE_4_MASK			0x0f000000
+
+// Override debug-level definition for your own in MMP file
+#ifndef DEBUG_LEVEL
+#define DEBUG_LEVEL 0x000000FF
+#endif
+
+/// @todo find the right macro for debug builds
+
+#pragma warning(disable : 4127)    // conditional expression is constant
+
+#if defined(_DEBUG) || defined(TRACES)
+
+// Do not directly use this macro
+//lint -emacro({717}, UtilDump)   do while(0)
+//lint -emacro({774}, UtilDump)   conditional expression is constant
+#define UtilDump(PFUNCTION,SRCLEVEL,TRGLEVEL,STRING) \
+		do { \
+			TUint32 _level = (TRGLEVEL); \
+			if (SRCLEVEL & _level) { \
+			PFUNCTION STRING; \
+			} \
+		} while (0)
+
+
+#if defined __MOMAP15XX__ || defined ALWAYS_KERNEL
+
+/** Macro for static tracing.
+	The first parameters defines the trace level set where this trace belongs to
+	and the second parameter contains the trace string used in ordinary RDebug::Print
+	command. Example:
+	TraceDump(INFO_LEVEL,(_L("My %d trace",1)));
+	*/
+
+#define TraceDump(LEVEL,STRING) UtilDump(Kern::Printf,DEBUG_LEVEL,LEVEL,STRING)
+
+
+/** Macro for dynamic tracing.
+	The first parameters defines the trace level set where this trace belongs to
+	and the second parameter contains the trace string used in ordinary RDebug::Print
+	command. Example:
+	TraceDump(INFO_LEVEL,(_L("My %d trace",1)));
+	*/
+
+#define RTraceDump(LEVEL,STRING) UtilDump(Kern::Printf,iDbgLevel,LEVEL,STRING)
+#else
+#define TraceDump(LEVEL,STRING) UtilDump(RDebug::Print,DEBUG_LEVEL,LEVEL,STRING)
+#define RTraceDump(LEVEL,STRING) UtilDump(RDebug::Print,iDbgLevel,LEVEL,STRING)
+#endif // __MOMAP15XX__ || ALWAYS_KERNEL
+
+#else
+//lint -emacro({717}, TraceDump) do while(0)
+#define TraceDump(LEVEL,STRING) do {} while (0)
+//lint -emacro({717}, RTraceDump) do while(0)
+#define RTraceDump(LEVEL,STRING) do {} while (0)
+#endif // _DEBUG
+
+#endif // GENDEBUG_H
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/keylockpolicyapi/inc/keylockpolicyapiimpl.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,216 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Keylock policy implementation
+ *
+*/
+
+
+#ifndef ___CKEYLOCKPOLICYAPIIMPL__
+#define ___CKEYLOCKPOLICYAPIIMPL__
+
+#include <w32std.h>
+#include <e32base.h>
+#include <cenrepnotifyhandler.h>
+#include "keylockpolicyapi.h"
+
+/**
+ * Keylock policy component supports three policy types:
+ *
+ * EPolicyActivateKeyguard keys used for keyguard locking
+ * EPolicyDeactivateKeyguard keys used for keyguard unlocking
+ * EPolicyDevicelockQuery keys used for showing devicelock query
+ */
+
+/**
+ *  CKeyLockPolicyApi. Trough CKeyLockPolicyApi users can
+ *
+ *  @lib keylockpolicy.lib
+ *  @since 3.2
+ */
+class CKeyLockPolicyApiImpl : public CBase, public MCenRepNotifyHandlerCallback
+	{
+public:
+
+	/**
+	 * Use this to create keylock policy
+	 * @param TLockPolicyType aType the policy used
+	 */
+	static CKeyLockPolicyApiImpl* NewL( TLockPolicyType aType );
+
+	/**
+	 * Destructor.
+	 */
+	~CKeyLockPolicyApiImpl( );
+
+	/**
+	 * If no policy has been defined for the type it cannot be used.
+	 * @return ETrue if has succesfully loaded policy
+	 */
+	TBool HasConfiguration( );
+
+	/**
+	 * Activates support for keyguard feature so  the phone keys cannot
+	 * be locked with keyguard. Does not affect the devicelock.
+	 * @return standard Symbian error code
+	 */
+	TInt EnableKeyguardFeature( );
+
+	/**
+	 * Disables support for keyguard feature so the phone keys cannot
+	 * be locked with keyguard. Does not affect the devicelock.
+	 * @return standard Symbian error code
+	 */
+	TInt DisableKeyguardFeature( );
+
+	/**
+	 * Whether keyguard feature is currently enabled or disabled.
+	 * @return ETrue if keyguard can be locked.
+	 */
+	TBool static KeyguardAllowed( );
+
+	/**
+	 * Adds a key combination for the policy type defined in the construction.
+	 *
+	 * @param TUint scan code for primary key
+	 * @param TUint scan code for secondary key
+	 * @return standard Symbian error code
+	 */
+	TInt AddKeyCombination(TUint32 aPrimaryKey, TUint32 aSecondaryKey );
+
+	/**
+	 * Removes a key combination for the policy type defined in the construction.
+	 *
+	 * @param TUint scan code for primary key
+	 * @param TUint scan code for secondary key
+	 * @return standard Symbian error code
+	 */
+	TInt RemoveKeyCombination(TUint32 aPrimaryKey, TUint32 aSecondaryKey );
+
+	/**
+	 * Retrieve a key combination on the given index.
+	 *
+	 * @param TInt aIndex index on the list that stores key combinations
+	 * @param TUint key code for primary key
+	 * @param TUint key code for secondary key
+	 * @return standard Symbian error code
+	 */
+	TInt GetKeyCombination(TInt aIndex, TUint32 &aPrimaryKey, TUint32 &aSecondaryKey );
+
+	/**
+	 * Clears all the defined key combinations from the policy.
+	 *
+	 * @return standard Symbian error code
+	 */
+	TInt ClearKeycombinations( );
+
+	/**
+	 * Handles Key events, returns ETrue the key events match any of the
+	 * defined key combinations. Only uses scancodes with type EEventKeyDown.
+	 *
+	 * @param TKeyEvent aKeyEvent the actual key event
+	 * @param TEventCode aType the type of the received key event
+	 * @return ETrue if a match was found.
+	 */
+	TBool HandleKeyEventL(const TKeyEvent& aKeyEvent, const TEventCode aType );
+
+	/**
+	 * Returns true if primary button is pressed and note should be shown.
+	 * @return boolean true if primary key is pressed.
+	 */
+	TBool PrimaryKeyPressed( );
+
+	/**
+	 * Returns Primary key scan code that has been pressed last.
+	 * @return scan code value of the primary key if found, NULL if not
+	 */
+	TUint GetLastPrimaryKey( );
+
+private:
+
+	/**
+	 * C++ default constructor (private so cannot be derived).
+	 * @param TLockPolicyType aType the policy (TLockPolicyType) used
+	 */
+	CKeyLockPolicyApiImpl( TLockPolicyType aType );
+
+	/**
+	 * Second constructor initializes the policy
+	 */
+	void ConstructL( );
+
+	TInt SetKeyCombination(TUint32 aPrimaryKey, TUint32 aSecondaryKey, TInt aIndex );
+
+	TInt FindKeyCombinationIndex(TUint32 aPrimaryKey, TUint32 aSecondaryKey, TInt &aIndex );
+
+	TInt GetNewKeyCombinationIndex(TInt &aIndex );
+
+	/**
+	 * From @c MCenRepNotifyHandlerCallback. Changes in the observed
+	 * central repository keys are communicated trough this method.
+	 * @param TUint32 aId central repository key
+	 * @param TInt aNewValue the new value
+	 */
+	void HandleNotifyInt( TUint32 aId, TInt aNewValue );
+
+	/**
+	 * A call back to the keylock timer
+	 * param TAny aSelf a pointer to the parent class
+	 */
+	static TInt HandleKeyLockTimerTimeout(TAny* aSelf );
+
+private:
+
+	// handle to central repository
+	CRepository* iRep;
+
+	// defined configuration
+	RArray<TUint> iPrimaryKeys;
+	RArray<TUint> iSecondaryKeys;
+	RArray<TUint> iWaitingKeys;
+
+	// defined timeout
+	TUint iTimeout;
+
+	// first key pressed
+	TBool iPrimaryKeyDown;
+
+	// index of last primary key in the policy
+	TUint iLastPrimaryKeyIndex;
+
+	// key configuration mask
+	TUint iMask;
+
+	// current policy mode
+	TUint iMode;
+
+	// initialized policy type
+	TUint iType;
+
+	// if the keyguard is allowed or not
+	TUint iAllowed;
+
+	// if the keylock policy exists
+	TBool iInitialised;
+
+	// timer used between primary and secondary keys
+	CPeriodic* iKeyLockTimer;
+
+	// notifies the changes in keyguard block
+	CCenRepNotifyHandler* iAllowNotif;
+
+	// notifies the changes in mode
+	CCenRepNotifyHandler* iModeNotif;
+	};
+
+#endif // ___CKEYLOCKPOLICYAPIIMPL__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/keylockpolicyapi/rom/keylockpolicyapi.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,24 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+#ifndef __KEYLOCKPOLICYAPI_IBY__
+#define __KEYLOCKPOLICYAPI_IBY__
+
+file=ABI_DIR\BUILD_DIR\keylockpolicyapi.dll SHARED_LIB_DIR\keylockpolicyapi.dll
+
+#endif // __KEYLOCKPOLICYAPI_IBY__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/keylockpolicyapi/src/keylockpolicyapi.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,162 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Keylock policy component offers a configuration support for keyguard
+ *
+*/
+
+
+#include "keylockpolicyapi.h"
+#include "keylockpolicyapiimpl.h"
+
+// ---------------------------------------------------------------------------
+// Standard two-phased construction
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CKeyLockPolicyApi* CKeyLockPolicyApi::NewL( TLockPolicyType aType )
+	{
+	CKeyLockPolicyApi *self = new ( ELeave ) CKeyLockPolicyApi( );
+	CleanupStack::PushL( self );
+	self->ConstructL( aType );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+EXPORT_C CKeyLockPolicyApi::~CKeyLockPolicyApi( )
+	{
+	delete iKeylockpolicyImplementation;
+	iKeylockpolicyImplementation = NULL;
+	}
+
+// ---------------------------------------------------------------------------
+// Returns true if the policy initialization has been successful.
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TBool CKeyLockPolicyApi::HasConfiguration( )
+	{
+	return iKeylockpolicyImplementation->HasConfiguration( );
+	}
+
+// ---------------------------------------------------------------------------
+// Set the central repository key to allow keyguard
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TInt CKeyLockPolicyApi::EnableKeyguardFeature( )
+	{
+	return iKeylockpolicyImplementation->EnableKeyguardFeature( );
+	}
+
+// ---------------------------------------------------------------------------
+// Set the central repository key to disable keyguard
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TInt CKeyLockPolicyApi::DisableKeyguardFeature( )
+	{
+	return iKeylockpolicyImplementation->DisableKeyguardFeature( );
+	}
+
+// ---------------------------------------------------------------------------
+// Return true if keyguard feature is allowed
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TBool CKeyLockPolicyApi::KeyguardAllowed( )
+	{
+	return CKeyLockPolicyApiImpl::KeyguardAllowed( );
+	}
+
+// ---------------------------------------------------------------------------
+// Add new key combination to the selected policy type+mode combination
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TInt CKeyLockPolicyApi::AddKeyCombination( TUint32 aPrimaryKey, TUint32 aSecondaryKey )
+	{
+	return iKeylockpolicyImplementation->AddKeyCombination(aPrimaryKey, aSecondaryKey);
+	}
+
+// ---------------------------------------------------------------------------
+// Removes a key set defined in the selected policy type+mode combination
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TInt CKeyLockPolicyApi::RemoveKeyCombination( TUint32 aPrimaryKey, TUint32 aSecondaryKey )
+	{
+	return iKeylockpolicyImplementation->RemoveKeyCombination(aPrimaryKey, aSecondaryKey);
+	}
+
+// ---------------------------------------------------------------------------
+// Receives a key set from spesified index
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TInt CKeyLockPolicyApi::GetKeyCombination( TInt aIndex, TUint32 &aPrimaryKey, TUint32 &aSecondaryKey )
+	{
+	return iKeylockpolicyImplementation->GetKeyCombination(aIndex, aPrimaryKey, aSecondaryKey);
+	}
+
+// ---------------------------------------------------------------------------
+// Clear all key combinations from the selected policy type+mode combination
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TInt CKeyLockPolicyApi::ClearKeycombinations( )
+	{
+	return iKeylockpolicyImplementation->ClearKeycombinations( );
+	}
+
+// ---------------------------------------------------------------------------
+// Receives keys and checks whether they match any primary+secondary key combination
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TBool CKeyLockPolicyApi::HandleKeyEventL( const TKeyEvent& aKeyEvent, const TEventCode aType )
+	{
+	return iKeylockpolicyImplementation->HandleKeyEventL(aKeyEvent, aType);
+	}
+
+// ---------------------------------------------------------------------------
+// Returns true if the last received key matched any of the primary keys
+// stored in the policy
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TBool CKeyLockPolicyApi::PrimaryKeyPressed( )
+	{
+	return iKeylockpolicyImplementation->PrimaryKeyPressed( );
+	}
+
+// ---------------------------------------------------------------------------
+// Returns the last received key if it was a primary key
+// ---------------------------------------------------------------------------
+//
+EXPORT_C TUint CKeyLockPolicyApi::GetLastPrimaryKey( )
+	{
+	return iKeylockpolicyImplementation->GetLastPrimaryKey( );
+	}
+
+// ---------------------------------------------------------------------------
+// Default C++ constructor
+// ---------------------------------------------------------------------------
+//
+CKeyLockPolicyApi::CKeyLockPolicyApi( )
+	{
+	}
+
+// ---------------------------------------------------------------------------
+// Keylock policy construction
+// ---------------------------------------------------------------------------
+//
+void CKeyLockPolicyApi::ConstructL( TLockPolicyType aType )
+	{
+	iKeylockpolicyImplementation = CKeyLockPolicyApiImpl::NewL( aType );
+	}
+
+// EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/keylockpolicyapi/src/keylockpolicyapiimpl.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,696 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Keylock policy Implementation
+ *
+*/
+
+
+#include "keylockpolicyapiimpl.h"
+#include <LockDomainCRKeys.h>
+
+#include <centralrepository.h>
+#include "gendebug.h"
+
+const TUint32 KModeShift = 16;
+const TUint32 KTypeShift = 12;
+
+// ---------------------------------------------------------------------------
+// Standard two-phased construction
+// ---------------------------------------------------------------------------
+//
+CKeyLockPolicyApiImpl* CKeyLockPolicyApiImpl::NewL( TLockPolicyType aType )
+	{
+	TraceDump( INFO_LEVEL, _L( "CKeyLockPolicyApiImpl::NewL()" ) );
+	CKeyLockPolicyApiImpl *self = new ( ELeave ) CKeyLockPolicyApiImpl( aType );
+	CleanupStack::PushL( self );
+	self->ConstructL( );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CKeyLockPolicyApiImpl::~CKeyLockPolicyApiImpl( )
+	{
+	// notifier listeners are stopped
+	if ( iAllowNotif )
+		{
+		iAllowNotif->StopListening( );
+		}
+	if ( iModeNotif )
+		{
+		iModeNotif->StopListening( );
+		}
+
+	// keys are removed from the arrays
+	iPrimaryKeys.Reset( );
+	iSecondaryKeys.Reset( );
+	iWaitingKeys.Reset( );
+
+	// timer between key presses is cancelled
+	if ( iKeyLockTimer )
+		{
+		iKeyLockTimer->Cancel( );
+		}
+
+	// childs are destroyed
+	delete iKeyLockTimer;
+	delete iAllowNotif;
+	delete iModeNotif;
+	delete iRep;
+	}
+
+// ---------------------------------------------------------------------------
+// Returns true if the policy initialization has been successful.
+// ---------------------------------------------------------------------------
+//
+TBool CKeyLockPolicyApiImpl::HasConfiguration( )
+	{
+	return iInitialised;
+	}
+
+// ---------------------------------------------------------------------------
+// Set the central repository key to allow keyguard
+// ---------------------------------------------------------------------------
+//
+TInt CKeyLockPolicyApiImpl::EnableKeyguardFeature( )
+	{
+	TraceDump( INFO_LEVEL, _L( "ENTER: CKeyLockPolicyApiImpl::EnableKeyguardFeature()" ) );
+	TInt err( KErrUnknown);
+
+	if ( iRep )
+		{
+		err = iRep->Set( KLockKeyguardAllow, ETrue );
+		}
+
+	TraceDump( INFO_LEVEL, _L( "EXIT : CKeyLockPolicyApiImpl::EnableKeyguardFeature()" ) );
+	return err;
+	}
+
+// ---------------------------------------------------------------------------
+// Set the central repository key to disable keyguard
+// ---------------------------------------------------------------------------
+//
+TInt CKeyLockPolicyApiImpl::DisableKeyguardFeature( )
+	{
+	TraceDump( INFO_LEVEL, _L( "ENTER: CKeyLockPolicyApiImpl::DisableKeyguardFeature()" ) );
+	TInt err( KErrUnknown);
+
+	if ( iRep )
+		{
+		err = iRep->Set( KLockKeyguardAllow, EFalse );
+		}
+
+	TraceDump( INFO_LEVEL, _L( "EXIT : CKeyLockPolicyApiImpl::DisableKeyguardFeature()" ) );
+	return err;
+	}
+
+// ---------------------------------------------------------------------------
+// Return true if keyguard feature is allowed
+// ---------------------------------------------------------------------------
+//
+TBool CKeyLockPolicyApiImpl::KeyguardAllowed( )
+	{
+	TraceDump( INFO_LEVEL, _L( "ENTER: CKeyLockPolicyApiImpl::KeyguardAllowed()" ) );
+	TBool ret( ETrue);
+
+	TInt tmp( 0);
+	CRepository* rep=  NULL;
+	TRAPD( err, rep = CRepository::NewL( KCRUidLockConf ) )
+	if ( err || !rep )
+		{
+		ret = ETrue;
+		}
+	else
+		if ( rep && rep->Get( KLockKeyguardAllow, tmp )== KErrNone )
+			{
+			if ( tmp )
+				{
+				ret = ETrue;
+				}
+			else
+				{
+				ret = EFalse;
+				}
+			}
+	delete rep;
+
+	TraceDump( INFO_LEVEL, _L( "EXIT : CKeyLockPolicyApiImpl::KeyguardAllowed()" ) );
+	return ret;
+	}
+
+// ---------------------------------------------------------------------------
+// Add new key combination to the selected policy type+mode combination
+// ---------------------------------------------------------------------------
+//
+TInt CKeyLockPolicyApiImpl::AddKeyCombination( TUint32 aPrimaryKey, TUint32 aSecondaryKey )
+	{
+	TraceDump( INFO_LEVEL, _L( "ENTER: CKeyLockPolicyApiImpl::AddKeyCombination()" ) );
+	TInt err( KErrNone);
+
+	// mode zero means no policies are defined
+	// and the implementation needs the repository
+	if ( iMode && iRep )
+		{
+		TInt putindex( 0);
+		err = GetNewKeyCombinationIndex( putindex );
+		err = SetKeyCombination( aPrimaryKey, aSecondaryKey, putindex );
+		}
+	else
+		{
+		err = KErrUnknown;
+		}
+
+	TraceDump( INFO_LEVEL, _L( "EXIT : CKeyLockPolicyApiImpl::AddKeyCombination()" ) );
+	return err;
+	}
+
+// ---------------------------------------------------------------------------
+// Removes a key set defined in the selected policy type+mode combination
+// ---------------------------------------------------------------------------
+//
+TInt CKeyLockPolicyApiImpl::RemoveKeyCombination( TUint32 aPrimaryKey, TUint32 aSecondaryKey )
+	{
+	TraceDump( INFO_LEVEL, _L( "ENTER: CKeyLockPolicyApiImpl::RemoveKeyCombination()" ) );
+	TInt err( KErrNone);
+
+	// the implementation needs the repository
+	if ( iMode && iRep )
+		{
+		TInt removeindex( 0);
+		err = FindKeyCombinationIndex( aPrimaryKey, aSecondaryKey, removeindex );
+		if ( err == KErrNone )
+			{
+			TInt lastindex( 0);
+			TUint32 tmpprimary( 0), tmpsecondary( 0);
+
+			// find out the index of the last key set
+			err = GetNewKeyCombinationIndex( lastindex );
+			lastindex--;
+
+			// collect the keys of the last existing key set
+			err = GetKeyCombination( lastindex, tmpprimary, tmpsecondary );
+			if ( err == KErrNone )
+				{
+				err = SetKeyCombination( tmpprimary, tmpsecondary, removeindex );
+				if ( err == KErrNone )
+					{
+					// delete the already copied last key set
+					iRep->Delete( iMask | KLockFirstPrimaryKey + lastindex );
+					iRep->Delete( iMask | KLockFirstSecondaryKey + lastindex );
+					}
+				}
+			}
+		else
+			{
+			// if err != KErrNone either keys were not found or
+			// there are problems in the repository
+			}
+		}
+	else
+		{
+		err = KErrUnknown;
+		}
+
+	TraceDump( INFO_LEVEL, _L( "EXIT : CKeyLockPolicyApiImpl::RemoveKeyCombination()" ) );
+	return err;
+	}
+
+// ---------------------------------------------------------------------------
+// Finds the index of the given combination.
+// ---------------------------------------------------------------------------
+//
+TInt CKeyLockPolicyApiImpl::FindKeyCombinationIndex(TUint32 aPrimaryKey, TUint32 aSecondaryKey,
+		TInt &aIndex )
+	{
+	TraceDump( INFO_LEVEL, _L( "ENTER: CKeyLockPolicyApiImpl::FindKeyCombinationIndex()" ) );
+	TInt err( KErrNone);
+
+	if ( iMode && iRep )
+		{
+		TInt index( 0), tmpprimary( 0), tmpsecondary( 0);
+
+		// go trough the keys until you find the primary key and secondary key
+		while (err == KErrNone && tmpprimary != aPrimaryKey && tmpsecondary != aSecondaryKey )
+			{
+			err = iRep->Get( iMask | KLockFirstPrimaryKey + index, tmpprimary );
+			if ( err == KErrNone )
+				{
+				err = iRep->Get( iMask | KLockFirstSecondaryKey + index, tmpsecondary );
+				}
+			index++;
+			}
+
+		// if we found it for sure
+		if ( tmpprimary == aPrimaryKey && tmpsecondary == aSecondaryKey )
+			{
+			aIndex = index - 1;
+			err = KErrNone;
+			}
+		}
+	else
+		{
+		err = KErrUnknown;
+		}
+
+	TraceDump( INFO_LEVEL, _L( "EXIT : CKeyLockPolicyApiImpl::FindKeyCombinationIndex()" ) );
+	return err;
+	}
+
+// ---------------------------------------------------------------------------
+// Finds the index for a new combination (last one + 1).
+// ---------------------------------------------------------------------------
+//
+TInt CKeyLockPolicyApiImpl::GetNewKeyCombinationIndex(TInt &aIndex )
+	{
+	TraceDump( INFO_LEVEL, _L( "ENTER: CKeyLockPolicyApiImpl::GetNewKeyCombinationIndex()" ) );
+	TInt err( KErrNone);
+
+	if ( iMode && iRep )
+		{
+		TInt index( 0), tmpvar( 0);
+		while ( iRep->Get( iMask | KLockFirstPrimaryKey + index, tmpvar )== KErrNone )
+			{
+			index++;
+			};
+
+		// set the return value
+		aIndex = index;
+		}
+	else
+		{
+		err = KErrUnknown;
+		}
+
+	TraceDump( INFO_LEVEL, _L( "EXIT : CKeyLockPolicyApiImpl::GetNewKeyCombinationIndex()" ) );
+	return err;
+	}
+
+// ---------------------------------------------------------------------------
+// Sets a combination at the given index.
+// ---------------------------------------------------------------------------
+//
+TInt CKeyLockPolicyApiImpl::SetKeyCombination(TUint32 aPrimaryKey, TUint32 aSecondaryKey,
+		TInt aIndex )
+	{
+	TraceDump( INFO_LEVEL, _L( "ENTER: CKeyLockPolicyApiImpl::SetKeyCombination()" ) );
+	TInt err( KErrNone);
+
+	if ( iMode && iRep )
+		{
+		// set the last key set over the removed key combination
+		err = iRep->Set( iMask | KLockFirstPrimaryKey + aIndex, (TInt) aPrimaryKey );
+		if ( err == KErrNone )
+			{
+			err = iRep->Set( iMask | KLockFirstSecondaryKey + aIndex, (TInt) aSecondaryKey );
+			}
+		}
+	else
+		{
+		err = KErrUnknown;
+		}
+
+	TraceDump( INFO_LEVEL, _L( "EXIT : CKeyLockPolicyApiImpl::SetKeyCombination()" ) );
+	return err;
+	}
+
+// ---------------------------------------------------------------------------
+// Returns a key combination from spesified index
+// ---------------------------------------------------------------------------
+//
+TInt CKeyLockPolicyApiImpl::GetKeyCombination( TInt aIndex, TUint32 &aPrimaryKey,
+		TUint32 &aSecondaryKey )
+	{
+	TraceDump( INFO_LEVEL, _L( "ENTER: CKeyLockPolicyApiImpl::GetKeyCombination()" ) );
+	TInt err( KErrNone);
+
+	// the implementation needs the repository
+	if ( iMode && iRep )
+		{
+		TInt tmppri( 0), tmpsec( 0);
+
+		// collect the primary key from the index
+		err = iRep->Get( iMask | KLockFirstPrimaryKey + aIndex, tmppri );
+		if ( err == KErrNone )
+			{
+			// devicelock query needs only one key
+			if ( iType == EPolicyDevicelockQuery )
+				{
+				tmpsec = 0;
+				}
+			else
+				{
+				// collect the secondary key from the index
+				err = iRep->Get( iMask | ( KLockFirstSecondaryKey + aIndex ), tmpsec );
+				}
+
+			if ( err == KErrNone )
+				{
+				TraceDump( INFO_LEVEL, ( _L( "CKeyLockPolicyApiImpl::GetKeyCombination(): key combination: 0x%x, 0x%x" ), tmppri, tmpsec ) );
+				}
+			else
+				{
+				// if err != KErrNone either the secondary key was
+				// not found or there are problems in the repository
+				}
+
+			aPrimaryKey = TUint32( tmppri );
+			aSecondaryKey = TUint32( tmpsec );
+			}
+		else
+			{
+			// if err != KErrNone either the primary key was
+			// not found or there are problems in the repository
+			}
+		}
+	else
+		{
+		err = KErrUnknown;
+		}
+
+	TraceDump( INFO_LEVEL, _L( "EXIT : CKeyLockPolicyApiImpl::GetKeyCombination()" ) );
+	return err;
+	}
+
+// ---------------------------------------------------------------------------
+// Clear all key combinations from the selected policy type+mode combination
+// ---------------------------------------------------------------------------
+//
+TInt CKeyLockPolicyApiImpl::ClearKeycombinations( )
+	{
+	TraceDump( INFO_LEVEL, _L( "ENTER: CKeyLockPolicyApiImpl::ClearKeycombinations()" ) );
+	TInt err( KErrNone);
+
+	// the implementation needs the repository
+	if ( iMode && iRep )
+		{
+		TInt index( 0), tmpvar( 0);
+		// go trough the primary keys and delete them
+		while ( iRep->Get( iMask | KLockFirstPrimaryKey + index, tmpvar )== KErrNone )
+			{
+			err = iRep->Delete( iMask | KLockFirstPrimaryKey + index );
+			index++;
+			}
+
+		index = 0;
+		// go trough the secondary keys and delete them
+		while ( iRep->Get( iMask | KLockFirstSecondaryKey + index, tmpvar )== KErrNone )
+			{
+			err = iRep->Delete( iMask | KLockFirstSecondaryKey + index );
+			index++;
+			}
+		}
+	else
+		{
+		err = KErrUnknown;
+		}
+
+	TraceDump( INFO_LEVEL, _L( "EXIT : CKeyLockPolicyApiImpl::ClearKeycombinations()" ) );
+	return err;
+	}
+
+// ---------------------------------------------------------------------------
+// Receives keys and checks whether they match any primary+secondary key combination
+// ---------------------------------------------------------------------------
+//
+TBool CKeyLockPolicyApiImpl::HandleKeyEventL( const TKeyEvent& aKeyEvent, const TEventCode aType )
+	{
+	TBool matchFound( EFalse);
+	// keylock policy only handles key events of type EEventKeyDown
+	TEventCode type( EEventKeyDown);
+
+	if ( aType == type )
+		{
+		// configuration keys in general are not handled if the policy has not been not initialized
+		// configuration keys for enabling are not handled if keyguard feature is disabled
+		if ( iInitialised && ( iAllowed || iType != EPolicyActivateKeyguard ) )
+			{
+
+			// if primary key has already been pressed check if the key matches
+			// the subsequent secondary key stored in the waiting keys array
+			if ( iPrimaryKeyDown )
+				{
+				TraceDump( INFO_LEVEL, ( _L( "CKeyLockPolicyApiImpl::HandleKeyEventL() : iPrimaryKeyDown, Mode: 0x%x" ), iMode ) );
+				if ( iWaitingKeys.Find( aKeyEvent.iScanCode )!= KErrNotFound )
+					{
+					TraceDump( INFO_LEVEL, _L( "CKeyLockPolicyApiImpl::HandleKeyEventL() : Secondary key Pressed" ) );
+					matchFound = ETrue;
+					}
+				// cancel the timer after secondary key candidate has been pressed
+				iKeyLockTimer->Cancel( );
+				iWaitingKeys.Reset( );
+				}
+
+			// if the received key did not provide a match for secondary keys
+			// the primary key match is investigated
+			if ( !matchFound )
+				{
+				// check if the key matches with primary key any of the primary keys
+				TInt prikeyIndex( iPrimaryKeys.Find( aKeyEvent.iScanCode ));
+
+				if ( prikeyIndex != KErrNotFound )
+					{
+					TraceDump( INFO_LEVEL, _L( "CKeyLockPolicyApiImpl::HandleKeyEventL() : Primary key pressed" ) );
+
+					// store the index of matched primary key
+					iLastPrimaryKeyIndex = prikeyIndex;
+
+					// devicelock query only needs the primary key to match
+					if ( iType == EPolicyDevicelockQuery )
+						{
+						matchFound = ETrue;
+						}
+					else
+						{
+						// collect the possible secondary key candidates to the waiting keys array
+						iWaitingKeys.Reset( );
+						for (TInt x( 0); x < iPrimaryKeys.Count( ); x++ )
+							{
+							if ( iPrimaryKeys[x] == aKeyEvent.iScanCode && iSecondaryKeys.Count( )> x )
+								{
+								TraceDump( INFO_LEVEL, ( _L( "CKeyLockPolicyApiImpl::HandleKeyEventL() : Waiting for key: 0x%x" ), iSecondaryKeys[x] ) );
+								iWaitingKeys.Append( iSecondaryKeys[x] );
+								}
+							}
+
+						// start timer for primary key timeout
+						iKeyLockTimer->Start( iTimeout, iTimeout, TCallBack(
+								HandleKeyLockTimerTimeout, this ) );
+
+						// primary key has been pressed
+						iPrimaryKeyDown = ETrue;
+						}
+					}
+				else
+					{
+					// if no match was found cancel timer and start over
+					TraceDump( INFO_LEVEL, ( _L( "CKeyLockPolicyApiImpl::HandleKeyEventL() : Unknown key, not handled: 0x%x" ), aKeyEvent.iScanCode ) );
+
+					iPrimaryKeyDown = EFalse;
+					iKeyLockTimer->Cancel( );
+					iLastPrimaryKeyIndex = 0xffffffff;
+					}
+				}
+			}
+		else
+			{
+			TraceDump( INFO_LEVEL, ( _L( "CKeyLockPolicyApiImpl::HandleKeyEventL() : not initialized or not allowed" ) ) );
+			}
+		}
+	return matchFound;
+	}
+
+// ---------------------------------------------------------------------------
+// Returns true if the last received key matched any of the primary keys
+// stored in the policy
+// ---------------------------------------------------------------------------
+//
+TBool CKeyLockPolicyApiImpl::PrimaryKeyPressed( )
+	{
+	return iPrimaryKeyDown;
+	}
+
+// ---------------------------------------------------------------------------
+// Returns the last received key if it was a primary key
+// ---------------------------------------------------------------------------
+//
+TUint CKeyLockPolicyApiImpl::GetLastPrimaryKey( )
+	{
+	if ( iLastPrimaryKeyIndex < iPrimaryKeys.Count( ) )
+		{
+		return iPrimaryKeys[iLastPrimaryKeyIndex];
+		}
+	else
+		{
+		return 0;
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// MCenRepNotifyHandlerCallback. Changes in the observed central
+// repository keys are communicated trough this method.
+// ---------------------------------------------------------------------------
+//
+void CKeyLockPolicyApiImpl::HandleNotifyInt( TUint32 aId, TInt aNewValue )
+	{
+	switch ( aId )
+		{
+		case KLockKeyguardAllow:
+            {
+			// keyguard feature has been enabled/disabled
+			TraceDump( INFO_LEVEL, _L( "CKeyLockPolicyApiImpl::HandleNotifyInt() : KLockKeyguardAllow" ) );
+			aNewValue == 0 ? iAllowed = EFalse : iAllowed = ETrue;
+            }
+			break;
+			
+		case KLockPolicyMode:
+            {
+			// keylock policy mode has been changed
+			TraceDump( INFO_LEVEL, _L( "CKeyLockPolicyApiImpl::HandleNotifyInt() : KLockPolicyMode" ) );
+			// mask has changed
+			iMask = iType << KTypeShift|aNewValue << KModeShift;
+			// key configuration has changed
+			iPrimaryKeys.Reset( );
+			iSecondaryKeys.Reset( );
+			TUint32 x(0), k1(0), k2(0);
+			while ( GetKeyCombination( x, k1, k2 )== KErrNone )
+				{
+				iPrimaryKeys.Append( k1 );
+				iSecondaryKeys.Append( k2 );
+				x++;
+				}
+			// reset the memory
+			iPrimaryKeyDown = EFalse;
+			iLastPrimaryKeyIndex = 0xffffffff;
+            }
+			break;
+		
+		default:
+			break;
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// Default C++ constructor
+// ---------------------------------------------------------------------------
+//
+CKeyLockPolicyApiImpl::CKeyLockPolicyApiImpl( TLockPolicyType aType ) :
+	iMode( 1), iType( aType), iInitialised( EFalse)
+	{
+	iMask = aType << KTypeShift;
+	}
+
+// ---------------------------------------------------------------------------
+// Keylock policy construction
+// ---------------------------------------------------------------------------
+//
+void CKeyLockPolicyApiImpl::ConstructL( )
+	{
+	TraceDump( INFO_LEVEL, _L( "CKeyLockPolicyApiImpl::ConstructL() started" ) );
+	TInt err( KErrNone);
+
+	// Create a connection to the repository
+	TRAP( err, iRep = CRepository::NewL( KCRUidLockConf ) );
+	if ( err == KErrNone )
+		{
+		// get the lock policy mode
+		TInt mode( NULL);
+		err = iRep->Get( KLockPolicyMode, mode );
+		if ( err == KErrNone && mode )
+			{
+			iMode = mode;
+
+			// every key in the configuration should have the mask below
+			iMask |= iMode << KModeShift;
+
+			// get the timeout between key presses
+			TInt timeout( NULL);
+			err = iRep->Get( KLockTimerInterval, timeout );
+			if ( err == KErrNone && timeout > NULL )
+				{
+				iTimeout = timeout;
+
+				// collect supported key configuration
+				iPrimaryKeys.Reset( );
+				iSecondaryKeys.Reset( );
+				TUint32 x(0), k1(0), k2(0);
+				while ( GetKeyCombination( x, k1, k2 )== KErrNone )
+					{
+					iPrimaryKeys.Append( k1 );
+					iSecondaryKeys.Append( k2 );
+					x++;
+					}
+				if ( iPrimaryKeys.Count( )> 0 && iSecondaryKeys.Count( )> 0 )
+					{
+					TraceDump( INFO_LEVEL, _L( "CRepository::NewL(): Initialised" ) );
+					iInitialised = ETrue;
+					}
+
+				iPrimaryKeyDown = EFalse;
+				iLastPrimaryKeyIndex = 0xffffffff;
+
+				// whether keyguard feature is enabled or disabled
+				// by default we want keyguard to be enabled
+				TInt allow( 1 );
+				iRep->Get( KLockKeyguardAllow, allow );
+				iAllowed = allow;
+
+				// create childs
+				iKeyLockTimer = CPeriodic::NewL( CActive::EPriorityUserInput );
+				iAllowNotif = CCenRepNotifyHandler::NewL( *this, *iRep,
+						CCenRepNotifyHandler::EIntKey, KLockKeyguardAllow );
+				iAllowNotif->StartListeningL( );
+				iModeNotif = CCenRepNotifyHandler::NewL( *this, *iRep,
+						CCenRepNotifyHandler::EIntKey, KLockPolicyMode );
+				iModeNotif->StartListeningL( );
+				}
+			else
+				{
+				TraceDump( INFO_LEVEL, _L( "No time out defined: FAILED!" ) );
+				}
+			}
+		else
+			{
+			TraceDump( INFO_LEVEL, _L( "No mode has been set: FAILED!" ) );
+			}
+		}
+	else
+		{
+		TraceDump( INFO_LEVEL, _L( "CRepository::NewL( KCRUidLockConf ) ) FAILED!!" ) );
+		}
+
+	TraceDump( INFO_LEVEL, _L( "CKeyLockPolicyApiImpl::ConstructL() finished" ) );
+	}
+
+// ---------------------------------------------------------------------------
+// A call back to the keylock timer, the allowed time window for pressing
+// the secondary key to get a match has passed.
+// ---------------------------------------------------------------------------
+//
+TInt CKeyLockPolicyApiImpl::HandleKeyLockTimerTimeout( TAny* aSelf )
+	{
+	TraceDump( INFO_LEVEL, _L( "CKeyLockPolicyApiImpl::HandleKeyLockTimerTimeout()" ) );
+	CKeyLockPolicyApiImpl *self = reinterpret_cast< CKeyLockPolicyApiImpl* >( aSelf );
+
+	// reset the memory
+	self->iPrimaryKeyDown = EFalse;
+	self->iLastPrimaryKeyIndex = 0xffffffff;
+	self->iKeyLockTimer->Cancel( );
+
+	return KErrNone;
+	}
+
+// EOF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/cenrep/AutolockPrivateCRKeys.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Autolock local variation Central Repository keys.
+ *
+*/
+
+
+#ifndef AUTOLOCKPRIVATECRKEYS_H
+#define AUTOLOCKPRIVATECRKEYS_H
+
+// =============================================================================
+// Autolock Configuration API
+// =============================================================================
+const TUid KCRUidAutolockConf = { 0x102824AE };
+
+/**
+ * Bitmask used in configuring automatic keylock.
+ */
+const TUint32 KAutoKeyLockConf = 0x00000001;
+
+// =============================================================================
+// Automatic Keylock Local Variation constants (KAutoKeyLockConf)
+// =============================================================================
+
+/** 
+ * KAutolockFeatureIdFlipOpenDisabled is an on/off setting for 
+ * disabling automatic keyguard locking when flip is open. By default off.
+ * Possible values: 0 (locking enabled), 1 (locking diabled) <-- 
+ */
+const TInt KAutoKeylockFeatureIdFlipOpenDisabled= 0x01;  // 2^0
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/data/lockapp.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  LockApp resource file
+ *
+*/
+
+
+// RESOURCE IDENTIFIER
+NAME LOCK
+
+//  INCLUDES
+#include "lockapp.loc"
+#include <eikon.rh>
+#include <eikon.rsg>
+#include <avkon.rh>
+#include <avkon.rsg>
+
+//  RESOURCE DEFINITIONS
+
+// ---------------------------------------------------------
+//    Define the resource file signature
+//    This resource should be empty.
+// ---------------------------------------------------------
+//
+RESOURCE RSS_SIGNATURE { }
+
+// ---------------------------------------------------------
+//    Default Document Name
+// ---------------------------------------------------------
+//
+RESOURCE TBUF r_default_document_name { buf=""; }
+
+// ---------------------------------------------------------
+//    Define default menu and CBA key.
+// ---------------------------------------------------------
+//
+RESOURCE EIK_APP_INFO
+    {
+    }
+    
+// ---------------------------------------------------------
+//    Define title pane in devicelock mode.
+// ---------------------------------------------------------
+//
+RESOURCE TBUF r_title_pane_locked
+    {
+    buf = qtn_set_sec_title_locked;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/data/lockapp_reg.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,28 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  RSS for creating the registration file for LockApp.
+ *
+*/
+
+
+#include <appinfo.rh>
+
+UID2 KUidAppRegistrationResourceFile
+UID3 0x10283322
+
+RESOURCE APP_REGISTRATION_INFO
+    {
+    app_file = "!LockApp";
+    hidden = KAppIsHidden;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/group/ABLD.BAT	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,15 @@
+@ECHO OFF
+
+REM Bldmake-generated batch file - ABLD.BAT
+REM ** DO NOT EDIT **
+
+perl -S ABLD.PL "\sf\mw\securitysrv\securitydialogs\lockapp\group\\" %1 %2 %3 %4 %5 %6 %7 %8 %9
+if errorlevel==1 goto CheckPerl
+goto End
+
+:CheckPerl
+perl -v >NUL
+if errorlevel==1 echo Is Perl, version 5.003_07 or later, installed?
+goto End
+
+:End
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  LockApp build info
+ *
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+../rom/lockapp.iby CORE_MW_LAYER_IBY_EXPORT_PATH(lockapp.iby)
+../rom/lockappresources.iby LANGUAGE_MW_LAYER_IBY_EXPORT_PATH(lockappresources.iby)
+../loc/lockapp.loc MW_LAYER_LOC_EXPORT_PATH(lockapp.loc)
+../pubsub/SecurityUIsPrivatePSKeys.h |../../../inc/securityuisprivatepskeys.h
+../sis/lockapp_stub.sis /epoc32/data/z/system/install/lockapp_stub.sis
+
+PRJ_EXTENSIONS
+
+START EXTENSION s60/mifconv
+OPTION TARGETFILE lockapp.mif
+OPTION HEADERFILE lockapp.mbg
+OPTION SOURCES -c8,8 qgn_graf_phone_locked
+END
+
+PRJ_MMPFILES
+//gnumakefile lockapp_icons_dc.mk
+lockapp.mmp
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/group/lockapp.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,136 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Keyguard and Devicelock application server LockApp
+ *
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET          lockapp.exe
+TARGETTYPE      exe
+EPOCSTACKSIZE   0x5000
+
+VENDORID        VID_DEFAULT
+
+// ProtServ for being a server
+// WriteDeviceData Devicelock configuration needs it
+// SWEvent for capturing/generating key events
+// NetworkServices for remote lock for devicelock
+
+CAPABILITY      CAP_APPLICATION ProtServ NetworkControl
+
+UID             0x100039CE 0x10283322
+
+SECUREID 0x100059B5
+
+//LANG            SC
+
+SOURCEPATH      ../src
+
+// AppArc framework
+SOURCE          lockappapplication.cpp
+SOURCE          lockappappui.cpp
+SOURCE          lockappdocument.cpp
+
+// State control
+SOURCE          lockappobserverlist.cpp
+SOURCE          lockappstatecontrol.cpp
+SOURCE          lockappbasecontrol.cpp
+
+// State observers
+SOURCE          lockappidlecontrol.cpp
+SOURCE          lockappkeyguardcontrol.cpp
+SOURCE          lockappdevicelockcontrol.cpp
+SOURCE          lockappdevicelockcontainer.cpp
+SOURCE          lockappecsdetector.cpp
+SOURCE          lockappstatepublisher.cpp
+
+// CenRep and PS observers
+SOURCE          lockappcenrepobserver.cpp
+SOURCE          lockapppubsubobserver.cpp
+
+// Keyguard notes
+SOURCE          lockappsleepingnote.cpp
+SOURCE          lockapplockednote.cpp
+SOURCE          lockappecsnote.cpp
+
+// LockApp Server
+SOURCE          lockappserver.cpp
+SOURCE          lockappsession.cpp
+
+// LockApp Utils
+SOURCE          lockappkeycapturecontroller.cpp
+SOURCE          lockappkeypattern.cpp
+SOURCE          lockapputils.cpp
+SOURCE          lockappwait.cpp
+
+SOURCEPATH      ../group
+
+USERINCLUDE     ../inc ../loc ../cenrep
+
+APP_LAYER_SYSTEMINCLUDE
+SYSTEMINCLUDE   ../../../inc
+
+
+LIBRARY         euser.lib // USER services
+LIBRARY         apparc.lib  // application architecture
+LIBRARY         cone.lib   // Cone
+LIBRARY         bafl.lib // BaflUtils, reading localisation resources
+LIBRARY         ws32.lib // accessing window groups
+LIBRARY         apgrfx.lib // accessing window group names
+LIBRARY         eikcore.lib  // eikon environment
+LIBRARY         eikcoctl.lib // ceikstatuspane
+LIBRARY         eikdlg.lib // eikdialogs
+LIBRARY         gdi.lib  // drawing
+LIBRARY         fbscli.lib // required for CFbsBitmap
+LIBRARY         efsrv.lib // server library
+LIBRARY         etel.lib  // telephony
+LIBRARY         etelmm.lib // telephony
+LIBRARY         customapi.lib // custom api
+LIBRARY         centralrepository.lib // central repository
+LIBRARY         cenrepnotifhandler.lib // central repository notify handler
+LIBRARY         featmgr.lib // feature manager
+LIBRARY         cdlengine.lib // layout engine
+LIBRARY         avkon.lib  // Avkon
+LIBRARY         aknicon.lib // icon support
+LIBRARY         aknlayout2.lib // old layouts
+LIBRARY         aknlayout2scalable.lib // new layouts
+LIBRARY         aknskins.lib // skins
+LIBRARY         aknnotify.lib // aknsmallindicator
+LIBRARY         activitymanager.lib // Activity manager
+LIBRARY         secui.lib // Security UI
+
+LIBRARY         flogger.lib // File logging
+
+LIBRARY         keylockpolicyapi.lib // Keylock policy
+
+#ifdef __SAP_TERMINAL_CONTROL_FW
+LIBRARY         scpclient.lib
+#endif // __SAP_TERMINAL_CONTROL_FW
+
+START RESOURCE ../data/lockapp.rss
+HEADER
+TARGETPATH APP_RESOURCE_DIR
+//LANG SC
+LANGUAGE_IDS
+END
+
+START RESOURCE ../data/lockapp_reg.rss
+TARGETPATH	/private/10003a3f/apps
+END
+
+
+SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/group/lockapp_icons_dc.mk	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,72 @@
+#
+# Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description: 
+#
+
+ifeq (WINS,$(findstring WINS, $(PLATFORM)))
+  ZDIR=\epoc32\release\$(PLATFORM)\$(CFG)\Z
+else
+  ZDIR=\epoc32\data\z
+endif
+
+# ----------------------------------------------------------------------------
+# TODO: Configure these
+# ----------------------------------------------------------------------------
+
+TARGETDIR=$(ZDIR)\resource\apps
+ICONTARGETFILENAME=$(TARGETDIR)\lockapp.mif
+
+HEADERDIR=\epoc32\include
+HEADERFILENAME=$(HEADERDIR)\lockapp.mbg
+
+do_nothing :
+	@rem do_nothing
+
+MAKMAKE : do_nothing
+
+BLD : do_nothing
+
+CLEAN : do_nothing
+
+LIB : do_nothing
+
+CLEANLIB : do_nothing
+
+# ----------------------------------------------------------------------------
+# TODO: Configure these.
+#
+# NOTE 1: DO NOT DEFINE MASK FILE NAMES! They are included automatically by
+# MifConv if the mask detph is defined.
+#
+# NOTE 2: Usually, source paths should not be included in the bitmap
+# definitions. MifConv searches for the icons in all icon directories in a
+# predefined order, which is currently \s60\icons, \s60\bitmaps2, \s60\bitmaps.
+# The directory \s60\icons is included in the search only if the feature flag
+# __SCALABLE_ICONS is defined.
+# ----------------------------------------------------------------------------
+
+RESOURCE :
+	mifconv $(ICONTARGETFILENAME) /h$(HEADERFILENAME) \
+		/c8,8 qgn_graf_phone_locked \
+
+
+FREEZE : do_nothing
+
+SAVESPACE : do_nothing
+
+RELEASABLES :
+	@echo $(HEADERFILENAME)&& \
+	@echo $(ICONTARGETFILENAME)
+
+FINAL : do_nothing
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockapp.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,96 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  General application spesific enumeration values
+ *
+*/
+
+
+#ifndef __LOCKAPP_HRH__
+#define __LOCKAPP_HRH__
+
+/**
+ *  LockApp panic codes
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+enum TLockAppPanic
+	{
+	ELockPanicGeneral,
+	ELockPanicIllegalMessage,
+	ELockUnknownValue,
+	ELockIllegalState,
+	ELockPanicOutOfRange,
+	ELockPanicObserverAlreadyExists,
+	ELockPanicObserverNotFound,
+	};
+
+/**
+ *  Three possible states of LockApp: unlocked, keyguard active, devicelock active
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+enum TLockStatus
+	{
+	ELockNotActive = 0,
+	EKeyguardActive,
+	EDevicelockActive
+	};
+
+/**
+ *  Three possible reason for devicelock: manual, remote, timer
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+enum TDevicelockReason
+	{
+	EDevicelockManual = 1,
+	EDevicelockRemote,
+	EDevicelockTimer
+	};
+
+/**
+ *  Bit-field representing screen saver status
+ */
+const TUint KLockAppEnvScreenSaverOn = 1;
+
+/**
+ *  Bit-field representing phonecall status
+ */
+const TUint KLockAppEnvPhonecallOngoing = 2;
+
+/**
+ *  Bit-field representing idle status
+ */
+const TUint KLockAppEnvIdleOnForeground = 4;
+
+/**
+ *  Bit-field representing grip status
+ */
+const TUint KLockAppEnvGrip = 8;
+
+/**
+ *  Bit-field representing FPS status
+ */
+const TUint KLockAppEnvFPS = 0x10;
+
+#endif // __LOCKAPP_HRH__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappapplication.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Application class that also creates the appserver
+ *
+*/
+
+
+#ifndef __LOCKAPP_APPLICATION_H__
+#define __LOCKAPP_APPLICATION_H__
+
+// INCLUDES
+#include <aknapp.h>
+
+/**
+ *  CLockAppApplication class, is the application part of the Avkon 
+ *  framework.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class CLockAppApplication : public CAknApplication
+	{
+	public:
+
+		/**
+		 * @return LockApp application Uid.
+		 */
+		TUid AppDllUid( ) const;
+
+	protected:
+
+		CApaDocument* CreateDocumentL( );
+
+	};
+
+#endif // __LOCKAPP_APPLICATION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappappui.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,117 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  LockApp Application UI class
+ *
+*/
+
+
+#ifndef __LOCKAPP_APPUI_H__
+#define __LOCKAPP_APPUI_H__
+
+// INCLUDES
+#include <aknappui.h>
+#include "lockapp.hrh"
+
+// FORWARD DECLARATIONS
+class CLockAppAppView;
+class MLockAppStateControl;
+class CLockAppStateControl;
+class CLockAppServer;
+
+/**
+ *  CLockAppApplication class is the central user interface class in Avkon.
+ *  Owns the LockApp state control and the server component.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class CLockAppAppUi : public CAknAppUi
+	{
+	public:
+
+		/**
+		 * Second constructor that can fail (leave).
+		 */
+		void ConstructL( );
+
+		/**
+		 * C++ default constructor.
+		 */
+		CLockAppAppUi( );
+
+		/**
+		 * Destructor.
+		 */
+		~CLockAppAppUi( );
+
+	public:
+
+		/** 
+		 * @see CAknAppUi::HandleResourceChangeL(TInt aType) 
+		 */
+		void HandleResourceChangeL( TInt aType );
+
+	public:
+
+		/**
+		 * Access to main lock state control (used by the server).
+		 *
+		 * @return pointer to state control
+		 */
+		MLockAppStateControl* StateControl( );
+
+	protected:
+
+#ifdef __SAP_TERMINAL_CONTROL_FW
+
+		/**
+		 * From CEikAppUi, handles the TARM unlock message, other messages
+		 * are propagated to the superclass handler.
+		 * 
+		 * @param aClientHandleOfTargetWindowGroup The window group that the message was sent to.
+		 * @param aMessageUid The message UID.
+		 * @param aMessageParameters The message parameters
+		 * @return TMessageResponse EMessageHandled if the message was the TARM unlock message,
+		 * otherwise the return value from the superclass handler.
+		 */
+		MCoeMessageObserver::TMessageResponse HandleMessageL(
+				TUint32 aClientHandleOfTargetWindowGroup,
+				TUid aMessageUid,
+				const TDesC8& aMessageParameters );
+
+#endif // __SAP_TERMINAL_CONTROL_FW
+
+		/** 
+		 * @see CAknAppUi::HandleWsEventL(const TWsEvent& aEvent,CCoeControl* aDestination) 
+		 */
+		void HandleWsEventL( const TWsEvent& aEvent, CCoeControl* aDestination );
+
+	private:
+
+		/**
+		 * Main control of the LockApp.
+		 * Owned.
+		 */
+		CLockAppStateControl* iStateControl;
+
+		/**
+		 * Main server of the LockApp.
+		 * Own.
+		 */
+		CLockAppServer* iLockServer;
+	};
+
+#endif // __LOCKAPP_APPUI_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappbasecontrol.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,158 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Base control for logical UI components
+ *
+*/
+
+
+#ifndef __LOCKAPPBASECONTROL_H__
+#define __LOCKAPPBASECONTROL_H__
+
+// INCLUDES
+#include <coecntrl.h>
+#include "lockappstateobserver.h"
+#include "lockapplockednote.h"
+#include "lockappkeypattern.h"
+#include <keylockpolicyapi.h>
+
+// FORWARD DECLARATIONS
+class MLockAppStateControl;
+class CEikButtonGroupContainer;
+
+/**
+ *  CLockAppBaseControl class is the base control of lockapp state controls,
+ *  provides common interface and some protected utility methods.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class CLockAppBaseControl : public CCoeControl, public MLockAppStateObserver
+	{
+	public:
+
+		/**
+		 * Destructor.
+		 */
+		~CLockAppBaseControl( );
+
+		/**
+		 * From @c MLockAppStateObserver. Method handles the lock state changes.
+		 *
+		 * @param aStatus The new lock state
+		 */
+		virtual void HandleLockStatusChangedL( TLockStatus aStatus );
+
+		/**
+		 * Handles control activation.
+		 * 
+		 * @param aEnvMask environment bitmask
+		 */
+		virtual void HandleActivateEventL( TUint aEnvMask );
+
+		/**
+		 * Handles control deactivation.
+		 * 
+		 * @param aEnvMask environment bitmask
+		 */
+		virtual void HandleDeActivateEventL( TUint aEnvMask );
+
+		/**
+		 * Handle environment bitmask change.
+		 * 
+		 * @param aEnvMask environment bitmask
+		 * @param aEventMask event bitmask
+		 */
+		virtual void HandleEnvironmentChange( TUint aEnvMask, TUint aEventMask );
+
+	protected:
+
+		/**
+		 * Default Constructor.
+		 * 
+		 * @param aStateControl state control interface
+		 */
+		CLockAppBaseControl( MLockAppStateControl& aStateControl );
+
+		/**
+		 * 2nd phase constructor.
+		 */
+		void ConstructL( );
+
+		/**
+		 * Set up the control's keypattern matcher with the specified keylockpolicy.
+		 * 
+		 * @param aType keylock policy type (lock,unlock,devicelock) 
+		 */
+		TBool SetupKeyPatternsWithPolicyL( TLockPolicyType aType );
+
+		/**
+		 * Show a note. (cancels previous one if shown)
+		 * 
+		 * @param aNote    note to be shown
+		 * @param aTimeout timeout for the note
+		 * @param aTone    tone type
+		 */
+		void ShowNote( CLockAppLockedNote* aNote, const TInt aTimeout,
+				const CAknNoteDialog::TTone aTone );
+
+		/**
+		 * Dismisses a note.
+		 */
+		void CancelNote( );
+
+		/**
+		 * Capture/Release primary keys.
+		 */
+		void CapturePrimaryKeys( const TBool aCapture );
+
+		/**
+		 * Show/Hide softkey cba.
+		 */
+		void ShowCba( const TBool aShow );
+		
+		/**
+		 * Capture/Release pointer events.
+		 */
+		void SetPointerEventCapture( const TBool aEnable );
+
+		/**
+		 * Show/Hide keyguard indicator state.
+		 */
+		void SetKeyguardIndicatorStateL( const TBool aEnable );
+
+	protected:
+
+		// interface to parent state control
+		MLockAppStateControl& iStateControl;
+
+		// application's window group
+		RWindowGroup& iWindowGroup;
+
+		// control's currently shown note (not owned)
+		CLockAppLockedNote* iCurrentNote;
+
+		// control's Cba (owned)
+		CEikButtonGroupContainer* iCba;
+
+		// key pattern matching (owned)
+		CLockAppKeyPattern* iKeyPattern;
+
+		// if control is active
+		TBool iActive;
+
+	};
+
+#endif // __LOCKAPPBASECONTROL_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappcenrepobserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,136 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Central Repository key observer
+ *
+*/
+
+
+#ifndef __LOCKAPPCENREPOBSERVER_H__
+#define __LOCKAPPCENREPOBSERVER_H__
+
+// INCLUDES
+#include <e32std.h>
+#include <cenrepnotifyhandler.h>
+#include "lockappobserverinterface.h"
+
+/**
+ *  CLockAppCenRepObserver class is a Central Repository key observer
+ *  which can be used to monitor and set a CenRep value.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Tamas Koteles
+ */
+class CLockAppCenRepObserver : public CBase, public MCenRepNotifyHandlerCallback
+	{
+	public:
+
+		/**
+		 * Two-phased constructor.
+		 *
+		 * @param aObserver   pointer to observer
+		 * @param aCenRepUid  repository Uid
+		 * @param aKeyId      repository key Id
+		 * @return            the instance just created
+		 */
+		static CLockAppCenRepObserver* NewL( MLockAppObserverInterface* aObserver, TUid aCenRepUid,
+				TUint32 aKeyId );
+
+		/**
+		 * Destructor.
+		 */
+		~CLockAppCenRepObserver( );
+
+		/**
+		 * Get key value from CenRep.
+		 */
+		TInt GetValue( TInt& aValue );
+
+		/**
+		 * Get the value from a different CenRep key.
+		 */
+		TInt GetKeyValue( TUint32 aKey, TInt& aValue );
+
+		/**
+		 * Set key value to CenRep.
+		 */
+		TInt SetValue( TInt aValue );
+
+		/**
+		 * Set the value of a different CenRep key.
+		 */
+		TInt SetKeyValue( TUint32 aKey, TInt aValue );
+
+	public:
+
+		/**
+		 * From MCenRepNotifyHandlerCallback. Handles change event. Called by CenRep.
+		 *
+		 * @param aId the id of the changed setting
+		 * @param aNewValue the new value of the changed setting
+		 */
+		void HandleNotifyInt( TUint32 aId, TInt aNewValue );
+
+		void HandleNotifyError( TUint32 aId, TInt error, CCenRepNotifyHandler* aHandler );
+
+		void HandleNotifyGeneric( TUint32 aId );
+
+	protected:
+
+		/**
+		 * C++ default constructor.
+		 *
+		 * @param aObserver  pointer to observer
+		 * @param aCenRepUid central repository Uid
+		 * @param aKeyId     key Id
+		 */
+		CLockAppCenRepObserver( MLockAppObserverInterface* aObserver, TUid aCenRepUid,
+				TUint32 aKeyId );
+
+		/**
+		 * Symbian OS constructor.
+		 */
+		void ConstructL( );
+
+	protected:
+
+		/**
+		 * Observer's callback interface. Not owned.
+		 */
+		MLockAppObserverInterface* iObserver;
+
+		/**
+		 * CenRep value notifier.
+		 */
+		CCenRepNotifyHandler* iNotifyHandler;
+
+		/**
+		 * Access to central repository.
+		 */
+		CRepository* iRepository;
+
+		/**
+		 * Repository Uid.
+		 */
+		TUid iCenRepUid;
+
+		/**
+		 * Repository key Id.
+		 */
+		TUint32 iKeyId;
+
+	};
+
+#endif // __LOCKAPPCENREPOBSERVER_H__
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappdevicelockcontainer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,98 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Devicelock Background UI (window owning control)
+ *
+*/
+
+
+#ifndef LOCKAPPDEVICELOCKCONTAINER_H
+#define LOCKAPPDEVICELOCKCONTAINER_H
+
+// INCLUDES
+#include <coecntrl.h>
+#include <eikimage.h>
+#include <eiklabel.h>
+#include <AknSkinnableClock.h>
+
+// FORWARD DECLARATIONS
+class CAknsLayeredBackgroundControlContext;
+
+/**
+ *  CLockAppDevicelockContainer class contains UI components 
+ *  for the devicelock control.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ *  @see    CLockAppDevicelockControl
+ */
+class CLockAppDevicelockContainer : public CCoeControl, MCoeControlObserver
+	{
+	public:
+
+		/**
+		 * Two-phased constructor.
+		 */
+		static CLockAppDevicelockContainer* CLockAppDevicelockContainer::NewL( RWindowGroup& aWg );
+
+		/**
+		 * Destructor.
+		 */
+		~CLockAppDevicelockContainer( );
+
+	public:
+
+		/**
+		 * From CCoeControl, MopSupplyObject
+		 */
+		TTypeUid::Ptr MopSupplyObject( TTypeUid aId );
+
+	private:
+
+		/**
+		 * 2nd stage construction
+		 */
+		void ConstructL( RWindowGroup& aWg );
+
+		TRect GetMainPaneRect( );
+
+	private:
+
+		void SizeChanged( );
+
+		TInt CountComponentControls( ) const;
+
+		CCoeControl* ComponentControl( TInt aIndex ) const;
+
+		void Draw( const TRect& aRect ) const;
+
+		void HandleControlEventL( CCoeControl* aControl, TCoeEvent aEventType );
+
+	private:
+
+		CEikImage* iEikBitmap;
+		CFbsBitmap* iBitmap;
+		CFbsBitmap* iMask;
+
+		// Owned background context.
+		CAknsLayeredBackgroundControlContext* iBgContext;
+
+		// Clock for landscape.
+		CAknSkinnableClock* iClock;
+	};
+
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappdevicelockcontrol.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,238 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Devicelock UI
+ *
+*/
+
+
+#ifndef LOCKAPPDEVICELOCKCONTROL_H
+#define LOCKAPPDEVICELOCKCONTROL_H
+
+// INCLUDES
+#include "lockappbasecontrol.h"
+#include "lockappobserverinterface.h"
+#include <etelmm.h>
+#include <rmmcustomapi.h>
+#include <LockDomainCRKeys.h>
+
+// FORWARD DECLARATIONS
+class CLockAppDevicelockContainer;
+class CUserActivityManager;
+class CLockAppPubSubObserver;
+class CLockAppCenRepObserver;
+
+/**
+ *  CLockAppDevicelockControl represents the devicelock state in the state machine.
+ *  Window-owning compound control that provides visible user interface,
+ *  shows the lock bitmap by its child container, handles all events 
+ *  and asks for security code if "unlock" is pressed.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ *  @see    CLockAppBaseControl
+ *  @see    CLockAppDevicelockContainer
+ *  @see    MLockAppStateControl
+ *  @see    CUserActivityManager
+ *  @see    CLockAppPubSubObserver
+ *  @see    CLockAppCenRepObserver
+ */
+class CLockAppDevicelockControl : public CLockAppBaseControl, public MEikCommandObserver,
+		public MLockAppObserverInterface
+	{
+	public:
+
+		/**
+		 * Two-phased constructor.
+		 */
+		static CLockAppDevicelockControl* NewL( MLockAppStateControl& aStateControl,
+				RWindowGroup& aWg );
+
+		/**
+		 * Destructor.
+		 */
+		~CLockAppDevicelockControl( );
+		
+		/**
+		 * Finalize the construction by connecting to Phone side.
+		 */
+		void CLockAppDevicelockControl::ConnectToPhoneL( RWindowGroup& aWg );
+
+		/**
+		 * Is it allowed to activate control.
+		 */
+		TBool ActivationAllowedL( TDevicelockReason aReason );
+
+		/**
+		 * is it allowed to deactivate control.
+		 */
+		TBool DeActivationAllowedL( );
+
+		virtual void HandleActivateEventL( TUint aEnvMask );
+
+		virtual void HandleDeActivateEventL( TUint aEnvMask );
+
+		virtual void HandleEnvironmentChange( TUint aEnvMask, TUint aEventMask );
+
+		/**
+		 * Set the reason for devicelock.
+		 */
+		void SetLockingReason( TDevicelockReason aReason );
+
+	private:
+
+		/**
+		 * Constructor for performing 1st stage construction
+		 */
+		CLockAppDevicelockControl( MLockAppStateControl& aStateControl );
+
+		/**
+		 * 2nd stage construction
+		 */
+		void ConstructL( RWindowGroup& aWg );
+
+		void DefinePubSubKeysL( );
+
+		void HandleUnlockCommandL( );
+
+	public:
+
+		/**
+		 * Handle Central Repository observer callback.
+		 */
+		void HandleCenRepNotify( TUid aCenRepUid, TUint32 aKeyId, TInt aValue );
+
+		/**
+		 * Handle Publish & Subscribe observer callback.
+		 */
+		void HandlePubSubNotify( TUid aPubSubUid, TUint aKeyId, TInt aValue );
+
+	public:
+
+		void HandleResourceChange( TInt aType );
+
+		TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+	private:
+
+		TInt CountComponentControls( ) const;
+
+		CCoeControl* ComponentControl( TInt aIndex ) const;
+
+	private:
+
+		/*
+		 * Checks whether we are booting from a Hidden Reset
+		 */
+		TBool IsHiddenReset( );
+
+		/*
+		 * Checks whether the pin is blocked.
+		 */
+		TBool IsPinBlocked( );
+
+		/*
+		 * Checks whether TARM admin flag is set (optionally unsets it).
+		 */
+		TBool TarmAdminFlag( TBool unSetFlag );
+
+		TBool ETelActivationAllowed( );
+
+		// Get autolock timeout (in seconds)
+		TInt GetAutoLockTimeout( );
+
+		// Starts monitoring user activity
+		void StartActivityMonitoringL( );
+
+		// Gets new autolock period and starts monitoring user activity
+		void ResetInactivityTimeout( );
+
+		// Stop monitoring user activity.
+		void StopActivityMonitoring( );
+
+		// Handles Active event. Called by ActivityManager
+		static TInt HandleActiveEventL( TAny* aPtr );
+
+		// Handles Inactive event. Called by ActivityManager
+		static TInt HandleInactiveEventL( TAny* aPtr );
+
+		// Set custom status pane visible/invisible
+		void ShowStatusPane( const TBool aVisible );
+
+	private:
+
+		/**
+		 * From @c MEikCommandObserver. Dialogs and CBA send
+		 * UI commands to parent using method ProcessCommandL.
+		 *
+		 * @param aCommandId Command to be handled
+		 */
+		void ProcessCommandL( TInt aCommandId );
+
+	private:
+
+		/*****************************************************
+		 *    S60 Customer / ETel
+		 *    S60 ETel API
+		 *****************************************************/
+
+		RTelServer iTelServer;
+		int iTelServerInitialized;
+		RMobilePhone iPhone;
+		int iPhoneInitialized;
+		RMmCustomAPI iCustomPhone;
+		int iCustomPhoneInitialized;
+
+		/**
+		 * Devicelock auto-locking timeout observer 
+		 * (value in minutes)
+		 */
+		CLockAppCenRepObserver* iCRAutoLockTime;
+
+		/**
+		 * Devicelock status publisher.
+		 * (Permamanent setting: On/Off)
+		 */
+		CLockAppCenRepObserver* iCRAutoLockStatus;
+
+		/**
+		 * Autolock state PubSub publisher.
+		 * (Runtime setting)
+		 */
+		CLockAppPubSubObserver* iPSAutolockState; 
+
+		/**
+		 * User activity manager/observer
+		 */
+		CUserActivityManager* iActivityManager;
+
+		/**
+		 * Background image container control
+		 */
+		CLockAppDevicelockContainer* iContainer;
+
+		/**
+		 * Feature manager value for CDMA protocol
+		 */
+		TBool iFeatureProtocolCdma;
+
+		/**
+		 * Is security code query shown
+		 */
+		TBool iShowingSecCodeQuery;
+
+	};
+
+#endif // LOCKAPPDEVICELOCKCONTROL_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappdocument.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,78 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  LockApp application document class
+ *
+*/
+
+
+#ifndef __LOCKAPP_DOCUMENT_H__
+#define __LOCKAPP_DOCUMENT_H__
+
+// INCLUDES
+#include <AknDoc.h>
+
+// FORWARD DECLARATIONS
+class CLockAppAppUi;
+class CEikApplication;
+
+/**
+ *  CLockAppDocument class is derived from CAknDocument,
+ *  based on standard Avkon document template.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class CLockAppDocument : public CAknDocument
+	{
+	public:
+
+		/**
+		 * Two-phased constructor.
+		 *
+		 * @param aApp application class
+		 */
+		static CLockAppDocument* NewL( CEikApplication& aApp );
+		static CLockAppDocument* NewLC( CEikApplication& aApp );
+
+		/**
+		 * Destructor
+		 */
+		~CLockAppDocument( );
+
+	public:
+
+		/*
+		 * From @c CAknDocument. Creates AppUi.
+		 *
+		 * @return generic AppUI object
+		 */
+		CEikAppUi* CreateAppUiL( );
+
+	private:
+
+		/**
+		 * Second constructor that can fail (leave).
+		 */
+		void ConstructL( );
+
+		/**
+		 * C++ default constructor.
+		 */
+		CLockAppDocument( CEikApplication& aApp );
+
+	};
+
+#endif // __LOCKAPP_DOCUMENT_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappecsdetector.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,119 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Provides emergency call support for keyguard/devicelock
+ *
+*/
+
+
+#ifndef __LOCKAPPSTATEDETECTOR_H__
+#define __LOCKAPPSTATEDETECTOR_H__
+
+// INCLUDES
+#include "lockappstateobserver.h"
+#include <AknEcs.h> // MAknEcsObserver and CAknEcsDetector
+
+// FORWARD DECLARATIONS
+class CLockAppEcsNote;
+
+/**
+ *  CLockAppEcsDetector class owns emergency note and emergency detector.
+ *  Taps directly to AppUi windowserver event source for receiving key events.
+ *  If user presses emergency numbers defined in SIM, emergency note is shown.
+ *  Only works when keyguard or devicelock is activated.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class CLockAppEcsDetector : public CBase, public MLockAppStateObserver, public MAknEcsObserver
+    {
+    public:
+
+        /**
+         * Two-phased constructor.
+         */
+        static CLockAppEcsDetector* NewL( );
+
+        /**
+         * Destructor
+         */
+        ~CLockAppEcsDetector( );
+
+    private:
+
+        /**
+         * C++ default constructor.
+         */
+        CLockAppEcsDetector( );
+
+        /**
+         * Second constructor that can fail (leave).
+         */
+        void ConstructL( );
+
+    public:
+
+        /**
+         * From @c CLockAppStateObserver. Method handles the lock state changes.
+         *
+         * @param aLockStatus The new lock state
+         */
+        virtual void HandleLockStatusChangedL( TLockStatus aLockStatus );
+
+    private:
+
+        /**
+         * From @c MAknEcsObserver. Handles changes in emergency call detector.
+         * @param aEcsDetector a pointer to ecsdetector component
+         * @param aState the new emergency detector state.
+         */
+        void HandleEcsEvent( CAknEcsDetector* aEcsDetector, CAknEcsDetector::TState aState );
+
+    public:
+
+        /**
+         * Emergency note is visible.
+         *
+         * @return true if emergency note is on the screen.
+         */
+        TBool EcsNoteOnScreen( ) const;
+
+        /**
+         * Internal Method only used for testing since emergency number
+         * detection does not work in emulator.
+         *
+         * @return KErrNone if there were no problems
+         */
+        TInt TestEcsNote( );
+
+    private:
+
+        /**
+         * Receives emergency number key events and handles emergency dialing.
+         * Own.
+         */
+        CAknEcsDetector* iEcsDetector;
+
+        /**
+         * Emergency note to be shown when user has dialed emergency number.
+         * Own.
+         */
+        CLockAppEcsNote* iEcsNote;
+
+    };
+
+#endif // __LOCKAPPSTATEDETECTOR_H__
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappecsnote.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,85 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Emergency number dialog
+ *
+*/
+
+
+#ifndef __LOCKAPPECSNOTE_H__
+#define __LOCKAPPECSNOTE_H__
+
+// INCLUDES
+#include <aknnotedialog.h>
+
+/**
+ *  CLockAppEcsNote class is derived from Avkon note implementation;
+ *  shows emergency numbers on a dialog once the user has dialed
+ *  the numbers.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class CLockAppEcsNote : public CAknNoteDialog
+    {
+    public:
+
+        /**
+         * C++ constructor.
+         */
+        CLockAppEcsNote( );
+
+        /**
+         * Destructor.
+         */
+        ~CLockAppEcsNote( );
+
+    public:
+
+        /**
+         * Constructs sleeping note
+         */
+        void ConstructSleepingNoteL( TInt aResourceId );
+
+        /**
+         * Shows sleeping note
+         */
+        TInt ShowNote( );
+
+        /**
+         * Hides sleeping note
+         */
+        void SleepNote( );
+
+        /**
+         * Consume key events
+         */
+        TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+        /**
+         * API to set the emergency number to be displayed
+         *
+         * aMatchedNumber    text to display (e.g. "112" )
+         */
+        void SetEmergencyNumber( const TDesC& aMatchedNumber );
+
+    public:
+
+        TBool iNoteOnScreen;
+
+    };
+
+#endif // __LOCKAPPECSNOTE_H__
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappidlecontrol.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,105 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Idle (unlocked) UI
+ *
+*/
+
+
+#ifndef LOCKAPPIDLECONTROL_H
+#define LOCKAPPIDLECONTROL_H
+
+// INCLUDES
+#include <eiknotapi.h>
+#include <eikbtgpc.h>
+#include <AknNotifyStd.h>
+#include <aknnotedialog.h>
+#include <AknNotifierControllerPlugin.h>
+#include <AknQueryDialog.h>   // phone query
+#include "lockappbasecontrol.h"
+
+/**
+ *  CLockAppIdleControl class represents the unlocked state in the locking state machine.
+ * 
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ *  @see    CLockAppBaseControl
+ *  @see    MLockAppStateControl
+ */
+class CLockAppIdleControl : public CLockAppBaseControl, public MEikCommandObserver
+    {
+    public:
+
+        /**
+         * Two-phased constructor.
+         */
+        static CLockAppIdleControl* NewL( MLockAppStateControl& aStateControl );
+
+        /**
+         * Destructor.
+         */
+        ~CLockAppIdleControl( );
+
+    private:
+
+        /**
+         * Constructor for performing 1st stage construction
+         */
+        CLockAppIdleControl( MLockAppStateControl& aStateControl );
+
+        /**
+         * EPOC default constructor for performing 2nd stage construction
+         */
+        void ConstructL( );
+
+    public:
+
+        void OfferKeyLock( );
+
+        void CancelOfferKeyLock( );
+
+        void HandleActivateEventL( TUint aEnvMask );
+
+        void HandleDeActivateEventL( TUint aEnvMask );
+
+    public:
+
+        void HandleResourceChange( TInt aType );
+
+        TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+    private:
+
+        TInt CountComponentControls( ) const;
+
+        CCoeControl* ComponentControl( TInt aIndex ) const;
+
+    private:
+        /**
+         * From @c MEikCommandObserver. Dialogs and CBA send
+         * UI commands to parent using method ProcessCommandL.
+         *
+         * @param aCommandId Command to be handled
+         */
+        void ProcessCommandL( TInt aCommandId );
+
+    private:
+
+        // "offer to lock keys" note
+        CLockAppLockedNote* iOfferLockNote;
+
+    };
+
+#endif // LOCKAPPIDLECONTROL_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappkeycapturecontroller.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,140 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Key capture controller
+ *
+*/
+
+
+#ifndef __LOCKAPPKEYCAPTURECONTROLLER_H__
+#define __LOCKAPPKEYCAPTURECONTROLLER_H__
+
+//  INCLUDES
+#include <e32base.h>
+#include <e32keys.h>
+
+// enumerated type for captured key events
+enum TPhoneKeyCaptureType
+    {
+    EKeyCaptureEvent,
+    EKeyCaptureUpAndDownEvents,
+    EKeyCaptureAllEvents
+    };
+
+// Key capture data structure
+class TPhoneKeyCapture
+    {
+    public:
+        TStdScanCode iKey; // primary identifier
+        TKeyCode iKeyCode;
+        TPhoneKeyCaptureType iType;
+        TInt32 iHandle;
+        TInt32 iHandleForUpAndDown;
+    };
+
+// FORWARD DECLARATIONS
+class RWindowGroup;
+
+/**
+ *  CLockAppKeyCaptureController class is a simple key capture utily that
+ *  provides a way to capture/release keys for the current window group.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class CLockAppKeyCaptureController : public CBase
+    {
+    public:
+
+        /**
+         * Initialize the utility
+         */
+        static CLockAppKeyCaptureController* InitL( RWindowGroup& aWindowGroup );
+
+        /**
+         * Destroy the utility
+         */
+        static void Destroy( );
+
+        /**
+         * Set key to be captured
+         */
+        static void CaptureKey( TUint32 aKey, TUint32 aKeyCode, TPhoneKeyCaptureType aType );
+
+        /**
+         * Set key to be released
+         */
+        static void ReleaseKey( TUint32 aKey );
+
+    private:
+
+        /**
+         * C++ default constructor.
+         */
+        CLockAppKeyCaptureController( RWindowGroup& aWindowGroup );
+
+        /**
+         * Destructor.
+         */
+        virtual ~CLockAppKeyCaptureController( );
+
+    private:
+
+        /**
+         * Set key to be captured
+         */
+        void StartCapturingKey( TUint32 aKey, TUint32 aKeyCode, TPhoneKeyCaptureType aType );
+
+        /**
+         * Set key not to be captured
+         */
+        void StopCapturingKey( TUint32 aKey );
+
+        /**
+         * May be used to ask whether a key has been set to be captured or not
+         * @param aKey is the iScanCode of the key
+         * @return ETrue if the key is currently captured via this mechanism
+         */
+        TBool IsKeyCaptured( TUint32 aKey ) const;
+
+        /**
+         * Set key not to be captured
+         * @param aKeyCapture is the key not to be captured
+         */
+        void StopKeyCapture( TPhoneKeyCapture aKeyCapture );
+
+    private:
+
+        /**
+         * Private instance of the utility
+         */
+        static CLockAppKeyCaptureController* instance;
+
+        /**
+         * Array of keycodes currently captured which includes the window
+         * server handles for the captured keys.
+         */
+        RArray<TPhoneKeyCapture> iCapturedKeys;
+
+        /**
+         * application's window group
+         */
+        RWindowGroup& iWindowGroup;
+
+    };
+
+#endif  // LOCKAPPKEYCAPTURECONTROLLER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappkeyguardcontrol.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,207 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Keyguard UI (window-owning compound control)
+ *
+*/
+
+
+#ifndef __LOCKAPPKEYGUARDCONTROL_H__
+#define __LOCKAPPKEYGUARDCONTROL_H__
+
+// INCLUDES
+#include "lockappbasecontrol.h"
+#include "lockappobserverinterface.h"
+#include <LockDomainCRKeys.h>
+
+// FORWARD DECLARATIONS
+class CLockAppPubSubObserver;
+class CLockAppCenRepObserver;
+class CUserActivityManager;
+
+/**
+ *  CLockAppKeyguardControl class represents the keyguard state in the state machine. 
+ *  Window-owning compound control that provides visible keyguard user interface. 
+ *  Owns all keyguard dialogs and commands received from the child controls like 
+ *  dialogs and cba.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ *  @see    CLockAppBaseControl
+ *  @see    MLockAppStateControl
+ *  @see    CUserActivityManager
+ *  @see    CLockAppPubSubObserver
+ *  @see    CLockAppCenRepObserver
+ */
+class CLockAppKeyguardControl : public CLockAppBaseControl, public MEikCommandObserver,
+        public MLockAppObserverInterface
+    {
+    public:
+
+        /**
+         * Two-phased constructor.
+         *
+         * @param aStateControl reference to the main state control
+         */
+        static CLockAppKeyguardControl* NewL( MLockAppStateControl& aStateControl );
+
+        /**
+         * Destructor.
+         */
+        ~CLockAppKeyguardControl( );
+
+        TBool ActivationAllowedL( );
+
+        TBool DeActivationAllowedL( );
+
+        virtual void HandleActivateEventL( TUint aEnvMask );
+
+        virtual void HandleDeActivateEventL( TUint aEnvMask );
+
+        virtual void HandleEnvironmentChange( TUint aEnvMask, TUint aEventMask );
+
+    private:
+
+        /**
+         * C++ default constructor.
+         *
+         * @param aStateControl reference to the main state control
+         */
+        CLockAppKeyguardControl( MLockAppStateControl& aStateControl );
+
+        /**
+         * Second constructor that can fail (leave).
+         */
+        void ConstructL( );
+
+    public:
+
+        void DisplayLockedNote( );
+
+        void DisplayKeysLockedNote( );
+
+        void DisplayKeysActiveNote( );
+
+    public:
+
+        void HandleResourceChange( TInt aType );
+
+        TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+    public:
+
+        /**
+         * Handle Central Repository observer callback.
+         */
+        void HandleCenRepNotify( TUid aCenRepUid, TUint32 aKeyId, TInt aValue );
+
+        /**
+         * Handle Publish & Subscribe observer callback.
+         */
+        void HandlePubSubNotify( TUid aPubSubUid, TUint aKeyId, TInt aValue );
+
+    private:
+
+        TInt CountComponentControls( ) const;
+
+        CCoeControl* ComponentControl( TInt aIndex ) const;
+
+    private:
+
+        /**
+         * UI commands to parent using method ProcessCommandL.
+         *
+         * @param aCommandId Command to be handled
+         */
+        void ProcessCommandL( TInt aCommandId );
+
+    private:
+
+        void DisplayConfirmationNote( );
+
+        // Is allowed to auto lock keys
+        TBool AutoActivationAllowedL( );
+
+        // Get auto keyguard timeout
+        TInt GetAutoKeyguardTimeout( );
+
+        // Starts monitoring user activity
+        void StartActivityMonitoringL( );
+
+        // Gets new autolock period and starts monitoring user activity
+        void ResetInactivityTimeout( );
+
+        // Stop monitoring user activity.
+        void StopActivityMonitoring( );
+
+        // Handles Active event. Called by ActivityManager
+        static TInt HandleActiveEventL( TAny* aPtr );
+
+        // Handles Inactive event. Called by ActivityManager
+        static TInt HandleInactiveEventL( TAny* aPtr );
+
+    private:
+
+        /**
+         * "Now press *" confirmation note.
+         */
+        CLockAppLockedNote* iConfirmationNote;
+
+        /**
+         * "Keys are locked. Press Unlock" note.
+         */
+        CLockAppLockedNote* iLockedNote;
+
+        /**
+         * "Keys locked" note
+         */
+        CLockAppLockedNote* iKeypadLockedNote;
+
+        /**
+         * "Keys activated" note
+         */
+        CLockAppLockedNote* iKeypadUnlockedNote;
+
+        /**
+         * CenRep observers
+         */
+        CLockAppCenRepObserver* iCRAutoKeyguardTime;
+        CLockAppCenRepObserver* iCRPersistentKeyguardStatus;
+
+        /**
+         * PubSub observers
+         */
+        CLockAppPubSubObserver* iPSStartupObserver;
+
+        /**
+         * User activity manager
+         */
+        CUserActivityManager* iActivityManager;
+
+        /**
+         * Hardware support for keyguard
+         */
+        TLockHardware iHardwareSupport;
+
+        /**
+         * Flags if we had already normal state
+         */
+        TBool iAlreadyNormalState;
+
+    };
+
+#endif // __LOCKAPPKEYGUARDCONTROL_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappkeypattern.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,183 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Key pattern matching component.
+ *
+*/
+
+
+#ifndef __LOCKAPPKEYPATTERN__
+#define __LOCKAPPKEYPATTERN__
+
+// INCLUDES
+#include <w32std.h>
+#include <e32base.h>
+
+enum TPatternState
+    {
+    EPatternNotInitialized = 1,
+    EPatternNotEnabled,
+    EPatternNoMatch,
+    EPatternPrimaryMatch,
+    EPatternSecondaryMatch,
+    };
+
+/**
+ *  CLockAppKeyPattern class implements a 2-key pattern matcher. 
+ *  Can be used for both iCodes and iScancodes, as it matches integer numbers. 
+ *  The caller's responsability is to make sense what is beeing matched. 
+ *  Multiple patterns can be defined.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Tamas Koteles
+ */
+class CLockAppKeyPattern : public CBase
+    {
+    public:
+
+        /**
+         * Two phased constructor.
+         */
+        static CLockAppKeyPattern* NewL( );
+
+        /**
+         * Destructor.
+         */
+        ~CLockAppKeyPattern( );
+
+        /**
+         * If no patterns have been defined it cannot be used.
+         * @return ETrue if has succesfully loaded policy
+         */
+        TBool HasPatterns( );
+
+        /**
+         * Gets the enabled state.
+         *
+         * @return true if the patterns are enabled, false othewise
+         */
+        TBool IsEnabled( );
+
+        /**
+         * Sets the enabled state.
+         */
+        void SetEnabled( TBool aEnabled );
+
+        /**
+         * Gets the primary key timeout.
+         *
+         * @return the timeout in miliseconds
+         */
+        TUint GetKeyTimeOut( );
+
+        /**
+         * Sets the primary key timeout.
+         *
+         */
+        void SetKeyTimeOut( TUint aTimeOut );
+
+        /**
+         * Adds a key combination.
+         *
+         * @param aPrimaryKey code for primary key
+         * @param aSecondaryKey code for secondary key
+         * @return standard Symbian error code
+         */
+        TInt AddPattern( TUint32 aPrimaryKey, TUint32 aSecondaryKey );
+
+        /**
+         * Gets a key combination.
+         *
+         * @param aIndex index of the key combination
+         * @param aPrimaryKey primary key code if found
+         * @param aSecondaryKey secondary key code if found
+         * @return standard Symbian error code
+         */
+        TInt GetPattern( TInt aIndex, TUint32& aPrimaryKey, TUint32& aSecondaryKey );
+
+        /**
+         * Clears all the defined key combinations.
+         *
+         * @return standard Symbian error code
+         */
+        TInt ClearPatterns( );
+
+        /**
+         * Handles Key events. Result of the event is returned in the pattern state.
+         *
+         * @param aKey the actual key event (code or scancode)
+         * @return TPatternState caused by the event.
+         */
+        TPatternState HandleKeyEvent( TUint32 aKey );
+
+    protected:
+
+        /**
+         * C++ default constructor (private so cannot be derived).
+         */
+        CLockAppKeyPattern( );
+
+        /**
+         * Second constructor initializes the policy
+         */
+        void ConstructL( );
+
+    private:
+
+        /**
+         * A primary key has been received, set primary-match state.
+         */
+        void HandlePrimaryKeyEvent( TUint32 aKey );
+
+        /**
+         * A secondary key has been received, set secondary-match state.
+         */
+        void HandleSecondaryKeyEvent( );
+
+        /**
+         * Any other key has been received, set no-match state.
+         */
+        void HandleOtherKeyEvent( );
+
+        /**
+         * A call back to the keylock timer
+         * param TAny aSelf a pointer to the parent class
+         */
+        static TInt HandleKeyTimerTimeout( TAny* aSelf );
+
+    private:
+
+        // defined configurations
+        RArray<TUint> iPrimaryKeys;
+        RArray<TUint> iSecondaryKeys;
+        RArray<TUint> iWaitingKeys;
+
+        // defined timeout
+        TUint iKeyTimeOut;
+
+        // first key pressed
+        TPatternState iState;
+
+        // if the keypatterns are enabled
+        TBool iEnabled;
+
+        // if the keylock policy exists
+        TBool iHasPatterns;
+
+        // timer used between primary and secondary keys
+        CPeriodic* iKeyTimer;
+
+    };
+
+#endif // __LOCKAPPKEYPATTERN__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockapplockednote.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,64 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Sleeping note with timeout and a reference flag that informs
+ *                the parent when the note is visible
+ *
+*/
+
+
+#include "lockappsleepingnote.h"
+
+#ifndef __LOCKAPPLOCKEDNOTE_H__
+#define __LOCKAPPLOCKEDNOTE_H__
+
+const TInt KNoteCmdFocusLost = 3100;
+
+/**
+ *  CLockAppLockedNote class is used as the basic dismissable note in Lockapp.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class CLockAppLockedNote : public CLockAppSleepingNote
+    {
+    public:
+
+        /**
+         * C++ default constructor.
+         *
+         * @param aCommandObserver pointer to parent implementing observer interface
+         */
+        CLockAppLockedNote( MEikCommandObserver* aCommandObserver = NULL );
+
+        /**
+         * Destructor.
+         */
+        ~CLockAppLockedNote( );
+
+        /**
+         * Locked note can be canceled.
+         */
+        void CancelNote( );
+
+        /**
+         * From @c CCoeControl. Used to inform parent that
+         * dialog is no longer in focus.
+         */
+        void FocusChanged( TDrawNow aDrawNow );
+
+    };
+
+#endif // __LOCKAPPLOCKEDNOTE_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappobserverinterface.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface for CenRep and PubSub observers
+ *
+*/
+
+
+#ifndef __LOCKAPPOBSERVERINTERFACE_H__
+#define __LOCKAPPOBSERVERINTERFACE_H__
+
+// INCLUDES
+#include "lockapp.hrh"
+
+/**
+ *  MLockAppObserverInterface class offers a CenRep/PubSub observer interface.
+ *  Observer classes should implement this interface to get callback notifications
+ *  on value changes.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Tamas Koteles
+ */
+class MLockAppObserverInterface
+	{
+	public:
+
+		/** 
+		 * Handle Central Repository observer callback.
+		 *
+		 * @param aCenRepUid  Central Repository category id
+		 * @param aKeyId      Central Repository key id
+		 * @param aValue      Central Repository key's new value
+		 */
+		virtual void HandleCenRepNotify( TUid aCenRepUid, TUint32 aKeyId, TInt aValue ) = 0;
+
+		/** 
+		 * Handle Publish & Subscribe observer callback.
+		 *
+		 * @param aPubSubUid  Publish & Subscribe category id
+		 * @param aKeyId      Publish & Subscribe key id
+		 * @param aValue      Publish & Subscribe key's new value
+		 */
+		virtual void HandlePubSubNotify( TUid aPubSubUid, TUint aKeyId, TInt aValue ) = 0;
+
+	};
+
+#endif // __LOCKAPPOBSERVERINTERFACE_H__
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappobserverlist.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Controls observers and publishes state changes
+ *
+*/
+
+
+#ifndef __LOCKAPPOBSERVERLIST_H__
+#define __LOCKAPPOBSERVERLIST_H__
+
+// INCLUDES
+#include <coecntrl.h>
+#include "lockapp.hrh"
+
+// FORWARD DECLARATIONS
+class MLockAppStateObserver;
+
+/**
+ *  CLockAppObserverList class publishes lock state changes to all implemented state 
+ *  observers. The list owns all childs and it is responsible for deleting them.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class CLockAppObserverList : public CCoeControl
+    {
+    public:
+
+        /**
+         * C++ default constructor.
+         */
+        CLockAppObserverList( );
+
+        /**
+         * Destructor.
+         */
+        virtual ~CLockAppObserverList( );
+
+    public:
+
+        /**
+         * Add new state observer.
+         * @param aObserver lock state observer
+         */
+        void AddObserverL( MLockAppStateObserver* aObserver );
+
+        /**
+         * Remove lock state observer.
+         * @param aObserver lock state observer
+         */
+        void RemoveObserver( MLockAppStateObserver* aObserver );
+
+    protected:
+
+        /**
+         * Has to be called by the derived class in the construction.
+         */
+        void BaseConstructL( );
+
+        /**
+         * Informs all observers about the status change.
+         *
+         * @param aStatusChange the new lock state.
+         */
+        void PostStatusChangeL( TLockStatus aStatusChange );
+
+        /**
+         * Class that derives from observer list will have first
+         * notification about the lock status chane.
+         *
+         * @param aLockStatus the new lock state.
+         */
+        virtual void HandleLockStatusChangedL( TLockStatus aLockStatus );
+
+    private:
+
+        /**
+         * Dynamic list storing observers. Both the list and observers are owned.
+         * Own.
+         */
+        RPointerArray<MLockAppStateObserver>* iObserverList;
+
+    };
+
+#endif // __LOCKAPPOBSERVERLIST_H__
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockapppubsubobserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,129 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Publish & Subscribe key observer
+ *
+*/
+
+
+#ifndef __LOCKAPPPUBSUBOBSERVER_H__
+#define __LOCKAPPPUBSUBOBSERVER_H__
+
+// INCLUDES
+#include <w32std.h>
+#include <e32svr.h>
+#include <e32property.h>
+#include "lockappobserverinterface.h"
+
+/**
+ *  CLockAppPubSubObserver class implements a Publish & Subscribe key observer.
+ *  It can be used to monitor and also to set a PubSub key.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Tamas Koteles
+ */
+class CLockAppPubSubObserver : public CActive
+	{
+	public:
+
+		/**
+		 * Two-phased constructor.
+		 *
+		 * @param aObserver   pointer to observer
+		 * @param aPubSubUid  publish & subscribe Uid
+		 * @param aKeyId      publish & subscribe key id
+		 * @return            the instance just created.
+		 */
+		static CLockAppPubSubObserver* NewL( MLockAppObserverInterface* aObserver, TUid aPubSubUid,
+				TUint32 aKeyId );
+
+		/**
+		 * Destructor.
+		 */
+		~CLockAppPubSubObserver( );
+
+		/**
+		 * Start obsering PubSub key
+		 */
+		TInt Start( );
+
+		/**
+		 * Stop observing PubSub key
+		 */
+		void Stop( );
+
+		/**
+		 * Get key value from P&S.
+		 */
+		TInt GetKeyValue( TInt& aValue );
+
+		/**
+		 * Set key value to P&S.
+		 */
+		TInt SetKeyValue( TInt aValue );
+
+	protected:
+
+		/**
+		 * C++ default constructor.
+		 *
+		 * @param aObserver observer
+		 * @param aPubSubUid publish & subscribe Uid
+		 * @param aKeyId key id
+		 */
+		CLockAppPubSubObserver( MLockAppObserverInterface* aObserver, TUid aPubSubUid,
+				TUint32 aKeyId );
+
+		/**
+		 * Symbian OS constructor.
+		 */
+		void ConstructL( );
+
+	private:
+
+		void RunL( );
+
+		void DoCancel( );
+
+	protected:
+
+		/**
+		 * Observer's callback interface. Not owned.
+		 */
+		MLockAppObserverInterface* iObserver;
+
+		/**
+		 * Access to Publish & Subscribe.
+		 */
+		RProperty iProperty;
+
+		/**
+		 * Publish & Subscribe Uid.
+		 */
+		TUid iPubSubUid;
+
+		/**
+		 * Publish & Subscribe key Id.
+		 */
+		TUint32 iKeyId;
+
+		/**
+		 * Publish & Subscribe key's value.
+		 */
+		TInt iValue;
+
+	};
+
+#endif // __LOCKAPPPUBSUBOBSERVER_H__
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,73 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Server implementation that responses to client API in
+ *                lockclient
+ *
+*/
+
+
+#ifndef __LOCKAPPSERVER_H__
+#define __LOCKAPPSERVER_H__
+
+// INCLUDES
+#include <apaserverapp.h>
+
+/**
+ *  CLockAppServer class implements the application server of LockApp.
+ *  The server is created with a fixed server name and offers only one service.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class CLockAppServer : public CApaAppServer
+	{
+	public:
+
+		/**
+		 * Two-phased constructor.
+		 */
+		static CLockAppServer* NewL( const TDesC& aFixedServerName );
+
+		/**
+		 * Offers support for multiple services, but only one is supported/used by LockApp Server.
+		 * 
+		 * @param aServiceType uid used to identify different services.
+		 */
+		CApaAppServiceBase* CreateServiceL( TUid aServiceType ) const;
+
+	private:
+
+		/**
+		 * C++ default constructor.
+		 */
+		CLockAppServer( );
+
+		/**
+		 * Establishes a new session between client and server.
+		 * 
+		 * @param aVersion for support of new server client-server API variations (not used).
+		 * @param aMessage message that started the session.
+		 */
+		CSession2* NewSessionL( const TVersion& aVersion, const RMessage2& aMessage ) const;
+
+	private:
+
+		// how many sessions are created to the server
+		TInt iSessionCount;
+
+	};
+
+#endif //__LOCKAPPSERVER_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappsession.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,126 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  LockApp server session requested by lockclient
+ *
+*/
+
+
+#ifndef __LOCKAPPSESSION_H__
+#define __LOCKAPPSESSION_H__
+
+// INCLUDES
+#include <apaserverapp.h>
+#include "lockapp.hrh"
+
+// FORWARD DECLARATIONS
+class MLockAppStateControl;
+
+/**
+ *  CLockAppSession class is the server side implementation of the Lockapp API. 
+ *  The session class offers keyguard and devicelock API for clients wanting to 
+ *  alter phone lock states.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class CLockAppSession : public CApaAppServiceBase
+	{
+	public:
+
+		/**
+		 * C++ default constructor.
+		 */
+		CLockAppSession( );
+
+	private:
+		/**
+		 * Destructor.
+		 */
+		~CLockAppSession( );
+
+		/**
+		 * From @c CApaAppServiceBase. Handles possible error in
+		 * service. Method is empty.
+		 * @param aMessage received message
+		 * @param aError an error id
+		 */
+		void ServiceError( const RMessage2& aMessage, TInt aError );
+
+		/**
+		 * From @c CApaAppServiceBase. Receives messages.
+		 * @param aMessage received message
+		 */
+		void ServiceL( const RMessage2& aMessage );
+
+	private:
+
+		/**
+		 * Ask state control to activate keyguard lock.
+		 *
+		 * @param aWithNote if "keys locked" note is shown
+		 * @return error code
+		 */
+		TInt DoEnableKeyguardL( TBool aWithNote );
+
+		/**
+		 * Ask state control to deacctivate keyguard lock.
+		 *
+		 * @param aWithNote if "keys active" note is shown.
+		 * @return error code
+		 */
+		TInt DoDisableKeyguardL( TBool aWithNote );
+
+		/**
+		 * Ask state control to activate devicelock.
+		 * @return error code
+		 */
+		TInt DoEnableDevicelockL( TDevicelockReason aReason );
+
+		/**
+		 * Ask state control to deactivate devicelock.
+		 * @return error code
+		 */
+		TInt DoDisableDevicelockL( );
+
+		/**
+		 * Ask state control to offer to enable keyguard.
+		 * by showing "offerkeylock" note.
+		 * @return error code
+		 */
+		TInt DoOfferKeyguardL( );
+
+		/**
+		 * Ask state control to inform user that keys are locked.
+		 * @return error code
+		 */
+		TInt DoShowKeysLockedNoteL( );
+
+	private:
+
+		/**
+		 * Access to lock state control
+		 * @return the main state control, from which lock states are changed
+		 */
+		MLockAppStateControl* StateControlL( );
+
+		/**
+		 * The main state control
+		 * Not owned.
+		 */
+		MLockAppStateControl* iStateControl;
+	};
+
+#endif //__LOCKAPPSESSION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappsleepingnote.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,87 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Sleeping note with timeout
+ *
+*/
+
+
+#include <aknnotedialog.h>
+
+#ifndef __LOCKAPPSLEEPINGNOTE_H__
+#define __LOCKAPPSLEEPINGNOTE_H__
+
+/**
+ *  CLockAppSleepingNote class implement notes that are not destroyed between use. 
+ *  Note is shown with timeout and internal changes are reported to parent 
+ *  trough command observer interface.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class CLockAppSleepingNote : public CAknNoteDialog
+	{
+	public:
+
+		/**
+		 * C++ default constructor.
+		 *
+		 * @param aCommandObserver pointer to parent
+		 *                         implementing observer interface
+		 */
+		CLockAppSleepingNote( MEikCommandObserver* aCommandObserver = NULL );
+
+		/**
+		 * Sleeping note is constructed from a resource
+		 */
+		void ConstructSleepingNoteL( TInt aResourceId );
+
+		/**
+		 * Destructor.
+		 */
+		~CLockAppSleepingNote( );
+
+		/**
+		 * Show sleeping note with given timeout.
+		 * @param aTimeout how long note will be displayed.
+		 * @param aTone tone to be played.
+		 */
+		TInt ShowNote( const TInt aTimeout, const TTone aTone );
+
+		/**
+		 * Always called when note is dismissed
+		 *
+		 * @param aCommand reason for exit.
+		 */
+		TBool OkToExitL( TInt aCommand );
+
+		/**
+		 * Handles key events (from CoeControl)
+		 */
+		TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+	protected:
+
+		void HandleResourceChange( TInt aType );
+
+		// pointer to keyguard UI
+		MEikCommandObserver* iCommandObserver;
+
+		// resource id is reserved for animation skin change
+		TInt iResourceId;
+
+	};
+
+#endif // __LOCKAPPSLEEPINGNOTE_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappstatecontrol.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,322 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Controls lock states (keyguard locked/unlocked, devicelock)
+ *
+*/
+
+
+#ifndef __LOCKAPPSTATECONTROL_H__
+#define __LOCKAPPSTATECONTROL_H__
+
+// INCLUDES
+#include "lockappobserverlist.h"
+#include "lockappstatecontrolinterface.h"
+#include "lockappobserverinterface.h"
+#include <lockappclientserver.h>
+
+// FORWARD DECLARATIONS
+class CLockAppBaseControl;
+class CLockAppIdleControl;
+class CLockAppKeyguardControl;
+class CLockAppDevicelockControl;
+class CLockAppEcsDetector;
+class CLockAppPubSubObserver;
+class CAknIncallBubble;
+
+/**
+ *  CLockAppStateControl class is the main locking state control class. 
+ *  Class is derived from CLockAppObserverList observer list class. 
+ *  Does not own visible user interface, but directs window server events like 
+ *  key events to window-owning child controls (keyguard ui, emergency support). 
+ *  All lock state changes should be handled through this class.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class CLockAppStateControl : public CLockAppObserverList, public MLockAppStateControl,
+		public MLockAppObserverInterface
+	{
+	public:
+
+		/**
+		 * Two-phased constructor.
+		 */
+		static CLockAppStateControl* NewL( );
+
+		/**
+		 * Destructor.
+		 */
+		~CLockAppStateControl( );
+
+	private:
+
+		/**
+		 * C++ default constructor.
+		 */
+		CLockAppStateControl( );
+
+		/**
+		 * Second phase constructor allowed to fail (leave).
+		 */
+		void ConstructL( );
+
+	public:
+
+		/**
+		 * Activate keyguard lock.
+		 *
+		 * @param aWithNote if "keys locked" note is shown
+		 * @return KErrAlreadyExists if already enabled
+		 *         KErrPermissionDenied if devicelock is activated
+		 *         KErrNone if succeeded
+		 */
+		TInt EnableKeyguardL( TBool aWithNote );
+
+		/**
+		 * Dectivate keyguard lock.
+		 *
+		 * @param aWithNote if "keys active" note is shown.
+		 * @return KErrAlreadyExists if already disabled
+		 *         KErrPermissionDenied if devicelock is activated
+		 *         KErrNone if succeeded
+		 */
+		TInt DisableKeyguardL( TBool aWithNote );
+
+		/**
+		 * Activate devicelock.
+		 *
+		 * @param aReason the device locking reason.
+		 * @return KErrAlreadyExists if already enabled.
+		 *         KErrNone if succeeded
+		 */
+		TInt EnableDevicelockL( TDevicelockReason aReason = EDevicelockManual );
+
+		/**
+		 * Dectivate devicelock.
+		 *
+		 * @return KErrAlreadyExists if already disabled
+		 *         KErrPermissionDenied if keyguard is activated
+		 *         KErrNone if succeeded
+		 */
+		TInt DisableDevicelockL( );
+
+		/**
+		 * Offer to enable keyguard by showing "offerkeylock" note.
+		 * @return KErrPermissionDenied if keyguard/devicelock already activated
+		 *         KErrNone if succeeded
+		 */
+		TInt OfferKeyguard( );
+
+		/**
+		 * Offer to enable keyguard by showing "offerkeylock" note.
+		 * 
+		 * @return KErrNone if succeeded
+		 *         KErrPermissionDenied if keyguard not enabled
+		 */
+		TInt ShowKeysLockedNote( );
+
+		/**
+		 * External access to lock state
+		 *
+		 * @return Current lock state
+		 */
+		TLockStatus LockStatus( ) const;
+
+		/**
+		 * External access to lock environment
+		 *
+		 * @return Current environment state mask
+		 */
+		TUint EnvironmentStatus( ) const;
+
+		/**
+		 * Only used for internal testing.
+		 * @return error code
+		 */
+		TInt ExecuteInternalTest( );
+
+	public:
+		// From MLockAppObserverInterface
+
+		/**
+		 * Handle Central Repository observer callback.
+		 */
+		void HandleCenRepNotify( TUid aCenRepUid, TUint32 aKeyId, TInt aValue );
+
+		/**
+		 * Handle Publish & Subscribe observer callback.
+		 */
+		void HandlePubSubNotify( TUid aPubSubUid, TUint aKeyId, TInt aValue );
+
+	public:
+		// from CCoeControl
+
+		TInt CountComponentControls( ) const;
+
+		CCoeControl* ComponentControl( TInt aIndex ) const;
+
+		TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+		void HandleWsEventL( const TWsEvent& aEvent, CCoeControl* aDestination );
+
+		void HandleResourceChange( TInt aType );
+
+	private:
+
+		/**
+		 * Creates the second "visibility gate" window group.
+		 */
+		void CreateVisibilityGateWgL( );
+
+		/**
+		 * Logs the telephony P&S call state.
+		 */
+		void PrintCallState( TInt aValue );
+
+		/**
+		 * Update the environment variable with the event.
+		 * @return ETrue if the environment value has changed
+		 *         EFalse otherwise
+		 */
+		TBool HandleEnvironmentChange( TUint aEventMask, TBool aEnable );
+
+		/**
+		 * Check if given transition is valid.
+		 * @return KErrNone if transition is legal
+		 *         KErrAlreadyExists if LockApp already is in requested state
+		 *         KErrPermissionDenied if illegal transition
+		 */
+		TInt CheckIfLegal( TLockAppMessageReason aReason );
+
+		/**
+		 * Handle lock state change. Should only called from
+		 * method PostStatusChangeL.
+		 *
+		 * @param aLockStatus The new lock state
+		 */
+		void HandleLockStatusChangedL( TLockStatus aLockStatus );
+
+		void BringForward( TBool aForeground );
+
+		/**
+		 * Mute/Unmute key sounds when phone is locked/unlocked.
+		 * 
+		 * @param aMuteSounds mute switch
+		 */
+		void MuteSounds( TBool aMuteSounds );
+
+		/**
+		 * Prescreen key events for special cases before giving them to child controls.
+		 */
+		TKeyResponse PreCheckKeyEvents( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+		/**
+		 * Power key needs to always activate lights.
+		 */
+		void CheckForPowerKeyLights( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+		/**
+		 * Green and Red keys should be passed to Phone during phone call.
+		 * @return ETrue if the keys have been forwarded
+		 *         EFalse otherwise
+		 */
+		TBool CheckForPhoneKeys( const TKeyEvent& aKeyEvent, TEventCode aType );
+
+	private:
+
+		/**
+		 * Internal lock state.
+		 */
+		TLockStatus iLockStatus;
+
+		/**
+		 * Current control;
+		 */
+		CLockAppBaseControl* iCurrentControl;
+
+		/**
+		 * Idle UI.
+		 * Owned by superclass.
+		 */
+		CLockAppIdleControl* iIdle; // owned by superclass
+
+		/**
+		 * Keyguard UI.
+		 * Owned by superclass.
+		 */
+		CLockAppKeyguardControl* iKeyguard; // owned by superclass
+
+		/**
+		 * Autolock UI
+		 * Owned by superclass. 
+		 */
+		CLockAppDevicelockControl* iDevicelock;
+
+		/**
+		 * Emergency call detector with emergency note.
+		 * Owned by superclass.
+		 */
+		CLockAppEcsDetector* iLockEcsDetector;
+
+		/**
+		 * PubSub observers
+		 */
+		CLockAppPubSubObserver* iPSScreenSaverObserver;
+		CLockAppPubSubObserver* iPSTelephonyObserver;
+		CLockAppPubSubObserver* iPSGripObserver;
+		CLockAppPubSubObserver* iPSFPSObserver;
+
+		/**
+		 * Application's main window group - Event gate
+		 */
+		RWindowGroup& iWGEventGate;
+
+		/**
+		 * Visibility gate (owned)
+		 */
+		RWindowGroup iWGVisibilityGate;
+
+		/**
+		 * Incall Bubble. (owned)
+		 */
+		CAknIncallBubble* iIncallBubble;
+
+	private:
+
+		/**
+		 *  feature manager keys
+		 */
+		TBool iFeatureNoPowerkey;
+
+		/**
+		 * Offset value used to free reserved localization resources
+		 */
+		TInt iResourceFileOffset;
+
+		/**
+		 * if sounds are muted
+		 */
+		TBool iSoundsMuted;
+
+		/**
+		 * Environment state descriptor bit-mask
+		 */
+		TUint iEnvState;
+
+	};
+
+#endif // __LOCKAPPSTATECONTROL_H__
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappstatecontrolinterface.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,117 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface for controls that want to modify lock status
+ *
+*/
+
+
+#ifndef __LOCKAPPSTATECONTROLINTERFACE_H__
+#define __LOCKAPPSTATECONTROLINTERFACE_H__
+
+// INCLUDES
+#include "lockapp.hrh"
+
+/**
+ *  MLockAppStateControl class offers safe interface methods for lockapp controls.
+ *  All internal child controls should use this interface for modifying
+ *  the phone lock state.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class MLockAppStateControl
+	{
+	public:
+
+		/** 
+		 * Activate keyguard lock.
+		 *
+		 * @param aWithNote if "keys locked" note is shown
+		 * @return KErrAlreadyExists if already enabled
+		 *         KErrPermissionDenied if devicelock is activated
+		 *         KErrNone if succeeded
+		 */
+		virtual TInt EnableKeyguardL( TBool aWithNote ) = 0;
+
+		/**
+		 * Dectivate keyguard lock.
+		 *
+		 * @param aWithNote if "keys active" note is shown.
+		 * @return KErrAlreadyExists if already disabled
+		 *         KErrPermissionDenied if devicelock is activated
+		 *         KErrNone if succeeded
+		 */
+		virtual TInt DisableKeyguardL( TBool aWithNote ) = 0;
+
+		/**
+		 * Activate devicelock.
+		 * 
+		 * @param aReason the device locking reason.
+		 * @return KErrAlreadyExists if already enabled.
+		 *         KErrNone if succeeded
+		 */
+		virtual TInt EnableDevicelockL( TDevicelockReason aReason = EDevicelockManual ) = 0;
+
+		/**
+		 * Dectivate devicelock.
+		 *
+		 * @return KErrAlreadyExists if already disabled
+		 *         KErrPermissionDenied if keyguard is activated
+		 *         KErrNone if succeeded
+		 */
+		virtual TInt DisableDevicelockL( ) = 0;
+
+		/**
+		 * Offer to enable keyguard by showing "offerkeylock" note.
+		 * 
+		 * @return KErrPermissionDenied if keyguard/devicelock already activated
+		 *         KErrNone if succeeded
+		 */
+		virtual TInt OfferKeyguard( ) = 0;
+
+		/**
+		 * Offer to enable keyguard by showing "offerkeylock" note.
+		 * 
+		 * @return KErrNone if succeeded
+		 *         KErrPermissionDenied if keyguard is not enabled
+		 */
+		virtual TInt ShowKeysLockedNote( ) = 0;
+
+		/**
+		 * External access to lock state
+		 *
+		 * @return Current lock state
+		 */
+		virtual TLockStatus LockStatus( ) const = 0;
+
+		/**
+		 * External access to lock environment
+		 *
+		 * @return Current environment state
+		 */
+		virtual TUint EnvironmentStatus( ) const = 0;
+
+		/**
+		 * Used for internal testing only, disabled normally
+		 * 
+		 * @return error code
+		 */
+		virtual TInt ExecuteInternalTest( ) = 0;
+
+	};
+
+#endif // __LOCKAPPSTATECONTROLINTERFACE_H__
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappstateobserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface for controls that want to be informed about lock status
+ *
+*/
+
+
+#ifndef __LOCKAPPSTATEOBSERVER_H__
+#define __LOCKAPPSTATEOBSERVER_H__
+
+// INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include "lockapp.hrh"
+
+/**
+ *  CLockAppStateObserver class offers a lockstate observer interface. 
+ *  All observer classes derived from MLockAppStateObserver should be added to 
+ *  the lockapp observer list in order to get notifications about lock state changes.
+ *
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ */
+class MLockAppStateObserver
+	{
+	public:
+
+		/**
+		 * Lock status changes are handled trough HandleLockStatusChangedL method.
+		 * Must be overriden by derived class for observing.
+		 */
+		virtual void HandleLockStatusChangedL( TLockStatus aLockStatus ) = 0;
+
+	};
+
+#endif // __LOCKAPPSTATEOBSERVER_H__
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappstatepublisher.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,72 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Publishes LockApp states to other applications
+ *
+*/
+
+
+#ifndef __LOCKAPPSTATEPUBLISHER_H__
+#define __LOCKAPPSTATEPUBLISHER_H__
+
+// INCLUDES
+#include "lockappstateobserver.h"
+#include <e32property.h>
+
+/**
+ *  CLockAppStatePublisher class publishes lock state to external parties using P&S key.
+ * 
+ *  @lib    lockapp
+ *  @since  5.0
+ *  @author Joona Petrell
+ *  @author Tamas Koteles
+ **/
+class CLockAppStatePublisher : public CBase, public MLockAppStateObserver
+	{
+	public:
+		/**
+		 * Two-phased constructor.
+		 */
+		static CLockAppStatePublisher* NewL( );
+
+		/**
+		 * C++ default constructor.
+		 */
+		CLockAppStatePublisher( );
+
+		/**
+		 * Destructor.
+		 */
+		~CLockAppStatePublisher( );
+	private:
+
+		/**
+		 * Second constructor that can fail (leave).
+		 */
+		void ConstructL( );
+
+	public:
+		// from CLockAppStateObserver
+
+		virtual void HandleLockStatusChangedL( TLockStatus aLockStatus );
+
+	private:
+
+		// stores locking state property
+		RProperty iStatusProperty;
+
+	};
+
+#endif // __LOCKAPPSTATEPUBLISHER_H__
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockapptrace.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,392 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Trace macro support for lockapp
+ *
+*/
+
+
+#ifndef LOCKAPPTRACE_H
+#define LOCKAPPTRACE_H
+
+#include "lockapptraceconfiguration.hrh"
+
+#ifdef TRACE_INTO_FILE
+#include <flogger.h> // RFileLogger
+#else
+#include <e32debug.h> // RDebug
+#endif
+
+//-----------------------------------------------------------------------------
+// Constants
+//-----------------------------------------------------------------------------
+//
+
+/**
+* Prefix trace macro to complete tracing with component name.
+* Returns TDesC which can be used directly with RDebug or RFileLogger.
+*/
+#define _PREFIX_TRACE( aMsg ) TPtrC( (const TText*)L"[LockApp]: " L##aMsg )
+
+/**
+* Prefix error trace
+*/
+#define _PREFIX_ERROR( aMsg ) _PREFIX_TRACE( "[ERROR: %d]: " L##aMsg )
+
+/**
+* Prefix info trace.
+*/
+#define _PREFIX_INFO( aMsg ) _PREFIX_TRACE( "[INFO]: " L##aMsg )
+
+/**
+* Prefix macro for strings
+*/
+#define _PREFIX_CHAR( aMsg ) (const char*)"[LockApp]: " ##aMsg
+
+/**
+* Define needed directories if TRACE_INTO_FILE macro in use
+*/
+#ifdef TRACE_INTO_FILE
+
+	_LIT( KDir, "lockapp" );
+	_LIT( KFile, "lockapp_log.txt" );
+	_LIT( KFullPath, "c:\\logs\\lockapp\\" );
+
+#endif
+
+//-----------------------------------------------------------------------------
+// Error trace macros
+//-----------------------------------------------------------------------------
+//
+#ifdef ERROR_TRACE
+
+	/**
+	* Error trace definitions.
+	*/
+	#ifdef TRACE_INTO_FILE
+
+		#define ERROR( aErr, aMsg )\
+			{\
+			if( aErr < KErrNone )\
+				{\
+				RFileLogger::WriteFormat( KDir, KFile, EFileLoggingModeAppend, _PREFIX_ERROR( aMsg ), aErr );\
+				}\
+			}
+		#define ERROR_1( aErr, aMsg, aP1 )\
+			{\
+			if( aErr < KErrNone )\
+				{\
+				RFileLogger::WriteFormat( KDir, KFile, EFileLoggingModeAppend, _PREFIX_ERROR( aMsg ), aErr, aP1 );\
+				}\
+			}
+		#define ERROR_2( aErr, aMsg, aP1, aP2 )\
+			{\
+			if( aErr < KErrNone )\
+				{\
+				RFileLogger::WriteFormat( KDir, KFile, EFileLoggingModeAppend, _PREFIX_ERROR( aMsg ), aErr, aP1, aP2 );\
+				}\
+			}
+		#define ERROR_3( aErr, aMsg, aP1, aP2, aP3 )\
+			{\
+			if( aErr < KErrNone )\
+				{\
+				RFileLogger::WriteFormat( KDir, KFile, EFileLoggingModeAppend, _PREFIX_ERROR( aMsg ), aErr, aP1, aP2, aP3 );\
+				}\
+			}
+
+	#else//TRACE_INTO_FILE not defined
+
+		#define ERROR( aErr, aMsg )\
+			{\
+			if( aErr < KErrNone )\
+				{\
+				RDebug::Print( _PREFIX_ERROR( aMsg ), aErr );\
+				}\
+			}
+		#define ERROR_1( aErr, aMsg, aP1 )\
+			{\
+			if( aErr < KErrNone )\
+				{\
+				RDebug::Print( _PREFIX_ERROR( aMsg ), aErr, aP1 );\
+				}\
+			}
+		#define ERROR_2( aErr, aMsg, aP1, aP2 )\
+			{\
+			if( aErr < KErrNone )\
+				{\
+				RDebug::Print( _PREFIX_ERROR( aMsg ), aErr, aP1, aP2 );\
+				}\
+			}
+		#define ERROR_3( aErr, aMsg, aP1, aP2, aP3 )\
+			{\
+			if( aErr < KErrNone )\
+				{\
+				RDebug::Print( _PREFIX_ERROR( aMsg ), aErr, aP1, aP2, aP3 );\
+				}\
+			}
+
+	#endif//TRACE_INTO_FILE
+
+	#define ERROR_GEN( aMsg ) ERROR( KErrGeneral, aMsg )
+	#define ERROR_GEN_1( aMsg, aP1 ) ERROR_1( KErrGeneral, aMsg, aP1 )
+	#define ERROR_GEN_2( aMsg, aP1, aP2 ) ERROR_2( KErrGeneral, aMsg, aP1, aP2 )
+	#define ERROR_GEN_3( aMsg, aP1, aP2, aP3 ) ERROR_3( KErrGeneral, aMsg, aP1, aP3 )
+
+#else//ERROR_TRACE not defined
+
+	#define ERROR( aErr, aMsg )
+	#define ERROR_1( aErr, aMsg, aP1 )
+	#define ERROR_2( aErr, aMsg, aP1, aP2 )
+	#define ERROR_3( aErr, aMsg, aP1, aP2, aP3 )
+	#define ERROR_GEN( aMsg )
+	#define ERROR_GEN_1( aMsg, aP1 )
+	#define ERROR_GEN_2( aMsg, aP1, aP2 )
+	#define ERROR_GEN_3( aMsg, aP1, aP2, aP3 )
+
+#endif//ERROR_TRACE
+
+//-----------------------------------------------------------------------------
+// Info trace macros
+//-----------------------------------------------------------------------------
+//
+#ifdef INFO_TRACE
+
+	/**
+	* Info log message definitions.
+	*/
+	#ifdef TRACE_INTO_FILE
+
+		#define INFO( aMsg )\
+			{\
+			RDebug::Print( _PREFIX_INFO( aMsg ) );\
+			RFileLogger::Write( KDir, KFile, EFileLoggingModeAppend, _PREFIX_INFO( aMsg ) );\
+			}
+		#define INFO_1( aMsg, aP1 )\
+			{\
+			RDebug::Print( _PREFIX_INFO( aMsg ), aP1 );\
+			RFileLogger::WriteFormat( KDir, KFile, EFileLoggingModeAppend, _PREFIX_INFO( aMsg ), aP1 );\
+			}
+		#define INFO_2( aMsg, aP1, aP2 )\
+			{\
+			RDebug::Print( _PREFIX_INFO( aMsg ), aP1, aP2 );\
+			RFileLogger::WriteFormat( KDir, KFile, EFileLoggingModeAppend, _PREFIX_INFO( aMsg ), aP1, aP2 );\
+			}
+		#define INFO_3( aMsg, aP1, aP2, aP3 )\
+			{\
+			RDebug::Print( _PREFIX_INFO( aMsg ), aP1, aP2, aP3 );\
+			RFileLogger::WriteFormat( KDir, KFile, EFileLoggingModeAppend, _PREFIX_INFO( aMsg ), aP1, aP2, aP3 );\
+			}
+		#define INFO_4( aMsg, aP1, aP2, aP3, aP4 )\
+			{\
+			RDebug::Print( _PREFIX_INFO( aMsg ), aP1, aP2, aP3, aP4 );\
+			RFileLogger::WriteFormat( KDir, KFile, EFileLoggingModeAppend, _PREFIX_INFO( aMsg ), aP1, aP2, aP3, aP4 );\
+			}
+
+	#else//TRACE_INTO_FILE not defined
+
+		#define INFO( aMsg )\
+			{\
+			RDebug::Print( _PREFIX_INFO( aMsg ) );\
+			}
+		#define INFO_1( aMsg, aP1 )\
+			{\
+			RDebug::Print( _PREFIX_INFO( aMsg ), aP1 );\
+			}
+		#define INFO_2( aMsg, aP1, aP2 )\
+			{\
+			RDebug::Print( _PREFIX_INFO( aMsg ), aP1, aP2 );\
+			}
+		#define INFO_3( aMsg, aP1, aP2, aP3 )\
+			{\
+			RDebug::Print( _PREFIX_INFO( aMsg ), aP1, aP2, aP3 );\
+			}
+		#define INFO_4( aMsg, aP1, aP2, aP3, aP4 )\
+			{\
+			RDebug::Print( _PREFIX_INFO( aMsg ), aP1, aP2, aP3, aP4 );\
+			}
+
+	#endif//TRACE_INTO_FILE
+
+#else//INFO_TRACE not defined
+
+	#define INFO( aMsg )
+	#define INFO_1( aMsg, aP1 )
+	#define INFO_2( aMsg, aP1, aP2 )
+	#define INFO_3( aMsg, aP1, aP2, aP3 )
+	#define INFO_4( aMsg, aP1, aP2, aP3, aP4 )
+
+#endif//INFO_TRACE
+
+//-----------------------------------------------------------------------------
+// Trace current client thread name and process id
+//-----------------------------------------------------------------------------
+//
+#ifdef CLIENT_TRACE
+
+	#define CLIENT( aMessage )\
+		{\
+		RThread thread;\
+		TInt err = aMessage.Client( thread );\
+		if( err == KErrNone )\
+			{\
+			RProcess process;\
+			err = thread.Process( process );\
+			if( err == KErrNone )\
+				{\
+				TPtrC thredName( thread.Name() );\
+				TUid processUid( process.SecureId() );\
+				INFO_2( "Current client process UID: [%x], thread name: [%S]",\
+					processUid,\
+					&thredName );\
+				}\
+			process.Close();\
+			}\
+		thread.Close();\
+		}
+
+#else
+
+	#define CLIENT( aMessage )
+
+#endif
+
+//-----------------------------------------------------------------------------
+// Function trace macros
+//-----------------------------------------------------------------------------
+//
+#ifdef FUNC_TRACE
+
+	/**
+	* Function logging definitions.
+	*/
+	#ifdef TRACE_INTO_FILE
+
+		#define FUNC( aMsg, aP1 )\
+			{\
+			TPtrC8 trace( _S8( aMsg ) );\
+			RFileLogger::WriteFormat( KDir, KFile, EFileLoggingModeAppend, trace, aP1 );\
+			}\
+
+	#else//TRACE_INTO_FILE not defined
+
+		#define FUNC( aMsg, aP1 )\
+			{\
+			RDebug::Printf( aMsg, aP1 );\
+			}\
+
+	#endif//TRACE_INTO_FILE
+
+	/**
+	* Function trace helper class.
+	*
+	* NOTE:
+	* LC -methods cannot be trapped. Therefore if LC -method leaves
+	* END trace is used instead of LEAVE trace.
+	* If you have an idea how to round this problem please tell.
+	*/
+	_LIT8( KFuncNameTerminator, "(" );
+	_LIT8( KFuncLeavePatternL, "L" );
+	class TFuncLog
+		{
+		public:
+			static void Cleanup( TAny* aPtr )
+				{
+				TFuncLog* self = static_cast< TFuncLog* >( aPtr );
+				self->iLeft = ETrue;
+				FUNC( _PREFIX_CHAR("%S-LEAVE"), &self->iFunc ); // Leave detected
+				}
+			inline TFuncLog( const char* aFunc ) :
+					iFunc( aFunc ? _S8( aFunc ) : _S8("") ),
+					iLeft( EFalse ),
+					iCleanupItem( Cleanup, this ),
+					iCanLeave( EFalse )
+				{
+				TInt pos( iFunc.Find( KFuncNameTerminator ) );
+				if( pos != KErrNotFound )
+					{
+					iFunc.Set( iFunc.Left( pos ) );
+					iCanLeave = !iFunc.Right( KFuncLeavePatternL().Length() ).Compare( KFuncLeavePatternL );
+					if ( iCanLeave )
+						{
+						CleanupStack::PushL( iCleanupItem ); // Ignore warnings
+						}
+					}
+				FUNC( _PREFIX_CHAR("%S-START"), &iFunc );
+				}
+
+			inline ~TFuncLog()
+				{
+				if ( !iLeft )
+					{
+					if ( iCanLeave )
+						{
+						CleanupStack::Pop( this ); // Pop the cleanup item
+						}
+					FUNC( _PREFIX_CHAR("%S-END"), &iFunc ); // Normally finished
+					}
+				}
+
+		private: // Data
+			TPtrC8 iFunc;
+			TBool iLeft;
+			TCleanupItem iCleanupItem;
+			TBool iCanLeave;
+		};
+	#define FUNC_LOG TFuncLog _fl( __PRETTY_FUNCTION__ );
+
+#else//FUNC_TRACE not defined
+
+	#define FUNC_LOG
+
+#endif//FUNC_TRACE
+
+//-----------------------------------------------------------------------------
+// Timestamp trace macros
+//-----------------------------------------------------------------------------
+//
+#ifdef TIMESTAMP_TRACE
+
+	#ifdef TRACE_INTO_FILE
+
+		#define TIMESTAMP( aCaption )\
+			{\
+			TTime t;\
+			t.HomeTime();\
+			TDateTime dt = t.DateTime();\
+			_LIT( KCaption, aCaption );\
+			RFileLogger::WriteFormat( KDir, KFile, EFileLoggingModeAppend,\
+				_PREFIX_TRACE("[TIMESTAMP] %S %d:%02d:%02d.%d us"),\
+					&KCaption, dt.Hour(), dt.Minute(), dt.Second(), dt.MicroSecond() );\
+			}
+
+	#else//TRACE_INTO_FILE not defined
+
+		#define TIMESTAMP( aCaption )\
+			{\
+			TTime t;\
+			t.HomeTime();\
+			TDateTime dt = t.DateTime();\
+			_LIT( KCaption, aCaption );\
+			RDebug::Print( _PREFIX_TRACE("[TIMESTAMP] %S %d:%02d:%02d.%d us"),\
+				&KCaption, dt.Hour(), dt.Minute(), dt.Second(), dt.MicroSecond() );\
+			}
+
+	#endif//TRACE_INTO_FILE
+
+#else//TIMESTAMP_TRACE not defined
+
+	#define TIMESTAMP( aCaption )
+
+#endif//TIMESTAMP_TRACE
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockapptraceconfiguration.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,78 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Trace definitions for lockapp 
+ *
+*/
+
+
+
+#ifndef LOCKAPPTRACECONFIGURATION_HRH
+#define LOCKAPPTRACECONFIGURATION_HRH
+
+//-----------------------------------------------------------------------------
+// Trace definitions
+//-----------------------------------------------------------------------------
+
+/**
+* Error trace enabled
+*/
+#ifdef _DEBUG
+    #define ERROR_TRACE
+#else
+    #undef ERROR_TRACE
+#endif
+
+/**
+* Info trace enabled
+*/
+#ifdef _DEBUG
+    #define INFO_TRACE
+#else
+    #undef INFO_TRACE
+#endif
+
+/**
+* Function trace enabled
+*/
+#ifdef _DEBUG
+    #define FUNC_TRACE
+#else
+    #undef FUNC_TRACE
+#endif
+
+/**
+* Timestamp tracing on
+*/
+#ifdef _DEBUG
+    #define TIMESTAMP_TRACE
+#else
+    #undef TIMESTAMP_TRACE
+#endif
+
+/**
+* Tracing current client process and thread
+*/
+#ifdef _DEBUG
+    #define CLIENT_TRACE
+#else
+    #undef CLIENT_TRACE
+#endif
+
+/**
+* Tracing into file enabled, default RDebug
+*/
+//#undef TRACE_INTO_FILE
+#define TRACE_INTO_FILE
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockapputils.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,72 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Internally used panic functions and test macros
+ *
+*/
+
+
+#ifndef __LOCKAPPUTILS_H__
+#define __LOCKAPPUTILS_H__
+
+// INCLUDES
+#include "lockapp.hrh"
+#include "lockapptrace.h"
+#include <w32std.h>
+
+/**
+ * Queries bits in aStatusMask specified by the aQueryMask
+ */
+TBool IsBitFieldSet( TUint aStatusMask, TUint aQueryMask );
+
+/**
+ * Sets bits in aResultMask specified by the aSetMask
+ */
+void SetBitField( TUint &aResultMask, TUint aSetMask, TBool aSet );
+
+/**
+ * Panic the LockApp (should only be used in debug)
+ *
+ * @param aPanic Identifies the reason to Panic
+ */
+void DoPanic( TLockAppPanic aPanic );
+
+/**
+ * Panic LockAppServer client for sending
+ * illegal message
+ *
+ * @param aMessage Event id
+ * @param aPanic Identifies the reason to Panic
+ */
+void PanicClient( const RMessagePtr2& aMessage, TLockAppPanic aPanic );
+
+/**
+ * Sends application spesific events to Sysap.
+ * Used mainly for lights control.
+ *
+ * @param aMessage Event id
+ */
+void SendMessageToSysAp(TInt aMessage);
+
+/**
+ * Sends a key event to the windowgroup in background.
+ * Used mainly for sending red and green keys to phone app when
+ * devicelock or keyguard is in foreground.
+ *
+ * @param aKey key event
+ * @param aType key event type
+ */
+void SendKeyToPhoneApp(const TKeyEvent& aKey, TEventCode aType);
+
+#endif // __LOCKAPPTILS_H__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/inc/lockappwait.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,130 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Async-Sync utility class
+ *
+*/
+
+
+#ifndef __LOCKAPPWAIT_H
+#define __LOCKAPPWAIT_H
+
+//  INCLUDES
+
+#include <e32base.h>
+#include <eikappui.h>
+#include <coecntrl.h>
+
+//  CLASS DEFINITIONS
+class CWait : public CActive
+	{
+public:
+	/**
+	 * Creates instance of the CWait class.
+	 *
+	 * @return Returns the instance just created.
+	 */
+	static CWait* NewL( );
+
+	/**
+	 * Destructor.
+	 */
+	~CWait( );
+
+	/**
+	 * Starts waiting for aReqStatus.
+	 */
+	TInt WaitForRequestL( );
+
+	/**
+	 * Sets active request type.
+	 */
+	void SetRequestType(TInt aRequestType );
+	
+	/**
+	 * Gets active request type.
+	 */
+	TInt GetRequestType( );
+
+private:
+	
+	/**
+	 * C++ default constructor.
+	 */
+	CWait( );
+	
+	/**
+	 * Symbian OS constructor.
+	 */
+	void ConstructL( );
+
+private: // from CActive
+
+	/** @see CActive::RunL() */
+	void RunL( );
+
+	/** @see CActive::DoCancel() */
+	void DoCancel( );
+
+private: // data
+
+	RTimer iTimer;
+
+	CActiveSchedulerWait iWait;
+
+	// Used if there is a need to cancel an active request;
+	// namely in situations where destructor is called when Wait
+	// is active.
+	TInt iRequestType;
+	};
+
+// ----------------------------------------------------------
+// CWaitAbsorbingControl
+// absorbs all the key presses.
+// ----------------------------------------------------------
+//
+class CWaitAbsorbingControl : public CCoeControl
+	{
+public:
+
+	/**
+	 * Creates instance of the CWaitAbsorbingControl class.
+	 *
+	 * @return Returns the instance just created.
+	 */
+	static CWaitAbsorbingControl* NewLC( );
+
+	/**
+	 * Destructor.
+	 */
+	virtual ~CWaitAbsorbingControl( );
+
+private:
+
+	virtual TKeyResponse OfferKeyEventL(const TKeyEvent& /*aKeyEvent*/, TEventCode /*aType*/);
+
+private:
+
+	CWaitAbsorbingControl( );
+
+	void ConstructL( );
+
+private: // data
+
+	CEikAppUi* iAppUi;
+
+	};
+
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/loc/lockapp.loc	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Localisation strings for LockApp
+ *
+*/
+
+
+// LOCALISATION STRINGS
+
+//d:Title pane text in System Lock View.(Phone is in locked mode)
+//l:title_pane_t2/opt9 
+//
+#define qtn_set_sec_title_locked "Locked"
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/pubsub/SecurityUIsPrivatePSKeys.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,65 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Private Publish&Subscribe definitions of the
+ *                Security UIs subsystem
+ *
+*/
+
+
+#ifndef SECURITYUISPRIVATEPSKEYS_H
+#define SECURITYUISPRIVATEPSKEYS_H
+
+// INCLUDES
+
+//CONSTANTS
+
+const TUid KPSUidSecurityUIs = { 0x100059b5 };
+// =============================================================================
+// Security Code UI Originator API
+// =============================================================================
+
+// Use TUid KPSUidSecurityUIs = { 0x100059b5 } 
+
+/**
+ * Used by SecUI to differentiate between ETel API originated and SecUI originated
+ * security queries.
+ * Old Shared Data constant name: KSecUIOriginatedQuery
+ */
+const TUint32 KSecurityUIsSecUIOriginatedQuery = 0x00000301;
+enum TSecurityUIsSecUIOriginatedQuery
+    {
+    ESecurityUIsSecUIOriginatedUninitialized = 0,
+    ESecurityUIsETelAPIOriginated,
+    ESecurityUIsSecUIOriginated,
+    ESecurityUIsSystemLockOriginated,
+    ESecurityUIsFpsOriginated
+    };
+
+/**
+ * Used by SecUI to tell if a query request set by some ETELMM API lock setting function (i.e. SetXXXXSetting)
+ * has been canceled sinnce canceling the setting request does not prompt a query cancel event from ETEL.
+ * Old Shared Data constant name: KSecUIOriginatedQuery
+ */    
+const TUint32 KSecurityUIsQueryRequestCancel = 0x00000302;
+enum TSecurityUIsQueryRequestCancel
+    {
+    ESecurityUIsQueryRequestUninitialized = 0,
+    ESecurityUIsQueryRequestOk,
+    ESecurityUIsQueryRequestCanceled
+    };
+
+#endif // SECURITYUISPRIVATEPSKEYS_H
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/rom/lockapp.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,31 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  LockApp files needed to image
+ *
+*/
+
+
+#ifndef __LOCKAPP_IBY__
+#define __LOCKAPP_IBY__
+
+#include <data_caging_paths_for_iby.hrh>
+
+//S60_APP_EXE(lockapp)
+S60_APP_EXE_UDEB(lockapp)
+S60_APP_AIF_RSC(lockapp)
+
+// To enable updating
+data=ZSYSTEM\install\lockapp_stub.sis system\install\lockapp_stub.sis
+
+#endif // __LOCKAPP_IBY__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/rom/lockappresources.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  LockApp resources needed to image
+ *
+*/
+
+
+#ifndef __LOCKAPPRESOURCES_IBY__
+#define __LOCKAPPRESOURCES_IBY__
+
+#include <data_caging_paths_for_iby.hrh>
+  
+S60_APP_RESOURCE(lockapp)
+
+#endif // __LOCKAPPRESOURCES_IBY__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/sis/lockapp.pkg	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,36 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description: ;Language - standard language definitions
+;
+;Language - standard language definitions
+;Language - standard language definitions
+&EN
+
+; standard SIS file header
+#{"LockApp"}, (0x10283322), 1, 0, 0, TYPE=SA
+
+;Localised Vendor name
+%{"Nokia"}
+
+;Unique Vendor name
+:"Nokia"
+
+;Supports Series 60 v 3.0
+[0x101F7961], 0, 0, 0, {"Series60ProductID"}
+
+;Files to install
+"\Epoc32\release\armv5\udeb\lockapp.exe"-"z:\sys\bin\lockapp.exe"
+"\Epoc32\data\z\resource\apps\lockapp.rsc"-"z:\resource\apps\lockapp.rsc"
+"\Epoc32\data\z\private\10003a3f\apps\lockapp_reg.rsc"-"z:\private\10003a3f\import\apps\lockapp_reg.rsc"
+"\Epoc32\data\z\resource\apps\lockapp.mif"-"z:\resource\apps\lockapp.mif"
Binary file securitydialogs/lockapp/sis/lockapp_stub.sis has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/sis/make_stubsis.bat	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,17 @@
+rem
+rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+rem All rights reserved.
+rem This component and the accompanying materials are made available
+rem under the terms of "Eclipse Public License v1.0"
+rem which accompanies this distribution, and is available
+rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+rem
+rem Initial Contributors:
+rem Nokia Corporation - initial contribution.
+rem
+rem Contributors:
+rem
+rem Description:
+rem
+
+makesis -s lockapp.pkg lockapp_stub.sis
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/sis/rd-key.pem	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICXAIBAAKBgQDLRF+r1FGGkCwTrb420kbnAps7gi1yYUcXYUdWeFTuBeQe5eW4
+6Y+LWaA8HMlDdoHRB0FgASisYcFagwno9+oFf4AJka4H1gWEs5XTGwAA1s0d8XGh
+7W7Dt9F5FZij8F7/9Pi6+FhhxZFIf1DD+yry9D7+Sp+BgdNALe4XOpf25QIBAwKB
+gQCHgupyjYuvCsgNHn7PNtnvVxInrB5MQNoPli+O+uNJWUK/Q+57Rl+yO8AoEzDX
+pFaLWiuVVhsdloDnAgabT/FXzYncs6uOHyEUV+dSXb78vtLPJqAX+Fg2i3hOXreB
+yskcZ13/OsKVOu5wgrJkx2baZufkqMwOSytf5y9nwjEIKwJBAP+inobagVNrN62j
+KQva3cC+UN/6XnKdTc0CA6bHyLOaJoH1xiMwG/VS2PGjHI0tiSMNtLn/QPpHJ003
+iabGhdUCQQDLjp/9UjFT6K6CF66Chqf30pZXhx+GTSQZmv/gvZiMly7X9fX9BGX3
+2MbJohBC4yI21XKTbisWywkF73Hwh+TRAkEAqmxprzxWN5zPyRdwspHpKymLP/w+
+9xOJM1atGdqFzRFvAU6EF3Vn+OHl9my9s3OwwgkjJqorUYTE3iUGby8D4wJBAIe0
+aqjhdjfwdFa6dFcEb/qMZDpaFQQzbWZnVUB+ZbMPdI/5TqitmU/l2dvBYCyXbCSO
+TGJJcg8yBgP09qBamIsCQFL7j1tM0XPVQJQ89WpKCld7O9ORxRGVj1eG0tWijrH8
+mGbYh8SGCVoWV3vrKSS8GBrFVgQnqUaHuEdtM7tpCAQ=
+-----END RSA PRIVATE KEY-----
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/sis/rd.cer	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIICzDCCAjWgAwIBAgIBADANBgkqhkiG9w0BAQUFADArMRAwDgYDVQQKEwdSRCBD
+ZXJ0MRcwFQYDVQQDEw5SRCBDZXJ0aWZpY2F0ZTAeFw0wNDExMTUxMjQyMDZaFw0z
+NzA5MjMxMjQyMDZaMCsxEDAOBgNVBAoTB1JEIENlcnQxFzAVBgNVBAMTDlJEIENl
+cnRpZmljYXRlMIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDLRF+r1FGGkCwT
+rb420kbnAps7gi1yYUcXYUdWeFTuBeQe5eW46Y+LWaA8HMlDdoHRB0FgASisYcFa
+gwno9+oFf4AJka4H1gWEs5XTGwAA1s0d8XGh7W7Dt9F5FZij8F7/9Pi6+FhhxZFI
+f1DD+yry9D7+Sp+BgdNALe4XOpf25QIBA6OCAQAwgf0wDAYDVR0TBAUwAwEB/zAL
+BgNVHQ8EBAMCAoQwHQYDVR0OBBYEFFi/kuGzxhVpjGxe9ZwlxC3fH9jFMFMGA1Ud
+IwRMMEqAFFi/kuGzxhVpjGxe9ZwlxC3fH9jFoS+kLTArMRAwDgYDVQQKEwdSRCBD
+ZXJ0MRcwFQYDVQQDEw5SRCBDZXJ0aWZpY2F0ZYIBADBsBgNVHSAEZTBjMGEGBFUd
+IAAwWTATBggrBgEFBQcCARYHaHR0cDovLzBCBggrBgEFBQcCAjA2GjRGb3IgUiZE
+IHVzYWdlIG9ubHkuIFRoaXMgY2VydGlmaWNhdGUgaXMgbm90IHRydXN0ZWQuMA0G
+CSqGSIb3DQEBBQUAA4GBAHGB4RQMAgBdeT2hxfOr6f2nA/dZm+M5yX5daUtZnET9
+Ed0A9sazLawfN2G1KFQT9kxEParAyoAkpbMAsRrnRz/9cM3OHgFm/NiKRnf50DpT
+7oCx0I/65mVD2kt+xXE62/Ii5KPnTufIkPi2uLvURCia1tTS8JmJ8dtxDGyQt8BR
+-----END CERTIFICATE-----
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappapplication.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,64 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Application class that also creates the appserver
+ *
+*/
+
+
+#include <eikstart.h>
+#include <eikenv.h>
+#include "lockappdocument.h"
+#include "lockappserver.h"
+#include "lockappapplication.h"
+
+// UID for the application, this should correspond to the uid defined in the mmp file
+static const TUid KUidLockAppApp =
+    {
+    0x10283322
+    };
+
+// ---------------------------------------------------------------------------
+// Create an application, and return a pointer to it
+// ---------------------------------------------------------------------------
+CApaApplication* NewApplication( )
+    {
+    return new CLockAppApplication;
+    }
+
+// ---------------------------------------------------------------------------
+// Main function of the application executable.
+// ---------------------------------------------------------------------------
+TInt E32Main( )
+    {
+    return EikStart::RunApplication( NewApplication );
+    }
+
+// ---------------------------------------------------------------------------
+// Returns the UID for the application
+// ---------------------------------------------------------------------------
+TUid CLockAppApplication::AppDllUid( ) const
+    {
+    // Return the UID for the LockApp application
+    return KUidLockAppApp;
+    }
+
+// ---------------------------------------------------------------------------
+// Creates a document object and passes ownership.
+// ---------------------------------------------------------------------------
+CApaDocument* CLockAppApplication::CreateDocumentL( )
+    {
+    // Create an LockApp document, and return a pointer to it
+    CApaDocument* document = CLockAppDocument::NewL( *this );
+    return document;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappappui.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,209 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  LockApp Application UI class
+*
+*/
+
+
+#include "lockappappui.h"
+#include "lockappstatecontrol.h"
+#include "lockappserver.h"
+#include "lockapptrace.h"
+#include <lockappclientserver.h>
+#include <aknglobalpopupprioritycontroller.h>
+#include <APGCLI.h>
+
+#ifdef __SAP_TERMINAL_CONTROL_FW
+#include <SCPClient.h>
+#endif // __SAP_TERMINAL_CONTROL_FW
+
+// ---------------------------------------------------------------------------
+// Second phase constructor
+// ---------------------------------------------------------------------------
+void CLockAppAppUi::ConstructL( )
+    {
+    	RDebug::Printf( "%s %s (%u) value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0x8 );
+    	    
+   // default appui constructor has to be called
+    BaseConstructL( );    	    
+    	    
+    TInt use_old_autolock=1;
+    if(use_old_autolock)
+    	{
+			// start autolock instead of lockapp . This is a backup solution to use in case that not all SysAp and Avkon changes are implemented
+	 	  RDebug::Printf( "%s %s (%u) 1=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0x1 );
+	    TApaTaskList taskList( iCoeEnv->WsSession() );
+	    TApaTask task( taskList.FindApp( _L("autolock.exe" )) );
+	    if ( !task.Exists() )
+	        {
+	        RApaLsSession ls;                   
+	        User::LeaveIfError(ls.Connect());   
+	        CleanupClosePushL(ls);         
+	        
+	        CApaCommandLine* commandLine = CApaCommandLine::NewLC();
+	        commandLine->SetExecutableNameL( _L("autolock.exe" ) );     
+	        commandLine->SetCommandL( EApaCommandRun );
+	        
+		    // Try to launch the application.        
+	        User::LeaveIfError(ls.StartApp(*commandLine));
+	    	  RDebug::Printf( "%s %s (%u) autolock.exe created=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0x7 );
+	        
+	        CleanupStack::PopAndDestroy(2); // commandLine, ls
+			}
+	    Exit();
+	  }
+
+    INFO( "CLockAppAppUi::ConstructL started" );
+
+    // start the server with the specified name
+	iLockServer = CLockAppServer::NewL( KLockAppServerName );
+	
+    // status pane is should not be visible
+    StatusPane()->MakeVisible( EFalse );
+
+    // we need high priority even if lockapp is not in the foreground
+    iEikonEnv->WsSession().ComputeMode( RWsSession::EPriorityControlDisabled );
+    RThread().SetProcessPriority( EPriorityHigh );
+
+    /*
+     * LockApp is set as system application (Symbian terminology).
+     * This means it does not get closed when system is asked to close applications.
+     */
+    iEikonEnv->SetSystem( ETrue );
+
+#ifdef _GLOBAL_PRIORITY_SUPPORTED
+    // Enable global popup notes
+    AknGlobalPopupPriorityController::EnablePriorityControlL();
+    AknGlobalPopupPriorityController::AllowGlobalPopups( ETrue );
+#endif
+
+    // main control storing and controling phone keylock/devicelock status
+    iStateControl = CLockAppStateControl::NewL( );
+
+    // the main control is given high stack priority
+    // ECoeStackPriorityEnvironmentFilter-1 used to allow hw keys for keyfiler even if keypad is locked.
+    AddToStackL( iStateControl, ECoeStackPriorityEnvironmentFilter-1, ECoeStackFlagStandard );
+    INFO( "CLockAppAppUi::ConstructL finished" );
+    }
+
+// ---------------------------------------------------------------------------
+// Default Constructor
+// ---------------------------------------------------------------------------
+CLockAppAppUi::CLockAppAppUi( )
+    {
+    // no implementation required
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+CLockAppAppUi::~CLockAppAppUi( )
+    {
+	if ( iLockServer )
+		{
+		delete iLockServer;
+		iLockServer = NULL;
+		}
+    if ( iStateControl )
+        {
+        // remove main control from stack
+        RemoveFromStack( iStateControl );
+        delete iStateControl;
+        iStateControl = NULL;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Returns interface to LockAppServer sessions for changing lock states
+// ---------------------------------------------------------------------------
+MLockAppStateControl* CLockAppAppUi::StateControl( )
+    {
+    return iStateControl;
+    }
+
+#ifdef __SAP_TERMINAL_CONTROL_FW
+// ---------------------------------------------------------------
+// Handles the TARM command to unlock the phone from WindowServer.
+// ---------------------------------------------------------------
+MCoeMessageObserver::TMessageResponse CLockAppAppUi::HandleMessageL(
+        TUint32 aClientHandleOfTargetWindowGroup,
+        TUid aMessageUid,
+        const TDesC8& aMessageParameters )
+    {
+    MCoeMessageObserver::TMessageResponse messageResponse( EMessageHandled);
+    if ( aMessageUid.iUid == SCP_CMDUID_UNLOCK)
+        {
+        // For security reasons we must check from the SCP server
+        // did this command originate from it.
+        RSCPClient scpClient;
+        if ( scpClient.Connect() == KErrNone )
+            {
+            CleanupClosePushL( scpClient );
+            if ( scpClient.QueryAdminCmd( ESCPCommandUnlockPhone ) )
+                {
+                INFO( "CLockAppAppUi::HandleMessageL(): Admin command received, unlocking" );
+                iStateControl->DisableDevicelockL();
+                }
+            else
+                {
+                INFO( "CLockAppAppUi::HandleMessageL(): Unauthorized attempt to unlock" );
+                }
+            CleanupStack::PopAndDestroy(); // calls Close() on scpClient
+            }
+        else
+            {
+            INFO( "CLockAppAppUi::HandleMessageL(): Failed to connect to SCP, ignoring unlock-message." );
+            }
+        }
+    else // aMessageUid.iUid != SCP_CMDUID_UNLOCK
+        {
+        messageResponse = CAknAppUi::HandleMessageL(
+                aClientHandleOfTargetWindowGroup,
+                aMessageUid,
+                aMessageParameters);
+        }
+    return messageResponse;
+    }
+#endif // __SAP_TERMINAL_CONTROL_FW
+
+// ----------------------------------------------------------
+// Handle window-server events
+// ----------------------------------------------------------
+void CLockAppAppUi::HandleWsEventL( const TWsEvent& aEvent, CCoeControl* aDestination )
+    {
+		RDebug::Printf( "%s %s (%u) value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+    if ( aEvent.Type() == TRawEvent::EKeyDown )
+        {
+        RDebug::Printf("CLockAppAppUi::HandleWsEventL() - aEvent.Key()->iCode: %d", aEvent.Key()->iCode );
+        }
+
+    // call super-class
+    CAknAppUi::HandleWsEventL( aEvent, aDestination );
+    // propagate call
+    iStateControl->HandleWsEventL( aEvent, aDestination);
+    }
+
+// ---------------------------------------------------------------------------
+// From @c CAknAppUiBase. Overriden the parent method, because otherwise
+// the main lock state control would not receive the call, because is is not
+// window-owning control (=without window->not visible). The call is needed
+// because the main state control owns window-owning child controls.
+// ---------------------------------------------------------------------------
+void CLockAppAppUi::HandleResourceChangeL( TInt aType )
+    {
+    // call super-class
+    CAknAppUi::HandleResourceChangeL( aType );
+    // propagate call - since does not own window
+    iStateControl->HandleResourceChange( aType );
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappbasecontrol.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,277 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Base control for logical UI components
+ *
+*/
+
+
+#include "lockappbasecontrol.h"
+#include "lockappkeycapturecontroller.h"
+#include "lockapputils.h"
+
+#include <eikenv.h>
+#include <eikbtgpc.h>
+#include <aknnotedialog.h>
+#include <AknSmallIndicator.h> // CAknSmallIndicator
+#include <AknUtils.h>
+
+// ---------------------------------------------------------------------------
+// Constructor.
+// ---------------------------------------------------------------------------
+CLockAppBaseControl::CLockAppBaseControl( MLockAppStateControl& aStateControl ) :
+    iStateControl(aStateControl), iWindowGroup( iEikonEnv->RootWin())
+    {
+	RDebug::Printf( "%s %s (%u) 1=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 1 );
+    }
+
+// ---------------------------------------------------------------------------
+// Second phase constructor.
+// ---------------------------------------------------------------------------
+void CLockAppBaseControl::ConstructL( )
+    {
+	RDebug::Printf( "%s %s (%u) 1=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 1 );
+    iKeyPattern = CLockAppKeyPattern::NewL( );
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor.
+// ---------------------------------------------------------------------------
+CLockAppBaseControl::~CLockAppBaseControl( )
+    {
+    CancelNote( );
+    if ( iActive )
+        {
+        TRAP_IGNORE(HandleDeActivateEventL( NULL ));
+        }
+    delete iCba;
+    delete iKeyPattern;
+    }
+
+// ---------------------------------------------------------------------------
+// Setup key pattern matcher.
+// ---------------------------------------------------------------------------
+TBool CLockAppBaseControl::SetupKeyPatternsWithPolicyL( TLockPolicyType aType )
+    {
+    INFO_1( "CLockAppBaseControl::SetupKeyPatternsL( type=%d )", aType );
+    TBool ret(EFalse);
+    __ASSERT_DEBUG( iKeyPattern, DoPanic(ELockIllegalState));
+    if ( iKeyPattern )
+        {
+        CKeyLockPolicyApi* keylockPolicy = CKeyLockPolicyApi::NewL( aType );
+                
+        // if the keylockpolicy has keycombinations
+        if ( keylockPolicy->HasConfiguration( ) )
+            {
+            // TESTING1!
+            INFO( "CLockAppBaseControl::SetupKeyPatternsWithPolicyL - HasConfiguration!" );
+            
+            TUint32 index(0), k1(0), k2(0);
+            while ( keylockPolicy->GetKeyCombination( index, k1, k2 )== KErrNone )
+                {
+                // TESTING2!
+                INFO( "CLockAppBaseControl::SetupKeyPatternsWithPolicyL - key combination found!" );
+                
+                // add each combination to our pattern matcher
+                iKeyPattern->AddPattern( k1, k2 );
+                index++;
+                }
+                        
+            ret = ETrue;
+            INFO_1( "CLockAppBaseControl::SetupKeyPatternsL: added %d patterns", index );
+            }
+        delete keylockPolicy;
+        }
+    return ret;
+    }
+
+// ---------------------------------------------------------------------------
+// Show note
+// ---------------------------------------------------------------------------
+void CLockAppBaseControl::ShowNote( CLockAppLockedNote* aNote, const TInt aTimeout,
+        const CAknNoteDialog::TTone aTone )
+    {
+    if ( aNote )
+        {
+        // cancel the current note if any
+        if ( iCurrentNote != aNote )
+            {
+            CancelNote( );
+            iCurrentNote = aNote;
+            }
+        iCurrentNote->ShowNote( aTimeout, aTone );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Cancel currently shown note
+// ---------------------------------------------------------------------------
+void CLockAppBaseControl::CancelNote( )
+    {
+    if ( iCurrentNote )
+        {
+        if ( iCurrentNote->IsVisible( ) )
+            {
+            iCurrentNote->CancelNote( );
+            }
+        iCurrentNote = NULL;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Internal lock state has been changed.
+// ---------------------------------------------------------------------------
+void CLockAppBaseControl::HandleLockStatusChangedL( TLockStatus aStatus )
+    {
+    switch ( aStatus )
+        {
+        case ELockNotActive:
+            break;
+        case EKeyguardActive:
+            break;
+        case EDevicelockActive:
+            break;
+        default:
+            DoPanic( ELockPanicGeneral );
+            break;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Handle activate event
+// ---------------------------------------------------------------------------
+void CLockAppBaseControl::HandleActivateEventL( TUint /*aEnvMask*/ )
+    {
+    __ASSERT_DEBUG( !iActive, DoPanic(ELockIllegalState));
+    if ( !iActive )
+        {
+        iActive = ETrue;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Handle de-activate event
+// ---------------------------------------------------------------------------
+void CLockAppBaseControl::HandleDeActivateEventL( TUint /*aEnvMask*/ )
+    {
+    __ASSERT_DEBUG( iActive, DoPanic(ELockIllegalState));
+    if ( iActive )
+        {
+        iActive = EFalse;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Capture/uncapture primary keys
+// ---------------------------------------------------------------------------
+void CLockAppBaseControl::CapturePrimaryKeys( const TBool aCapture )
+    {   
+    	RDebug::Printf( "%s %s (%u) aCapture=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aCapture );
+    	RDebug::Printf( "%s %s (%u) iKeyPattern=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iKeyPattern );
+    if ( iKeyPattern )
+        {
+        if ( aCapture )
+            {
+            // capture primary keys
+            TUint32 index( 0), primaryKey( 0), secondaryKey( 0);
+            while (iKeyPattern->GetPattern( index, primaryKey, secondaryKey )== KErrNone )
+                {
+                CLockAppKeyCaptureController::CaptureKey( primaryKey, 0, EKeyCaptureUpAndDownEvents );
+                index++;
+                }
+            }
+        else
+            {
+            // uncapture primary keys
+            TUint32 index( 0), primaryKey( 0), secondaryKey( 0);
+            while (iKeyPattern->GetPattern( index, primaryKey, secondaryKey )== KErrNone )
+                {
+                CLockAppKeyCaptureController::ReleaseKey( primaryKey );
+                index++;
+                }
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Bring keyguard cba forwards/backwards.
+// ---------------------------------------------------------------------------
+void CLockAppBaseControl::ShowCba( const TBool aShow )
+    {
+    if ( iCba )
+        {
+        RDrawableWindow* cbaWindow = iCba->ButtonGroup()->AsControl()->DrawableWindow( );
+        if ( aShow )
+            {
+            cbaWindow->SetNonFading( ETrue );
+            cbaWindow->SetOrdinalPosition( 0 );
+            iCba->MakeVisible( ETrue );
+            }
+        else
+            {
+            // hide the window
+            iCba->MakeVisible( EFalse );
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Method used for capturing/releasing pointer events when key lock is enabled.
+// Capturing is done using button/cba group window.
+// ---------------------------------------------------------------------------
+void CLockAppBaseControl::SetPointerEventCapture(const TBool aEnable )
+    {
+#ifdef RD_SCALABLE_UI_V2
+    if ( AknLayoutUtils::PenEnabled( )&& iCba )
+        {
+        // cba captures all pointer events
+        RDrawableWindow* cbaWindow = iCba->ButtonGroup()->AsControl()->DrawableWindow( );
+        if ( aEnable )
+            {
+            cbaWindow->SetPointerCapture( RWindowBase::TCaptureDragDrop );
+            }
+        else
+            {
+            cbaWindow->SetPointerCapture( RWindowBase::TCaptureDisabled );
+            }
+        cbaWindow->ClaimPointerGrab( aEnable );
+        }
+#endif // RD_SCALABLE_UI_V2
+    }
+
+// ---------------------------------------------------------------------------
+// Set Keyguard indicator on Idle.
+// ---------------------------------------------------------------------------
+void CLockAppBaseControl::SetKeyguardIndicatorStateL( const TBool aEnable )
+    {
+    CAknSmallIndicator* theIndicator = CAknSmallIndicator::NewLC( TUid::Uid( EAknIndicatorKeyguard ) );
+    if ( aEnable )
+        {
+        theIndicator->SetIndicatorStateL( EAknIndicatorStateOn );
+        }
+    else
+        {
+        theIndicator->SetIndicatorStateL( EAknIndicatorStateOff );
+        }
+    CleanupStack::PopAndDestroy( theIndicator );
+    }
+
+// ---------------------------------------------------------------------------
+// Handle environment changes (Screensaver, Telephony, etc.)
+// ---------------------------------------------------------------------------
+void CLockAppBaseControl::HandleEnvironmentChange( TUint /*aEnvMask*/, TUint /*aEventMask*/ )
+    {
+    // no implementation needed - virtual function
+    }
+
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappcenrepobserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,146 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Central Repository key observer
+ *
+*/
+
+
+#include <centralrepository.h>
+#include "lockappcenrepobserver.h"
+#include "lockapputils.h"
+
+// ---------------------------------------------------------------------------
+// Two-phased constructor.
+// ---------------------------------------------------------------------------
+CLockAppCenRepObserver* CLockAppCenRepObserver::NewL( MLockAppObserverInterface* aObserver,
+        TUid aCenRepUid, TUint32 aKeyId )
+    {
+    CLockAppCenRepObserver* self = new (ELeave) CLockAppCenRepObserver(aObserver, aCenRepUid, aKeyId);
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+CLockAppCenRepObserver::~CLockAppCenRepObserver( )
+    {
+    if ( iNotifyHandler )
+        {
+        iNotifyHandler->StopListening( );
+        delete iNotifyHandler;
+        iNotifyHandler = NULL;
+        }
+    if ( iRepository )
+        {
+        delete iRepository;
+        iRepository = NULL;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// C++ default constructor
+// ---------------------------------------------------------------------------
+CLockAppCenRepObserver::CLockAppCenRepObserver( MLockAppObserverInterface* aObserver,
+        TUid aCenRepUid, TUint32 aKeyId ) :
+    iObserver(aObserver),
+    iCenRepUid(aCenRepUid),
+    iKeyId(aKeyId)
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// Symbian OS default constructor
+// ---------------------------------------------------------------------------
+void CLockAppCenRepObserver::ConstructL( )
+    {
+    // init cenrep connection
+RDebug::Printf( "%s %s (%u) value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+    iRepository = CRepository::NewL( iCenRepUid );
+    iNotifyHandler = CCenRepNotifyHandler::NewL( *this, *iRepository,
+            CCenRepNotifyHandler::EIntKey, iKeyId );
+    iNotifyHandler->StartListeningL( );
+    }
+
+// ---------------------------------------------------------------------------
+// Gets value of the default key from CenRep.
+// ---------------------------------------------------------------------------
+TInt CLockAppCenRepObserver::GetValue(TInt& aValue )
+    {
+    return iRepository->Get( iKeyId, aValue );
+    }
+
+// ---------------------------------------------------------------------------
+// Gets value of the key from CenRep.
+// ---------------------------------------------------------------------------
+TInt CLockAppCenRepObserver::GetKeyValue(TUint32 aKey, TInt& aValue )
+    {
+    	    RDebug::Printf( "%s %s (%u) aKey=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKey );
+
+    return iRepository->Get( aKey, aValue );
+    }
+
+// ---------------------------------------------------------------------------
+// Sets a value for the default key in CenRep.
+// ---------------------------------------------------------------------------
+TInt CLockAppCenRepObserver::SetValue(TInt aValue )
+    {
+    return iRepository->Set( iKeyId, aValue );
+    }
+
+// ---------------------------------------------------------------------------
+// Sets a value for the key in CenRep.
+// ---------------------------------------------------------------------------
+TInt CLockAppCenRepObserver::SetKeyValue(TUint32 aKey, TInt aValue )
+    {
+    return iRepository->Set( aKey, aValue );
+    }
+
+// ---------------------------------------------------------------------------
+// Handles changes. Called by CenRep.
+// ---------------------------------------------------------------------------
+void CLockAppCenRepObserver::HandleNotifyInt(TUint32 aKeyId, TInt aValue )
+    {
+RDebug::Printf( "%s %s (%u) value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+    if ( aKeyId == iKeyId )
+        {
+        if ( iObserver )
+            {
+            iObserver->HandleCenRepNotify( iCenRepUid, iKeyId, aValue );
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Handles errors. Called by CenRep.
+// ---------------------------------------------------------------------------
+void CLockAppCenRepObserver::HandleNotifyError(TUint32 aId, TInt error, CCenRepNotifyHandler* /*aHandler*/)
+    {
+    ERROR_1(error, "CLockAppCenRepObserver::HandleNotifyError - %d", aId);
+    }
+
+// ---------------------------------------------------------------------------
+// Handles Repository wide reset caused generic notifications. Called by CenRep.
+// ---------------------------------------------------------------------------
+void CLockAppCenRepObserver::HandleNotifyGeneric(TUint32 aId )
+    {
+    if ( aId == NCentralRepositoryConstants::KInvalidNotificationId )
+        {
+        // TODO implement what to do in this case
+        }
+    }
+
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappdevicelockcontainer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,300 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Devicelock Background UI (window owning control)
+ *
+*/
+
+
+// INCLUDE FILES
+#include "lockappdevicelockcontainer.h"
+#include "lockapputils.h"
+
+#include <eikenv.h>
+#include <lockapp.mbg>
+#include <avkon.hrh>
+#include <aknlayoutscalable_avkon.cdl.h>
+#include <aknlayoutscalable_apps.cdl.h>
+#include <AknsLayeredBackgroundControlContext.h>
+#include <AknsDrawUtils.h>
+#include <AknBitmapAnimation.h>
+#include <AknsUtils.h>
+#include <AknUtils.h>
+#include <aknappui.h>
+
+#include <layoutmetadata.cdl.h>
+#include <data_caging_path_literals.hrh>
+#include <eikdef.h>
+
+_LIT(LOCKBITMAPNAME, "AutoLock.mbm"); // TODO change filename
+
+// CONSTANTS
+
+#ifdef RD_FULLSCREEN_WALLPAPER
+enum TAutolockBgLayers
+    {
+    EAutolockBgLayerWallpaper = 0,
+    EAutolockBgLayerBackground = 1,
+    EAutolockBgLayersN = 2
+    };
+#else
+enum TAutolockBgLayers
+    {
+    EAutolockBgLayerBackground = 0,
+    EAutolockBgLayerWallpaper = 1,
+    EAutolockBgLayersN = 2
+    };
+#endif //RD_FULLSCREEN_WALLPAPER
+
+// ---------------------------------------------------------------------------
+// Standard Symbian OS construction sequence
+// ---------------------------------------------------------------------------
+CLockAppDevicelockContainer* CLockAppDevicelockContainer::NewL( RWindowGroup& aWg )
+    {
+    CLockAppDevicelockContainer* self = new (ELeave) CLockAppDevicelockContainer( );
+    CleanupStack::PushL( self );
+    self->ConstructL( aWg );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------
+// Symbian OS two phased constructor
+// ---------------------------------------------------------
+void CLockAppDevicelockContainer::ConstructL( RWindowGroup& aWg )
+    {
+    INFO( "CLockAppDevicelockContainer::ConstructL started" );
+
+    CreateWindowL( aWg );
+    MakeVisible( EFalse );
+
+    HBufC* bitMapPath = HBufC::NewLC( KMaxPath );
+    TPtr BitmapFile( bitMapPath->Des( ) );
+    BitmapFile.Append( _L("Z:") );
+    BitmapFile.Append( KDC_APP_BITMAP_DIR );
+    BitmapFile.Append( LOCKBITMAPNAME );
+
+    TRect mainPaneRect = GetMainPaneRect( );
+
+    iClock = NULL;
+    iEikBitmap = NULL;
+    AknsUtils::CreateIconL( AknsUtils::SkinInstance( ), KAknsIIDQgnGrafPhoneLocked, iBitmap, iMask,
+            BitmapFile, EMbmLockappQgn_graf_phone_locked, EMbmLockappQgn_graf_phone_locked_mask );
+
+#ifdef RD_FULLSCREEN_WALLPAPER
+    TSize screenSize = iCoeEnv->ScreenDevice()->SizeInPixels( );
+    TRect wallpaperRect( TPoint( 0, 0 ), screenSize);
+    iBgContext = CAknsLayeredBackgroundControlContext::NewL( KAknsIIDWallpaper, wallpaperRect,
+            ETrue, EAutolockBgLayersN );
+#else
+    // Create background control context for skins. Use parent absolute mode,
+    // as this is window owning control
+    iBgContext = CAknsLayeredBackgroundControlContext::NewL(
+            KAknsIIDQsnBgAreaMainIdle, mainPaneRect, ETrue, EAutolockBgLayersN );
+    iBgContext->SetLayerImage( EAutolockBgLayerWallpaper, KAknsIIDWallpaper );
+    iBgContext->SetLayerRect( EAutolockBgLayerWallpaper, mainPaneRect );
+#endif // RD_FULLSCREEN_WALLPAPER
+
+    SetRect( mainPaneRect );
+    CleanupStack::PopAndDestroy( bitMapPath ); //bitMapPath
+    INFO( "CLockAppDevicelockContainer::ConstructL completed" );
+    }
+
+// ---------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------
+CLockAppDevicelockContainer::~CLockAppDevicelockContainer( )
+    {
+    delete iBgContext;
+    delete iBitmap;
+    delete iMask;
+    delete iClock;
+    }
+
+// ---------------------------------------------------------
+// Return the rectangle for this control
+// ---------------------------------------------------------
+TRect CLockAppDevicelockContainer::GetMainPaneRect( )
+    {
+    TRect screen( iAvkonAppUi->ApplicationRect());
+    TAknLayoutRect applicationWindow;
+    applicationWindow.LayoutRect( screen, AknLayoutScalable_Avkon::application_window( 0 ) );
+    TInt mainPaneVariety = ( Layout_Meta_Data::IsLandscapeOrientation() ? 4 : 3 );
+    TAknLayoutRect mainPane;
+    mainPane.LayoutRect( applicationWindow.Rect( ),
+            AknLayoutScalable_Avkon::main_pane( mainPaneVariety ) );
+    return mainPane.Rect( );
+    }
+
+// ---------------------------------------------------------
+// Called by framework when the view size is changed
+// ---------------------------------------------------------
+void CLockAppDevicelockContainer::SizeChanged()
+    {
+    INFO( "CLockAppDevicelockContainer::SizeChanged" );
+    TRect mainPaneRect( Rect( ));
+    TAknLayoutRect idleTradPane;
+    idleTradPane.LayoutRect( mainPaneRect, AknLayoutScalable_Avkon::main_idle_trad_pane( ) );
+
+    TInt variety = ( Layout_Meta_Data::IsLandscapeOrientation() ? 2 : 3 );
+
+    TAknLayoutRect idlePaneG2;
+    idlePaneG2.LayoutRect( idleTradPane.Rect( ),
+            AknLayoutScalable_Avkon::main_idle_pane_g2( variety ) );
+    AknIconUtils::SetSize( iBitmap, idlePaneG2.Rect().Size( ) );
+
+    TPoint parentPos( 0, 0);
+#ifdef RD_FULLSCREEN_WALLPAPER
+    TSize screenSize = iCoeEnv->ScreenDevice()->SizeInPixels( );
+    TRect wallpaperRect( TPoint( 0, 0 ), screenSize);
+    iBgContext->SetLayerRect( EAutolockBgLayerBackground, Rect( ) );
+    iBgContext->SetLayerRect( EAutolockBgLayerWallpaper, wallpaperRect );
+#else
+    iBgContext->SetLayerRect( EAutolockBgLayerBackground, Rect() );
+    iBgContext->SetLayerRect( EAutolockBgLayerWallpaper, Rect() );
+    //parent must be set when using parent absolute mode.
+    parentPos = PositionRelativeToScreen();
+#endif //RD_FULLSCREEN_WALLPAPER
+
+    iBgContext->SetParentPos( parentPos );
+
+    if ( !Layout_Meta_Data::IsLandscapeOrientation() )
+        {
+        // the screen is in portrait mode
+        if ( iClock )
+            {
+            // remove clock, if it exists
+            delete iClock;
+            iClock = NULL;
+            }
+        RRegion autolockRegion;
+#ifdef  RD_FULLSCREEN_WALLPAPER
+        autolockRegion.AddRect( wallpaperRect );
+#else
+        autolockRegion.AddRect( Rect() );
+#endif //RD_FULLSCREEN_WALLPAPER
+        Window().SetShape( autolockRegion );
+        autolockRegion.Close( );
+        }
+    else
+        {
+        // the screen is in landscape mode.
+        // get the correct area from layout utils.
+        TAknLayoutRect popupClockDigitalAnalogueWindowLayoutRect;
+        popupClockDigitalAnalogueWindowLayoutRect.LayoutRect( idleTradPane.Rect( ),
+                AknLayoutScalable_Avkon::popup_clock_digital_analogue_window( 3 ) );
+        TRect popupClockDigitalAnalogueWindowRect(popupClockDigitalAnalogueWindowLayoutRect.Rect( ));
+
+        // since the clock is not shown in app shell when the screen is in landscape,
+        // we'll show a clock here.
+        if ( !iClock )
+            {
+            TRAP_IGNORE({
+                        CAknSkinnableClock* clock = CAknSkinnableClock::NewL( this, ETrue, EFalse );
+                        CleanupStack::PushL( clock );
+                        clock->SetRect( popupClockDigitalAnalogueWindowRect );
+                        clock->ActivateL();
+                        CleanupStack::Pop( clock );
+                        iClock = clock;
+                        });
+            }
+        else
+            {
+            iClock->SetRect( popupClockDigitalAnalogueWindowRect );
+            }
+        RRegion autolockRegion;
+#ifdef RD_FULLSCREEN_WALLPAPER
+        autolockRegion.AddRect( wallpaperRect );
+#else
+        autolockRegion.AddRect( Rect() );
+#endif //RD_FULLSCREEN_WALLPAPER
+        autolockRegion.AddRect( iClock->Rect( ) );
+        Window().SetShape( autolockRegion );
+        autolockRegion.Close( );
+        }
+     }
+
+// ---------------------------------------------------------
+// CLockAppDevicelockContainer::CountComponentControls() const
+// ---------------------------------------------------------
+TInt CLockAppDevicelockContainer::CountComponentControls( ) const
+    {
+    TInt controlCount = 0;
+    if ( Layout_Meta_Data::IsLandscapeOrientation( ) )
+        {
+        if ( iClock )
+            {
+            controlCount++;
+            }
+        }
+    return controlCount;
+    }
+
+// ---------------------------------------------------------
+// CLockAppDevicelockContainer::ComponentControl(TInt aIndex) const
+// ---------------------------------------------------------
+CCoeControl* CLockAppDevicelockContainer::ComponentControl(TInt /*aIndex*/) const
+    {
+    return iClock;
+    }
+
+// ---------------------------------------------------------
+// CLockAppDevicelockContainer::Draw(const TRect& aRect) const
+// ---------------------------------------------------------
+void CLockAppDevicelockContainer::Draw(const TRect& aRect) const
+    {
+    CWindowGc& gc = SystemGc( );
+    gc.SetPenStyle( CGraphicsContext::ENullPen );
+    gc.SetBrushColor( KRgbWhite );
+    gc.SetBrushStyle( CGraphicsContext::ESolidBrush );
+    MAknsSkinInstance* skin = AknsUtils::SkinInstance( );
+    MAknsControlContext* cc = AknsDrawUtils::ControlContext( this );
+    AknsDrawUtils::Background( skin, cc, this, gc, aRect );
+
+    if ( iBitmap )
+        {
+        // Draw "lock" icon centered to this control
+        TInt x = (Rect().Width( ) - iBitmap->SizeInPixels().iWidth) / 2;
+        TInt y = (Rect().Height( ) - iBitmap->SizeInPixels().iHeight) / 2;
+        if ( iMask )
+            {
+            gc.BitBltMasked( TPoint( x, y ), iBitmap, TRect( TPoint( 0, 0 ),
+                    iBitmap->SizeInPixels( ) ), iMask, ETrue );
+            }
+        else
+            {
+            gc.BitBlt( TPoint( x, y ), iBitmap );
+            }
+        }
+    }
+
+// ---------------------------------------------------------
+// CLockAppDevicelockContainer::HandleControlEventL( CCoeControl* aControl,TCoeEvent aEventType)
+// ---------------------------------------------------------
+void CLockAppDevicelockContainer::HandleControlEventL(CCoeControl* /*aControl*/, TCoeEvent /*aEventType*/)
+    {
+    }
+
+// ---------------------------------------------------------
+// CLockAppDevicelockContainer::MopSupplyObject
+// ---------------------------------------------------------
+TTypeUid::Ptr CLockAppDevicelockContainer::MopSupplyObject( TTypeUid aId )
+    {
+    if ( aId.iUid == MAknsControlContext::ETypeId )
+        {
+        return MAknsControlContext::SupplyMopObject( aId, iBgContext );
+        }
+    return CCoeControl::MopSupplyObject( aId );
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappdevicelockcontrol.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1178 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Devicelock UI
+ *
+*/
+
+
+#include "lockappdevicelockcontrol.h"
+#include "lockappdevicelockcontainer.h"
+#include "lockappstatecontrolinterface.h"
+#include "lockapppubsubobserver.h"
+#include "lockappcenrepobserver.h"
+#include "lockapputils.h"
+#include "lockappwait.h"
+#include "lockappkeycapturecontroller.h"
+
+#include <lockapp.rsg> // general avkon resources
+#include <avkon.rsg> // general avkon resources
+#include <aknnotpi.rsg> // keyguard spesific resources
+#include <AknUtils.h>
+#include <akntitle.h> // CAknTitlePane
+#include <activitymanager.h>
+#include <e32property.h>
+#include <etelmm.h>
+#include <mmtsy_names.h>
+#include <featmgr.h>
+#include <secui.h>
+#include <SecUiSecurityHandler.h>
+
+#include <settingsinternalcrkeys.h>  // KSettingsAutolockStatus
+#include <coreapplicationuisdomainpskeys.h>
+#include <securityuisprivatepskeys.h>
+#include <startupdomainpskeys.h>
+#include <startupdomaincrkeys.h>
+#include <ctsydomainpskeys.h>
+
+#ifdef __SAP_TERMINAL_CONTROL_FW
+#include <SCPClient.h>
+#endif // __SAP_TERMINAL_CONTROL_FW
+
+const TInt KAutoDeviceLockOff( 60000 );
+const TInt KPhoneIndex( 0 );
+const TInt KTriesToConnectServer( 2 );
+const TInt KTimeBeforeRetryingServerConnection( 50000 );
+
+// ---------------------------------------------------------------------------
+// Standard Symbian OS construction sequence
+// ---------------------------------------------------------------------------
+CLockAppDevicelockControl* CLockAppDevicelockControl::NewL(MLockAppStateControl& aStateControl, RWindowGroup& aWg )
+    {
+    CLockAppDevicelockControl* self = new (ELeave) CLockAppDevicelockControl( aStateControl );
+    RDebug::Printf( "%s %s (%u) self=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, self );
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aWg );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Constructor passes the reference to the main state control.
+// ---------------------------------------------------------------------------
+CLockAppDevicelockControl::CLockAppDevicelockControl(MLockAppStateControl& aStateControl) :
+    CLockAppBaseControl(aStateControl), iShowingSecCodeQuery(EFalse)
+    {
+    	RDebug::Printf( "%s %s (%u) value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor.
+// ---------------------------------------------------------------------------
+CLockAppDevicelockControl::~CLockAppDevicelockControl( )
+    {
+    	RDebug::Printf( "%s %s (%u) value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+
+    /*****************************************************
+    *    S60 Customer / ETel
+    *    S60  ETel API
+    *****************************************************/
+    /*****************************************************
+    *    S60 Customer / TSY
+    *    Needs customer TSY implementation
+    *****************************************************/
+    RDebug::Printf( "%s %s (%u) iCustomPhoneInitialized=%x -> -1 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iCustomPhoneInitialized );
+    iCustomPhoneInitialized=-1;
+    if ( iCustomPhone.SubSessionHandle( ) )
+        {
+        iCustomPhone.Close( );
+        RDebug::Printf( "%s %s (%u) iCustomPhoneInitialized=%x -> -2 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iCustomPhoneInitialized );
+        iCustomPhoneInitialized=-2;
+        }
+
+		RDebug::Printf( "%s %s (%u) iPhoneInitialized=%x -> -1 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iPhoneInitialized );
+		iPhoneInitialized=-1;
+    if ( iPhone.SubSessionHandle( ) )
+        {
+        iPhone.Close( );
+        RDebug::Printf( "%s %s (%u) iPhoneInitialized=%x -> -2 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iPhoneInitialized );
+				iPhoneInitialized=-2;
+        }
+
+    RDebug::Printf( "%s %s (%u) iTelServerInitialized=%x -> -1 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iTelServerInitialized );
+    iTelServerInitialized=-1;
+    if ( iTelServer.Handle( ) )
+        {
+        iTelServer.UnloadPhoneModule( KMmTsyModuleName );
+        iTelServer.Close( );
+        RDebug::Printf( "%s %s (%u) iTelServerInitialized=%x -> -2 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iTelServerInitialized );
+        iTelServerInitialized=-2;
+        }
+    if ( iActivityManager )
+        {
+        iActivityManager->Cancel( );
+        delete iActivityManager;
+        iActivityManager = NULL;
+        }
+    // CenRep observers
+    if ( iCRAutoLockTime )
+        {
+        delete iCRAutoLockTime;
+        iCRAutoLockTime = NULL;
+        }
+    if ( iCRAutoLockStatus )
+        {
+        delete iCRAutoLockStatus;
+        iCRAutoLockStatus = NULL;
+        }
+    // PuSub observers
+    if ( iPSAutolockState )
+        {
+        delete iPSAutolockState;
+        iPSAutolockState = NULL;
+        }
+    if ( iContainer )
+        {
+        delete iContainer;
+        iContainer = NULL;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Devicelock UI constructor reserves localized resources, configures itself
+// using CenRep and FeatureManager and reserves child controls.
+// ---------------------------------------------------------------------------
+void CLockAppDevicelockControl::ConstructL( RWindowGroup& aWg )
+    {
+    INFO( "CLockAppDevicelockControl::ConstructL started" );
+    CLockAppBaseControl::ConstructL( );
+
+    // feature manager is used for determining if the phone is a slider
+    FeatureManager::InitializeLibL( );
+    iFeatureProtocolCdma = FeatureManager::FeatureSupported( KFeatureIdProtocolCdma );
+    INFO_1("CLockAppDevicelockControl::ConstructL - iFeatureProtocolCdma: %d", iFeatureProtocolCdma);
+    FeatureManager::UnInitializeLib( );
+
+    // Cba control
+    iCba = CEikButtonGroupContainer::NewL( CEikButtonGroupContainer::ECba,
+            CEikButtonGroupContainer::EHorizontal, this,
+            R_KEYLOCK_SOFTKEYS_UNLOCK_EMPTY );
+
+    TRect screenRect;
+    AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::EScreen, screenRect );
+    iCba->SetBoundingRect( screenRect );
+    iCba->MakeVisible( EFalse );
+
+    // Set up the status pane
+    CEikStatusPane* sp = iAvkonAppUi->StatusPane();
+    if ( sp )
+        {
+        // Switch the layout to show analog clock
+        TRAPD(err, sp->SwitchLayoutL( R_AVKON_STATUS_PANE_LAYOUT_IDLE ) )
+        ERROR(err, "CLockAppDevicelockControl::ConstructL - failed to switch status pane layout");
+        if ( sp->PaneCapabilities(TUid::Uid(EEikStatusPaneUidTitle)).IsPresent( ) )
+            {
+            // Get the title pane control from status pane
+            CAknTitlePane* titlePane = NULL;
+            TRAPD(err2, titlePane = static_cast<CAknTitlePane*>( sp->ControlL( TUid::Uid( EEikStatusPaneUidTitle) ) ) )
+            ERROR(err2, "CLockAppDevicelockControl::ConstructL - failed to get status title pane");
+            if ( titlePane )
+                {
+                // Read localized "Locked" text from resource.
+                HBufC* lockedString = iCoeEnv->AllocReadResourceL( R_TITLE_PANE_LOCKED );
+                // Set as title pane text - titlepane takes ownership of the string
+                titlePane->SetText( lockedString );
+                }
+            }
+        }
+
+    INFO( "CLockAppDevicelockControl::ConstructL completed" );
+    }
+
+void CLockAppDevicelockControl::ConnectToPhoneL( RWindowGroup& aWg )
+		{
+    INFO( "CLockAppDevicelockControl::ConnectToPhoneL - connecting to etel server" );
+    // All server connections are tried to be made KTiesToConnectServer times because
+    // occasional fails on connections are possible at least on some servers
+    TInt err( KErrGeneral);
+    TInt thisTry( 0);
+    while ( ( err = iTelServer.Connect() ) != KErrNone && ( thisTry++ ) <= KTriesToConnectServer )
+        {
+        User::After( KTimeBeforeRetryingServerConnection );
+        }
+    ERROR(err, "CLockAppDevicelockControl::ConnectToPhoneL - connecting to etel server");
+    User::LeaveIfError( err );
+    RDebug::Printf( "%s %s (%u) iTelServerInitialized=%x -> 2 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iTelServerInitialized );
+    iTelServerInitialized=2;
+
+
+    /*****************************************************
+    *    S60 Customer / ETel
+    *    S60  ETel API
+    *****************************************************/
+    /*****************************************************
+    *    S60 Customer / TSY
+    *    Needs customer TSY implementation
+    *****************************************************/
+    INFO( "CLockAppDevicelockControl::ConnectToPhoneL - loading TSY");
+    err = iTelServer.LoadPhoneModule( KMmTsyModuleName );
+    if ( err != KErrAlreadyExists )
+        {
+        // may return also KErrAlreadyExists if some other
+        // is already loaded the tsy module. And that is not an error.
+        ERROR(err, "CLockAppDevicelockControl::ConnectToPhoneL - loading TSY");
+        User::LeaveIfError( err );
+        }
+    RDebug::Printf( "%s %s (%u) iTelServerInitialized=%x -> 3 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iTelServerInitialized );
+    iTelServerInitialized=3;
+
+    /*****************************************************
+    *    S60 Customer / ETel
+    *    S60  ETel API
+    *****************************************************/
+    INFO( "CLockAppDevicelockControl::ConnectToPhoneL - opening phone");
+    RTelServer::TPhoneInfo PhoneInfo;
+    User::LeaveIfError( iTelServer.SetExtendedErrorGranularity( RTelServer::EErrorExtended ) );
+    RDebug::Printf( "%s %s (%u) iTelServerInitialized=%x -> 5 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iTelServerInitialized );
+    iTelServerInitialized=5;
+    User::LeaveIfError( iTelServer.GetPhoneInfo( KPhoneIndex, PhoneInfo ) );
+    RDebug::Printf( "%s %s (%u) iTelServerInitialized=%x -> 6 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iTelServerInitialized );
+    iTelServerInitialized=6;
+    User::LeaveIfError( iPhone.Open( iTelServer, PhoneInfo.iName ) );
+		RDebug::Printf( "%s %s (%u) iPhoneInitialized=%x -> 2 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iPhoneInitialized );
+		iPhoneInitialized=2;
+    User::LeaveIfError( iCustomPhone.Open( iPhone ) );
+		RDebug::Printf( "%s %s (%u) iCustomPhoneInitialized=%x -> 2 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iCustomPhoneInitialized );
+		iCustomPhoneInitialized=2;
+
+    INFO( "CLockAppDevicelockControl::ConnectToPhoneL - phone opened");
+
+
+    TBool systemLocked(EFalse);
+
+    // Set up CenRep observers
+    iCRAutoLockTime = CLockAppCenRepObserver::NewL(this, KCRUidSecuritySettings, KSettingsAutoLockTime);
+    iCRAutoLockStatus = CLockAppCenRepObserver::NewL(this, KCRUidSecuritySettings, KSettingsAutolockStatus);
+
+    #ifndef __WINS__
+
+    /*****************************************************
+    *    S60 Customer / ETel
+    *    S60 ETel API
+    *****************************************************/
+
+    RMobilePhone::TMobilePhoneLock lockType = RMobilePhone::ELockPhoneDevice;
+    RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;
+    RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
+
+    TRequestStatus getLockInfoStatus;
+    iPhone.GetLockInfo( getLockInfoStatus, lockType, lockInfoPkg );
+		RDebug::Printf( "%s %s (%u) iPhoneInitialized=%x -> 3 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iPhoneInitialized );
+		iPhoneInitialized=3;
+    User::WaitForRequest( getLockInfoStatus );
+
+    TInt lockValue(0);
+    TInt cRresult = iCRAutoLockStatus->GetValue( lockValue );
+    INFO_2( "CLockAppDevicelockControl::ConnectToPhoneL - CR autolockstatus=%d , res=%d", lockValue, cRresult);
+    TBool hiddenReset = IsHiddenReset( );
+    INFO_1( "CLockAppDevicelockControl::ConnectToPhoneL - hiddenReset=%d", hiddenReset );
+    if ( lockInfo.iSetting == RMobilePhone::ELockSetDisabled )
+        {
+        INFO( "CLockAppDevicelockControl::ConnectToPhoneL - ELockSetDisabled");
+        iCRAutoLockTime->SetValue( 0 );
+        if ( iFeatureProtocolCdma )
+            {
+            iCRAutoLockTime->SetKeyValue( KSettingsLockOnPowerUp, 0 );
+            }
+        }
+    else
+        {
+        if ( iFeatureProtocolCdma || (hiddenReset && (lockValue == 1)) )
+            {
+            // In CDMA, the system can stay locked on after the boot-up sequence.
+            INFO( "CLockAppDevicelockControl::ConnectToPhoneL - Hidden reset when locked");
+            systemLocked = ETrue;
+            }
+        }
+    #endif //__WINS__
+
+    // Create devicelock UI container
+    INFO_1( "CLockAppDevicelockControl::ConnectToPhoneL - creating CLockAppDevicelockContainer=%d", 1 );
+    iContainer = CLockAppDevicelockContainer::NewL( aWg );
+    INFO_1( "CLockAppDevicelockControl::ConnectToPhoneL - creating CLockAppDevicelockContainer=%d done", 1 );
+
+    INFO_1( "CLockAppDevicelockControl::ConnectToPhoneL - creating DefinePubSubKeysL=%d", 1 );
+    DefinePubSubKeysL( );
+    INFO_1( "CLockAppDevicelockControl::ConnectToPhoneL - creating DefinePubSubKeysL=%d", 1 );
+
+    // The following sequence is used to validate the configuration on SCP server.
+    // This is needed on the first boot (initial or RFS) or if the C-drive
+    // has been formatted (3-button format) and Autolock is not active.
+#ifdef __SAP_TERMINAL_CONTROL_FW
+		// This seems to be defined always.
+    INFO( "CLockAppDevicelockControl::ConnectToPhoneL - Validate SCP Config" );
+    RSCPClient scpClient;
+    if ( scpClient.Connect() == KErrNone )
+        {
+        CleanupClosePushL( scpClient );
+        TInt confStatus = scpClient.CheckConfiguration( KSCPInitial );
+        if ( confStatus == KErrAccessDenied )
+            {
+#ifndef __WINS__
+            if ( ( lockInfo.iSetting == RMobilePhone::ELockSetDisabled ) )
+#else // __WINS__
+            if ( ETrue ) // DOS lock is never active in WINS
+#endif // __WINS__
+                {
+                // DOS lock is not active. Note that if DOS is locked, checking the code here will
+                // mess up the query sequence. On initial startup DOS is not locked.
+                TInt finalConfStatus = scpClient.CheckConfiguration( KSCPComplete );
+                if ( finalConfStatus == KErrAccessDenied )
+                    {
+#ifdef __WINS__
+                    ERROR(finalConfStatus, "CLockAppDevicelockControl::ConnectToPhoneL - DOS validation FAILED in WINS!");
+#else // !__WINS__
+                    // The SCP server is out of sync and Autolock is not active. (c-drive formatted)
+                    // We must ask the security code. ( Note that it is very rare that this is executed )
+                    INFO( "CLockAppDevicelockControl::ConnectToPhoneL - Lock setting disabled, calling setlocksetting");
+
+                    // Wait here until the startup is complete
+                    TInt tarmErr(KErrNone);
+                    while ( tarmErr == KErrNone )
+                        {
+                        TInt sysState;
+                        tarmErr = RProperty::Get(KPSUidStartup, KPSGlobalSystemState, sysState);
+                        if ((sysState == ESwStateNormalRfOn) ||
+                            (sysState == ESwStateNormalRfOff) ||
+                            (sysState == ESwStateNormalBTSap))
+                            {
+                            break;
+                            }
+                        User::After(500000); // half a second
+                        }
+
+                    // Just change the lock setting again to disabled to request the security code.
+                    // Set the TARM flag so SecUi knows it should display the "login" query.
+                    TInt tarmFlag;
+                    TInt tRet = RProperty::Get( KSCPSIDAutolock, SCP_TARM_ADMIN_FLAG_UID, tarmFlag );
+                    if ( tRet == KErrNone )
+                        {
+                        tarmFlag |= KSCPFlagResyncQuery;
+                        tRet = RProperty::Set( KSCPSIDAutolock, SCP_TARM_ADMIN_FLAG_UID, tarmFlag );
+                        }
+                    ERROR(tRet, "CLockAppDevicelockControl::ConnectToPhoneL - FAILED to set TARM Admin Flag" );
+
+                    TRequestStatus setLockSettingStatus;
+                    RMobilePhone::TMobilePhoneLockSetting lockChange = RMobilePhone::ELockSetDisabled;
+                    iPhone.SetLockSetting( setLockSettingStatus, lockType, lockChange );
+                    User::WaitForRequest( setLockSettingStatus );
+#endif // __WINS__
+                    }
+                }
+            }
+        CleanupStack::PopAndDestroy(); // calls Close() on scpClient
+        }
+#endif // __SAP_TERMINAL_CONTROL_FW
+
+    // Set up P&S observers
+    iPSAutolockState = CLockAppPubSubObserver::NewL( this, KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus );
+
+    if ( systemLocked )
+        {
+        INFO( "CLockAppDevicelockControl::ConnectToPhoneL - Lock system");
+        RDebug::Printf( "%s %s (%u) 1=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 1 );
+        iStateControl.EnableDevicelockL( EDevicelockManual );
+        INFO( "CLockAppDevicelockControl::ConnectToPhoneL - Lock system. Done");
+        }
+
+    // Activity manager
+    iActivityManager = CUserActivityManager::NewL( CActive::EPriorityStandard );
+    StartActivityMonitoringL( );
+
+    // Setup key pattern matcher
+    if ( !SetupKeyPatternsWithPolicyL( EPolicyDevicelockQuery ) )
+        {
+        INFO( "CLockAppDevicelockControl::ConnectToPhoneL - No CenRep policy defined" );
+        iKeyPattern->AddPattern( EStdKeyDevice0, 0 ); // '0' = second key code doesnt matter
+        }
+#ifdef __WINS__
+    iKeyPattern->AddPattern( EStdKeyDevice0, 0 ); // LSK + *
+#endif
+
+    INFO( "CLockAppDevicelockControl::ConstructL completed" );
+    }
+
+// ---------------------------------------------------------------------------
+// Define internal P&S autolock status key
+// ---------------------------------------------------------------------------
+void CLockAppDevicelockControl::DefinePubSubKeysL()
+    {
+    INFO( "CLockAppDevicelockControl::DefinePubSubKeysL" );
+
+    // Create the write policy. Also processes with write device data can write the value.
+    TSecurityPolicy writePolicy( ECapabilityWriteDeviceData );
+    // Create the read policy. Also processes with read device data can read the value.
+    TSecurityPolicy readPolicy( ECapabilityReadDeviceData );
+
+    TInt ret = RProperty::Define( KPSUidSecurityUIs,
+            KSecurityUIsSecUIOriginatedQuery, RProperty::EInt, readPolicy, writePolicy );
+    ERROR(ret, "CLockAppDevicelockControl::DefinePubSubKeysL - FAILED to define the SECUI query Flag");
+
+    ret = RProperty::Define( KPSUidSecurityUIs,
+            KSecurityUIsQueryRequestCancel, RProperty::EInt, readPolicy, writePolicy );
+    ERROR(ret, "CLockAppDevicelockControl::DefinePubSubKeysL - FAILED to define the SECUI query request state Flag");
+
+    _LIT_SECURITY_POLICY_PASS(KReadPolicy);
+    _LIT_SECURITY_POLICY_C1(KWritePolicy, ECapabilityWriteDeviceData);
+    ret = RProperty::Define( KPSUidCoreApplicationUIs,
+            KCoreAppUIsAutolockStatus, RProperty::EInt, KReadPolicy, KWritePolicy);
+    RProperty::Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, EAutolockOff);
+    if (ret != KErrAlreadyExists)
+        {
+        ERROR(ret, "CLockAppDevicelockControl::DefinePubSubKeysL - FAILED to set autolock status");
+        User::LeaveIfError(ret);
+        }
+
+    #ifdef __SAP_TERMINAL_CONTROL_FW
+    // Define the TARM admin flag.
+    ret = RProperty::Define( KSCPSIDAutolock,
+            SCP_TARM_ADMIN_FLAG_UID, RProperty::EInt, readPolicy, writePolicy );
+    ERROR(ret, "CLockAppDevicelockControl::DefinePubSubKeysL - FAILED to define the TARM Admin Flag");
+    #endif // __SAP_TERMINAL_CONTROL_FW
+    }
+
+// ----------------------------------------------------------
+// Checks whether we are booting from a Hidden Reset
+// ----------------------------------------------------------
+TBool CLockAppDevicelockControl::IsHiddenReset( )
+    {
+    	    	RDebug::Printf( "%s %s (%u) value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+
+    TBool ret( EFalse );
+    TInt startupReason( ENormalStartup );
+    TInt err( KErrNone);
+    err = RProperty::Get( KPSUidStartup, KPSStartupReason, startupReason );
+    ERROR(err, "CLockAppDevicelockControl::IsHiddenReset - error getting startup reason" );
+    ret = (startupReason != ENormalStartup);
+    INFO_1( "CLockAppDevicelockControl::IsHiddenReset = %d", ret );
+		#ifdef _DEBUG
+			// test to simulate HiddenReset
+			RFs fs;
+			_LIT(KTestHiddenReset,"f:\\TestHiddenReset.txt");
+			RFile file;
+			User::LeaveIfError(fs.Connect());
+			err=file.Open(fs, KTestHiddenReset, EFileStreamText|EFileRead|EFileShareReadersOnly);
+			if(err==KErrNone)
+				{
+				RDebug::Printf( "%s %s (%u) ??? TestHiddenReset=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 1 );
+				ret = ETrue;
+				}
+			file.Close();
+			fs.Close();
+		#endif
+    return ret;
+    }
+
+// ----------------------------------------------------------
+// Checks whether PIN1/UPIN is blocked
+// ----------------------------------------------------------
+TBool CLockAppDevicelockControl::IsPinBlocked( )
+    {
+    INFO( "CLockAppDevicelockControl::IsPinBlocked" );
+    TBool ret( EFalse );
+    RMmCustomAPI::TSecurityCodeType secCodeType;
+#if defined(__PROTOCOL_WCDMA) || defined(__UPIN)
+    RMobilePhone::TMobilePhoneSecurityCode activePin;
+    iCustomPhone.GetActivePin( activePin );
+    if ( activePin == RMobilePhone::ESecurityUniversalPin )
+        secCodeType = RMmCustomAPI::ESecurityUniversalPin;
+    else
+        secCodeType = RMmCustomAPI::ESecurityCodePin1;
+#else
+    secCodeType = RMmCustomAPI::ESecurityCodePin1;
+#endif //(__PROTOCOL_WCDMA) || defined(__UPIN)
+    iCustomPhone.IsBlocked( secCodeType, ret );
+    INFO_1( "CLockAppDevicelockControl::IsPinBlocked = %d", ret );
+    return ret;
+    }
+
+// ----------------------------------------------------------
+// Try to get (and optionally unset) the TARM Admin Flag
+// ----------------------------------------------------------
+TBool CLockAppDevicelockControl::TarmAdminFlag( TBool unSetFlag )
+    {
+    INFO_1( "CLockAppDevicelockControl::TarmAdminFlag(unSet = %d)", unSetFlag );
+    TBool ret(EFalse);
+#ifdef __SAP_TERMINAL_CONTROL_FW
+    // Get the TARM admin flag value
+    TInt tarmFlag;
+    TInt err = RProperty::Get( KSCPSIDAutolock, SCP_TARM_ADMIN_FLAG_UID, tarmFlag );
+    if ( err != KErrNone )
+        {
+        ERROR(err, "CLockAppDevicelockControl::TarmAdminFlag - Failed to get TARM flag" );
+        }
+    else
+        {
+        INFO_1( "CLockAppDevicelockControl::TarmAdminFlag - TARM flag: %d", tarmFlag );
+        }
+
+    if ( tarmFlag & KSCPFlagAdminLock )
+        {
+        ret = ETrue;
+        // Unset the TARM admin flag if set
+        if ( unSetFlag )
+            {
+            tarmFlag &= ~KSCPFlagAdminLock;
+            err = RProperty::Set( KSCPSIDAutolock, SCP_TARM_ADMIN_FLAG_UID, tarmFlag );
+            ERROR(err, "CLockAppDevicelockControl::TarmAdminFlag - FAILED to unset TARM flag" );
+            }
+        }
+#endif // __SAP_TERMINAL_CONTROL_FW
+    INFO_1( "CLockAppDevicelockControl::TarmAdminFlag = %d", ret );
+    return ret;
+    }
+
+// ---------------------------------------------------------------------------
+// Check ETEL lock info and ask sec code if neccessary
+// ---------------------------------------------------------------------------
+TBool CLockAppDevicelockControl::ETelActivationAllowed( )
+    {
+    INFO( "CLockAppDevicelockControl::ETelActivationAllowed" );
+    TBool ret(EFalse);
+#ifdef __WINS__
+    ret = ETrue;
+#else //__WINS__
+
+    /*****************************************************
+    *    S60 Customer / ETel
+    *    S60  ETel API
+    *****************************************************/
+
+
+		RDebug::Printf( "%s %s (%u) 111 value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+
+    // RDebug::Printf( "%s %s (%u) iStateControl=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iStateControl );
+
+		RDebug::Printf( "%s %s (%u) checking iPhoneInitialized=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+		RDebug::Printf( "%s %s (%u) iPhoneInitialized=%x -> 4 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iPhoneInitialized );
+		iPhoneInitialized=4;
+
+    RMobilePhone::TMobilePhoneLock lockType = RMobilePhone::ELockPhoneDevice;
+    RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;
+    RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
+    RMobilePhone::TMobilePhoneLockSetting lockChange(RMobilePhone::ELockSetDisabled);
+
+		RDebug::Printf( "%s %s (%u) before getLockInfoStatus=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+    TRequestStatus getLockInfoStatus;
+		RDebug::Printf( "%s %s (%u) after getLockInfoStatus=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+		
+		RDebug::Printf( "%s %s (%u) iPhoneInitialized=%x -> 5 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iPhoneInitialized );
+		iPhoneInitialized=5;
+    iPhone.GetLockInfo( getLockInfoStatus, lockType, lockInfoPkg );
+		RDebug::Printf( "%s %s (%u) iPhoneInitialized=%x -> 6 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iPhoneInitialized );
+		iPhoneInitialized=6;
+    User::WaitForRequest( getLockInfoStatus );
+
+    INFO_1( "CLockAppDevicelockControl::ETelActivationAllowed - GetLockInfo status: %d ", getLockInfoStatus.Int() );
+    if ( getLockInfoStatus.Int( )== KErrNone )
+        {
+        if ( lockInfo.iSetting == RMobilePhone::ELockSetDisabled )
+            {
+            // ask code
+            INFO( "CLockAppDevicelockControl::ETelActivationAllowed - ETel ELockSetDisabled, Ask Code" );
+            // Raise a flag to indicate that the UPIN request coming from ETEL
+            // has originated from SecUi and not from Engine.
+            RProperty::Set( KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsSystemLockOriginated );
+            TRequestStatus setLockSettingStatus;
+            lockChange = RMobilePhone::ELockSetEnabled;
+            iPhone.SetLockSetting( setLockSettingStatus, lockType, lockChange );
+            User::WaitForRequest( setLockSettingStatus );
+            INFO_1( "CLockAppDevicelockControl::ETelActivationAllowed - SetLockSetting status: %d ", setLockSettingStatus.Int() );
+            // Lower the flag
+            RProperty::Set( KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsETelAPIOriginated );
+            if (setLockSettingStatus.Int() == KErrNone)
+                {
+                ret = ETrue;
+                }
+            }
+        else
+            {
+            INFO( "CLockAppDevicelockControl::ETelActivationAllowed - Lock System Ok" );
+            ret = ETrue;
+            }
+        }
+    else
+        {
+        INFO( "CLockAppDevicelockControl::ETelActivationAllowed - Error getting LockInfo - Ask code (SLS)" );
+        // Raise a flag to indicate that the UPIN request coming from ETEL
+        // has originated from SecUi and not from Engine.
+        RProperty::Set( KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsSystemLockOriginated );
+        TRequestStatus setLockSettingStatus;
+        lockChange = RMobilePhone::ELockSetEnabled;
+				RDebug::Printf( "%s %s (%u) iPhoneInitialized=%x -> 8 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iPhoneInitialized );
+				iPhoneInitialized=8;
+        iPhone.SetLockSetting( setLockSettingStatus, lockType, lockChange );
+				RDebug::Printf( "%s %s (%u) iPhoneInitialized=%x -> 9 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iPhoneInitialized );
+				iPhoneInitialized=9;
+        User::WaitForRequest(setLockSettingStatus);
+        INFO_1( "CLockAppDevicelockControl::ETelActivationAllowed - SetLockSetting status: %d ", setLockSettingStatus.Int() );
+        // Lower the flag
+        RProperty::Set( KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsETelAPIOriginated );
+        if (setLockSettingStatus.Int() == KErrNone)
+            {
+            ret = ETrue;
+            }
+        }
+#endif
+    INFO_1( "CLockAppDevicelockControl::ETelActivationAllowed = %d", ret );
+    return ret;
+    }
+
+// ---------------------------------------------------------------------------
+// Check weather its allowed to activate the control
+// ---------------------------------------------------------------------------
+TBool CLockAppDevicelockControl::ActivationAllowedL( TDevicelockReason aReason )
+    {
+    INFO_1( "CLockAppDevicelockControl::ActivationAllowedL aReason= %d", aReason );
+    
+    if (aReason==ETimerLocked)
+    	{
+ 			 { // REQ 414-5466 Prevention of device lock in context of Hands Free Voice UI
+	     TInt vuiValue = 0;
+	     TUid KHFVuiModePSUid = { 0x102818E7 };
+	     enum THFVuiModePSKeys
+	         {
+	         EHFVuiPSModeId = 1000
+	         };
+	     TInt tRet = RProperty::Get(KHFVuiModePSUid, EHFVuiPSModeId, vuiValue);  // also 0 if can't get because permissions or because doesn't exists
+	     #if defined(_DEBUG)
+	         RDebug::Printf( "%s %s (%u) getting KHFVuiModePSUid+EHFVuiPSModeId=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, tRet );
+	         RDebug::Printf( "%s %s (%u) vuiValue=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, vuiValue );
+	     #endif
+	     if(vuiValue)
+	         {
+	         #if defined(_DEBUG)
+	         RDebug::Print(_L("(LOCKAPP)CLockAppDevicelockControl::ActivationAllowedL() Voice functions active. No locking possible."));
+	         #endif
+	         return EFalse;
+	         }
+	     }
+	     { // if another query is displayed, the future un-lock query will crash. Don't allow time-lock in this case.
+	     TInt secQueryStatus = ESecurityQueryUninitialized;
+	     TInt tRet = RProperty::Get(KPSUidStartup, KStartupSecurityCodeQueryStatus, secQueryStatus);  // also 0 if can't get because permissions or because doesn't exists
+	     #if defined(_DEBUG)
+	         RDebug::Printf( "%s %s (%u) getting KPSUidStartup+KStartupSecurityCodeQueryStatus=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, tRet );
+	         RDebug::Printf( "%s %s (%u) secQueryStatus=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, secQueryStatus );
+	     #endif
+	     if(secQueryStatus==ESecurityQueryActive)
+	         {
+	         #if defined(_DEBUG)
+	         RDebug::Print(_L("(LOCKAPP)CLockAppDevicelockControl::ActivationAllowedL() Asking some other security code. No locking possible."));
+	         #endif
+	         return EFalse;
+	         }
+	     }
+    	}
+    
+    TInt lightStatus=EForcedLightsUninitialized; 
+    RProperty::Get(KPSUidCoreApplicationUIs,KLightsVTForcedLightsOn,lightStatus ); 
+    //If display is forced on. don't lock 
+    if(lightStatus == EForcedLightsOn ) 
+        { 
+        #if defined(_DEBUG) 
+        RDebug::Print(_L("(LOCKAPP)CLockAppDevicelockControl::ActivationAllowedL() Display is forced on deivce not locked")); 
+        #endif 
+        return EFalse;
+        } 
+
+    // first check ETEL side - and ask sec code if needed
+    if ( !ETelActivationAllowed() )
+        {
+        return EFalse;
+        }
+
+    if ( IsPinBlocked( ) )
+        {
+        return EFalse;
+        }
+
+    TBool ret(EFalse);
+    TInt sysState(0);
+    RProperty::Get( KPSUidStartup, KPSGlobalSystemState, sysState );
+    //If NOT in CDMA the Autolock should come up only after the phone has booted up.
+    if ( iFeatureProtocolCdma || IsHiddenReset( ) )
+        {
+        if ( sysState == ESwStateNormalRfOn ||
+             sysState == ESwStateNormalRfOff ||
+             sysState == ESwStateCriticalPhaseOK )
+            {
+            INFO( "CLockAppDevicelockControl::ActivationAllowedL - Locked after Hidden Reset" );
+            ret = ETrue;
+            }
+        }
+    else
+        {
+        if ( sysState == ESwStateNormalRfOn || sysState == ESwStateNormalRfOff )
+            {
+            ret = ETrue;
+            }
+        }
+
+    if ( IsBitFieldSet( iStateControl.EnvironmentStatus( ), KLockAppEnvPhonecallOngoing ) && !TarmAdminFlag(EFalse) )
+        {
+        if ( aReason == EDevicelockRemote )
+            {
+            INFO( "CLockAppDevicelockControl::ActivationAllowedL - remote lock allowed" );
+            ret = ETrue;
+            }
+        }
+    return ret;
+    }
+
+// ---------------------------------------------------------------------------
+// Check weather its allowed to deactivate the control
+// ---------------------------------------------------------------------------
+TBool CLockAppDevicelockControl::DeActivationAllowedL()
+    {
+    if ( iShowingSecCodeQuery )
+        {
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Set the devicelocking reason
+// ---------------------------------------------------------------------------
+void CLockAppDevicelockControl::SetLockingReason( TDevicelockReason aReason )
+    {
+#ifndef RD_REMOTELOCK
+    iPSAutolockState->SetKeyValue( EAutolockOn );
+#else
+    switch ( aReason )
+        {
+        case EDevicelockManual:
+            iPSAutolockState->SetKeyValue( EManualLocked );
+            break;
+        case EDevicelockRemote:
+            iPSAutolockState->SetKeyValue( ERemoteLocked );
+            break;
+        case EDevicelockTimer:
+            iPSAutolockState->SetKeyValue( ETimerLocked );
+            break;
+        default:
+            DoPanic( ELockIllegalState );
+        }
+#endif // RD_REMOTELOCK
+    }
+
+// ---------------------------------------------------------------------------
+// Activate control
+// ---------------------------------------------------------------------------
+void CLockAppDevicelockControl::HandleActivateEventL( TUint aEnvMask )
+    {
+    INFO_1("CLockAppDevicelockControl::HandleActivateEventL - aEnvMask: %d", aEnvMask);
+    
+    CLockAppBaseControl::HandleActivateEventL( aEnvMask );
+
+    if ( IsBitFieldSet( aEnvMask, KLockAppEnvScreenSaverOn ) )
+        {
+        // if screensaver is on - capture primary keys
+        CapturePrimaryKeys( ETrue );
+        }
+    // capture keys
+    CLockAppKeyCaptureController::CaptureKey( EStdKeyApplication0, EKeyApplication0, EKeyCaptureAllEvents ); // App key
+    CLockAppKeyCaptureController::CaptureKey( EStdKeyDevice2, EKeyDevice2, EKeyCaptureAllEvents ); // Power key (for lights)
+    CLockAppKeyCaptureController::CaptureKey( EStdKeyDevice6, EKeyDevice6, EKeyCaptureAllEvents ); // Voice key (for lights)
+    CLockAppKeyCaptureController::CaptureKey( EStdKeyNo, EKeyNo, EKeyCaptureAllEvents ); // End key (for Rosetta lights)
+    CLockAppKeyCaptureController::CaptureKey( EStdKeyDeviceF, EKeyDeviceF, EKeyCaptureAllEvents ); // switch key (for touch devices)
+
+    SetPointerEventCapture( ETrue );
+    SetKeyguardIndicatorStateL( ETrue );
+    iContainer->MakeVisible( ETrue ); // maybe not needed - as its in different windowgroup
+    ShowCba( ETrue );
+    ShowStatusPane( ETrue );
+    // close task-list in case it is displayed : fast-swap window
+    iEikonEnv->DismissTaskList( );
+    iCRAutoLockStatus->SetValue( ETrue );
+    }
+
+// ---------------------------------------------------------------------------
+// DeActivate control
+// ---------------------------------------------------------------------------
+void CLockAppDevicelockControl::HandleDeActivateEventL( TUint aEnvMask )
+    {
+    INFO_1("CLockAppDevicelockControl::HandleDeActivateEventL - aEnvMask: %d", aEnvMask);
+    
+    CLockAppBaseControl::HandleDeActivateEventL( aEnvMask );
+
+    if ( IsBitFieldSet( aEnvMask, KLockAppEnvScreenSaverOn ) )
+        {
+        // if screensaver is on - uncapture primary keys
+        CapturePrimaryKeys( EFalse );
+        }
+
+    // uncapture keys
+    CLockAppKeyCaptureController::ReleaseKey( EStdKeyApplication0 );
+    CLockAppKeyCaptureController::ReleaseKey( EStdKeyDevice2 );
+    CLockAppKeyCaptureController::ReleaseKey( EStdKeyDevice6 );
+    CLockAppKeyCaptureController::ReleaseKey( EStdKeyNo );
+    CLockAppKeyCaptureController::ReleaseKey( EStdKeyDeviceF );
+    
+    SetPointerEventCapture( EFalse );
+    SetKeyguardIndicatorStateL( EFalse );
+    iContainer->MakeVisible( EFalse ); // maybe not needed - as its in different windowgroup
+    ShowCba( EFalse );
+    ShowStatusPane( EFalse );
+    iPSAutolockState->SetKeyValue( EAutolockOff );
+    iCRAutoLockStatus->SetValue( EFalse );
+    }
+
+// ---------------------------------------------------------------------------
+// Handle environment changes (Screensaver, Telephony, etc.)
+// ---------------------------------------------------------------------------
+void CLockAppDevicelockControl::HandleEnvironmentChange( TUint aEnvMask, TUint aEventMask )
+    {
+    RDebug::Printf( "%s %s (%u) aEnvMask=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aEnvMask );
+    RDebug::Printf( "%s %s (%u) aEventMask=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aEventMask );
+
+    if ( IsBitFieldSet( aEventMask, KLockAppEnvScreenSaverOn ) )
+        {
+        // screen saver state changed
+        CapturePrimaryKeys( IsBitFieldSet( aEnvMask, KLockAppEnvScreenSaverOn ) );
+        }
+    if ( IsBitFieldSet( aEventMask, KLockAppEnvFPS ) )
+        {
+        TInt lockValue=0;
+    		iPSAutolockState->GetKeyValue( lockValue );
+    		RDebug::Printf( "%s %s (%u) lockValue=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, lockValue );
+    		if(lockValue>EAutolockOff)	// device is locked and query is not open
+    			{
+    			// indicate to TARM that it should not ask for password
+    			TInt secUiOriginatedQuery(ESecurityUIsSecUIOriginatedUninitialized);
+    			RProperty::Get(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, secUiOriginatedQuery);
+    			RDebug::Printf( "%s %s (%u) secUiOriginatedQuery=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, secUiOriginatedQuery );
+    			RProperty::Set( KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsFpsOriginated );
+
+        	HandleUnlockCommandL( );
+    			RProperty::Set( KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, secUiOriginatedQuery );	// reset to initial
+        	}
+        else												// device needs to be locked. Same happens in keyguard control becasue probably this is never called
+        	iStateControl.EnableDevicelockL( EDevicelockManual );
+        }
+    if ( IsBitFieldSet( aEnvMask, KLockAppEnvGrip ) )
+    	{
+      RDebug::Printf( "%s %s (%u) iShowingSecCodeQuery=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iShowingSecCodeQuery );
+	    if ( IsBitFieldSet( aEventMask, KLockAppEnvGrip ) )	//Grip opened
+	        {
+	        if(iShowingSecCodeQuery==EFalse)
+	        	{
+	        		TInt lockValue=0;
+	        		iPSAutolockState->GetKeyValue( lockValue );
+	        		RDebug::Printf( "%s %s (%u) lockValue=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, lockValue );
+	        		if(lockValue>EAutolockOff)
+	        			{
+				        // ask unlock code by sending the menu key. This works on touch?
+			        	TApaTaskList tasklist( iEikonEnv->WsSession() );
+			        	#define KAknCapServerUid TUid::Uid( 0x10207218 )
+			        	TApaTask capserver = tasklist.FindApp( KAknCapServerUid );
+    						RDebug::Printf( "%s %s (%u) KAknCapServerUid=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, KAknCapServerUid );
+			        	if( capserver.Exists() )
+			        	    {
+	        	        RDebug::Printf( "%s %s (%u) capserver.Exists() EStdKeyDevice0=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, EStdKeyDevice0 );
+			        	    TKeyEvent key;
+			        	    key.iCode = EKeyDevice0;
+			        	    key.iModifiers = 0;
+			        	    key.iRepeats = 0;
+			        	    key.iScanCode = EStdKeyDevice0;
+			        	    capserver.SendKey( key );
+			        	    }
+			        	}
+			       }
+        	}
+			else
+					{
+					if(iShowingSecCodeQuery==EFalse)
+	        	{
+            //the device lock query is on top
+	        	//generate cancel key event
+	        	const TInt KCancelKeyCode( 165 );
+	        	RDebug::Printf( "%s %s (%u) KCancelKeyCode=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, KCancelKeyCode );
+
+	        	TRawEvent rawEvent;
+	        	rawEvent.Set( TRawEvent::EKeyDown, KCancelKeyCode );
+	        	iEikonEnv->WsSession().SimulateRawEvent( rawEvent );        	
+						}
+					}
+			}
+    }
+
+// ---------------------------------------------------------------------------
+// Handle all Central Repository observer callbacks.
+// ---------------------------------------------------------------------------
+void CLockAppDevicelockControl::HandleCenRepNotify(TUid /*aCenRepUid*/, TUint32 aKeyId, TInt aValue )
+    {
+    RDebug::Printf( "%s %s (%u) aKeyId=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKeyId );
+    RDebug::Printf( "%s %s (%u) aValue=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aValue );
+    switch ( aKeyId )
+        {
+        case KSettingsAutoLockTime:
+            {
+            INFO_1( "CLockAppDevicelockControl::HandleCenRepNotify - KSettingsAutoLockTime = %d", aValue );
+            ResetInactivityTimeout( );
+            }
+            break;
+        default:
+            break;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Handle all Publish & Subscribe observer callbacks.
+// ---------------------------------------------------------------------------
+void CLockAppDevicelockControl::HandlePubSubNotify(TUid aPubSubUid, TUint aKeyId, TInt aValue )
+    {
+    RDebug::Printf( "%s %s (%u) KPSUidCoreApplicationUIs=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, KPSUidCoreApplicationUIs );
+    RDebug::Printf( "%s %s (%u) aKeyId=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKeyId );
+    RDebug::Printf( "%s %s (%u) aValue=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aValue );
+    if ( aPubSubUid == KPSUidCoreApplicationUIs )
+        {
+        switch ( aKeyId )
+            {
+            case KCoreAppUIsAutolockStatus:
+                {
+                INFO_1( "CLockAppDevicelockControl::HandlePubSubNotify - KCoreAppUIsAutolockStatus = %d", aValue );
+                // Autolock used to react to this PubSub key - but its unsafe and
+                // in future API will be used, and the key will be published by Lockapp
+                INFO_1( "CLockAppDevicelockControl::HandlePubSubNotify - nothing done. LockApp reacts only to API = %d", aValue );
+                }
+                break;
+            default:
+                break;
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Devicelock UI key events are handled trough here.
+// ---------------------------------------------------------------------------
+TKeyResponse CLockAppDevicelockControl::OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+    RDebug::Printf( "%s %s (%u) aKeyEvent.iCode=%x aType=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKeyEvent.iCode, aType );
+    RDebug::Printf( "%s %s (%u) iActive=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iActive );
+    if ( iActive )
+        {
+    		if(AknLayoutUtils::PenEnabled())
+    			{
+    			if(aKeyEvent.iCode == EKeyDeviceF)	// any Type
+    				{
+    				HandleUnlockCommandL( );
+    				}
+    			}
+        if ( aType == EEventKeyDown )
+            {
+            if ( !iShowingSecCodeQuery )
+                {
+                switch ( iKeyPattern->HandleKeyEvent( aKeyEvent.iScanCode ) )
+                    {
+                    case EPatternPrimaryMatch:
+                        HandleUnlockCommandL( );
+                        break;
+                    default:
+                        break;
+                    }
+                }
+            }
+        }
+    return EKeyWasConsumed;
+    }
+
+// ---------------------------------------------------------------------------
+// Handle unlock command
+// ---------------------------------------------------------------------------
+void CLockAppDevicelockControl::HandleUnlockCommandL( )
+    {
+    INFO( "CLockAppDevicelockControl::HandleUnlockCommandL" );
+    // inform sysap to put lights on left soft key press
+    SendMessageToSysAp( EEikKeyLockLightsOnRequest );
+		RDebug::Printf( "%s %s (%u) iPhoneInitialized=%x -> 10 ", __FILE__, __PRETTY_FUNCTION__, __LINE__, iPhoneInitialized );
+		iPhoneInitialized=10;
+    CSecurityHandler* handler = new (ELeave) CSecurityHandler( iPhone );
+		RDebug::Printf( "%s %s (%u) got handler=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 1 );
+    CleanupStack::PushL( handler );
+    TSecUi::InitializeLibL( );
+		RDebug::Printf( "%s %s (%u) got TSecUi::InitializeLibL=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 1 );
+    iShowingSecCodeQuery = ETrue;
+    TRAPD(err, {
+								RDebug::Printf( "%s %s (%u) before AskSecCodeInAutoLockL=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 1 );
+                TBool ret = handler->AskSecCodeInAutoLockL();
+								RDebug::Printf( "%s %s (%u) after AskSecCodeInAutoLockL=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, ret );
+                INFO_1( "CLockAppDevicelockControl::HandleUnlockCommandL - AskSecCodeInAutoLockL = %d", ret );
+                if ( ret )
+                    {
+                    iStateControl.DisableDevicelockL();
+                    }
+                })
+    ERROR(err, "CLockAppDevicelockControl::HandleUnlockCommandL - AskSecCodeInAutoLockL");
+    iShowingSecCodeQuery = EFalse;
+    TSecUi::UnInitializeLib( );
+    CleanupStack::PopAndDestroy( handler );
+    }
+
+// ---------------------------------------------------------------------------
+// Get autolock timeout (in seconds)
+// ---------------------------------------------------------------------------
+TInt CLockAppDevicelockControl::GetAutoLockTimeout( )
+    {
+    TInt timeoutInMinutes = 0;
+    iCRAutoLockTime->GetValue( timeoutInMinutes );
+    return timeoutInMinutes * 60;
+    }
+
+// ----------------------------------------------------------
+// Starts monitoring user activity
+// ----------------------------------------------------------
+void CLockAppDevicelockControl::StartActivityMonitoringL( )
+    {
+    __ASSERT_DEBUG( iActivityManager, DoPanic(ELockIllegalState));
+    if ( iActivityManager && !iActivityManager->IsActive() )
+        {
+        TInt value = GetAutoLockTimeout( );
+        INFO_1( "CLockAppDevicelockControl::StartActivityMonitoringL - %d sec", value);
+        if ( value )
+            {
+            iActivityManager->Start( value,
+                    TCallBack( HandleInactiveEventL, this ),
+                    TCallBack( HandleActiveEventL, this ) );
+            }
+        else
+            {
+            iActivityManager->Start( KAutoDeviceLockOff,
+                    TCallBack(HandleInactiveEventL, this ),
+                    TCallBack(HandleActiveEventL, this ) );
+            }
+        }
+    }
+
+// ----------------------------------------------------------
+// Gets autolock period and starts monitoring user activity
+// ----------------------------------------------------------
+void CLockAppDevicelockControl::ResetInactivityTimeout( )
+    {
+    __ASSERT_DEBUG( iActivityManager, DoPanic(ELockIllegalState));
+    if ( iActivityManager )
+        {
+        TInt value = GetAutoLockTimeout( );
+        INFO_1( "CLockAppDevicelockControl::ResetInactivityTimeout - %d sec", value);
+        if ( value )
+            {
+            iActivityManager->SetInactivityTimeout( value );
+            }
+        else
+            {
+            iActivityManager->SetInactivityTimeout( KAutoDeviceLockOff );
+            }
+        }
+    }
+
+// ----------------------------------------------------------
+// Stop monitoring user activity.
+// ----------------------------------------------------------
+void CLockAppDevicelockControl::StopActivityMonitoring( )
+    {
+    __ASSERT_DEBUG( iActivityManager, DoPanic(ELockIllegalState));
+    if ( iActivityManager )
+        {
+        iActivityManager->Cancel( );
+        }
+    }
+
+// ----------------------------------------------------------
+// Handle Active event. Called by ActivityManager
+// ----------------------------------------------------------
+TInt CLockAppDevicelockControl::HandleActiveEventL(TAny* /*aPtr*/)
+    {
+    return KErrNone;
+    }
+
+// ----------------------------------------------------------
+// Handles InActive event. Called by ActivityManager
+// ----------------------------------------------------------
+TInt CLockAppDevicelockControl::HandleInactiveEventL(TAny* aPtr )
+    {
+    CLockAppDevicelockControl* devicelock = STATIC_CAST(CLockAppDevicelockControl*, aPtr);
+    if ( devicelock->GetAutoLockTimeout( ) )
+        {
+        devicelock->iStateControl.EnableDevicelockL( EDevicelockTimer );
+        }
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// Set custom status pane visible
+// ---------------------------------------------------------------------------
+void CLockAppDevicelockControl::ShowStatusPane( const TBool aVisible )
+    {
+    CEikStatusPane* statuspane = iAvkonAppUi->StatusPane();
+    if ( statuspane )
+        {
+        statuspane->MakeVisible( aVisible );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Handle UI commands received from the child controls
+// ---------------------------------------------------------------------------
+void CLockAppDevicelockControl::ProcessCommandL(TInt aCommandId)
+    {
+    INFO_1("CLockAppDevicelockControl::ProcessCommandL : %d ", aCommandId );
+    }
+
+TInt CLockAppDevicelockControl::CountComponentControls() const
+    {
+    return 2;
+    }
+
+CCoeControl* CLockAppDevicelockControl::ComponentControl(TInt aIndex ) const
+    {
+    switch ( aIndex )
+        {
+        case 0:
+            return iCba;
+        case 1:
+            return iContainer;
+        default:
+            return NULL;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Notification if layout changes.
+// ---------------------------------------------------------------------------
+void CLockAppDevicelockControl::HandleResourceChange(TInt aType )
+    {
+    if ( aType == KEikDynamicLayoutVariantSwitch && iCba )
+        {
+        TRect screenRect;
+        AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::EScreen, screenRect );
+        iCba->SetBoundingRect( screenRect );
+        }
+    CCoeControl::HandleResourceChange( aType );
+    }
+
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappdocument.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,67 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  LockApp application document class
+ *
+*/
+
+
+#include "lockappappui.h"
+#include "lockappdocument.h"
+
+// ---------------------------------------------------------------------------
+// Standard Symbian OS construction sequence
+// ---------------------------------------------------------------------------
+CLockAppDocument* CLockAppDocument::NewL(CEikApplication& aApp)
+    {
+    CLockAppDocument* self = NewLC(aApp);
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Standard Symbian OS construction sequence
+// ---------------------------------------------------------------------------
+CLockAppDocument* CLockAppDocument::NewLC(CEikApplication& aApp)
+    {
+    CLockAppDocument* self = new (ELeave) CLockAppDocument(aApp);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    return self;
+    }
+
+CLockAppDocument::~CLockAppDocument()
+    {
+    // no implementation required
+    }
+
+// ---------------------------------------------------------------------------
+//  Create the application user interface, and return a pointer to it,
+//  The framework takes ownership of this object.
+// ---------------------------------------------------------------------------
+CEikAppUi* CLockAppDocument::CreateAppUiL()
+    {
+    CEikAppUi* appUi = new (ELeave) CLockAppAppUi;
+    return appUi;
+    }
+
+void CLockAppDocument::ConstructL()
+    {
+    // no implementation required
+    }
+
+CLockAppDocument::CLockAppDocument( CEikApplication& aApp ) :
+	CAknDocument(aApp)
+	{
+	// no implementation required
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappecsdetector.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,159 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Provides emergency call support for keyguard/devicelock
+ *
+*/
+
+
+#include "lockappecsdetector.h"
+#include "lockappecsnote.h"
+#include "lockapputils.h"
+#include <aknappui.h>
+#include <avkon.rsg>
+
+// ---------------------------------------------------------------------------
+// Standard Symbian OS construction sequence
+// ---------------------------------------------------------------------------
+CLockAppEcsDetector* CLockAppEcsDetector::NewL( )
+    {
+    CLockAppEcsDetector* self = new (ELeave) CLockAppEcsDetector();
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Standard C++ constructor
+// ---------------------------------------------------------------------------
+CLockAppEcsDetector::CLockAppEcsDetector( )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// Constructs the emergency detector and the note.
+// ---------------------------------------------------------------------------
+void CLockAppEcsDetector::ConstructL( )
+    {
+    // emergency call support
+    iEcsDetector = CAknEcsDetector::NewL( );
+    iEcsDetector->SetObserver( this );
+
+    // emergency call note
+    iEcsNote = new (ELeave) CLockAppEcsNote();
+    iEcsNote->ConstructSleepingNoteL( R_AVKON_EMERGENCY_CALL_NOTE );
+    iEcsNote->ButtonGroupContainer().ButtonGroup()->AsControl()->DrawableWindow()->SetOrdinalPosition( 0, 2 );
+
+    // needs to be called for ecs detector to work/receive events.
+    iAvkonAppUi->EventMonitor()->Enable( ETrue );
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor.
+// ---------------------------------------------------------------------------
+CLockAppEcsDetector::~CLockAppEcsDetector( )
+    {
+    delete iEcsDetector;
+    delete iEcsNote;
+    }
+
+// ---------------------------------------------------------------------------
+// Detector starts/stops listening to key events if keys are locked/unlocked.
+// The detector key event queue is always reseted when lock status is changed.
+// ---------------------------------------------------------------------------
+void CLockAppEcsDetector::HandleLockStatusChangedL( TLockStatus aLockStatus )
+    {
+    iEcsDetector->Reset( );
+    switch ( aLockStatus )
+        {
+        case ELockNotActive:
+            {
+            iEcsDetector->CloseEventSource( );
+            }
+            break;
+        case EKeyguardActive:
+        case EDevicelockActive:
+            {
+            iEcsDetector->ConnectToEventSource( );
+            }
+            break;
+        default:
+            DoPanic( ELockUnknownValue );
+            break;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// The main state controller needs to know if emergency call note is
+// on the screen.
+// ---------------------------------------------------------------------------
+TBool CLockAppEcsDetector::EcsNoteOnScreen( ) const
+    {
+    return iEcsNote->iNoteOnScreen;
+    }
+
+// ---------------------------------------------------------------------------
+// From @c MAknEcsObserver.. Handles changes in emergency the emergency number
+// queue (i.e. if the user has dialed emergency numbers or not).
+// ---------------------------------------------------------------------------
+void CLockAppEcsDetector::HandleEcsEvent( CAknEcsDetector* aEcsDetector,
+        CAknEcsDetector::TState aState )
+    {
+    switch ( aState )
+        {
+        case CAknEcsDetector::ECompleteMatchThenSendKey:
+            // Do nothing since note will be removed on ECallAttempted event
+            break;
+            // user has successfully dialed emergency numbers
+        case CAknEcsDetector::ECompleteMatch:
+            iEcsNote->SetEmergencyNumber( aEcsDetector->CurrentMatch( ) );
+            // Tell sysAp to switch lights on
+            SendMessageToSysAp( EEikEcsQueryLights );
+            iEcsNote->ShowNote( );
+            break;
+        case CAknEcsDetector::EPartialMatch:
+            iEcsNote->SleepNote( );
+            break;
+        case CAknEcsDetector::ECallAttempted:
+            iEcsNote->SleepNote( );
+            break;
+        case CAknEcsDetector::EEmpty:
+            iEcsNote->SleepNote( );
+            break;
+        case CAknEcsDetector::ENoMatch:
+            iEcsNote->SleepNote( );
+            break;
+        default:
+            break;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Tests the emergency note ui. Only used for testing purposes,
+// Created, because emergency detector does not work in emulator.
+// ---------------------------------------------------------------------------
+TInt CLockAppEcsDetector::TestEcsNote( )
+    {
+#ifdef _DEBUG
+    HandleEcsEvent( iEcsDetector, CAknEcsDetector::EEmpty );
+    HandleEcsEvent( iEcsDetector, CAknEcsDetector::ENoMatch );
+    HandleEcsEvent( iEcsDetector, CAknEcsDetector::EPartialMatch );
+    HandleEcsEvent( iEcsDetector, CAknEcsDetector::ECompleteMatch );
+    _LIT( NText, "112Test");
+    iEcsNote->SetEmergencyNumber( NText );
+    SendMessageToSysAp( EEikEcsQueryLights );
+    iEcsNote->ShowNote( );
+#endif
+    return KErrNone;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappecsnote.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,157 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Emergency number dialog
+ *
+*/
+
+
+#include "lockappecsnote.h"
+#include "lockapputils.h"
+#include <AknUtils.h>
+#include <aknlayoutscalable_avkon.cdl.h>
+#include <aknappui.h>
+#include <AknEcs.h> // for KAknEcsMaxMatchingLength
+
+#include <aknglobalpopupprioritycontroller.h>
+#include <GlobalWindowPriorities.h>
+
+// ---------------------------------------------------------------------------
+// Standard C++ constructor
+// ---------------------------------------------------------------------------
+CLockAppEcsNote::CLockAppEcsNote( ) :
+	iNoteOnScreen(EFalse)
+	{
+	// no implementation required
+	}
+
+// ---------------------------------------------------------------------------
+// Destructor.
+// ---------------------------------------------------------------------------
+CLockAppEcsNote::~CLockAppEcsNote( )
+    {
+#ifdef _GLOBAL_PRIORITY_SUPPORTED
+    AknGlobalPopupPriorityController::RemovePopupPriority(*this);
+#endif
+    }
+
+// ---------------------------------------------------------------------------
+// Emergency note is a sleeping note
+// ---------------------------------------------------------------------------
+void CLockAppEcsNote::ConstructSleepingNoteL(TInt aResourceId )
+    {
+    CAknNoteDialog::ConstructSleepingDialogL( aResourceId );
+#ifdef _GLOBAL_PRIORITY_SUPPORTED
+    // global ui component order is handled trhoug global popup priority controller
+    AknGlobalPopupPriorityController::SetPopupPriorityL( *this, KGlobalWindowPriority_KeyLock );
+#endif
+    }
+
+// ---------------------------------------------------------------------------
+// Show note with time out.
+// ---------------------------------------------------------------------------
+TInt CLockAppEcsNote::ShowNote( )
+    {
+    ReportUserActivity( );
+    iTimeoutInMicroseconds = CAknNoteDialog::EUndefinedTimeout;
+    iTone = CAknNoteDialog::ENoTone;
+    TInt error = KErrNone;
+    if ( !iNoteOnScreen )
+        {
+        error = RouseSleepingDialog( );
+        }
+    iNoteOnScreen = ETrue;
+    // return value not used
+    return error;
+    }
+
+// ---------------------------------------------------------------------------
+// Hide note from screen.
+// ---------------------------------------------------------------------------
+void CLockAppEcsNote::SleepNote( )
+    {
+    if ( iNoteOnScreen )
+        {
+        ExitSleepingDialog( ); // Causes flicker to other notes if called when note is not on screen
+        }
+    iNoteOnScreen = EFalse;
+    }
+
+// ---------------------------------------------------------------------------
+// Emergency dialog consumes all key events it receives.
+// ---------------------------------------------------------------------------
+TKeyResponse CLockAppEcsNote::OfferKeyEventL(const TKeyEvent& /*aKeyEvent*/, TEventCode /*aType*/)
+    {
+    return EKeyWasConsumed;
+    }
+
+// ---------------------------------------------------------------------------
+// Format the emergency number for the dialog text.
+// ---------------------------------------------------------------------------
+void CLockAppEcsNote::SetEmergencyNumber( const TDesC& aMatchedNumber )
+    {
+    TRect mainPaneRect;
+    AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::EMainPane, mainPaneRect );
+    TAknLayoutRect popupNoteWindow;
+    AknLayoutUtils::TAknCbaLocation cbaLocation( AknLayoutUtils::CbaLocation( ));
+    TInt variety( 0);
+    if ( cbaLocation == AknLayoutUtils::EAknCbaLocationRight )
+        {
+        variety = 5;
+        }
+    else
+        if ( cbaLocation == AknLayoutUtils::EAknCbaLocationLeft )
+            {
+            variety = 8;
+            }
+        else
+            {
+            variety = 2;
+            }
+
+    popupNoteWindow.LayoutRect( mainPaneRect, AknLayoutScalable_Avkon::popup_note_window( variety ) );
+    TAknLayoutText textRect;
+    textRect.LayoutText( popupNoteWindow.Rect( ), AknLayoutScalable_Avkon::popup_note_window_t5(2).LayoutLine( ) );
+
+    // Size of a temporary buffer that contains new lines, spaces and
+    // emergency number for a note.
+    TBuf16<KAknEcsMaxMatchingLength+80> number;
+    number.Append( '\n' );
+    number.Append( '\n' );
+
+    TInt spaceCharWidthInPixels = textRect.Font()->CharWidthInPixels( ' ' );
+    if ( spaceCharWidthInPixels < 1 )
+        {
+        // Avoid divide by zero situation even the space char would have zero length.
+        spaceCharWidthInPixels = 1;
+        }
+
+    TInt length = (textRect.TextRect().Width() - textRect.Font()->TextWidthInPixels(aMatchedNumber))/ spaceCharWidthInPixels;
+
+    const TInt matchedNumberLength = aMatchedNumber.Length( );
+    const TInt numberLength = number.Length( );
+    const TInt numberMaxLength = number.MaxLength( );
+
+    if ( numberLength + length + matchedNumberLength > numberMaxLength )
+        {
+        // To make sure that buffer overflow does not happen.
+        length = numberMaxLength - numberLength - matchedNumberLength;
+        }
+    for (int i = 0; i < length; i++ )
+        {
+        number.Append( ' ' );
+        }
+
+    number.Append( aMatchedNumber );
+    TRAP_IGNORE(SetTextL(number));
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappidlecontrol.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,223 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Idle (unlocked) UI
+ *
+*/
+
+
+#include "lockappidlecontrol.h"
+#include "lockappstatecontrolinterface.h"
+#include "lockapputils.h"
+#include "lockapplockednote.h" // keyguard notes
+#include "lockappkeycapturecontroller.h"
+
+#include <avkon.rsg> // general avkon resources
+
+#include <aknnotpi.rsg> // keyguard spesific resources
+
+#include <featmgr.h> // feature manager
+
+// from keyguard ui spesification, 6 sec.
+const TInt KAknOfferKeyguardTimeout = 6000000;
+
+// Asterisk key code for the keylock
+const TUint KStdKeyAsterisk = 42;
+//const TUint KAknChineseAsterisk = 0xFF0A;
+
+// ---------------------------------------------------------------------------
+// Standard Symbian OS construction sequence
+// ---------------------------------------------------------------------------
+CLockAppIdleControl* CLockAppIdleControl::NewL(MLockAppStateControl& aStateControl )
+    {
+    CLockAppIdleControl* self = new (ELeave) CLockAppIdleControl( aStateControl );
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Constructor passes the reference of the main state control.
+// ---------------------------------------------------------------------------
+CLockAppIdleControl::CLockAppIdleControl( MLockAppStateControl& aStateControl ) :
+    CLockAppBaseControl( aStateControl )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor.
+// ---------------------------------------------------------------------------
+CLockAppIdleControl::~CLockAppIdleControl( )
+    {
+    delete iOfferLockNote;
+    }
+
+// ---------------------------------------------------------------------------
+// Idle UI constructor reserves localized resources, configures itself
+// using CenRep and FeatureManager and reserves child controls.
+// ---------------------------------------------------------------------------
+void CLockAppIdleControl::ConstructL( )
+    {
+    INFO( "CLockAppIdleControl::ConstructL started" );
+    CLockAppBaseControl::ConstructL( );
+
+    iOfferLockNote = new (ELeave) CLockAppLockedNote(this);
+    iOfferLockNote->ConstructSleepingNoteL( R_KEYLOCK_OFFER_LOCK_NOTE );
+    iOfferLockNote->ButtonGroupContainer().ButtonGroup()->AsControl()->DrawableWindow()->SetOrdinalPosition( 0, 2 );
+    
+    // Setup key pattern matcher
+    if ( !SetupKeyPatternsWithPolicyL( EPolicyActivateKeyguard ) )
+        {
+        INFO( "CLockAppIdleControl::ConstructL - No CenRep policy defined" );
+        iKeyPattern->AddPattern( EStdKeyDevice0, KStdKeyAsterisk ); // LSK + *
+        }
+#ifdef __WINS__
+    iKeyPattern->AddPattern( EStdKeyDevice0, EStdKeyNkpAsterisk ); // LSK + *
+#endif
+                                                                                                                                                                                                           
+    INFO( "CLockAppIdleControl::ConstructL completed" );
+    }
+
+// ---------------------------------------------------------------------------
+// Offers keylock.
+// ---------------------------------------------------------------------------
+void CLockAppIdleControl::OfferKeyLock( )
+    {
+    ShowNote( iOfferLockNote, (CAknNoteDialog::TTimeout)KAknOfferKeyguardTimeout, CAknNoteDialog::ENoTone );
+    }
+
+// ---------------------------------------------------------------------------
+// Cancels offering keylock.
+// ---------------------------------------------------------------------------
+void CLockAppIdleControl::CancelOfferKeyLock( )
+    {
+    CancelNote( );
+    }
+
+// ---------------------------------------------------------------------------
+// Activate control
+// ---------------------------------------------------------------------------
+void CLockAppIdleControl::HandleActivateEventL( TUint aEnvMask )
+    {  
+		RDebug::Printf( "%s %s (%u) value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+    CLockAppBaseControl::HandleActivateEventL( aEnvMask );
+    }
+
+// ---------------------------------------------------------------------------
+// DeActivate control
+// ---------------------------------------------------------------------------
+void CLockAppIdleControl::HandleDeActivateEventL( TUint aEnvMask )
+    {
+    CLockAppBaseControl::HandleDeActivateEventL( aEnvMask );
+    CancelOfferKeyLock( );
+    }
+
+// ---------------------------------------------------------------------------
+// Idle UI key events are handled trough here.
+// ---------------------------------------------------------------------------
+TKeyResponse CLockAppIdleControl::OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode /*aType*/ )
+    {
+		RDebug::Printf( "%s %s (%u) aKeyEvent.iCode=%x 1=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKeyEvent.iCode, 1 );
+    TKeyResponse keyResponse = EKeyWasNotConsumed;
+    if ( iActive )
+        {
+        if ( iOfferLockNote->IsVisible( ) )
+            {
+            // if keylock has been offered
+            switch ( aKeyEvent.iCode )
+                {
+                case EKeyOK:
+                    iStateControl.EnableKeyguardL( ETrue );
+                    keyResponse = EKeyWasConsumed;
+                    break;
+                case EKeyLeftArrow:
+                case EKeyRightArrow:
+                case EKeyUpArrow:
+                case EKeyDownArrow:
+                case EKeyApplication:
+                    keyResponse = EKeyWasConsumed;
+                    break;
+                default:
+                    break;
+                }
+            }
+        else
+            {
+            // keys pressed normally in idle - however keys are not captured
+            // this is where locking policy could be monitored to check keyguard activation
+            /*if ( aType == EEventKeyDown )
+                {
+                switch ( iKeyPattern->HandleKeyEvent( aKeyEvent.iScanCode ) )
+                    {
+                    case EPatternNoMatch:
+                    case EPatternPrimaryMatch:
+                        break;
+                    case EPatternSecondaryMatch:
+                        iStateControl.EnableKeyguardL( ETrue );
+                        keyResponse = EKeyWasConsumed;
+                        break;
+                    default:
+                        break;
+                    }
+                }
+            */
+            }
+        }
+    return keyResponse;
+    }
+
+// ---------------------------------------------------------------------------
+// Handle UI commands received from the child controls
+// ---------------------------------------------------------------------------
+void CLockAppIdleControl::ProcessCommandL(TInt aCommandId )
+    {
+    // handle command
+		RDebug::Printf( "%s %s (%u) value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+    switch ( aCommandId )
+        {
+        case EAknSoftkeyLock:
+            {
+            // user has accepted offer keyguard enquiry - lock keys
+            iStateControl.EnableKeyguardL( ETrue );
+            }
+            break;
+        case EAknSoftkeyExit:
+        case KNoteCmdFocusLost:
+            {
+            // user has declined offer keyguard enquiry -  cancel offer
+            CancelOfferKeyLock( );
+            }
+            break;
+        default:
+            break;
+        }
+    }
+
+TInt CLockAppIdleControl::CountComponentControls( ) const
+    {
+    return 0;
+    }
+
+CCoeControl* CLockAppIdleControl::ComponentControl(TInt /*aIndex*/) const
+    {
+    return NULL;
+    }
+
+// ---------------------------------------------------------------------------
+// Notification if layout changes.
+// ---------------------------------------------------------------------------
+void CLockAppIdleControl::HandleResourceChange(TInt aType )
+    {
+    CCoeControl::HandleResourceChange( aType );
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappkeycapturecontroller.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,224 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Key capture utility
+ *
+*/
+
+
+// INCLUDE FILES
+#include "lockappkeycapturecontroller.h"
+#include <w32std.h>
+
+// ================= STATIC MEMBERS =========================
+
+CLockAppKeyCaptureController* CLockAppKeyCaptureController::instance = NULL;
+
+
+// ================= STATIC FUNCTIONS =======================
+
+// ---------------------------------------------------------
+// Initializes the key capture utility by creating an instance of it
+// ---------------------------------------------------------
+CLockAppKeyCaptureController* CLockAppKeyCaptureController::InitL( RWindowGroup& aWindowGroup )
+    {
+    if ( !instance )
+        {
+        instance = new ( ELeave ) CLockAppKeyCaptureController( aWindowGroup );
+        }
+    return instance;
+    }
+
+// ---------------------------------------------------------
+// Destroys the key capture utility's instance
+// ---------------------------------------------------------
+void CLockAppKeyCaptureController::Destroy( )
+    {
+    if ( instance )
+        {
+        delete instance;
+        instance = NULL;
+        }
+    }
+
+// ---------------------------------------------------------
+// Capture a key
+// ---------------------------------------------------------
+void CLockAppKeyCaptureController::CaptureKey( TUint32 aKey, TUint32 aKeyCode, TPhoneKeyCaptureType aType )
+    {
+    	RDebug::Printf( "%s %s (%u) aKey=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKey );
+    	RDebug::Printf( "%s %s (%u) aKeyCode=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKeyCode );
+    	RDebug::Printf( "%s %s (%u) aType=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aType );
+
+    if ( instance )
+        {
+        instance->StartCapturingKey( aKey, aKeyCode, aType );
+        }
+    }
+
+// ---------------------------------------------------------
+// Release a key (previously captured)
+// ---------------------------------------------------------
+void CLockAppKeyCaptureController::ReleaseKey( TUint32 aKey )
+    {
+    	RDebug::Printf( "%s %s (%u) aKey=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKey );
+
+    if ( instance )
+        {
+        instance->StopCapturingKey( aKey );
+        }
+    }
+
+// ================= INSTANCE FUNCTIONS ============================
+
+// ---------------------------------------------------------
+// Private default constructor
+// ---------------------------------------------------------
+CLockAppKeyCaptureController::CLockAppKeyCaptureController( RWindowGroup& aWindowGroup ) :
+    iWindowGroup( aWindowGroup)
+    {
+    }
+
+// ---------------------------------------------------------
+// Private destructor
+// ---------------------------------------------------------
+CLockAppKeyCaptureController::~CLockAppKeyCaptureController( )
+    {
+    	RDebug::Printf( "%s %s (%u) value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+
+    // should we have any captured keys, stop capturing now
+    TInt capturedKeyCount = iCapturedKeys.Count( );
+    for (TInt i = 0; i < capturedKeyCount; i++ )
+        {
+        StopKeyCapture( iCapturedKeys[i] );
+        }
+    iCapturedKeys.Close( );
+    }
+
+// ---------------------------------------------------------
+// Starts capturing a key
+// ---------------------------------------------------------
+void CLockAppKeyCaptureController::StartCapturingKey( TUint32 aKey, TUint32 aKeyCode, TPhoneKeyCaptureType aType )
+    {
+    TInt32 handle = KErrNotFound;
+		RDebug::Printf( "%s %s (%u) aKey=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKey );
+		RDebug::Printf( "%s %s (%u) aKeyCode=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKeyCode );
+		RDebug::Printf( "%s %s (%u) aType=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aType );
+
+    if ( !IsKeyCaptured( aKey ) )
+        {
+        TPhoneKeyCapture keyCapture;
+        keyCapture.iKey = (TStdScanCode) aKey;
+        keyCapture.iKeyCode = (TKeyCode) aKeyCode;
+        keyCapture.iHandle = 0; // set as initial value
+        keyCapture.iHandleForUpAndDown = 0; // set as initial value
+
+        switch( aType )
+            {
+            case EKeyCaptureEvent:
+                keyCapture.iType = EKeyCaptureEvent;
+                keyCapture.iHandle = iWindowGroup.CaptureKey( keyCapture.iKeyCode, 0, 0 );
+                handle = keyCapture.iHandle;
+                break;
+            case EKeyCaptureUpAndDownEvents:
+                keyCapture.iType = EKeyCaptureUpAndDownEvents;
+                keyCapture.iHandleForUpAndDown = iWindowGroup.CaptureKeyUpAndDowns( keyCapture.iKey, 0, 0 );
+                handle = keyCapture.iHandleForUpAndDown;
+                break;
+            default: // EKeyCaptureAllEvents
+                {
+                keyCapture.iType = EKeyCaptureAllEvents;
+                keyCapture.iHandle = iWindowGroup.CaptureKey( keyCapture.iKeyCode, 0, 0 );
+                if ( keyCapture.iHandle >= 0 )
+                    {
+                    keyCapture.iHandleForUpAndDown = iWindowGroup.CaptureKeyUpAndDowns( keyCapture.iKey, 0, 0 );
+                    if ( keyCapture.iHandleForUpAndDown < 0 )
+                        {
+                        iWindowGroup.CancelCaptureKey( keyCapture.iHandle );
+                        }
+                    handle = keyCapture.iHandleForUpAndDown;
+                    }
+                break;
+                }
+            }
+
+        RDebug::Printf( "CLockAppKeyCaptureController::StartCapturingKey - handle: 0x%08x", handle );
+
+        if ( handle >= 0 )
+            {
+            if ( iCapturedKeys.Append( keyCapture )!= KErrNone )
+                {
+                StopKeyCapture( keyCapture );
+                }
+            }
+        }
+    }
+
+// ---------------------------------------------------------
+// Stops capturing a key
+// ---------------------------------------------------------
+void CLockAppKeyCaptureController::StopCapturingKey( TUint32 aKey )
+    {
+		RDebug::Printf( "%s %s (%u) aKey=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKey );
+    const TInt capturedKeyCount = iCapturedKeys.Count( );
+    TBool foundKey = EFalse;
+    for (TInt i = 0; ( i < capturedKeyCount ) && !foundKey; i++ )
+        {
+        if ( iCapturedKeys[i].iKey == aKey )
+            {
+            foundKey = ETrue;
+            StopKeyCapture( iCapturedKeys[i] );
+            iCapturedKeys.Remove( i );
+            }
+        }
+    }
+
+// ---------------------------------------------------------
+// May be used to ask whether a key has been set to be captured
+// ---------------------------------------------------------
+TBool CLockAppKeyCaptureController::IsKeyCaptured( TUint32 aKey ) const
+    {
+		RDebug::Printf( "%s %s (%u) aKey=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKey );
+    const TInt capturedKeyCount = iCapturedKeys.Count( );
+    TBool isCaptured = EFalse;
+    for (TInt i = 0; ( i < capturedKeyCount ) && !isCaptured; i++ )
+        {
+        isCaptured = iCapturedKeys[i].iKey == aKey;
+        }
+    return isCaptured;
+    }
+
+// ---------------------------------------------------------
+// Stops capturing a key
+// ---------------------------------------------------------
+void CLockAppKeyCaptureController::StopKeyCapture( TPhoneKeyCapture aKeyCapture )
+    {
+		RDebug::Printf( "%s %s (%u) value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 0 );
+    switch ( aKeyCapture.iType )
+        {
+        case EKeyCaptureEvent:
+            iWindowGroup.CancelCaptureKey( aKeyCapture.iHandle );
+            break;
+        case EKeyCaptureUpAndDownEvents:
+            iWindowGroup.CancelCaptureKeyUpAndDowns( aKeyCapture.iHandleForUpAndDown );
+            break;
+        default: // EPhoneKeyCaptureAllEvents
+            {
+            iWindowGroup.CancelCaptureKey( aKeyCapture.iHandle );
+            iWindowGroup.CancelCaptureKeyUpAndDowns( aKeyCapture.iHandleForUpAndDown );
+            break;
+            }
+        }
+    }
+
+// end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappkeyguardcontrol.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,690 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Keyguard UI
+ *
+*/
+
+
+#include "lockappkeyguardcontrol.h"
+#include "lockappstatecontrolinterface.h"
+#include "lockappcenrepobserver.h"
+#include "lockapppubsubobserver.h"
+#include "lockapputils.h"
+#include "lockapplockednote.h" // keyguard notes
+#include "lockappkeycapturecontroller.h"
+
+#include <avkon.rsg> // general avkon resources
+#include <aknnotpi.rsg> // keyguard spesific resources
+#include <AknUtils.h>
+#include <activitymanager.h>
+#include <SecondaryDisplay/AknSecondaryDisplayDefs.h> // publishing keyguard notes to secondary display
+#include <featmgr.h> // feature manager
+#include <eikcba.h> // keyguard soft buttons
+#include <eikspane.h>
+
+#include "AutolockPrivateCRKeys.h"
+#include <settingsinternalcrkeys.h>
+#include <ScreensaverInternalPSKeys.h>
+#include <hwrmdomainpskeys.h>
+#include <activeidle2domainpskeys.h>
+//#include <CoreApplicationUIsPrivateCRKeys.h> TODO remove
+#include <coreapplicationuisdomainpskeys.h>
+#include <ctsydomainpskeys.h>
+#include <startupdomainpskeys.h>
+
+// Asterisk key's scan code for the keylock
+const TUint KStdKeyAsterisk = 42;
+//const TUint KAknChineseAsterisk = 0xFF0A;
+
+// timeout defined in keyguard ui specification custom value
+// since avkon note TTimeout values don't support 1 second timeout
+const TInt KKeyLockCustomShortTimeout = 1000000;
+
+// Auto Keyguard Off value
+const TInt KAutoKeyguardOff( 60000 );
+
+// Flip open value
+const TInt KFlipOpen = 1;
+
+// Screensaver started fron idle status value
+const TInt KSsStartedFromIdle = 1;
+
+// ---------------------------------------------------------------------------
+// Standard Symbian OS construction sequence
+// ---------------------------------------------------------------------------
+CLockAppKeyguardControl* CLockAppKeyguardControl::NewL(MLockAppStateControl& aStateControl )
+    {
+    CLockAppKeyguardControl* self = new (ELeave) CLockAppKeyguardControl( aStateControl );
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Notes, cba and localized resources are freed in Keyguard UI destruction.
+// ---------------------------------------------------------------------------
+CLockAppKeyguardControl::~CLockAppKeyguardControl( )
+    {
+#ifdef RD_AUTO_KEYGUARD
+    if ( iActivityManager )
+        {
+        iActivityManager->Cancel( );
+        delete iActivityManager;
+        iActivityManager = NULL;
+        }
+    // CenRep observers
+    if ( iCRAutoKeyguardTime )
+        {
+        delete iCRAutoKeyguardTime;
+        iCRAutoKeyguardTime = NULL;
+        }
+#endif //RD_AUTO_KEYGUARD
+    if ( iCRPersistentKeyguardStatus )
+        {
+        delete iCRPersistentKeyguardStatus;
+        iCRPersistentKeyguardStatus = NULL;
+        }
+    if ( iPSStartupObserver )
+        {
+        delete iPSStartupObserver;
+        iPSStartupObserver = NULL;
+        }
+    // child notes
+    delete iConfirmationNote;
+    delete iLockedNote;
+    delete iKeypadUnlockedNote;
+    delete iKeypadLockedNote;
+    }
+
+// ---------------------------------------------------------------------------
+// Constructor passes the reference to the main state control.
+// ---------------------------------------------------------------------------
+CLockAppKeyguardControl::CLockAppKeyguardControl(MLockAppStateControl& aStateControl ) :
+    CLockAppBaseControl(aStateControl)
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// Keyguard UI constructor reserves localized resources, configures itself
+// using CenRep and FeatureManager and reserves child controls.
+// ---------------------------------------------------------------------------
+void CLockAppKeyguardControl::ConstructL( )
+    {
+    INFO( "CLockAppKeyguardControl::ConstructL started" );
+    CLockAppBaseControl::ConstructL( );
+
+    // feature manager is used for determining if the phone is a slider
+    TBool aFeatureKeypadNoSlider(ETrue);
+    FeatureManager::InitializeLibL( );
+    aFeatureKeypadNoSlider = FeatureManager::FeatureSupported( KFeatureIdKeypadNoSlider );
+    INFO_1("CLockAppKeyguardControl::ConstructL - aFeatureKeypadNoSlider: %d", aFeatureKeypadNoSlider);
+    FeatureManager::UnInitializeLib( );
+
+    // keyguard hardware switch support
+    CRepository* repository = CRepository::NewLC( KCRUidLockConf );
+    TInt hardwareSupport(0);
+    repository->Get( KKeyguardHardwareConf, hardwareSupport );
+    CleanupStack::PopAndDestroy( repository );
+    iHardwareSupport = TLockHardware( hardwareSupport );
+    iHardwareSupport = TLockHardware( 0 );
+
+    TBool touchEnabled( AknLayoutUtils::PenEnabled() );
+    
+    // Cba control
+    iCba = CEikButtonGroupContainer::NewL( CEikButtonGroupContainer::ECba,
+                                           CEikButtonGroupContainer::EHorizontal,
+                                           this,
+                                           touchEnabled ? R_AVKON_SOFTKEYS_EMPTY :
+                                           R_KEYLOCK_SOFTKEYS_UNLOCK_EMPTY );
+    TRect screenRect;
+    AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::EScreen, screenRect );
+    iCba->SetBoundingRect( screenRect );
+    iCba->MakeVisible( EFalse );
+
+    // Construct Keyguard Notes
+    iKeypadLockedNote = new (ELeave) CLockAppLockedNote();
+    iKeypadLockedNote->ConstructSleepingNoteL( touchEnabled ? R_KEYLOCK_NOTE_DISPLAY_LOCK_ON_TOUCH :
+                                               R_KEYLOCK_NOTE_LOCK_ON );
+    iKeypadLockedNote->ButtonGroupContainer().ButtonGroup()->AsControl()->DrawableWindow()->SetOrdinalPosition( 0, 2 );
+    iKeypadLockedNote->PublishDialogL( EAknKeysLockedNote );
+
+    iKeypadUnlockedNote = new (ELeave) CLockAppLockedNote();
+    iKeypadUnlockedNote->ConstructSleepingNoteL( touchEnabled ? R_KEYLOCK_NOTE_DISPLAY_LOCK_OFF_TOUCH :
+                                                 R_KEYLOCK_NOTE_LOCK_OFF );
+    iKeypadUnlockedNote->ButtonGroupContainer().ButtonGroup()->AsControl()->DrawableWindow()->SetOrdinalPosition( 0, 2 );
+    iKeypadUnlockedNote->PublishDialogL( EAknKeysReleasedNote );
+
+    iLockedNote = new (ELeave) CLockAppLockedNote();
+    if ( touchEnabled )
+        {
+        iLockedNote->ConstructSleepingNoteL( R_KEYLOCK_NOTE_DISPLAY_LOCKED_TOUCH );
+        }
+    else
+        {
+        switch ( iHardwareSupport )
+            {
+            case EKeyguardOnePositionSwitch:
+            case EKeyguardTwoPositionSwitch:
+                {
+                iLockedNote->ConstructSleepingNoteL( R_KEYLOCK_NOTE_KEYLOCKED_SWITCH );
+                break;
+                }
+            case EKeyguardDefaultHardware:
+            default:
+                {
+                iLockedNote->ConstructSleepingNoteL( R_KEYLOCK_NOTE_KEYLOCKED );
+                break;
+                }
+            }
+        }
+    iLockedNote->ButtonGroupContainer().ButtonGroup()->AsControl()->DrawableWindow()->SetOrdinalPosition( 0, 2 );
+
+    // These are created only if touch is not enabled, since
+    // currently in touch devices the keylock state is controlled
+    // with switch.
+    if ( !touchEnabled )
+        {
+        //Note showing "Now Press *" - when user has pressed "Unlock" in locked state.
+        if ( aFeatureKeypadNoSlider )
+            {
+            // for normal phones
+            iConfirmationNote = new (ELeave) CLockAppLockedNote();
+            iConfirmationNote->ConstructSleepingNoteL( R_KEYLOCK_NOTE_UNLOCK_ASTERISK );
+            }
+        else
+            {
+            // for special slider phones
+            iConfirmationNote = new (ELeave) CLockAppLockedNote();
+            iConfirmationNote->ConstructSleepingNoteL( R_KEYLOCK_NOTE_UNLOCK_CONFIRM );
+            }
+        iConfirmationNote->ButtonGroupContainer().ButtonGroup()->AsControl()->DrawableWindow()->SetOrdinalPosition( 0, 2 );
+        
+        }
+    
+    
+    // CenRep observers
+    // TODO create private CR key for storing persistent keyguard state (currently in Sysap)
+    // iCRPersistentKeyguardStatus = CLockAppCenRepObserver::NewL ( this, KCRUidCoreApplicationUIsSysAp, KSysApKeyguardActive );
+
+#ifdef RD_AUTO_KEYGUARD
+    iCRAutoKeyguardTime = CLockAppCenRepObserver::NewL ( this, KCRUidSecuritySettings, KSettingsAutomaticKeyguardTime );
+    // Activity manager
+    iActivityManager = CUserActivityManager::NewL( CActive::EPriorityStandard );
+    StartActivityMonitoringL( );
+#endif //RD_AUTO_KEYGUARD
+
+    // PubSub observers
+    iPSStartupObserver = CLockAppPubSubObserver::NewL( this, KPSUidStartup, KPSGlobalSystemState );
+
+    // Setup key pattern matcher
+    if ( !SetupKeyPatternsWithPolicyL( EPolicyDeactivateKeyguard ) )
+        {
+        INFO( "CLockAppKeyguardControl::ConstructL - No CenRep policy defined" );
+        if ( aFeatureKeypadNoSlider )
+            {
+            iKeyPattern->AddPattern( EStdKeyDevice0, KStdKeyAsterisk ); // LSK + *
+            }
+        else
+            {
+            iKeyPattern->AddPattern( EStdKeyDevice0, EStdKeyDevice1 ); // LSK + RSK
+            }
+        }
+#ifdef __WINS__
+    // In Emulator add the LSK+* pattern also.
+    iKeyPattern->AddPattern( EStdKeyDevice0, EStdKeyNkpAsterisk ); // LSK + *
+#endif
+
+    INFO( "CLockAppKeyguardControl::ConstructL completed" );
+    }
+
+// ---------------------------------------------------------------------------
+// Check weather its allowed to automatically lock the keys
+// ---------------------------------------------------------------------------
+TBool CLockAppKeyguardControl::AutoActivationAllowedL( )
+    {
+#ifdef RD_AUTO_KEYGUARD
+    TInt value = 0;
+    TBool flipOpen(EFalse);
+    RProperty::Get( KPSUidHWRM, KHWRMFlipStatus, value );
+    flipOpen = (value = KFlipOpen);
+    INFO_1("CLockAppKeyguardControl::AutoActivationAllowedL - flipOpen: %d", flipOpen);
+    if ( flipOpen )
+        {
+        CRepository* repository = CRepository::NewL( KCRUidAutolockConf );
+        repository->Get( KAutoKeyLockConf, value );
+        delete repository;
+        if ( value & KAutoKeylockFeatureIdFlipOpenDisabled )
+            {
+            INFO( "CLockAppKeyguardControl::AutoActivationAllowedL : False because flipOpenDisabled" );
+            return EFalse;
+            }
+        }
+
+    TInt lightStatus=EForcedLightsUninitialized; 
+    RProperty::Get(KPSUidCoreApplicationUIs,KLightsVTForcedLightsOn,lightStatus ); 
+    INFO_1("CLockAppKeyguardControl::AutoActivationAllowedL - lightStatus: %d", lightStatus);
+    if ( lightStatus == EForcedLightsOn )
+	{
+	INFO( "CLockAppKeyguardControl::AutoActivationAllowedL : False because EForcedLightsOn" );
+	return EFalse;
+	}
+
+    TBool keysLocked(EFalse);
+    TBool idle(EFalse);
+    TBool ongoingCall(EFalse);
+    TBool screenSaverOn(EFalse);
+    TBool screenSaverStertedFromIdle(EFalse);
+
+    keysLocked = (iStateControl.LockStatus() != ELockNotActive);
+    INFO_1("CLockAppKeyguardControl::AutoActivationAllowedL - keysLocked: %d", keysLocked);
+    value = 0;
+    RProperty::Get( KPSUidCtsyCallInformation, KCTsyCallState, value );
+    ongoingCall = (value > EPSCTsyCallStateNone);
+    INFO_2("CLockAppKeyguardControl::AutoActivationAllowedL - ongoingCall: %d %d", value, ongoingCall);
+    value = 0;
+    RProperty::Get( KPSUidAiInformation, KActiveIdleState, value );
+    idle = (value == EPSAiForeground);
+    INFO_2("CLockAppKeyguardControl::AutoActivationAllowedL - idle: %d %d", value, idle);
+    value = 0;
+    RProperty::Get( KPSUidScreenSaver, KScreenSaverOn, value );
+    screenSaverOn = (value > 0);
+    INFO_2("CLockAppKeyguardControl::AutoActivationAllowedL - screenSaverOn: %d %d", value, screenSaverOn);
+    value = 0;
+    RProperty::Get( KPSUidScreenSaver, KScreenSaverActivatedFromIdle, value );
+    screenSaverStertedFromIdle = (value == KSsStartedFromIdle);
+    INFO_2("CLockAppKeyguardControl::AutoActivationAllowedL - screenSaverStertedFromIdle: %d %d", value, screenSaverStertedFromIdle);
+
+    // If a call is ongoing or idle doesnt have foreground and
+    // screensaver is not started from idle -> dont lock keys
+    if ( keysLocked || ongoingCall || (!idle && !(screenSaverOn && screenSaverStertedFromIdle)) )
+        {
+        INFO("CLockAppKeyguardControl::AutoActivationAllowedL : False");
+        return EFalse;
+        }
+#endif //RD_AUTO_KEYGUARD
+    INFO("CLockAppKeyguardControl::AutoActivationAllowedL : True");
+    return ETrue;
+    }
+
+// ---------------------------------------------------------------------------
+// Check weather its allowed to activate the control
+// ---------------------------------------------------------------------------
+TBool CLockAppKeyguardControl::ActivationAllowedL( )
+    {
+    return ETrue;
+    }
+
+// ---------------------------------------------------------------------------
+// Check weather its allowed to deactivate the control
+// ---------------------------------------------------------------------------
+TBool CLockAppKeyguardControl::DeActivationAllowedL( )
+    {
+    return ETrue;
+    }
+
+// ---------------------------------------------------------------------------
+// Activate control
+// ---------------------------------------------------------------------------
+void CLockAppKeyguardControl::HandleActivateEventL( TUint aEnvMask )
+    {    
+    INFO_1("CLockAppKeyguardControl::HandleActivateEventL - aEnvMask: %x", aEnvMask);
+    
+    CLockAppBaseControl::HandleActivateEventL( aEnvMask );
+
+    if ( IsBitFieldSet( aEnvMask, KLockAppEnvScreenSaverOn ) )
+        {
+        // if screensaver is on - capture primary keys
+        CapturePrimaryKeys( ETrue );
+        }
+
+    // capture keys
+    CLockAppKeyCaptureController::CaptureKey( EStdKeyApplication0, EKeyApplication0, EKeyCaptureAllEvents ); // App key
+    CLockAppKeyCaptureController::CaptureKey( EStdKeyDevice2, EKeyDevice2, EKeyCaptureAllEvents ); // Power key (for lights)
+    CLockAppKeyCaptureController::CaptureKey( EStdKeyDevice6, EKeyDevice6, EKeyCaptureAllEvents ); // Voice key (for lights)
+    CLockAppKeyCaptureController::CaptureKey( EStdKeyNo, EKeyNo, EKeyCaptureAllEvents ); // End key (for Rosetta lights)
+
+    SetPointerEventCapture( ETrue );
+    SetKeyguardIndicatorStateL( ETrue );
+    ShowCba( ETrue );
+    // close task-list in case it is displayed : fast-swap window
+    iEikonEnv->DismissTaskList( );
+    if ( iCba )
+        {
+        TBool areWeInIdleState = CEikStatusPaneBase::Current()->PaneCapabilities(TUid::Uid(EEikStatusPaneUidClock)).IsInCurrentLayout( );
+        if ( areWeInIdleState )
+            {
+            (static_cast<CEikCba*>(iCba->ButtonGroup()))->SetSkinBackgroundId( KAknsIIDQsnBgAreaControlIdle );
+            }
+        else
+            {
+            (static_cast<CEikCba*>(iCba->ButtonGroup()))->SetSkinBackgroundId( KAknsIIDQsnBgAreaControl );
+            }
+        }
+
+    if ( iCRPersistentKeyguardStatus )
+        {
+        iCRPersistentKeyguardStatus->SetValue( 1 );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// DeActivate control
+// ---------------------------------------------------------------------------
+void CLockAppKeyguardControl::HandleDeActivateEventL( TUint aEnvMask )
+    {
+    INFO_1("CLockAppKeyguardControl::HandleDeActivateEventL - aEnvMask: 0x%x", aEnvMask);
+    
+    CLockAppBaseControl::HandleDeActivateEventL( aEnvMask );
+
+    if ( IsBitFieldSet( aEnvMask, KLockAppEnvScreenSaverOn ) )
+        {
+        // if screensaver is on - uncapture primary keys
+        CapturePrimaryKeys( EFalse );
+        }
+
+    // phonecall or not - uncapture keys anyway
+    CLockAppKeyCaptureController::ReleaseKey( EStdKeyApplication0 );
+    CLockAppKeyCaptureController::ReleaseKey( EStdKeyDevice2 );
+    CLockAppKeyCaptureController::ReleaseKey( EStdKeyDevice6 );
+    CLockAppKeyCaptureController::ReleaseKey( EStdKeyNo );
+
+    SetPointerEventCapture( EFalse );
+    SetKeyguardIndicatorStateL( EFalse );
+    ShowCba( EFalse );
+
+    if ( iCRPersistentKeyguardStatus )
+        {
+        iCRPersistentKeyguardStatus->SetValue( 0 );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Handle environment changes (Screensaver, Telephony, etc.)
+// ---------------------------------------------------------------------------
+void CLockAppKeyguardControl::HandleEnvironmentChange( TUint aEnvMask, TUint aEventMask )
+    {
+    if ( IsBitFieldSet( aEventMask, KLockAppEnvScreenSaverOn ) )
+        {
+        // screen saver state changed
+        CapturePrimaryKeys( IsBitFieldSet( aEnvMask, KLockAppEnvScreenSaverOn ) );
+        }
+    if ( IsBitFieldSet( aEventMask, KLockAppEnvFPS ) )
+        {
+    		// iStateControl.DisableKeyguardL( ETrue );
+    		// iStateControl.LockStatus() != ELockNotActive		// no need to check, because keyguard will catch fingerprint only if not locked
+    		iStateControl.EnableDevicelockL( EDevicelockManual );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Inform the user that keys are locked (i.e. "Please press LSK+'*' to unlock).
+// ---------------------------------------------------------------------------
+void CLockAppKeyguardControl::DisplayLockedNote( )
+    {
+    ShowNote( iLockedNote, CAknNoteDialog::ELongTimeout, CAknNoteDialog::ENoTone );
+    }
+
+// ---------------------------------------------------------------------------
+// Handle all Central Repository observer callbacks.
+// ---------------------------------------------------------------------------
+void CLockAppKeyguardControl::HandleCenRepNotify(TUid aCenRepUid, TUint32 aKeyId, TInt aValue )
+    {
+    if ( aCenRepUid == KCRUidSecuritySettings )
+        {
+        switch ( aKeyId )
+            {
+            case KSettingsAutomaticKeyguardTime:
+                {
+                INFO_1( "CLockAppKeyguardControl::HandleCenRepNotify - KSettingsAutomaticKeyguardTime = %d", aValue );
+                ResetInactivityTimeout( );
+                }
+                break;
+            default:
+                break;
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Handle all Publish & Subscribe observer callbacks.
+// ---------------------------------------------------------------------------
+void CLockAppKeyguardControl::HandlePubSubNotify(TUid aPubSubUid, TUint aKeyId, TInt aValue )
+    {
+    if ( aPubSubUid == KPSUidStartup )
+        {
+        switch ( aKeyId )
+            {
+            case KPSGlobalSystemState:
+                {
+                // In case of unexpected reset (e.g. hidden boot) the keylock must be enabled silently.
+                if ( !iAlreadyNormalState && (aValue == ESwStateNormalRfOn || aValue == ESwStateNormalRfOff) )
+                    {
+                    iAlreadyNormalState = ETrue;
+                    TInt keylockWasEnabled = 0;
+                    if ( iCRPersistentKeyguardStatus )
+                        {
+                        iCRPersistentKeyguardStatus->GetValue( keylockWasEnabled );
+                        if ( keylockWasEnabled )
+                            {
+                            TRAPD(err, iStateControl.EnableKeyguardL( EFalse ));
+                            ERROR(err, "CLockAppKeyguardControl::HandlePubSubNotify - EnableKeyguardL");
+                            }
+                        }
+                    }
+                }
+                break;
+            default:
+                break;
+            }
+        }
+    INFO_3( "CLockAppKeyguardControl::HandlePubSubNotify %x %x = %x", aPubSubUid.iUid, aKeyId, aValue );
+    }
+
+// ---------------------------------------------------------------------------
+// Show that keys are locked.
+// ---------------------------------------------------------------------------
+void CLockAppKeyguardControl::DisplayKeysLockedNote( )
+    {
+    ShowNote( iKeypadLockedNote, KKeyLockCustomShortTimeout, CAknNoteDialog::ENoTone );
+    }
+
+// ---------------------------------------------------------------------------
+// Show that keys are unlocked.
+// ---------------------------------------------------------------------------
+void CLockAppKeyguardControl::DisplayKeysActiveNote( )
+    {
+    ShowNote( iKeypadUnlockedNote, KKeyLockCustomShortTimeout, CAknNoteDialog::ENoTone );
+    }
+
+// ---------------------------------------------------------------------------
+// Show confirmation note when user has pressed "Unlock".
+// ---------------------------------------------------------------------------
+void CLockAppKeyguardControl::DisplayConfirmationNote( )
+    {
+    ShowNote( iConfirmationNote, CAknNoteDialog::EShortTimeout, CAknNoteDialog::EConfirmationTone );
+    // inform sysap to put lights on left soft key press
+    SendMessageToSysAp( EEikKeyLockLightsOnRequest );
+    }
+
+// ---------------------------------------------------------------------------
+// Keyguard UI key events are handled trough here.
+// ---------------------------------------------------------------------------
+TKeyResponse CLockAppKeyguardControl::OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+    RDebug::Printf( "%s %s (%u) aKeyEvent.iCode=%x aType=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKeyEvent.iCode, aType );
+    RDebug::Printf( "%s %s (%u) iActive=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iActive );
+    if ( iActive )
+        {
+        		if(AknLayoutUtils::PenEnabled())
+        			{
+        			if(aKeyEvent.iCode == EKeyDeviceF)	// any Type
+        				{
+        				iStateControl.DisableKeyguardL( ETrue );
+        				}
+        			}
+        if ( aType == EEventKeyDown )
+            {
+            switch ( iKeyPattern->HandleKeyEvent( aKeyEvent.iScanCode ) )
+                {
+                case EPatternNoMatch:
+                    DisplayLockedNote( );
+                    break;
+                case EPatternPrimaryMatch:
+                    DisplayConfirmationNote( );
+                    break;
+                case EPatternSecondaryMatch:
+                    iStateControl.DisableKeyguardL( ETrue );
+                    break;
+                default:
+        						RDebug::Printf( "%s %s (%u) default=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 1 );
+                    break;
+                }
+            }
+        }
+    return EKeyWasConsumed;
+    }
+
+// ---------------------------------------------------------------------------
+// Get autokeyguard timeout (in seconds)
+// @return 0 means Off
+// ---------------------------------------------------------------------------
+TInt CLockAppKeyguardControl::GetAutoKeyguardTimeout( )
+    {
+    TInt timeoutInSeconds( 0 );
+#ifdef RD_AUTO_KEYGUARD
+    iCRAutoKeyguardTime->GetValue( timeoutInSeconds );
+#endif //RD_AUTO_KEYGUARD
+    return timeoutInSeconds;
+    }
+
+// ----------------------------------------------------------
+// Starts monitoring user activity
+// ----------------------------------------------------------
+void CLockAppKeyguardControl::StartActivityMonitoringL( )
+    {
+#ifdef RD_AUTO_KEYGUARD
+    __ASSERT_DEBUG( iActivityManager, DoPanic(ELockIllegalState));
+    if ( iActivityManager && !iActivityManager->IsActive() )
+        {
+        TInt value = GetAutoKeyguardTimeout( );
+        INFO_1( "CLockAppKeyguardControl::StartActivityMonitoringL - %d sec", value);
+        if ( value )
+            {
+            iActivityManager->Start( value,
+                    TCallBack( HandleInactiveEventL, this ),
+                    TCallBack( HandleActiveEventL, this ) );
+            }
+        else
+            {
+            iActivityManager->Start( KAutoKeyguardOff,
+                    TCallBack( HandleInactiveEventL, this ),
+                    TCallBack( HandleActiveEventL, this ) );
+            }
+        }
+#endif //RD_AUTO_KEYGUARD
+    }
+
+// ----------------------------------------------------------
+// Gets keyguard period and starts monitoring user activity
+// ----------------------------------------------------------
+void CLockAppKeyguardControl::ResetInactivityTimeout( )
+    {
+#ifdef RD_AUTO_KEYGUARD
+    __ASSERT_DEBUG( iActivityManager, DoPanic(ELockIllegalState));
+    if ( iActivityManager )
+        {
+        TInt value = GetAutoKeyguardTimeout( );
+        INFO_1( "CLockAppKeyguardControl::ResetInactivityTimeout - %d sec", value);
+        if ( value )
+            {
+            iActivityManager->SetInactivityTimeout( value );
+            }
+        else
+            {
+            iActivityManager->SetInactivityTimeout( KAutoKeyguardOff );
+            }
+        }
+#endif //RD_AUTO_KEYGUARD
+    }
+
+// ----------------------------------------------------------
+// Stop monitoring user activity.
+// ----------------------------------------------------------
+void CLockAppKeyguardControl::StopActivityMonitoring( )
+    {
+#ifdef RD_AUTO_KEYGUARD
+    if ( iActivityManager )
+        {
+        iActivityManager->Cancel( );
+        }
+#endif //RD_AUTO_KEYGUARD
+    }
+
+// ----------------------------------------------------------
+// Handle Active event. Called by ActivityManager
+// ----------------------------------------------------------
+TInt CLockAppKeyguardControl::HandleActiveEventL(TAny* /*aPtr*/)
+    {
+    return KErrNone;
+    }
+
+// ----------------------------------------------------------
+// Handles InActive event. Called by ActivityManager
+// ----------------------------------------------------------
+TInt CLockAppKeyguardControl::HandleInactiveEventL(TAny* aPtr )
+    {
+#ifdef RD_AUTO_KEYGUARD
+    CLockAppKeyguardControl* keyguard = STATIC_CAST(CLockAppKeyguardControl*, aPtr);
+    if ( keyguard->GetAutoKeyguardTimeout( ) && keyguard->AutoActivationAllowedL( ) )
+        {
+        keyguard->iStateControl.EnableKeyguardL( EFalse );
+        }
+#endif //RD_AUTO_KEYGUARD
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// Handle UI commands received from the child controls
+// ---------------------------------------------------------------------------
+void CLockAppKeyguardControl::ProcessCommandL( TInt aCommandId )
+    {
+    INFO_1("CLockAppKeyguardControl::ProcessCommandL : %d ", aCommandId );
+    }
+
+TInt CLockAppKeyguardControl::CountComponentControls( ) const
+    {
+    return 1;
+    }
+
+CCoeControl* CLockAppKeyguardControl::ComponentControl(TInt /*aIndex*/) const
+    {
+    return iCba;
+    }
+
+// ---------------------------------------------------------------------------
+// Notification if layout changes.
+// ---------------------------------------------------------------------------
+void CLockAppKeyguardControl::HandleResourceChange(TInt aType )
+    {
+    if ( aType == KEikDynamicLayoutVariantSwitch && iCba )
+        {
+        TRect screenRect;
+        AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::EScreen, screenRect );
+        iCba->SetBoundingRect( screenRect );
+        }
+    CCoeControl::HandleResourceChange( aType );
+    }
+
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappkeypattern.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,281 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Key pattern matching component.
+ *
+*/
+
+
+#include "lockapptrace.h"
+#include "lockappkeypattern.h"
+
+const TInt KDefaultTimeout = 2000000;
+
+// ---------------------------------------------------------------------------
+// Standard two-phased construction
+// ---------------------------------------------------------------------------
+CLockAppKeyPattern* CLockAppKeyPattern::NewL( )
+    {
+    CLockAppKeyPattern *self = new ( ELeave ) CLockAppKeyPattern();
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Default C++ constructor
+// ---------------------------------------------------------------------------
+CLockAppKeyPattern::CLockAppKeyPattern( ) :
+    iKeyTimeOut( KDefaultTimeout ),
+    iState( EPatternNoMatch ),
+    iEnabled ( ETrue ),
+    iHasPatterns( EFalse )
+    {
+    // no implementation required
+    }
+
+// ---------------------------------------------------------------------------
+// Key pattern construction
+// ---------------------------------------------------------------------------
+void CLockAppKeyPattern::ConstructL( )
+    {
+    iKeyTimer = CPeriodic::NewL( CActive::EPriorityUserInput );
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+CLockAppKeyPattern::~CLockAppKeyPattern( )
+    {
+    ClearPatterns( );
+    // timer between key presses is cancelled
+    if ( iKeyTimer )
+        {
+        iKeyTimer->Cancel( );
+        delete iKeyTimer;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Gets the enabled state.
+// ---------------------------------------------------------------------------
+TBool CLockAppKeyPattern::IsEnabled( )
+    {
+    return iEnabled;
+    }
+
+// ---------------------------------------------------------------------------
+// Sets the enabled state.
+// ---------------------------------------------------------------------------
+void CLockAppKeyPattern::SetEnabled(TBool aEnabled )
+    {
+    iEnabled = aEnabled;
+    }
+
+// ---------------------------------------------------------------------------
+// Gets the primary key timeout.
+// ---------------------------------------------------------------------------
+TUint CLockAppKeyPattern::GetKeyTimeOut( )
+    {
+    return iKeyTimeOut;
+    }
+
+// ---------------------------------------------------------------------------
+// Sets the primary key timeout.
+// ---------------------------------------------------------------------------
+void CLockAppKeyPattern::SetKeyTimeOut(TUint aTimeOut )
+    {
+    iKeyTimeOut = aTimeOut;
+    }
+
+// ---------------------------------------------------------------------------
+// Add new key combination
+// ---------------------------------------------------------------------------
+TInt CLockAppKeyPattern::AddPattern( TUint32 aPrimaryKey, TUint32 aSecondaryKey )
+    {
+    TInt err(KErrNone);
+    iPrimaryKeys.Append( aPrimaryKey );
+    iSecondaryKeys.Append( aSecondaryKey );
+    iHasPatterns = ETrue;
+    return err;
+    }
+
+// ---------------------------------------------------------------------------
+// Get key combination
+// ---------------------------------------------------------------------------
+TInt CLockAppKeyPattern::GetPattern(TInt aIndex, TUint32& aPrimaryKey, TUint32& aSecondaryKey )
+    {
+    TInt err( KErrNone);
+    if ( iHasPatterns && aIndex < iPrimaryKeys.Count( )&& aIndex < iSecondaryKeys.Count( ) )
+        {
+        aPrimaryKey = iPrimaryKeys[aIndex];
+        aSecondaryKey = iSecondaryKeys[aIndex];
+        }
+    else
+        {
+        err = KErrNotFound;
+        }
+    return err;
+    }
+
+// ---------------------------------------------------------------------------
+// Returns true if the key pattern matcher has been initialized
+// ---------------------------------------------------------------------------
+TBool CLockAppKeyPattern::HasPatterns( )
+    {
+    return (iHasPatterns && iPrimaryKeys.Count() > 0 && iSecondaryKeys.Count() > 0);
+    }
+
+// ---------------------------------------------------------------------------
+// Clear all key combinations
+// ---------------------------------------------------------------------------
+TInt CLockAppKeyPattern::ClearPatterns( )
+    {
+    TInt err( KErrNone);
+    if ( iHasPatterns )
+        {
+        iPrimaryKeys.Reset( );
+        iSecondaryKeys.Reset( );
+        iWaitingKeys.Reset( );
+        iHasPatterns = EFalse;
+        // cancel the timer
+        iKeyTimer->Cancel( );
+        }
+    return err;
+    }
+
+// ---------------------------------------------------------------------------
+// Receives keys and checks whether they match any primary+secondary key combination
+// ---------------------------------------------------------------------------
+TPatternState CLockAppKeyPattern::HandleKeyEvent( TUint32 aKey )
+    {  
+    if ( iEnabled )
+        {
+        if ( iHasPatterns )
+            {
+            switch (iState)
+                {
+                case EPatternNoMatch:
+                case EPatternSecondaryMatch:
+                    {
+                    if ( iPrimaryKeys.Find( aKey ) != KErrNotFound )
+                        {
+                        HandlePrimaryKeyEvent( aKey );
+                        }
+                    else
+                        {
+                        HandleOtherKeyEvent();
+                        }
+                    }
+                    break;
+                case EPatternPrimaryMatch:
+                    {
+                    if ( iWaitingKeys.Find( aKey ) != KErrNotFound )
+                        {
+                        HandleSecondaryKeyEvent();
+                        }
+                    else
+                        {
+                        if ( iPrimaryKeys.Find( aKey ) != KErrNotFound )
+                            {
+                            HandlePrimaryKeyEvent( aKey );
+                            }
+                        else
+                            {
+                            HandleOtherKeyEvent();
+                            }
+                        }
+                    }
+                    break;
+                default:
+                    break;
+                }
+            }
+        else
+            {
+            return EPatternNotInitialized;
+            }
+        }
+    else
+        {
+        return EPatternNotEnabled;
+        }
+
+    return iState;
+    }
+
+// ---------------------------------------------------------------------------
+// Handles primary key events
+// ---------------------------------------------------------------------------
+void CLockAppKeyPattern::HandlePrimaryKeyEvent( TUint32 aKey )
+    {
+    // cancel the timer
+    iKeyTimer->Cancel( );
+    // clear the waiting keys
+    iWaitingKeys.Reset( );
+    // add those secondary keys to the waiting keys, which have the same primary key
+    for (TInt i( 0); i < iPrimaryKeys.Count( ); i++ )
+        {
+        if ( iPrimaryKeys[i] == aKey && i < iSecondaryKeys.Count( ) )
+            {
+            iWaitingKeys.Append( iSecondaryKeys[i] );
+            }
+        }
+
+    // start timer for primary key timeout
+    iKeyTimer->Start( iKeyTimeOut, iKeyTimeOut, TCallBack( HandleKeyTimerTimeout, this ) );
+
+    // set the state
+    iState = EPatternPrimaryMatch;
+    }
+
+// ---------------------------------------------------------------------------
+// Handles secondary key events
+// ---------------------------------------------------------------------------
+void CLockAppKeyPattern::HandleSecondaryKeyEvent( )
+    {
+    // cancel the timer
+    iKeyTimer->Cancel( );
+    // clear the waiting keys
+    iWaitingKeys.Reset( );
+    // set the state
+    iState = EPatternSecondaryMatch;
+    }
+
+// ---------------------------------------------------------------------------
+// Handles other key events
+// ---------------------------------------------------------------------------
+void CLockAppKeyPattern::HandleOtherKeyEvent( )
+    {
+    // cancel the timer
+    iKeyTimer->Cancel( );
+    // clear the waiting keys
+    iWaitingKeys.Reset( );
+    // set the state
+    iState = EPatternNoMatch;
+    }
+
+// ---------------------------------------------------------------------------
+// A call back to the key pattern timer, the allowed time window for pressing
+// the secondary key to get a match has passed.
+// ---------------------------------------------------------------------------
+TInt CLockAppKeyPattern::HandleKeyTimerTimeout( TAny* aSelf )
+    {
+    CLockAppKeyPattern* self = reinterpret_cast< CLockAppKeyPattern* >( aSelf );
+    // reset the state
+    self->HandleOtherKeyEvent( );
+    return KErrNone;
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockapplockednote.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Sleeping note with timeout and a reference flag that informs
+ *                the parent when the note is visible
+ *
+*/
+
+
+#include "lockapplockednote.h"
+
+// ---------------------------------------------------------------------------
+// Construction passes the parent implementing command observer interface
+// and a reference to variable that is true if note with timeout is shown,
+// false if not
+// ---------------------------------------------------------------------------
+CLockAppLockedNote::CLockAppLockedNote( MEikCommandObserver* aCommandObserver ) :
+	CLockAppSleepingNote(aCommandObserver)
+	{
+	// no implementation required
+	}
+
+// ---------------------------------------------------------------------------
+// In destruction set reference value (is note shown) to not true.
+// ---------------------------------------------------------------------------
+CLockAppLockedNote::~CLockAppLockedNote( )
+	{
+	}
+
+// ---------------------------------------------------------------------------
+// Method to cancel note from screen.
+// ---------------------------------------------------------------------------
+void CLockAppLockedNote::CancelNote( )
+	{
+	ExitSleepingDialog( );
+	}
+
+// ---------------------------------------------------------------------------
+// Inform the command observer (parent) about the focus lost event.
+// ---------------------------------------------------------------------------
+void CLockAppLockedNote::FocusChanged( TDrawNow /*aDrawNow*/)
+	{
+	if ( !IsFocused( ) && iCommandObserver )
+		{
+		TRAP_IGNORE(iCommandObserver->ProcessCommandL(KNoteCmdFocusLost))
+		}
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappobserverlist.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,126 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Lock App internal state control
+ *
+*/
+
+
+#include "lockappstatecontrol.h"
+#include "lockappstatepublisher.h"
+#include "lockappkeyguardcontrol.h"
+#include "lockapputils.h"
+#include "lockappecsdetector.h"
+
+const TInt KLockAppObserverListGranularity = 4;
+
+// ---------------------------------------------------------------------------
+// Standard C++ constructor
+// ---------------------------------------------------------------------------
+CLockAppObserverList::CLockAppObserverList( )
+    {
+    // no implementation required
+    }
+
+// ---------------------------------------------------------------------------
+// Destroys the observer list and all existing observers.
+// ---------------------------------------------------------------------------
+CLockAppObserverList::~CLockAppObserverList( )
+    {
+    if ( iObserverList )
+        {
+        TInt count = iObserverList->Count( );
+        for (TInt index=0; index<count; index++ )
+            {
+            delete (*iObserverList)[index];
+            }
+        iObserverList->Reset( );
+        delete iObserverList;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Adds lock state observer to the observer list.
+// ---------------------------------------------------------------------------
+void CLockAppObserverList::AddObserverL( MLockAppStateObserver* aObserver )
+    {
+    if ( aObserver )
+        {
+        TBool found(EFalse);
+        // check that the observer has not been added before
+        TInt count = iObserverList->Count( );
+        for ( TInt index=0; index<count; index++ )
+            {
+            if ( ((*iObserverList)[index]) == aObserver )
+                {
+                found = ETrue;
+                }
+            }
+        if ( !found )
+            {
+            iObserverList->AppendL( aObserver );
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Removes lock state observer from the observer list.
+// ---------------------------------------------------------------------------
+void CLockAppObserverList::RemoveObserver( MLockAppStateObserver* aObserver )
+    {
+    if ( aObserver )
+        {
+        TInt count = iObserverList->Count( );
+        for ( TInt index=0; index<count; index++ )
+            {
+            if ( ((*iObserverList)[index]) == aObserver )
+                {
+                iObserverList->Remove( index );
+                return;
+                }
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Constructs the observer list.
+// ---------------------------------------------------------------------------
+void CLockAppObserverList::BaseConstructL( )
+    {
+    // create observer list
+    iObserverList = new (ELeave) RPointerArray<MLockAppStateObserver>(KLockAppObserverListGranularity);
+    }
+
+// ---------------------------------------------------------------------------
+// Not implemented, meant for derived classes
+// ---------------------------------------------------------------------------
+void CLockAppObserverList::HandleLockStatusChangedL( TLockStatus /*aLockStatus*/)
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// Informs observers that the lock state has changed.
+// ---------------------------------------------------------------------------
+void CLockAppObserverList::PostStatusChangeL( TLockStatus aStatusChange )
+    {
+    // first inform the main control
+    HandleLockStatusChangedL( aStatusChange );
+
+    // for child observers
+    TInt count = iObserverList->Count( );
+    for ( TInt index=count-1; index>=0; index-- )
+        {
+        //TRAP_IGNORE
+        ((*iObserverList)[index])->HandleLockStatusChangedL( aStatusChange );
+        }
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockapppubsubobserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,146 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Publish & Subscribe key observer
+ *
+*/
+
+
+#include "lockapppubsubobserver.h"
+#include "lockapputils.h"
+
+// ---------------------------------------------------------------------------
+// Two-phased constructor.
+// ---------------------------------------------------------------------------
+CLockAppPubSubObserver* CLockAppPubSubObserver::NewL(MLockAppObserverInterface* aObserver,
+        TUid aPubSubUid, TUint32 aKeyId )
+    {
+    CLockAppPubSubObserver* self = new (ELeave) CLockAppPubSubObserver(aObserver, aPubSubUid, aKeyId);
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// C++ default constructor
+// ---------------------------------------------------------------------------
+CLockAppPubSubObserver::CLockAppPubSubObserver(MLockAppObserverInterface* aObserver,
+        TUid aPubSubUid, TUint32 aKeyId ) :
+    CActive( 0 ),
+    iObserver( aObserver ),
+    iPubSubUid( aPubSubUid ),
+    iKeyId( aKeyId ),
+    iValue( NULL )
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+CLockAppPubSubObserver::~CLockAppPubSubObserver( )
+    {
+    Cancel( );
+    iProperty.Close( );
+    }
+
+// ---------------------------------------------------------------------------
+// Symbian OS default constructor
+// ---------------------------------------------------------------------------
+void CLockAppPubSubObserver::ConstructL( )
+    {
+    // Add this active object to the scheduler.
+    CActiveScheduler::Add( this );
+    TInt err = iProperty.Attach( iPubSubUid, iKeyId );
+    ERROR_2(err, "CLockAppPubSubObserver::ConstructL - Property(%d,%d) attach", iPubSubUid, iKeyId);
+    User::LeaveIfError( err );
+    Start( );
+    }
+
+// ---------------------------------------------------------------------------
+// Starts listening
+// ---------------------------------------------------------------------------
+TInt CLockAppPubSubObserver::Start( )
+    {
+    if ( !IsActive( ) )
+        {
+        iStatus = KRequestPending;
+        iProperty.Subscribe( iStatus );
+        SetActive( );
+        return KErrNone;
+        }
+    else
+        {
+        return KErrInUse;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Stops listening
+// ---------------------------------------------------------------------------
+void CLockAppPubSubObserver::Stop( )
+    {
+    if ( IsActive( ) )
+        {
+        Cancel( );
+        iProperty.Cancel( );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Gets value of the key from P&S.
+// ---------------------------------------------------------------------------
+TInt CLockAppPubSubObserver::GetKeyValue(TInt& aValue )
+    {
+    RDebug::Printf( "%s %s (%u) 1=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 1 );
+    return iProperty.Get( aValue );
+    }
+
+// ---------------------------------------------------------------------------
+// Sets a value for the key in P&S.
+// ---------------------------------------------------------------------------
+TInt CLockAppPubSubObserver::SetKeyValue(TInt aValue )
+    {
+    RDebug::Printf( "%s %s (%u) aValue=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aValue );
+    return iProperty.Set( aValue );
+    }
+
+// ---------------------------------------------------------------------------
+// CLockAppPubSubObserver::RunL()
+// ---------------------------------------------------------------------------
+void CLockAppPubSubObserver::RunL( )
+    {
+    TInt value( NULL);
+    iProperty.Get( value );
+    if ( iValue != value )
+        {
+        // on value change
+        iValue = value;
+        if ( iObserver )
+            {
+            iObserver->HandlePubSubNotify( iPubSubUid, iKeyId, iValue );
+            }
+        }
+    // re-subscribe to events
+    Start( );
+    }
+
+// ---------------------------------------------------------------------------
+// Cancels event listening
+// ---------------------------------------------------------------------------
+void CLockAppPubSubObserver::DoCancel( )
+    {
+    iProperty.Cancel( );
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,73 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Server implementation that responds to client API in lockclient
+ *
+*/
+
+
+#include "lockappserver.h"
+#include "lockappsession.h"
+#include <lockappclientserver.h>
+#include <coemain.h>
+
+// ---------------------------------------------------------------------------
+// Two-phased constructor.
+// ---------------------------------------------------------------------------
+CLockAppServer* CLockAppServer::NewL( const TDesC& aFixedServerName )
+	{
+
+	CLockAppServer* self = new (ELeave) CLockAppServer();
+	CleanupStack::PushL( self );
+	self->SetPriority( EActivePriorityIpcEventsHigh );
+	self->ConstructL( aFixedServerName );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// Constructor.
+// ---------------------------------------------------------------------------
+CLockAppServer::CLockAppServer( )
+	{
+
+	// no implementation required
+	}
+
+// ---------------------------------------------------------------------------
+// From @c CApaAppServer. Creates LockApp Session, only one type of
+// service is supported by the server.
+// ---------------------------------------------------------------------------
+CApaAppServiceBase* CLockAppServer::CreateServiceL( TUid aServiceType ) const
+	{
+
+	// only one service is offered through server
+	if ( aServiceType == KLockAppServiceUid )
+		{
+		return new (ELeave) CLockAppSession();
+		}
+	else
+		{
+		return CApaAppServer::CreateServiceL( aServiceType );
+		}
+	}
+
+// ---------------------------------------------------------------------------
+// From @c CApaAppServer. Creates a new client session, version
+// numbering not supported.
+// ---------------------------------------------------------------------------
+CSession2* CLockAppServer::NewSessionL( const TVersion&, const RMessage2& ) const
+	{
+
+	return new (ELeave) CLockAppSession();
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappsession.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,236 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  LockApp server session requested by lockclient
+ *
+*/
+
+
+#include "lockapptrace.h"
+#include "lockappsession.h"
+#include "lockappappui.h"
+#include "lockappstatecontrolinterface.h"
+#include "lockapputils.h"
+#include <lockappclientserver.h>
+
+// ---------------------------------------------------------------------------
+// Default Constructor.
+// ---------------------------------------------------------------------------
+CLockAppSession::CLockAppSession( )
+    {
+
+    // no implementation required
+    }
+
+// ---------------------------------------------------------------------------
+// Default Destructor.
+// ---------------------------------------------------------------------------
+CLockAppSession::~CLockAppSession( )
+    {
+    // no implementation required
+    }
+
+// ---------------------------------------------------------------------------
+// From @c CApaAppServiceBase. Handles possible error in the lock app session
+// Method is empty.
+// ---------------------------------------------------------------------------
+void CLockAppSession::ServiceError( const RMessage2& aMessage, TInt aError )
+    {
+
+    if ( aError == KErrNotReady )
+        {
+        // initialization not yet ready
+        aMessage.Complete( KErrNotReady );
+        ERROR( aError, "LockApp initialization not yet ready, KErrNotReady" );
+        }
+    else
+        {
+        ERROR_1( aError, "Service request has caused a leave, message: %d", aMessage.Function());
+        CApaAppServiceBase::ServiceError( aMessage, aError );
+#ifdef _DEBUG
+        if ( aMessage.Function( )== ELockAppTestDestruct )
+            {
+            User::Leave( KErrGeneral );
+            }
+#endif
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// From @c CApaAppServiceBase. Handles a client request. Leaving is handled by
+// CLockAppSession::ServiceError() which reports the error code to the client
+// ---------------------------------------------------------------------------
+void CLockAppSession::ServiceL(const RMessage2& aMessage )
+    {  
+		RThread clientThread;
+		TInt err=aMessage.Client(clientThread);
+		// RDebug::Print( _L("called by %S"), &(clientThread.FullName()) );
+		// RDebug::Print( clientThread.FullName() );
+
+    TInt response = KErrNone;
+    // log the message
+    // whole provided server API is implemented here
+
+    switch ( aMessage.Function( ) )
+        {
+        case ELockAppEnableKeyguard:
+            // enable with or without note (depends on first parameter)
+            response = DoEnableKeyguardL( aMessage.Int0() );
+            break;
+        case ELockAppDisableKeyguard:
+            // disable with or without note (depends on first parameter)
+            response = DoDisableKeyguardL( aMessage.Int0() );
+            break;
+        case ELockAppEnableDevicelock:
+            // check that client has needed capabilities to enable devicelock
+            if ( aMessage.HasCapability( ECapabilityWriteDeviceData ) )
+                {
+                // first parameter contains the reason
+                response = DoEnableDevicelockL( (TDevicelockReason) aMessage.Int0() );
+                }
+            else
+                {
+                response = KErrPermissionDenied;
+                }
+            break;
+        case ELockAppDisableDevicelock:
+            // check that client has needed capabilities to disable devicelock
+            if ( aMessage.HasCapability( ECapabilityWriteDeviceData ) )
+                {
+                response = DoDisableDevicelockL( );
+                }
+            else
+                {
+                response = KErrPermissionDenied;
+                }
+            break;
+        case ELockAppOfferKeyguard:
+            // offer to lock keyguard
+            response = DoOfferKeyguardL( );
+            break;
+        case ELockAppOfferDevicelock:
+            // TODO implement this someday if needed
+            response = KErrNotSupported;
+            break;
+        case ELockAppShowKeysLockedNote:
+            response = DoShowKeysLockedNoteL( );
+            break;
+#ifdef _DEBUG
+        case ELockAppTestDestruct:
+            // test for leave
+            User::Leave( KErrGeneral );
+            break;
+        case ELockAppTestInternal:
+            // test internal functions (which cannot be tested trough client API)
+            response = StateControlL()->ExecuteInternalTest( );
+            break;
+#endif
+        default:
+            // illegal message call, panic the client process
+            PanicClient( aMessage, ELockPanicIllegalMessage );
+            return;
+        }
+
+    INFO_2( "CLockAppSession received service message: %d. Result: %d", aMessage.Function(), response );
+    aMessage.Complete( response );
+    }
+
+// ---------------------------------------------------------------------------
+// Request lockapp to enable keyguard on device (might not be approved, e.g.
+// devicelock activated).
+// ---------------------------------------------------------------------------
+TInt CLockAppSession::DoEnableKeyguardL( TBool aShowNote )
+    {
+    // calls the main control
+
+    return StateControlL()->EnableKeyguardL( aShowNote );
+    }
+
+// ---------------------------------------------------------------------------
+// Request lockapp to disable keyguard on device (might not be approved, e.g.
+// already disabled).
+// ---------------------------------------------------------------------------
+TInt CLockAppSession::DoDisableKeyguardL( TBool aShowNote )
+    {
+    // calls the main control
+
+    return StateControlL()->DisableKeyguardL( aShowNote );
+    }
+
+// ---------------------------------------------------------------------------
+// Request lockapp to enable devicelock on device (might not be approved).
+// ---------------------------------------------------------------------------
+TInt CLockAppSession::DoEnableDevicelockL( TDevicelockReason aReason )
+    {
+    // calls the main control
+
+    return StateControlL()->EnableDevicelockL( aReason );
+    }
+
+// ---------------------------------------------------------------------------
+// Request lockapp to disable devicelock on device (might not be approved).
+// ---------------------------------------------------------------------------
+TInt CLockAppSession::DoDisableDevicelockL( )
+    {
+    // TODO Investigate if this should be allowed in API or not
+    // calls the main control
+    // StateControlL()->DisableDevicelockL( );
+    return KErrPermissionDenied;
+    }
+
+// ---------------------------------------------------------------------------
+// Request to offer keyguard on device (might not be approved, e.g.
+// already locked).
+// ---------------------------------------------------------------------------
+TInt CLockAppSession::DoOfferKeyguardL( )
+    {
+    // calls the main control
+    return StateControlL()->OfferKeyguard( );
+    }
+
+// ---------------------------------------------------------------------------
+// Request to show keys locked note, only works if keyguard is enabled
+// ---------------------------------------------------------------------------
+TInt CLockAppSession::DoShowKeysLockedNoteL( )
+    {
+    // calls the main control
+
+    return StateControlL()->ShowKeysLockedNote( );
+    }
+
+// ---------------------------------------------------------------------------
+// Return the main state control to the server session.
+// Application appui and the main state control might not be constructed yet.
+// ---------------------------------------------------------------------------
+MLockAppStateControl* CLockAppSession::StateControlL( )
+    {
+
+    // other parts of lockapp construction may not be finished
+    if ( !iStateControl )
+        {
+        CLockAppAppUi* appUi = (CLockAppAppUi*) CEikonEnv::Static()->EikAppUi();
+        if ( appUi )
+            {
+            iStateControl = appUi->StateControl( );
+            if ( !iStateControl )
+                {
+                User::Leave( KErrNotReady );
+                }
+            }
+        else
+            {
+            User::Leave( KErrNotReady );
+            }
+        }
+    return iStateControl;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappsleepingnote.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,128 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Sleeping note with timeout
+ *
+*/
+
+
+#include "lockappsleepingnote.h"
+#include <avkon.rsg> // avkon animation resources
+#include <aknnotpi.rsg> // keyguard note resources
+#include <aknnotecontrol.h> // access to note control
+#include "lockapputils.h"
+#include <GlobalWindowPriorities.h>
+
+// ---------------------------------------------------------------------------
+// Pointer to parent (implements MEikCommandObserver) is given in construction.
+// ---------------------------------------------------------------------------
+CLockAppSleepingNote::CLockAppSleepingNote( MEikCommandObserver* aCommandObserver ) :
+	iCommandObserver(aCommandObserver)
+	{
+	}
+
+// ---------------------------------------------------------------------------
+// Note construction on startup.
+// Sleeping note owns a timer that controls the note timeout.
+// ---------------------------------------------------------------------------
+void CLockAppSleepingNote::ConstructSleepingNoteL( TInt aResourceId )
+	{
+	iResourceId = aResourceId;
+	CAknNoteDialog::ConstructSleepingDialogL( aResourceId );
+	// Construct now rather than in PreLayoutDynInit
+	}
+
+// ---------------------------------------------------------------------------
+// In destruction set reference value (is note shown) to not true.
+// ---------------------------------------------------------------------------
+CLockAppSleepingNote::~CLockAppSleepingNote( )
+	{
+	}
+
+// ---------------------------------------------------------------------------
+// Show note with timeout.
+// ---------------------------------------------------------------------------
+TInt CLockAppSleepingNote::ShowNote( const TInt aTimeout, const TTone aTone )
+	{
+	ReportUserActivity( );
+	iTimeoutInMicroseconds = aTimeout;
+	iTone = aTone;
+	return RouseSleepingDialog( );
+	}
+
+// ---------------------------------------------------------------------------
+// Key events are handled here.
+// ---------------------------------------------------------------------------
+TKeyResponse CLockAppSleepingNote::OfferKeyEventL( const TKeyEvent& /*aKeyEvent*/, TEventCode /*aType*/)
+	{
+	//return CAknNoteDialog::OfferKeyEventL( aKeyEvent, aType );
+	return EKeyWasConsumed;
+	}
+
+// ---------------------------------------------------------------------------
+// Always called when note exists, the reason (command) for exit
+// is delivered to parent.
+// ---------------------------------------------------------------------------
+TBool CLockAppSleepingNote::OkToExitL( TInt aCommand )
+	{
+	if ( iCommandObserver )
+		{
+		iCommandObserver->ProcessCommandL( aCommand );
+		}
+	return ETrue;
+	}
+
+// ---------------------------------------------------------------------------
+// Always called when note exists, the reason (command) for exit
+// is delivered to parent.
+// ---------------------------------------------------------------------------
+void CLockAppSleepingNote::HandleResourceChange( TInt aType )
+	{
+	if ( aType == KAknsMessageSkinChange )
+		{
+		TInt animationRes(0);
+		switch ( iResourceId )
+			{
+			case R_KEYLOCK_NOTE_KEYLOCKED:
+				animationRes = R_QGN_NOTE_INFO_ANIM;
+				break;
+			case R_KEYLOCK_NOTE_UNLOCK_CONFIRM:
+				animationRes = R_QGN_NOTE_QUERY_ANIM;
+				break;
+			case R_KEYLOCK_NOTE_UNLOCK_ASTERISK:
+				animationRes = R_QGN_NOTE_INFO_ANIM;
+				break;
+			case R_KEYLOCK_NOTE_LOCK_ON:
+				animationRes = R_QGN_NOTE_KEYGUARD_LOCKED_ANIM;
+				break;
+			case R_KEYLOCK_NOTE_LOCK_OFF:
+				animationRes = R_QGN_NOTE_KEYGUARD_OPEN_ANIM;
+				break;
+			case R_KEYLOCK_OFFER_LOCK_NOTE:
+				animationRes = R_QGN_NOTE_QUERY_ANIM;
+				break;
+			default:
+				break;
+			} // end of switch
+
+		if ( animationRes )
+			{
+			CAknNoteControl* ctrl = NoteControl( );
+			if ( ctrl )
+				{
+				TRAP_IGNORE(ctrl->SetAnimationL( animationRes ));
+				}
+			}
+		}
+	CAknNoteDialog::HandleResourceChange( aType );
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappstatecontrol.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,945 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Controls lock states (unlocked, keylock, devicelock)
+ *
+*/
+
+
+#include "lockappstatecontrol.h"
+
+// child controls
+#include "lockappidlecontrol.h"
+#include "lockappkeyguardcontrol.h"
+#include "lockappdevicelockcontrol.h"
+
+#include "lockapppubsubobserver.h"
+#include "lockappcenrepobserver.h"
+
+#include "lockappkeycapturecontroller.h"
+#include "lockappstatepublisher.h"
+#include "lockappecsdetector.h"
+#include "lockapputils.h"
+#include <featmgr.h>
+
+#include <settingsinternalcrkeys.h>
+#include <ScreensaverInternalPSKeys.h>
+#include <ctsydomainpskeys.h>
+#include <activeidle2domainpskeys.h>
+
+#include "GlobalWindowPriorities.h"
+
+#include <avkon.rsg> // general avkon resources
+#include <aknnotpi.rsg> // keyguard spesific resources
+#include <aknsoundsystem.h>
+#include <AknIncallBubbleNotify.h> // incall bubble
+#include <bautils.h> // BaflUtils
+#include <apgwgnam.h>
+
+#include <keylockpolicyapi.h>
+
+#include <hwrmdomainpskeys.h>
+    TUid KUidFpsCategory = {0x1020507E};
+const		TInt KFpsAuthenticationKey = 1;
+
+// used avkon dialog resources
+_LIT(KRESOURCEFILE, "z:\\resource\\aknnotpi.rsc");
+
+// Visibility gate WG priority's relative offset from ECoeWinPriorityAlwaysAtFront
+// Now equals -1000 to be an absolute 0.
+const TInt KGlobalWindowPriority_LockVisibilityGate = -1000;
+
+// ---------------------------------------------------------------------------
+// Standard Symbian OS construction sequence
+// ---------------------------------------------------------------------------
+CLockAppStateControl* CLockAppStateControl::NewL( )
+    {
+    CLockAppStateControl* self = new (ELeave) CLockAppStateControl();
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Destruction releases key captures.
+// ---------------------------------------------------------------------------
+CLockAppStateControl::~CLockAppStateControl( )
+    {
+    // localized resources are freed
+    if ( iResourceFileOffset )
+        {
+        // We implicitely trust that eikon env exists (though in practice it does not make the
+        // difference as this destructor is really never called...)
+        iEikonEnv->DeleteResourceFile(iResourceFileOffset);
+        }
+
+    // PuSub observers
+    if ( iPSScreenSaverObserver )
+        {
+        delete iPSScreenSaverObserver;
+        iPSScreenSaverObserver = NULL;
+        }
+
+    if ( iPSTelephonyObserver )
+        {
+        delete iPSTelephonyObserver;
+        iPSTelephonyObserver = NULL;
+        }
+
+    if ( iPSGripObserver )
+        {
+        delete iPSGripObserver;
+        iPSGripObserver = NULL;
+        }
+
+    if ( iPSFPSObserver )
+        {
+        delete iPSFPSObserver;
+        iPSFPSObserver = NULL;
+        }
+
+    CLockAppKeyCaptureController::Destroy( );
+
+    if ( iIncallBubble )
+        {
+        delete iIncallBubble;
+        iIncallBubble = NULL;
+        }
+
+    if ( iSoundsMuted )
+        {
+        MuteSounds( EFalse );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// The uninitialized status is ELockNoteActive.
+// ---------------------------------------------------------------------------
+CLockAppStateControl::CLockAppStateControl( ) :
+    iLockStatus( ELockNotActive),
+    iWGEventGate( iEikonEnv->RootWin()),
+    iEnvState( 0 )
+    {
+    // no implementation required
+    }
+
+// ---------------------------------------------------------------------------
+// All lock state observers are created here.
+// ---------------------------------------------------------------------------
+void CLockAppStateControl::ConstructL( )
+    {
+    INFO( "CLockAppStateControl::ConstructL started" );
+
+    // creates observer list
+    BaseConstructL( );
+
+    // localized resources are loaded
+    TFileName resourceFile;
+    resourceFile.Append( KRESOURCEFILE );
+    BaflUtils::NearestLanguageFile( iEikonEnv->FsSession(), resourceFile );
+    iResourceFileOffset = iEikonEnv->AddResourceFileL(resourceFile);
+
+    // fetch power key configuration from feature manager
+    FeatureManager::InitializeLibL( );
+    iFeatureNoPowerkey = FeatureManager::FeatureSupported( KFeatureIdNoPowerkey );
+    FeatureManager::UnInitializeLib( );
+
+    // allow autoforwarding for the application (stacked bringforwards)
+    iEikonEnv->SetAutoForwarding( ETrue );
+
+    CLockAppKeyCaptureController::InitL( iEikonEnv->RootWin() );
+
+    // Create second windowgroup for visibility gate
+    CreateVisibilityGateWgL( );
+
+    INFO_1( "CLockAppStateControl - EventGate WgID = %d", iWGEventGate.WindowGroupId() );
+    INFO_1( "CLockAppStateControl - VisibilityGate WgID = %d", iWGVisibilityGate.WindowGroupId() );
+
+    //
+    // Construct Controls
+    //
+    iIdle = CLockAppIdleControl::NewL( *this );
+    AddObserverL( iIdle ); // ownership is transfered
+
+    iCurrentControl = iIdle;
+    iCurrentControl->HandleActivateEventL( iEnvState );
+
+    iKeyguard = CLockAppKeyguardControl::NewL( *this );
+    AddObserverL( iKeyguard ); // ownership is transfered
+    
+    RDebug::Printf( "%s %s (%u) iDevicelock=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iDevicelock );
+    iDevicelock = CLockAppDevicelockControl::NewL( *this, iWGVisibilityGate ); 
+    RDebug::Printf( "%s %s (%u) iDevicelock=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iDevicelock );
+    iDevicelock->ConnectToPhoneL( iWGVisibilityGate );
+    RDebug::Printf( "%s %s (%u) iDevicelock=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iDevicelock );
+    AddObserverL( iDevicelock ); // ownership is transfered
+
+    // Emergency support
+    iLockEcsDetector = CLockAppEcsDetector::NewL( );
+    AddObserverL( iLockEcsDetector ); // ownership is transfered
+
+    // Lock state publisher
+    CLockAppStatePublisher* lockPublisher = CLockAppStatePublisher::NewL( );
+    AddObserverL( lockPublisher ); // ownership is transfered
+
+    // PubSub observers
+    iPSScreenSaverObserver = CLockAppPubSubObserver::NewL( this, KPSUidScreenSaver, KScreenSaverOn );
+    iPSTelephonyObserver = CLockAppPubSubObserver::NewL( this, KPSUidCtsyCallInformation, KCTsyCallState );
+    iPSGripObserver = CLockAppPubSubObserver::NewL( this, KPSUidHWRM, KHWRMGripStatus );
+
+    iPSFPSObserver = CLockAppPubSubObserver::NewL( this, KUidFpsCategory, KFpsAuthenticationKey );
+
+    // Call bubble
+    iIncallBubble = CAknIncallBubble::NewL( );
+
+    ActivateL( );
+
+    INFO( "CLockAppStateControl::ConstructL completed" );
+    }
+
+// ---------------------------------------------------------------------------
+// Create visibility gate window group
+// ---------------------------------------------------------------------------
+void CLockAppStateControl::CreateVisibilityGateWgL( )
+    {
+    INFO( "CLockAppStateControl - CreateVisibilityGateL" );
+
+    iWGVisibilityGate = RWindowGroup( iCoeEnv->WsSession( ) );
+    User::LeaveIfError( iWGVisibilityGate.Construct( (TUint32) &iWGVisibilityGate ) );
+
+    /* hide this window group from the app switcher */
+    iWGVisibilityGate.SetOrdinalPosition( 0, ECoeWinPriorityNeverAtFront );
+    iWGVisibilityGate.EnableReceiptOfFocus( EFalse );
+
+    /*CApaWindowGroupName* wn = CApaWindowGroupName::NewLC( ws );
+    wn->SetHidden( ETrue );
+    wn->SetWindowGroupName( iWGVisibilityGate );
+    CleanupStack::PopAndDestroy( wn );*/
+    }
+
+// ---------------------------------------------------------------------------
+// This method should be called to enable keyguard.
+// ---------------------------------------------------------------------------
+TInt CLockAppStateControl::EnableKeyguardL( TBool aWithNote )
+    {
+    INFO_1( "CLockAppStateControl::EnableKeyguardL aWithNote= %d", aWithNote );
+    TInt err = CheckIfLegal( ELockAppEnableKeyguard );
+    if ( err == KErrNone && !iKeyguard->ActivationAllowedL( ) )
+        {
+        err = KErrPermissionDenied;
+        }
+    if ( err == KErrNone )
+        {
+        PostStatusChangeL( EKeyguardActive );
+        __ASSERT_DEBUG( iLockStatus == EKeyguardActive, DoPanic(ELockIllegalState));
+        INFO( "CLockAppStateControl - Keyguard Enabled" );
+        if ( aWithNote )
+            {
+            iKeyguard->DisplayKeysLockedNote( );
+            }
+        }
+    return err;
+    }
+
+// ---------------------------------------------------------------------------
+// This method should be called to disable keyguard.
+// ---------------------------------------------------------------------------
+TInt CLockAppStateControl::DisableKeyguardL( TBool aWithNote )
+    {
+    INFO_1( "CLockAppStateControl::DisableKeyguardL aWithNote= %d", aWithNote );
+    TInt err = CheckIfLegal( ELockAppDisableKeyguard );
+    if ( err == KErrNone && !iKeyguard->DeActivationAllowedL( ) )
+        {
+        err = KErrPermissionDenied;
+        }
+    if ( err == KErrNone )
+        {
+        PostStatusChangeL( ELockNotActive );
+        __ASSERT_DEBUG( iLockStatus == ELockNotActive, DoPanic(ELockIllegalState));
+        INFO( "CLockAppStateControl - Keyguard Disabled" );
+        if ( aWithNote )
+            {
+            iKeyguard->DisplayKeysActiveNote( );
+            }
+        }
+    return err;
+    }
+
+// ---------------------------------------------------------------------------
+// This method should be called to enable device lock.
+// ---------------------------------------------------------------------------
+TInt CLockAppStateControl::EnableDevicelockL( TDevicelockReason aReason )
+    {
+    INFO_1( "CLockAppStateControl::EnableDevicelockL aReason= %d", aReason );
+    RDebug::Printf( "%s %s (%u) iDevicelock=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iDevicelock );
+    TInt err = CheckIfLegal( ELockAppEnableDevicelock );
+    if ( err == KErrNone && !iDevicelock->ActivationAllowedL( aReason ) )
+        {
+        err = KErrPermissionDenied;
+        }
+    if ( err == KErrNone )
+        {
+        PostStatusChangeL( EDevicelockActive );
+        __ASSERT_DEBUG( iLockStatus == EDevicelockActive, DoPanic(ELockIllegalState));
+        iDevicelock->SetLockingReason( aReason );
+        INFO( "CLockAppStateControl - Devicelock Enabled" );
+        }
+    return err;
+    }
+
+// ---------------------------------------------------------------------------
+// This method should be called to disable device lock.
+// ---------------------------------------------------------------------------
+TInt CLockAppStateControl::DisableDevicelockL( )
+    {
+    INFO_1( "CLockAppStateControl::DisableDevicelockL 1= %d", 1 );
+    TInt err = CheckIfLegal( ELockAppDisableDevicelock );
+    if ( err == KErrNone && !iDevicelock->DeActivationAllowedL( ) )
+        {
+        err = KErrPermissionDenied;
+        }
+    if ( err == KErrNone )
+        {
+        PostStatusChangeL( ELockNotActive );
+        __ASSERT_DEBUG( iLockStatus == ELockNotActive, DoPanic(ELockIllegalState));
+        INFO( "CLockAppStateControl - Devicelock Disabled" );
+        }
+    return err;
+    }
+
+// ---------------------------------------------------------------------------
+// Checks if offer keyguard is allowed and if it is, offers to lock keyguard.
+// ---------------------------------------------------------------------------
+TInt CLockAppStateControl::OfferKeyguard( )
+    {
+    INFO_1( "CLockAppStateControl::OfferKeyguard 1= %d", 1 );
+    TInt err = CheckIfLegal( ELockAppOfferKeyguard );
+    if ( err == KErrNone )
+        {
+        __ASSERT_DEBUG( iLockStatus == ELockNotActive, DoPanic(ELockIllegalState));
+        INFO( "CLockAppStateControl - OfferKeyguard" );
+        iIdle->OfferKeyLock( );
+        }
+    return err;
+    }
+
+// ---------------------------------------------------------------------------
+// Shows keys locked note if keyguard is enabled.
+// ---------------------------------------------------------------------------
+TInt CLockAppStateControl::ShowKeysLockedNote( )
+    {
+    INFO_1( "CLockAppStateControl::ShowKeysLockedNote 1= %d", 1 );
+    TInt err = CheckIfLegal( ELockAppShowKeysLockedNote );
+    if ( err == KErrNone )
+        {
+        __ASSERT_DEBUG( iLockStatus == EKeyguardActive, DoPanic(ELockIllegalState));
+        INFO( "CLockAppStateControl - ShowKeysLockedNote" );
+        iKeyguard->DisplayLockedNote( );
+        }
+    return err;
+    }
+
+// ---------------------------------------------------------------------------
+// A method for returning the lock status.
+// ---------------------------------------------------------------------------
+TLockStatus CLockAppStateControl::LockStatus( ) const
+    {
+    INFO_1( "CLockAppStateControl::LockStatus iLockStatus= %d", iLockStatus );
+    return iLockStatus;
+    }
+
+// ---------------------------------------------------------------------------
+// A method for returning the environment status bitmask.
+// ---------------------------------------------------------------------------
+TUint CLockAppStateControl::EnvironmentStatus( ) const
+    {
+    return iEnvState;
+    }
+
+// ---------------------------------------------------------------------------
+// A method for executing different internal tests.
+// ---------------------------------------------------------------------------
+TInt CLockAppStateControl::ExecuteInternalTest( )
+    {
+#ifdef _DEBUG
+    return iLockEcsDetector->TestEcsNote( );
+#else
+    return KErrNone;
+#endif
+    }
+
+// ---------------------------------------------------------------------------
+// Number of owned UI controls (idle, keyguard, devicelock)
+// ---------------------------------------------------------------------------
+TInt CLockAppStateControl::CountComponentControls( ) const
+    {
+    return 3;
+    }
+
+// ---------------------------------------------------------------------------
+// Owned UI controls (idle, keyguard, devicelock)
+// ---------------------------------------------------------------------------
+CCoeControl* CLockAppStateControl::ComponentControl( TInt aIndex ) const
+    {
+    RDebug::Printf( "%s %s (%u) aIndex=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aIndex );
+    switch ( aIndex )
+        {
+        case 0:
+            return iIdle;
+        case 1:
+            return iKeyguard;
+        case 2:
+     		    RDebug::Printf( "%s %s (%u) iDevicelock=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iDevicelock );
+            return iDevicelock;
+        default:
+            return NULL;
+        }
+    }
+
+// ----------------------------------------------------------
+// Handle window-server events
+// ----------------------------------------------------------
+void CLockAppStateControl::HandleWsEventL( const TWsEvent& aEvent, CCoeControl* /*aDestination*/)
+    {
+    TInt type = aEvent.Type( );
+    	RDebug::Printf( "%s %s (%u) type=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, type );
+    switch ( type )
+        {
+        case KAknFullOrPartialForegroundLost: // partial or full fg lost
+        case KAknFullOrPartialForegroundGained: // partial or full fg gained
+            {
+    				RDebug::Printf( "%s %s (%u) type=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, type );
+            RWsSession& ws = iCoeEnv->WsSession( );
+            TFileName windowName;
+            TInt fwgid = ws.GetFocusWindowGroup( );
+            ws.GetWindowGroupNameFromIdentifier( fwgid, windowName );
+            INFO_3( "CLockAppStateControl::HandleWsEventL type: %d - FocusWg: %d %S", type, fwgid, &windowName);
+            }
+            break;
+        case EEventKeyUp:
+        case EEventKey:
+        case EEventKeyDown:
+        		{
+        		RDebug::Printf( "%s %s (%u) EEventKey*=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, EEventKeyDown );
+        		TKeyEvent* aKeyEvent = aEvent.Key();
+        		TKeyResponse response = OfferKeyEventL( *aKeyEvent, (TEventCode)type );
+        		}
+            break;
+        default:
+            break;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// From @c CAknAppUiBase. Overriden the parent method, because otherwise
+// the main lock state control would not receive the call, because is is not
+// window-owning control (=without window->not visible). The call is needed
+// because the main state control owns window-owning child controls.
+// ---------------------------------------------------------------------------
+void CLockAppStateControl::HandleResourceChange( TInt aType )
+    {
+    // these would not normally get handleresource call since they do not own window
+		RDebug::Printf( "%s %s (%u) aType=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aType );
+	if(iIdle)
+		iIdle->HandleResourceChange( aType );
+	if(iKeyguard)
+		iKeyguard->HandleResourceChange( aType );
+	if(iDevicelock)
+		iDevicelock->HandleResourceChange( aType );
+    // call parent
+    CCoeControl::HandleResourceChange( aType );
+    }
+
+// ---------------------------------------------------------------------------
+// Update the environment state variable with the event.
+// ---------------------------------------------------------------------------
+TBool CLockAppStateControl::HandleEnvironmentChange( TUint aEventMask, TBool aEnable )
+    {
+    // check if there will be a change
+
+    if ( IsBitFieldSet( iEnvState, aEventMask ) != aEnable )
+        {
+        // set the bit-field
+        SetBitField( iEnvState, aEventMask, aEnable );
+        // notify current control
+        __ASSERT_DEBUG( iCurrentControl, DoPanic(ELockIllegalState));
+        iCurrentControl->HandleEnvironmentChange( iEnvState, aEventMask );
+        // return true because the environment changed
+        return ETrue;
+        }
+    return EFalse;
+    }
+
+// ---------------------------------------------------------------------------
+// Handle all Central Repository observer callbacks.
+// ---------------------------------------------------------------------------
+void CLockAppStateControl::HandleCenRepNotify(TUid aCenRepUid, TUint32 aKeyId, TInt aValue )
+    {
+    	RDebug::Printf( "%s %s (%u) ???? Nothing done for aKeyId=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKeyId );
+
+    INFO_3( "CLockAppStateControl::HandleCenRepNotify %d %d = %d", aCenRepUid.iUid, aKeyId, aValue );
+    }
+
+// ---------------------------------------------------------------------------
+// Handle all Publish & Subscribe observer callbacks.
+// ---------------------------------------------------------------------------
+void CLockAppStateControl::HandlePubSubNotify(TUid aPubSubUid, TUint aKeyId, TInt aValue )
+    {
+    INFO_3( "CLockAppStateControl::HandlePubSubNotify %x %x = %d", aPubSubUid.iUid, aKeyId, aValue );
+    INFO_3( "CLockAppStateControl::HandlePubSubNotify KPSUidScreenSaver=%x KPSUidCtsyCallInformation=%x KPSUidAiInformation=%x", KPSUidScreenSaver, KPSUidCtsyCallInformation, KPSUidAiInformation );
+    INFO_3( "CLockAppStateControl::HandlePubSubNotify KPSUidHWRM=%x KHWRMGripStatus=%x KPSUidAiInformation=%x", KPSUidHWRM, KHWRMGripStatus, KPSUidAiInformation );
+    if ( aPubSubUid == KPSUidScreenSaver )
+        {
+        switch ( aKeyId )
+            {
+            case KScreenSaverOn:
+                {
+                INFO_1("CLockAppStateControl::ScreenSaver - %d", (aValue > 0));
+                HandleEnvironmentChange( KLockAppEnvScreenSaverOn, (aValue > 0) );
+                }
+                break;
+            default:
+                break;
+            }
+        }
+    else if ( aPubSubUid == KPSUidCtsyCallInformation )
+        {
+        switch ( aKeyId )
+            {
+            case KCTsyCallState:
+                {
+                PrintCallState( aValue );
+                HandleEnvironmentChange( KLockAppEnvPhonecallOngoing, (aValue > EPSCTsyCallStateNone) );
+                }
+                break;
+            default:
+                break;
+            }
+        }
+    else if ( aPubSubUid == KPSUidAiInformation )	// ActiveIdle
+            {
+            switch ( aKeyId )
+                {
+                case KActiveIdleState:
+                    {
+                    INFO_1("CLockAppStateControl::ActiveIdle - %d", (aValue == EPSAiForeground));
+                    HandleEnvironmentChange( KLockAppEnvIdleOnForeground, (aValue == EPSAiForeground) );
+                    }
+                    break;
+                default:
+                    break;
+                }
+            }
+    else if ( aPubSubUid == KPSUidHWRM )
+        {
+        switch ( aKeyId )
+            {
+            case KHWRMGripStatus:
+                {
+                INFO_1("CLockAppStateControl::Grip - %d", aValue );
+                HandleEnvironmentChange( KLockAppEnvGrip, (aValue == EPSHWRMGripOpen) );
+                }
+                break;
+            default:
+                break;
+            }
+        }
+    else if ( aPubSubUid == KUidFpsCategory )
+        {
+        switch ( aKeyId )
+            {
+            case KFpsAuthenticationKey:
+                {
+                INFO_1("CLockAppStateControl::Grip - %d", aValue );
+                #define EAuthenticationSuccess 1
+                HandleEnvironmentChange( KLockAppEnvFPS, (aValue == EAuthenticationSuccess) );
+                }
+                break;
+            default:
+                break;
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// All keyevents should go trough here.
+// ---------------------------------------------------------------------------
+TKeyResponse CLockAppStateControl::OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+    	RDebug::Printf( "%s %s (%u) iDevicelock=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iDevicelock );
+    	RDebug::Printf( "%s %s (%u) aKeyEvent.iCode=%x aType=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKeyEvent.iCode, aType );
+    TKeyResponse keyResponse = PreCheckKeyEvents( aKeyEvent, aType );
+    if ( keyResponse == EKeyWasNotConsumed )
+        {
+        if ( aKeyEvent.iRepeats == 0 )
+            {
+            // handle only without the repeats
+            INFO_3("KeyEvent %d, %d, %d", aType, aKeyEvent.iCode, aKeyEvent.iScanCode );
+            __ASSERT_DEBUG( iCurrentControl, DoPanic(ELockIllegalState));
+            keyResponse = iCurrentControl->OfferKeyEventL( aKeyEvent, aType );
+            }
+        else
+            {
+            // set consumed which are repeated
+            keyResponse = EKeyWasConsumed;
+            }
+        }
+
+    return keyResponse;
+    }
+
+// ---------------------------------------------------------------------------
+// From @c CLockAppObserverList. The main state control is the first
+// to handle the lock state changes, locks/unlocks the phone depending
+// on the state change.
+// ---------------------------------------------------------------------------
+void CLockAppStateControl::HandleLockStatusChangedL( TLockStatus aLockStatus )
+    {    
+    __ASSERT_DEBUG( iCurrentControl, DoPanic(ELockIllegalState));
+    INFO_1("CLockAppStateControl::HandleLockStatusChangedL - %d", aLockStatus);
+    iCurrentControl->HandleDeActivateEventL( iEnvState );
+
+    switch ( aLockStatus )
+        {
+        case ELockNotActive:
+            {
+            iCurrentControl = iIdle;
+            MuteSounds( EFalse );
+            BringForward( EFalse );
+            }
+            break;
+        case EKeyguardActive:
+            {
+            iCurrentControl = iKeyguard;
+            MuteSounds( ETrue );
+            BringForward( ETrue );
+            }
+            break;
+        case EDevicelockActive:
+            {
+       	    RDebug::Printf( "%s %s (%u) iDevicelock=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iDevicelock );
+            iCurrentControl = iDevicelock;
+            MuteSounds( ETrue );
+            BringForward( ETrue );
+            }
+            break;
+        default:
+        		INFO_1("CLockAppStateControl::HandleLockStatusChangedL - ???? aLockStatus=%d", aLockStatus);
+            DoPanic( ELockUnknownValue );
+            break;
+        }
+
+    __ASSERT_DEBUG( iCurrentControl, DoPanic(ELockIllegalState));
+    iCurrentControl->HandleActivateEventL( iEnvState );
+
+    // finally we update the value (only place were changing the status is allowed)
+    iLockStatus = aLockStatus;
+    }
+
+// ---------------------------------------------------------------------------
+// Check if requested transition is valid.
+// ---------------------------------------------------------------------------
+TInt CLockAppStateControl::CheckIfLegal( TLockAppMessageReason aReason )
+    {
+    INFO_1("CLockAppStateControl::CheckIfLegal aReason=%d", aReason);
+    INFO_1("CLockAppStateControl::CheckIfLegal iLockStatus=%d", iLockStatus);
+    switch ( aReason )
+        {
+        case ELockAppEnableKeyguard:
+            {
+           	RDebug::Printf( "%s %s (%u) ELockAppEnableKeyguard iLockStatus=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iLockStatus );
+            switch ( iLockStatus )
+                {
+                case ELockNotActive:
+                    if ( !CKeyLockPolicyApi::KeyguardAllowed() )
+                        return KErrPermissionDenied;
+                    else
+                        return KErrNone;
+                case EKeyguardActive:
+                    return KErrAlreadyExists;
+                case EDevicelockActive:
+                    return KErrPermissionDenied;
+                }
+            }
+            break;
+        case ELockAppDisableKeyguard:
+            {
+           	RDebug::Printf( "%s %s (%u) ELockAppDisableKeyguard iLockStatus=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iLockStatus );
+            switch ( iLockStatus )
+                {
+                case ELockNotActive:
+                    return KErrAlreadyExists;
+                case EKeyguardActive:
+                    return KErrNone;
+                case EDevicelockActive:
+                    return KErrPermissionDenied;
+                }
+            }
+            break;
+        case ELockAppEnableDevicelock:
+            {
+           	RDebug::Printf( "%s %s (%u) ELockAppEnableDevicelock iLockStatus=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iLockStatus );
+            switch ( iLockStatus )
+                {
+                case ELockNotActive:
+                    return KErrNone;
+                case EKeyguardActive:
+                    return KErrNone;
+                case EDevicelockActive:
+                    return KErrAlreadyExists;
+                }
+            }
+            break;
+        case ELockAppDisableDevicelock:
+            {
+           	RDebug::Printf( "%s %s (%u) ELockAppDisableDevicelock iLockStatus=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iLockStatus );
+            switch ( iLockStatus )
+                {
+                case ELockNotActive:
+                    return KErrAlreadyExists;
+                case EKeyguardActive:
+                    return KErrPermissionDenied;
+                case EDevicelockActive:
+                    return KErrNone;
+                }
+            }
+            break;
+        case ELockAppOfferKeyguard:
+            {
+           	RDebug::Printf( "%s %s (%u) ELockAppOfferKeyguard iLockStatus=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iLockStatus );
+            switch ( iLockStatus )
+                {
+                case ELockNotActive:
+                    return KErrNone;
+                case EKeyguardActive:
+                    return KErrPermissionDenied;
+                case EDevicelockActive:
+                    return KErrPermissionDenied;
+                }
+            }
+            break;
+        case ELockAppShowKeysLockedNote:
+            {
+           	RDebug::Printf( "%s %s (%u) ELockAppShowKeysLockedNote iLockStatus=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iLockStatus );
+            switch ( iLockStatus )
+                {
+                case ELockNotActive:
+                    return KErrPermissionDenied;
+                case EKeyguardActive:
+                    return KErrNone;
+                case EDevicelockActive:
+                    return KErrPermissionDenied;
+                }
+            }
+            break;
+        }
+    return KErrPermissionDenied;
+    }
+
+// ---------------------------------------------------------------------------
+// Prescreen key events for special cases before giving them to child controls
+// ---------------------------------------------------------------------------
+TKeyResponse CLockAppStateControl::PreCheckKeyEvents(const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+    	RDebug::Printf( "%s %s (%u) aKeyEvent.iCode=%x aType=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKeyEvent.iCode, aType );
+    TKeyResponse keyResponse = EKeyWasNotConsumed;
+    // power key always turns the lights on
+    CheckForPowerKeyLights( aKeyEvent, aType );
+    if ( iLockEcsDetector->EcsNoteOnScreen( ) )
+        {
+        // the key events are fully handled by the emergency
+        // detector when emergency note is shown
+        keyResponse = EKeyWasConsumed;
+        }
+    else
+        {
+        if ( CheckForPhoneKeys( aKeyEvent, aType ) )
+            {
+            keyResponse = EKeyWasConsumed;
+            }
+        else if ( aKeyEvent.iCode == EKeyLeftShift || aKeyEvent.iCode == EKeyRightShift )
+            {
+            // eat these modifier events as they just cause problems elsewhere
+            keyResponse = EKeyWasConsumed;
+            }
+        }
+    return keyResponse;
+    }
+
+// ---------------------------------------------------------------------------
+// Checks if power key has been pressed and inform the sysap accordingly.
+// ---------------------------------------------------------------------------
+void CLockAppStateControl::CheckForPowerKeyLights( const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+    // only handle power key when keys are locked
+    	RDebug::Printf( "%s %s (%u) aKeyEvent.iCode=%x aType=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKeyEvent.iCode, aType );
+    	RDebug::Printf( "%s %s (%u) iLockStatus=%x ELockNotActive=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iLockStatus, ELockNotActive );
+    if ( iLockStatus != ELockNotActive )
+        {
+    		RDebug::Printf( "%s %s (%u) iFeatureNoPowerkey=%x EStdKeyDevice2=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iFeatureNoPowerkey, EStdKeyDevice2 );
+        if ( (aType == EEventKey && aKeyEvent.iRepeats == 0) || (aType == EEventKeyDown && aKeyEvent.iScanCode == EStdKeyDevice2) ) // Power key
+            {
+            // If power key pressed, tell SysAp about if
+            if ( (aKeyEvent.iScanCode == EStdKeyDevice2 && aType == EEventKeyDown) || (iFeatureNoPowerkey && aKeyEvent.iCode == EKeyNo) )
+                {
+                // normal power key event
+                RDebug::Printf( "%s %s (%u) EEikKeyLockPowerKeyPressed=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iFeatureNoPowerkey );
+                SendMessageToSysAp( EEikKeyLockPowerKeyPressed );
+                if ( iFeatureNoPowerkey )
+                    {
+                		RDebug::Printf( "%s %s (%u) EEikKeyLockLightsOnRequest=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, EEikKeyLockLightsOnRequest );
+                    // end key as power key needs additional info (ugly solution)
+                    SendMessageToSysAp( EEikKeyLockLightsOnRequest );
+                    }
+                }
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Checks if green or red key has been pressed and forward it to phone
+// in case there is a phone call ongoing.
+// ---------------------------------------------------------------------------
+TBool CLockAppStateControl::CheckForPhoneKeys( const TKeyEvent& aKeyEvent, TEventCode aType )
+    {
+    	RDebug::Printf( "%s %s (%u) aKeyEvent.iCode=%x aType=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aKeyEvent.iCode, aType );
+#ifndef RD_GLOBALWG_PRIORITY_CHANGE
+    // only handle phone keys when locked and phonecall ongoing
+    	RDebug::Printf( "%s %s (%u) iLockStatus=%x ELockNotActive=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, iLockStatus, ELockNotActive );
+    if ( iLockStatus != ELockNotActive )
+        {
+        if ( aKeyEvent.iScanCode == EStdKeyYes || aKeyEvent.iScanCode == EStdKeyNo )
+            {
+            if ( IsBitFieldSet( iEnvState, KLockAppEnvPhonecallOngoing ) )	// TODO what about video-call
+                {
+                // send Green and Red keys to phoneapp's windowgroup
+                INFO( "CLockAppStateControl::CheckForPhoneKeys - SendKeyToPhoneApp");
+                SendKeyToPhoneApp( aKeyEvent, aType );
+                return ETrue;
+                }
+            }
+        }
+#endif // !RD_GLOBALWG_PRIORITY_CHANGE
+    return EFalse;
+    }
+
+// ---------------------------------------------------------------------------
+// Brings foreground/background the root window.
+// ---------------------------------------------------------------------------
+void CLockAppStateControl::BringForward(TBool aForeground )
+    {
+    	RDebug::Printf( "%s %s (%u) aForeground=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aForeground );
+    if ( aForeground )
+        {
+        INFO_4( "CLockAppStateControl::BringForward(1) STA - EvWG(%d,%d) ViWG(%d,%d)",
+                iWGEventGate.OrdinalPosition(), iWGEventGate.OrdinalPriority(),
+                iWGVisibilityGate.OrdinalPosition(), iWGVisibilityGate.OrdinalPriority());
+        // not sure if these cause flush in WindowServer
+        iWGVisibilityGate.SetOrdinalPosition( 0, ECoeWinPriorityAlwaysAtFront + KGlobalWindowPriority_LockVisibilityGate );
+        iWGEventGate.SetOrdinalPosition( 0, ECoeWinPriorityAlwaysAtFront + KGlobalWindowPriority_LockVisibilityGate );
+        iEikonEnv->BringForwards( ETrue, ECoeWinPriorityAlwaysAtFront + KGlobalWindowPriority_KeyLock );
+        /*if ( iIncallBubble )
+            {
+            iIncallBubble->SetIncallBubbleAllowedInIdleL( ETrue );
+            }*/
+        }
+    else
+        {
+        INFO_4( "CLockAppStateControl::BringForward(0) STA - EvWG(%d,%d) ViWG(%d,%d)",
+                iWGEventGate.OrdinalPosition(), iWGEventGate.OrdinalPriority(),
+                iWGVisibilityGate.OrdinalPosition(), iWGVisibilityGate.OrdinalPriority());
+
+        // not sure if these cause flush in WindowServer
+        iWGVisibilityGate.SetOrdinalPosition( 0, ECoeWinPriorityNeverAtFront );
+		iWGEventGate.SetOrdinalPosition( 0, ECoeWinPriorityNeverAtFront );
+        iEikonEnv->BringForwards( EFalse );
+        /*if ( iIncallBubble )
+            {
+            iIncallBubble->SetIncallBubbleAllowedInIdleL( EFalse );
+            }*/
+        }
+
+    INFO_4( "CLockAppStateControl::BringForward END - EvWG(%d,%d) ViWG(%d,%d)",
+            iWGEventGate.OrdinalPosition(), iWGEventGate.OrdinalPriority(),
+            iWGVisibilityGate.OrdinalPosition(), iWGVisibilityGate.OrdinalPriority());
+    }
+
+// ---------------------------------------------------------------------------
+// Mute key sounds when phone is locked.
+// ---------------------------------------------------------------------------
+void CLockAppStateControl::MuteSounds(TBool aMuteSounds )
+    {
+    	RDebug::Printf( "%s %s (%u) aMuteSounds=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aMuteSounds );
+    if ( iSoundsMuted != aMuteSounds )
+        {
+        if ( aMuteSounds )
+            {
+            TRAPD(err, iAvkonAppUiBase->KeySounds()->PushContextL(R_AVKON_SILENT_SKEY_LIST))
+            if ( !err )
+                {
+                iAvkonAppUiBase->KeySounds()->BringToForeground();
+                iAvkonAppUiBase->KeySounds()->LockContext();
+                iSoundsMuted = ETrue;
+                }
+            }
+        else
+            {
+            iAvkonAppUiBase->KeySounds()->ReleaseContext();
+            iAvkonAppUiBase->KeySounds()->PopContext();
+            iSoundsMuted = EFalse;
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Print out call state.
+// ---------------------------------------------------------------------------
+void CLockAppStateControl::PrintCallState( TInt aValue )
+    {
+    RDebug::Printf( "%s %s (%u) aValue=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, aValue );
+    switch ( aValue )
+        {
+        case EPSCTsyCallStateUninitialized:
+            INFO("CLockAppStateControl::PrintCallState - Uninitialized")
+            break;
+        case EPSCTsyCallStateNone:
+            INFO("CLockAppStateControl::PrintCallState - None")
+            break;
+        case EPSCTsyCallStateAlerting:
+            INFO("CLockAppStateControl::PrintCallState - Alerting")
+            break;
+        case EPSCTsyCallStateRinging:
+            INFO("CLockAppStateControl::PrintCallState - Ringing")
+            break;
+        case EPSCTsyCallStateDialling:
+            INFO("CLockAppStateControl::PrintCallState - Dialling")
+            break;
+        case EPSCTsyCallStateAnswering:
+            INFO("CLockAppStateControl::PrintCallState - Answering")
+            break;
+        case EPSCTsyCallStateDisconnecting:
+            INFO("CLockAppStateControl::PrintCallState - Disconnecting")
+            break;
+        case EPSCTsyCallStateConnected:
+            INFO("CLockAppStateControl::PrintCallState - Connected")
+            break;
+        case EPSCTsyCallStateHold:
+            INFO("CLockAppStateControl::PrintCallState - Hold")
+            break;
+        default:
+            break;
+        }
+    }
+
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappstatepublisher.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,107 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Publishes LockApp states to other applications
+ *
+*/
+
+
+#include "lockappstatepublisher.h"
+#include "lockapputils.h"
+
+// defines keys KPSUidAvkonDomain, KAknKeyguardStatus, TAknKeyguardStatus
+#include <avkondomainpskeys.h>
+
+// ---------------------------------------------------------------------------
+// Standard Symbian OS construction sequence
+// ---------------------------------------------------------------------------
+CLockAppStatePublisher* CLockAppStatePublisher::NewL( )
+    {
+    CLockAppStatePublisher* self = new (ELeave) CLockAppStatePublisher();
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Standard C++ constructor
+// ---------------------------------------------------------------------------
+CLockAppStatePublisher::CLockAppStatePublisher()
+    {
+    // no implementation required
+    }
+
+// ---------------------------------------------------------------------------
+// Closes the property handle.
+// ---------------------------------------------------------------------------
+CLockAppStatePublisher::~CLockAppStatePublisher()
+    {
+    iStatusProperty.Close();
+    }
+
+// ---------------------------------------------------------------------------
+// Defines the P&S key storing keyguard status
+// ---------------------------------------------------------------------------
+void CLockAppStatePublisher::ConstructL()
+    {
+    // for some reason P&S capability policy macros do not work with codetest
+#ifdef _LOCKAPP_CODETEST_DEBUG
+    RProperty::Define(
+        KPSUidAvkonDomain,
+        KAknKeyguardStatus,
+        RProperty::EInt,
+        TSecurityPolicy(TSecurityPolicy::EAlwaysPass),
+        TSecurityPolicy(TSecurityPolicy::EAlwaysPass));
+#else
+    // defines the P&S key
+    _LIT_SECURITY_POLICY_C1(KWritePolicy, ECapabilityWriteDeviceData);
+    RProperty::Define(
+        KPSUidAvkonDomain,
+        KAknKeyguardStatus,
+        RProperty::EInt,
+        TSecurityPolicy(TSecurityPolicy::EAlwaysPass),
+        KWritePolicy);
+#endif
+    // creates handle to property
+    iStatusProperty.Attach(KPSUidAvkonDomain, KAknKeyguardStatus);
+    }
+
+// ---------------------------------------------------------------------------
+// From @c CLockAppStateObserver. Used to publish lockapp state
+// to external parties.
+// ---------------------------------------------------------------------------
+void CLockAppStatePublisher::HandleLockStatusChangedL( TLockStatus aLockStatus )
+    {
+    switch ( aLockStatus )
+        {
+        case ELockNotActive:
+            {
+            iStatusProperty.Set(EKeyguardNotActive);
+            }
+            break;
+        case EDevicelockActive:
+            {
+            iStatusProperty.Set(EKeyguardAutolockEmulation);
+            }
+            break;
+        case EKeyguardActive:
+            {
+            iStatusProperty.Set(EKeyguardLocked);
+            }
+            break;
+        default:
+            DoPanic(ELockUnknownValue);
+            break;
+        }
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockapputils.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,111 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Lock App internal utils
+ *
+*/
+
+
+#include <e32base.h>
+#include <coemain.h>
+#include <apgwgnam.h>
+#include "lockapputils.h"
+
+#define KSysApUid TUid::Uid(0x100058F3)
+#define KPhoneAppUid TUid::Uid(0x100058B3)
+
+// ---------------------------------------------------------------------------
+// Queries bits in aStatusMask specified by the aQueryMask
+// ---------------------------------------------------------------------------
+TBool IsBitFieldSet( TUint aStatusMask, TUint aQueryMask )
+    {
+    return (aStatusMask & aQueryMask);
+    }
+
+// ---------------------------------------------------------------------------
+// Sets bits in aResultMask specified by the aSetMask
+// ---------------------------------------------------------------------------
+void SetBitField( TUint &aResultMask, TUint aSetMask, TBool aSet )
+    {
+    if ( aSet )
+        {
+        aResultMask = aResultMask | aSetMask;
+        }
+    else
+        {
+        aResultMask = aResultMask & ~ aSetMask;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Panic function for LockApp internal panics.
+// ---------------------------------------------------------------------------
+void DoPanic( TLockAppPanic aPanic )
+    {
+    _LIT(KPanic,"LockApp");
+    User::Panic( KPanic, aPanic );
+    }
+
+// ---------------------------------------------------------------------------
+// Causes client Panic (illegal use of the server services).
+// Used RMessagePtr2::Panic() also completes the message.
+// ---------------------------------------------------------------------------
+void PanicClient(const RMessagePtr2& aMessage, TLockAppPanic aPanic )
+    {
+    _LIT(KPanic, "LockAppServer");
+    aMessage.Panic( KPanic, aPanic );
+    }
+
+// ---------------------------------------------------------------------------
+// Sends application spesific events to Sysap.
+// Used mainly for lights control.
+// ---------------------------------------------------------------------------
+void SendMessageToSysAp( TInt aMessage )
+    {
+    RWsSession& ws = CCoeEnv::Static()->WsSession( );
+    TInt wgId = 0;
+    CApaWindowGroupName::FindByAppUid( KSysApUid, ws, wgId );
+
+    // if sysap window group exists
+    if ( wgId )
+        {
+        TWsEvent event;
+        event.SetType( aMessage );
+        event.SetTimeNow( );
+        ws.SendEventToWindowGroup( wgId, event );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Sends a key event to the windowgroup in background.
+// Used mainly for sending red and green keys to phone app when
+// devicelock or keyguard is in foreground.
+// ---------------------------------------------------------------------------
+void SendKeyToPhoneApp( const TKeyEvent& aKey, TEventCode aType )
+    {
+    RWsSession& ws = CCoeEnv::Static()->WsSession( );
+    TInt wgId = 0;
+    CApaWindowGroupName::FindByAppUid( KPhoneAppUid, ws, wgId );
+
+    // if sysap window group exists
+    if ( wgId )
+        {
+        TWsEvent event;
+        *event.Key() = aKey;
+        event.SetType( aType );
+        event.SetTimeNow( );
+        ws.SendEventToWindowGroup( wgId, event );
+        }
+    }
+
+// END OF FILE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockapp/src/lockappwait.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,176 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Async-Sync utility class
+ *
+*/
+
+
+#include <e32base.h>
+#include <eikenv.h>
+#include <eikappui.h>
+#include "lockappwait.h"
+
+// ----------------------------------------------------------
+// Standard Symbian OS construction sequence
+// ----------------------------------------------------------
+//
+CWait* CWait::NewL( )
+    {
+    CWait* self = new (ELeave) CWait( );
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ----------------------------------------------------------
+// 2nd phase constructor.
+// ----------------------------------------------------------
+//
+void CWait::ConstructL( )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// ----------------------------------------------------------
+// Constructor
+// ----------------------------------------------------------
+//
+CWait::CWait( ) :
+    CActive(0)
+    {
+    // no implementation required
+    }
+
+// ----------------------------------------------------------
+// Destructor.
+// ----------------------------------------------------------
+//
+CWait::~CWait( )
+    {
+    Cancel( );
+    }
+
+// ----------------------------------------------------------
+//
+// ----------------------------------------------------------
+//
+TInt CWait::WaitForRequestL( )
+    {
+    CWaitAbsorbingControl* absorbing = CWaitAbsorbingControl::NewLC( );
+    SetActive( );
+    iWait.Start( );
+    CleanupStack::PopAndDestroy( absorbing );
+    return iStatus.Int( );
+    }
+
+// ----------------------------------------------------------
+//
+// ----------------------------------------------------------
+//
+void CWait::RunL( )
+    {
+    if ( iWait.IsStarted( ) )
+        {
+        iWait.AsyncStop( );
+        }
+    }
+
+// ----------------------------------------------------------
+// Cancels code request
+// ----------------------------------------------------------
+//
+void CWait::DoCancel( )
+    {
+    if ( iWait.IsStarted( ) )
+        {
+        iWait.AsyncStop( );
+        }
+    }
+
+// ----------------------------------------------------------
+// Sets active request type
+// ----------------------------------------------------------
+//
+void CWait::SetRequestType(TInt aRequestType )
+    {
+    iRequestType = aRequestType;
+    }
+
+// ----------------------------------------------------------
+// Gets active request type
+// ----------------------------------------------------------
+//
+TInt CWait::GetRequestType( )
+    {
+    return iRequestType;
+    }
+
+// ----------------------------------------------------------
+// Standard Symbian OS construction sequence
+// ----------------------------------------------------------
+//
+CWaitAbsorbingControl* CWaitAbsorbingControl::NewLC( )
+    {
+    CWaitAbsorbingControl* self= new (ELeave) CWaitAbsorbingControl();
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    return self;
+    }
+
+// ----------------------------------------------------------
+//
+// ----------------------------------------------------------
+//
+CWaitAbsorbingControl::CWaitAbsorbingControl( )
+    {
+    // no implementation required
+    }
+
+// ----------------------------------------------------------
+// Destructor.
+// ----------------------------------------------------------
+//
+CWaitAbsorbingControl::~CWaitAbsorbingControl( )
+    {
+    if ( iCoeEnv && iAppUi )
+        iAppUi->RemoveFromStack( this );
+    }
+
+// ----------------------------------------------------------
+//
+// ----------------------------------------------------------
+//
+void CWaitAbsorbingControl::ConstructL( )
+    {
+    CreateWindowL( );
+    SetExtent( TPoint( 0, 0 ), TSize( 0, 0 ) );
+    ActivateL( );
+    SetPointerCapture( ETrue );
+    ClaimPointerGrab( ETrue );
+    iAppUi = iEikonEnv->EikAppUi();
+    iAppUi->AddToStackL( this, ECoeStackPriorityEnvironmentFilter );
+    }
+
+// ----------------------------------------------------------
+//
+// ----------------------------------------------------------
+//
+TKeyResponse CWaitAbsorbingControl::OfferKeyEventL(const TKeyEvent& /*aKeyEvent*/, TEventCode /*aType*/)
+    {
+    	RDebug::Printf( "%s %s (%u) value=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, 1 );
+    return EKeyWasConsumed;
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockclient/bwins/lockclientu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,20 @@
+EXPORTS
+	?ShowKeysLockedNote@CKeyguardAccessApi@@QAEHXZ @ 1 NONAME ; int CKeyguardAccessApi::ShowKeysLockedNote(void)
+	?TestDestruct@CKeyguardAccessApi@@QAEHXZ @ 2 NONAME ; int CKeyguardAccessApi::TestDestruct(void)
+	?NewL@CDevicelockAccessApi@@SAPAV1@XZ @ 3 NONAME ; class CDevicelockAccessApi * CDevicelockAccessApi::NewL(void)
+	?OfferKeyguard@CKeyguardAccessApi@@QAEHXZ @ 4 NONAME ; int CKeyguardAccessApi::OfferKeyguard(void)
+	?IsKeyguardEnabled@CKeyguardAccessApi@@QAEHXZ @ 5 NONAME ; int CKeyguardAccessApi::IsKeyguardEnabled(void)
+	?EnableKeyguard@CKeyguardAccessApi@@QAEHH@Z @ 6 NONAME ; int CKeyguardAccessApi::EnableKeyguard(int)
+	?IsKeylockEnabled@CKeyguardAccessApi@@QAEHXZ @ 7 NONAME ; int CKeyguardAccessApi::IsKeylockEnabled(void)
+	?IsDevicelockEnabled@CDevicelockAccessApi@@QAEHXZ @ 8 NONAME ; int CDevicelockAccessApi::IsDevicelockEnabled(void)
+	?DisableDevicelock@CDevicelockAccessApi@@QAEHXZ @ 9 NONAME ; int CDevicelockAccessApi::DisableDevicelock(void)
+	?TestPanicClient@CKeyguardAccessApi@@QAEHXZ @ 10 NONAME ; int CKeyguardAccessApi::TestPanicClient(void)
+	?TestInternal@CKeyguardAccessApi@@QAEHXZ @ 11 NONAME ; int CKeyguardAccessApi::TestInternal(void)
+	?DisableKeyguard@CKeyguardAccessApi@@QAEHH@Z @ 12 NONAME ; int CKeyguardAccessApi::DisableKeyguard(int)
+	?EnableDevicelock@CDevicelockAccessApi@@QAEHW4TDevicelockReason@@@Z @ 13 NONAME ; int CDevicelockAccessApi::EnableDevicelock(enum TDevicelockReason)
+	?IsKeylockEnabled@CDevicelockAccessApi@@QAEHXZ @ 14 NONAME ; int CDevicelockAccessApi::IsKeylockEnabled(void)
+	??1CKeyguardAccessApi@@UAE@XZ @ 15 NONAME ; CKeyguardAccessApi::~CKeyguardAccessApi(void)
+	??1CDevicelockAccessApi@@UAE@XZ @ 16 NONAME ; CDevicelockAccessApi::~CDevicelockAccessApi(void)
+	?OfferDevicelock@CDevicelockAccessApi@@QAEHXZ @ 17 NONAME ; int CDevicelockAccessApi::OfferDevicelock(void)
+	?NewL@CKeyguardAccessApi@@SAPAV1@XZ @ 18 NONAME ; class CKeyguardAccessApi * CKeyguardAccessApi::NewL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockclient/eabi/lockclientu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,28 @@
+EXPORTS
+	_ZN18CKeyguardAccessApi12TestDestructEv @ 1 NONAME
+	_ZN18CKeyguardAccessApi12TestInternalEv @ 2 NONAME
+	_ZN18CKeyguardAccessApi13OfferKeyguardEv @ 3 NONAME
+	_ZN18CKeyguardAccessApi14EnableKeyguardEi @ 4 NONAME
+	_ZN18CKeyguardAccessApi15DisableKeyguardEi @ 5 NONAME
+	_ZN18CKeyguardAccessApi15TestPanicClientEv @ 6 NONAME
+	_ZN18CKeyguardAccessApi16IsKeylockEnabledEv @ 7 NONAME
+	_ZN18CKeyguardAccessApi17IsKeyguardEnabledEv @ 8 NONAME
+	_ZN18CKeyguardAccessApi18ShowKeysLockedNoteEv @ 9 NONAME
+	_ZN18CKeyguardAccessApi4NewLEv @ 10 NONAME
+	_ZN18CKeyguardAccessApiD0Ev @ 11 NONAME
+	_ZN18CKeyguardAccessApiD1Ev @ 12 NONAME
+	_ZN18CKeyguardAccessApiD2Ev @ 13 NONAME
+	_ZN20CDevicelockAccessApi15OfferDevicelockEv @ 14 NONAME
+	_ZN20CDevicelockAccessApi16EnableDevicelockE17TDevicelockReason @ 15 NONAME
+	_ZN20CDevicelockAccessApi16IsKeylockEnabledEv @ 16 NONAME
+	_ZN20CDevicelockAccessApi17DisableDevicelockEv @ 17 NONAME
+	_ZN20CDevicelockAccessApi19IsDevicelockEnabledEv @ 18 NONAME
+	_ZN20CDevicelockAccessApi4NewLEv @ 19 NONAME
+	_ZN20CDevicelockAccessApiD0Ev @ 20 NONAME
+	_ZN20CDevicelockAccessApiD1Ev @ 21 NONAME
+	_ZN20CDevicelockAccessApiD2Ev @ 22 NONAME
+	_ZTI18CKeyguardAccessApi @ 23 NONAME ; #<TI>#
+	_ZTI20CDevicelockAccessApi @ 24 NONAME ; #<TI>#
+	_ZTV18CKeyguardAccessApi @ 25 NONAME ; #<VT>#
+	_ZTV20CDevicelockAccessApi @ 26 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockclient/group/ABLD.BAT	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,15 @@
+@ECHO OFF
+
+REM Bldmake-generated batch file - ABLD.BAT
+REM ** DO NOT EDIT **
+
+perl -S ABLD.PL "\sf\mw\securitysrv\securitydialogs\lockclient\group\\" %1 %2 %3 %4 %5 %6 %7 %8 %9
+if errorlevel==1 goto CheckPerl
+goto End
+
+:CheckPerl
+perl -v >NUL
+if errorlevel==1 echo Is Perl, version 5.003_07 or later, installed?
+goto End
+
+:End
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockclient/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  LockClient build file
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+PRJ_EXPORTS
+
+../rom/lockclient.iby CORE_MW_LAYER_IBY_EXPORT_PATH(lockclient.iby)
+
+PRJ_MMPFILES
+
+lockclient.mmp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockclient/group/lockclient.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,47 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  LockClient mmp file
+ *
+*/
+
+
+#include <platform_paths.hrh>
+#include <data_caging_paths.hrh>
+
+TARGET          lockclient.dll
+TARGETTYPE      DLL
+UID             0x1000008D 0x2000B124
+
+LANG            SC
+
+CAPABILITY      CAP_GENERAL_DLL
+VENDORID        VID_DEFAULT
+
+USERINCLUDE     ../inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          devicelockaccessapi.cpp
+SOURCE          keyguardaccessapi.cpp
+SOURCE          lockaccessextension.cpp
+
+LIBRARY         cone.lib   // Cone, CoeEnv
+LIBRARY         euser.lib // std libraries, rsessionbase
+LIBRARY         apgrfx.lib // TApaTask, TApaTaskList
+
+SMPSAFE
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockclient/inc/lockaccessextension.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,93 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Extension to lockapp clients.
+ *
+*/
+
+
+#ifndef __LOCKACCESSEXTENSION_H__
+#define __LOCKACCESSEXTENSION_H__
+
+#include <e32base.h>
+
+class RWsSession;
+
+/**
+ *  RLockAccessExtension class.
+ *  Extension class used to access lockapp.
+ *
+ *  @lib    lockclient
+ *  @since  5.0
+ *  @author Tamas Koteles
+ */
+class RLockAccessExtension : public RSessionBase
+	{
+	public:
+
+		/**
+		 * From @c RSessionBase. Sends a message.
+		 * @return KErrNone if succeeded or already connected.
+		 *         KErrNotReady if the server is not yet fully initialized.
+		 *         otherwise standard RSessionBase error values.
+		 */
+		TInt SendMessage( TInt aMessage );
+
+		/**
+		 * From @c RSessionBase. Sends a message with a parameter.
+		 * @return KErrNone if succeeded or already connected.
+		 *         KErrNotReady if the server is not yet fully initialized.
+		 *         otherwise standard RSessionBase error values.
+		 */
+		TInt SendMessage( TInt aMessage, TInt aParam1 );
+
+		/**
+		 * From @c RSessionBase. Sends a message with two parameter.
+		 * @return KErrNone if succeeded or already connected.
+		 *         KErrNotReady if the server is not yet fully initialized.
+		 *         otherwise standard RSessionBase error values.
+		 */
+		TInt SendMessage( TInt aMessage, TInt aParam1, TInt aParam2 );
+
+	private:
+
+		/**
+		 * Returns the server's version.
+		 */
+		TVersion GetVersion( );
+
+		/**
+		 * Tries to create session to service.
+		 * Must be called before accessing other methods in the API.
+		 *
+		 * @return KErrNone if succeeded or already connected.
+		 *         KErrNotReady if the server is not yet fully initialized.
+		 *         KErrNotSupported if the CoeEnv is not available
+		 *         otherwise standard RSessionBase error values.
+		 */
+		TInt TryConnect( RWsSession& aWsSession );
+
+		/**
+		 * Ensures that the connection to the service is alive.
+		 * Tries to connect to service if not connected.
+		 *
+		 * @return KErrNone if succeeded or already connected.
+		 *         KErrNotReady if the server is not yet fully initialized.
+		 *         KErrNotSupported if the CoeEnv is not available
+		 *         otherwise standard RSessionBase error values.
+		 */
+		TInt EnsureConnected( );
+
+	};
+
+#endif // __LOCKACCESSEXTENSION_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockclient/rom/lockclient.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+#ifndef __LOCKCLIENT_IBY__
+#define __LOCKCLIENT_IBY__
+
+#include <data_caging_paths_for_iby.hrh>
+ 
+//file=ABI_DIR\BUILD_DIR\lockclient.dll SHARED_LIB_DIR\lockclient.dll
+file=ABI_DIR\UDEB\lockclient.dll SHARED_LIB_DIR\lockclient.dll
+
+#endif // __LOCKCLIENT_IBY__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockclient/src/devicelockaccessapi.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,170 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface to access devicelock.
+ *
+*/
+
+
+#include <devicelockaccessapi.h>
+#include <lockappclientserver.h>
+#include "lockaccessextension.h"
+
+#include <avkondomainpskeys.h>  // KPSUidAvkonDomain, KAknKeyguardStatus, TAknKeyguardStatus
+#include <e32property.h> // P&S API
+#include <e32debug.h>
+
+// ---------------------------------------------------------------------------
+// Standard Symbian OS construction sequence
+// ---------------------------------------------------------------------------
+EXPORT_C CDevicelockAccessApi* CDevicelockAccessApi::NewL( )
+    {
+    CDevicelockAccessApi* self = new (ELeave) CDevicelockAccessApi( );
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Constructor.
+// ---------------------------------------------------------------------------
+CDevicelockAccessApi::CDevicelockAccessApi()
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor.
+// ---------------------------------------------------------------------------
+EXPORT_C CDevicelockAccessApi::~CDevicelockAccessApi( )
+    {
+    if ( iLockAccessExtension )
+        {
+        iLockAccessExtension->Close( );
+        delete iLockAccessExtension;
+        iLockAccessExtension = NULL;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Second phase construction
+// ---------------------------------------------------------------------------
+void CDevicelockAccessApi::ConstructL( )
+    {
+    iLockAccessExtension = new (ELeave) RLockAccessExtension;
+    }
+
+// ---------------------------------------------------------------------------
+// Checks if the phone has been locked using P&S key storing lock states
+// ---------------------------------------------------------------------------
+EXPORT_C TBool CDevicelockAccessApi::IsKeylockEnabled()
+    {
+    TInt value;
+    TInt err = RProperty::Get(KPSUidAvkonDomain, KAknKeyguardStatus, value);
+    if ( err == KErrNone )
+        {
+        switch( value )
+            {
+            case EKeyguardLocked:
+            case EKeyguardAutolockEmulation:
+            return ETrue;
+            case EKeyguardNotActive:
+            default:
+            return EFalse;
+            }
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Checks if the devicelock is enabled or not
+// ---------------------------------------------------------------------------
+EXPORT_C TBool CDevicelockAccessApi::IsDevicelockEnabled()
+    {
+    TInt value;
+    TInt err = RProperty::Get(KPSUidAvkonDomain, KAknKeyguardStatus, value);
+    if ( err == KErrNone )
+        {
+        switch( value )
+            {
+            case EKeyguardAutolockEmulation:
+                return ETrue;
+            case EKeyguardLocked:
+            case EKeyguardNotActive:
+            default:
+                return EFalse;
+            }
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Requests lockapp server to enable devicelock.
+// ---------------------------------------------------------------------------
+EXPORT_C TInt CDevicelockAccessApi::EnableDevicelock( TDevicelockReason aReason )
+    {
+    if ( iLockAccessExtension )
+        {
+        switch (aReason)
+            {
+            case EDevicelockManual:
+            case EDevicelockRemote:
+                return iLockAccessExtension->SendMessage( ELockAppEnableDevicelock, aReason );
+            default:
+                return KErrNotSupported;
+            }
+        }
+    else
+        {
+        return KErrNotFound;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Requests lockapp server to offer devicelock to user.
+// ---------------------------------------------------------------------------
+EXPORT_C TInt CDevicelockAccessApi::OfferDevicelock()
+    {
+    if ( iLockAccessExtension )
+        {
+        return iLockAccessExtension->SendMessage( ELockAppOfferDevicelock );
+        }
+    else
+        {
+        return KErrNotFound;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// TODO: remove this method!
+// Requests lockapp server to disable devicelock.
+// ---------------------------------------------------------------------------
+EXPORT_C TInt CDevicelockAccessApi::DisableDevicelock()
+    {
+    if ( iLockAccessExtension )
+        {
+        return iLockAccessExtension->SendMessage( ELockAppDisableDevicelock );
+        }
+    else
+        {
+        return KErrNotFound;
+        }
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockclient/src/keyguardaccessapi.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,237 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface to access keyguard.
+ *
+*/
+
+
+#include <keyguardaccessapi.h>
+#include <lockappclientserver.h>
+#include "lockaccessextension.h"
+
+#include <avkondomainpskeys.h>      // KPSUidAvkonDomain, KAknKeyguardStatus, TAknKeyguardStatus
+#include <e32property.h> // P&S API
+#include <e32debug.h>
+
+// ---------------------------------------------------------------------------
+// Standard Symbian OS construction sequence
+// ---------------------------------------------------------------------------
+EXPORT_C CKeyguardAccessApi* CKeyguardAccessApi::NewL( )
+    {
+    CKeyguardAccessApi* self = new (ELeave) CKeyguardAccessApi( );
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Constructor.
+// ---------------------------------------------------------------------------
+CKeyguardAccessApi::CKeyguardAccessApi()
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor.
+// ---------------------------------------------------------------------------
+EXPORT_C CKeyguardAccessApi::~CKeyguardAccessApi( )
+    {
+    if ( iLockAccessExtension )
+        {
+        iLockAccessExtension->Close( );
+        delete iLockAccessExtension;
+        iLockAccessExtension = NULL;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Second phase construction
+// ---------------------------------------------------------------------------
+void CKeyguardAccessApi::ConstructL( )
+    {
+    iLockAccessExtension = new (ELeave) RLockAccessExtension;
+    }
+
+// ---------------------------------------------------------------------------
+// Checks if the phone has been locked using P&S key storing lock states
+// ---------------------------------------------------------------------------
+EXPORT_C TBool CKeyguardAccessApi::IsKeylockEnabled()
+    {
+    TInt value;
+    TInt err = RProperty::Get(KPSUidAvkonDomain, KAknKeyguardStatus, value);
+    if ( err == KErrNone )
+        {
+        switch( value )
+            {
+            case EKeyguardLocked:
+            case EKeyguardAutolockEmulation:
+                return ETrue;
+            case EKeyguardNotActive:
+            default:
+                return EFalse;
+            }
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Checks if the keyguard is enabled or not
+// ---------------------------------------------------------------------------
+EXPORT_C TBool CKeyguardAccessApi::IsKeyguardEnabled()
+    {
+    TInt value;
+    TInt err = RProperty::Get(KPSUidAvkonDomain, KAknKeyguardStatus, value);
+    if ( err == KErrNone )
+        {
+        switch( value )
+            {
+            case EKeyguardLocked:
+                return ETrue;
+            case EKeyguardAutolockEmulation:
+            case EKeyguardNotActive:
+            default:
+                return EFalse;
+            }
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Requests lockapp server to enable keyguard with or without note.
+// ---------------------------------------------------------------------------
+EXPORT_C TInt CKeyguardAccessApi::EnableKeyguard( TBool aWithNote )
+    {
+    if ( iLockAccessExtension )
+        {
+        return iLockAccessExtension->SendMessage( ELockAppEnableKeyguard, aWithNote );
+        }
+    else
+        {
+        return KErrNotFound;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Requests lockapp server to disable keyguard with or without note.
+// ---------------------------------------------------------------------------
+EXPORT_C TInt CKeyguardAccessApi::DisableKeyguard( TBool aWithNote )
+    {
+    if ( iLockAccessExtension )
+        {
+        return iLockAccessExtension->SendMessage( ELockAppDisableKeyguard, aWithNote );
+        }
+    else
+        {
+        return KErrNotFound;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Requests lockapp server to offer keyguard to user.
+// ---------------------------------------------------------------------------
+EXPORT_C TInt CKeyguardAccessApi::OfferKeyguard()
+    {
+    if ( iLockAccessExtension )
+        {
+        return iLockAccessExtension->SendMessage( ELockAppOfferKeyguard );
+        }
+    else
+        {
+        return KErrNotFound;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// Shows note informing that keys are locked. Only works if keyguard is already enabled.
+// ---------------------------------------------------------------------------
+EXPORT_C TInt CKeyguardAccessApi::ShowKeysLockedNote()
+    {
+    if ( iLockAccessExtension )
+        {
+        return iLockAccessExtension->SendMessage( ELockAppShowKeysLockedNote );
+        }
+    else
+        {
+        return KErrNotFound;
+        }
+    }
+
+
+
+// ---------------------------------------------------------------------------
+// 
+// ---------------------------------------------------------------------------
+EXPORT_C TInt CKeyguardAccessApi::TestInternal( )
+    {
+#ifdef _DEBUG
+    if ( iLockAccessExtension )
+        {
+        return iLockAccessExtension->SendMessage( ELockAppTestInternal );
+        }
+    else
+        {
+        return KErrNotFound;
+        }
+#else
+    return KErrNotSupported;
+#endif
+    }
+
+// ---------------------------------------------------------------------------
+// 
+// ---------------------------------------------------------------------------
+EXPORT_C TInt CKeyguardAccessApi::TestDestruct( )
+    {
+#ifdef _DEBUG
+    if ( iLockAccessExtension )
+        {
+        return iLockAccessExtension->SendMessage( ELockAppTestDestruct );
+        }
+    else
+        {
+        return KErrNotFound;
+        }
+#else
+    return KErrNotSupported;
+#endif
+    }
+
+// ---------------------------------------------------------------------------
+// 
+// ---------------------------------------------------------------------------
+EXPORT_C TInt CKeyguardAccessApi::TestPanicClient( )
+    {
+#ifdef _DEBUG
+    if ( iLockAccessExtension )
+        {
+        return iLockAccessExtension->SendMessage( ELockAppTestPanicClient );
+        }
+    else
+        {
+        return KErrNotFound;
+        }
+#else
+    return KErrNotSupported;
+#endif
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockclient/src/lockaccessextension.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,139 @@
+/*
+* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Extension to lockapp clients.
+ *
+*/
+
+
+#include "lockaccessextension.h"
+#include <lockappclientserver.h>
+#include <e32property.h> // P&S API
+#include <apgtask.h> // TApaTask, TApaTaskList
+#include <coemain.h> // CCoeEnv
+
+
+// Constants
+const TInt KTimesToConnectServer( 2);
+const TInt KTimeoutBeforeRetrying( 50000);
+
+// ---------------------------------------------------------------------------
+// Gets server version, needed for connection
+// ---------------------------------------------------------------------------
+TVersion RLockAccessExtension::GetVersion( )
+	{
+	return TVersion( KLockAppServMajorVersion, KLockAppServMinorVersion, KLockAppServBuildVersion );
+	}
+
+// ---------------------------------------------------------------------------
+// Connects client to lockapp application server
+// ---------------------------------------------------------------------------
+TInt RLockAccessExtension::TryConnect( RWsSession& aWsSession )
+	{
+	TInt ret(KErrNone);
+	TApaTaskList list(aWsSession);
+	// check that lockapp is running
+	TApaTask task = list.FindApp( KLockAppUid );
+	if ( task.Exists( ) )
+		{
+		if ( Handle( )== NULL )
+			{
+			// connect session to the server
+			ret = CreateSession( KLockAppServerName, GetVersion( ) );
+			}
+		else
+			{
+			// not CreateSession because Handle( ) not NULL
+			}
+		}
+	else
+		{
+		// LockApp task not found
+		RDebug::Printf( "%s %s (%u) ???? LockApp task not found=%x", __FILE__, __PRETTY_FUNCTION__, __LINE__, KLockAppUid );
+		ret = KErrNotReady;
+		}
+	return ret;
+	}
+
+// ---------------------------------------------------------------------------
+// Ensures that the connection to the service is alive.
+// ---------------------------------------------------------------------------
+TInt RLockAccessExtension::EnsureConnected( )
+	{
+	TInt ret(KErrNone);
+	// we need CCoeEnv because of window group list
+	CCoeEnv* coeEnv = CCoeEnv::Static( );
+	if ( coeEnv )
+		{
+		// All server connections are tried to be made KTriesToConnectServer times because
+		// occasional fails on connections are possible at least on some servers
+		TInt retry(0);
+		while ( (ret = TryConnect( coeEnv->WsSession( ) ) ) != KErrNone && 
+				(retry++) <= KTimesToConnectServer )
+			{
+			User::After( KTimeoutBeforeRetrying );
+			}
+		// the connection state gets returned
+		}
+	else
+		{
+		// No CCoeEnv
+		ret = KErrNotSupported;
+		}
+	return ret;
+	}
+
+// ---------------------------------------------------------------------------
+// Sends blind message to lockapp if the session is connected.
+// ---------------------------------------------------------------------------
+TInt RLockAccessExtension::SendMessage( TInt aMessage )
+	{
+	TInt ret = EnsureConnected( );
+	if ( ret == KErrNone )
+		{
+		ret = SendReceive( aMessage );
+		}
+	return ret;
+	}
+
+// ---------------------------------------------------------------------------
+// Sends blind message to lockapp if the session is connected.
+// ---------------------------------------------------------------------------
+TInt RLockAccessExtension::SendMessage( TInt aMessage, TInt aParam1 )
+	{
+	TInt ret = EnsureConnected( );
+	if ( ret == KErrNone )
+		{
+		// assign parameters to IPC argument
+		TIpcArgs args(aParam1);
+		ret = SendReceive( aMessage, args );
+		}
+	return ret;
+	}
+
+// ---------------------------------------------------------------------------
+// Sends blind message to lockapp if the session is connected.
+// ---------------------------------------------------------------------------
+TInt RLockAccessExtension::SendMessage( TInt aMessage, TInt aParam1, TInt aParam2 )
+	{
+	TInt ret = EnsureConnected( );
+	if ( ret == KErrNone )
+		{
+		// assign parameters to IPC argument
+		TIpcArgs args( aParam1, aParam2);
+		ret = SendReceive( aMessage, args );
+		}
+	return ret;
+	}
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockclient/tsrc/public/basic/bwins/MT_RDevicelockAccessApiu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?CreateTestSuiteL@@YAPAVMEUnitTest@@XZ @ 1 NONAME ; class MEUnitTest * CreateTestSuiteL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitydialogs/lockclient/tsrc/public/basic/bwins/MT_RKeyguardAccessApiu.def	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,3 @@
+EXPORTS
+	?CreateTestSuiteL@@YAPAVMEUnitTest@@XZ @ 1 NONAME ; class MEUnitTest * CreateTestSuiteL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/securitysrv_info/securitysrv_metadata/securitysrv_metadata.mrp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,6 @@
+component           securitysrv_metadata
+source   \sf\mw\securitysrv\securitysrv_info\securitysrv_metadata 
+source   \sf\mw\securitysrv\package_definition.xml
+source   \sf\mw\securitysrv\distribution.policy.s60
+notes_source      \component_defs\release.src
+ipr T 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sysdef_1_4_0.dtd	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,86 @@
+ <!ELEMENT SystemDefinition (systemModel?, build?)>
+ <!ATTLIST SystemDefinition
+  name CDATA #REQUIRED
+  schema CDATA #REQUIRED>
+ <!ELEMENT systemModel (layer+)>
+ <!ELEMENT layer (logicalset* | module*)*>
+ <!ATTLIST layer
+  name CDATA #REQUIRED
+  levels CDATA #IMPLIED
+  span CDATA #IMPLIED>
+ <!ELEMENT logicalset (logicalsubset* | module* | unit* | package* | prebuilt*)*>
+ <!ATTLIST logicalset name CDATA #REQUIRED>
+ <!ELEMENT logicalsubset (module* | unit* | package* | prebuilt*)*>
+ <!ATTLIST logicalsubset name CDATA #REQUIRED>
+ <!ELEMENT module (component* | unit* | package* | prebuilt*)*>
+ <!ATTLIST module
+  name CDATA #REQUIRED
+  level CDATA #IMPLIED>
+ <!ELEMENT component (unit* | package* | prebuilt*)*>
+ <!ATTLIST component name CDATA #REQUIRED>
+ <!ELEMENT unit EMPTY>
+ <!ATTLIST unit
+  unitID ID #REQUIRED
+  name CDATA #REQUIRED
+  mrp CDATA #REQUIRED
+  filter CDATA #IMPLIED
+  bldFile CDATA #REQUIRED
+  priority CDATA #IMPLIED
+  contract CDATA #IMPLIED>
+ <!ELEMENT package EMPTY>
+ <!ATTLIST package
+  name CDATA #REQUIRED
+  mrp CDATA #REQUIRED
+  filter CDATA #IMPLIED
+  contract CDATA #IMPLIED>
+ <!ELEMENT prebuilt EMPTY>
+ <!ATTLIST prebuilt
+  name CDATA #REQUIRED
+  version CDATA #REQUIRED
+  late (Y|N) #IMPLIED
+  filter CDATA #IMPLIED
+  contract CDATA #IMPLIED>
+ <!ELEMENT build (option* | target+ | targetList+ | unitList+ | configuration+)*>
+ <!ELEMENT unitList (unitRef+)>
+ <!ATTLIST unitList
+  name ID #REQUIRED
+  description CDATA #REQUIRED>
+ <!ELEMENT unitRef EMPTY>
+ <!ATTLIST unitRef unit IDREF #REQUIRED>
+ <!ELEMENT targetList EMPTY>
+ <!ATTLIST targetList
+  name ID #REQUIRED
+  description CDATA #REQUIRED
+  target IDREFS #REQUIRED>
+ <!ELEMENT target EMPTY>
+ <!ATTLIST target
+  name ID #REQUIRED
+  abldTarget CDATA #REQUIRED
+  description CDATA #REQUIRED>
+ <!ELEMENT option EMPTY>
+ <!ATTLIST option
+  name ID #REQUIRED
+  abldOption CDATA #REQUIRED
+  description CDATA #REQUIRED
+  enable (Y | N | y | n) #REQUIRED>
+ <!ELEMENT configuration (unitListRef+ | layerRef+ | task+)*>
+ <!ATTLIST configuration
+  name ID #REQUIRED
+  description CDATA #REQUIRED
+  filter CDATA #REQUIRED>
+ <!ELEMENT task ( unitListRef* , (buildLayer | specialInstructions))>
+ <!ELEMENT unitListRef EMPTY>
+ <!ATTLIST unitListRef unitList IDREF #REQUIRED>
+ <!ELEMENT layerRef EMPTY>
+ <!ATTLIST layerRef layerName CDATA #REQUIRED>
+ <!ELEMENT buildLayer EMPTY>
+ <!ATTLIST buildLayer
+  command CDATA #REQUIRED
+  targetList IDREFS #IMPLIED
+  unitParallel (Y | N | y | n) #REQUIRED
+  targetParallel (Y | N | y | n) #IMPLIED>
+ <!ELEMENT specialInstructions EMPTY>
+ <!ATTLIST specialInstructions
+  name CDATA #REQUIRED
+  cwd CDATA #REQUIRED
+  command CDATA #REQUIRED>  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tsrc/group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file for securitysrv test modules
+*
+*/
+
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_TESTEXPORTS
+
+PRJ_TESTMMPFILES
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Group/bld.inf	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,63 @@
+/*
+* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#include <platform_paths.hrh>
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+//Digital Signature notes
+../inc/DigSigningNote.h         |../../inc/DigSigningNote.h
+
+// export iby files
+../rom/wim.iby  CORE_MW_LAYER_IBY_EXPORT_PATH( wim.iby )
+
+// Wimi.lib is needed by WimServer. Provided as binary file.
+../WimSoft/winscw/udeb/WIMI.LIB   /epoc32/release/winscw/udeb/Wimi.lib
+../WimSoft/winscw/urel/WIMI.LIB   /epoc32/release/winscw/urel/Wimi.lib
+
+#ifndef SBSV2
+../WimSoft/armv5/udeb/wimi.lib    /epoc32/release/armv5/udeb/Wimi.lib
+../WimSoft/armv5/urel/wimi.lib    /epoc32/release/armv5/urel/Wimi.lib
+#else
+
+// For raptor, Static libraries needs to be added using PRJ_EXTENSION section;this way
+PRJ_EXTENSIONS
+START EXTENSION utility.prebuilt
+ OPTION PRE_PLATFORM armv5
+ OPTION PRE_TYPE urel
+ OPTION BINARIES ../WimSoft/armv5/urel/Wimi.lib
+END
+
+START EXTENSION utility.prebuilt
+ OPTION PRE_PLATFORM armv5
+ OPTION PRE_TYPE udeb
+ OPTION BINARIES ../WimSoft/armv5/udeb/Wimi.lib
+END
+#endif
+//Do not add any other exports here as above the prj_extension section starts. Add it before the #ifndef SBSV2 line.
+
+PRJ_MMPFILES
+../SwimReader/group/SwimReader.mmp
+../Scard/group/Scard.mmp
+../WimUtil/group/WimUtil.mmp
+../WimServer/group/WimServer.mmp
+../WimClient/group/WimClient.mmp
+../WimPlugin/group/WimPlugin.mmp
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/EABI/ScardU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,82 @@
+EXPORTS
+	_Z11StartThreadv @ 1 NONAME
+	_ZN10CScardComm4NewLEP6RScardR27TScardConnectionRequirementR4TBufILi32EER14TRequestStatusl @ 2 NONAME
+	_ZN10CScardCommD0Ev @ 3 NONAME
+	_ZN10CScardCommD1Ev @ 4 NONAME
+	_ZN10CScardCommD2Ev @ 5 NONAME
+	_ZN14CScardListener16ListenCardEventsERK4TBufILi32EE @ 6 NONAME
+	_ZN14CScardListener4RunLEv @ 7 NONAME
+	_ZN14CScardListener8DoCancelEv @ 8 NONAME
+	_ZN14CScardListenerC2EP6RScard @ 9 NONAME
+	_ZN14CScardListenerD0Ev @ 10 NONAME
+	_ZN14CScardListenerD1Ev @ 11 NONAME
+	_ZN14CScardListenerD2Ev @ 12 NONAME
+	_ZN17CScardReaderQuery11ListGroupsLEP13CArrayFixFlatI4TBufILi32EEE @ 13 NONAME
+	_ZN17CScardReaderQuery12ListReadersLEP13CArrayFixFlatI4TBufILi32EEERKS2_ @ 14 NONAME
+	_ZN17CScardReaderQuery4NewLEv @ 15 NONAME
+	_ZN17CScardReaderQueryD0Ev @ 16 NONAME
+	_ZN17CScardReaderQueryD1Ev @ 17 NONAME
+	_ZN17CScardReaderQueryD2Ev @ 18 NONAME
+	_ZN20CScardNotifyRegistry15NotifyCardEventE19TScardServiceStatuss @ 19 NONAME
+	_ZN27TScardConnectionRequirement12NewCardsOnlyEi @ 20 NONAME
+	_ZN27TScardConnectionRequirement12SetAIDBytesLER6TDesC8 @ 21 NONAME
+	_ZN27TScardConnectionRequirement12SetExcludedLER4TBufILi32EE @ 22 NONAME
+	_ZN27TScardConnectionRequirement12SetExplicitLER4TBufILi32EE @ 23 NONAME
+	_ZN27TScardConnectionRequirement14ClearAIDBytesLEv @ 24 NONAME
+	_ZN27TScardConnectionRequirement14ClearExcludedLEv @ 25 NONAME
+	_ZN27TScardConnectionRequirement14ClearExplicitLEv @ 26 NONAME
+	_ZN27TScardConnectionRequirement14NewReadersOnlyEi @ 27 NONAME
+	_ZN27TScardConnectionRequirement7SetATRLER5TBuf8ILi33EE @ 28 NONAME
+	_ZN27TScardConnectionRequirement9ClearATRLEv @ 29 NONAME
+	_ZN27TScardConnectionRequirementC1Ev @ 30 NONAME
+	_ZN27TScardConnectionRequirementC2Ev @ 31 NONAME
+	_ZN6RScard4NewLEv @ 32 NONAME
+	_ZN6RScardD0Ev @ 33 NONAME
+	_ZN6RScardD1Ev @ 34 NONAME
+	_ZN6RScardD2Ev @ 35 NONAME
+	_ZNK10CScardComm13ManageChannelE20TScChannelManagementaR5TDes8R14TRequestStatusl @ 36 NONAME
+	_ZNK10CScardComm14CancelTransmitEv @ 37 NONAME
+	_ZNK10CScardComm14TransmitToCardERK6TDesC8R5TDes8R14TRequestStatusla @ 38 NONAME
+	_ZNK10CScardComm16GetCapabilitiesLElR5TDes8l @ 39 NONAME
+	_ZNK10CScardComm5ScardEv @ 40 NONAME
+	_ZNK10CScardComm7GetATRLER5TBuf8ILi33EE @ 41 NONAME
+	_ZTI10CScardComm @ 42 NONAME DATA 12 ; #<TI>#
+	_ZTI12CScardServer @ 43 NONAME DATA 32 ; #<TI>#
+	_ZTI13CScardSession @ 44 NONAME DATA 12 ; #<TI>#
+	_ZTI14CScardListener @ 45 NONAME DATA 12 ; #<TI>#
+	_ZTI14CScardNotifier @ 46 NONAME DATA 12 ; #<TI>#
+	_ZTI15CScardConnector @ 47 NONAME DATA 12 ; #<TI>#
+	_ZTI16CScardEventStack @ 48 NONAME DATA 12 ; #<TI>#
+	_ZTI17CScardReaderQuery @ 49 NONAME DATA 12 ; #<TI>#
+	_ZTI18CScardCommandTimer @ 50 NONAME DATA 12 ; #<TI>#
+	_ZTI18CScardMessageStack @ 51 NONAME DATA 12 ; #<TI>#
+	_ZTI19CScardAccessControl @ 52 NONAME DATA 12 ; #<TI>#
+	_ZTI20CScardChannelManager @ 53 NONAME DATA 12 ; #<TI>#
+	_ZTI20CScardNotifyRegistry @ 54 NONAME DATA 32 ; #<TI>#
+	_ZTI20CScardReaderRegistry @ 55 NONAME DATA 12 ; #<TI>#
+	_ZTI21CScardConnectionTimer @ 56 NONAME DATA 12 ; #<TI>#
+	_ZTI22CScardResourceRegistry @ 57 NONAME DATA 12 ; #<TI>#
+	_ZTI24CScardConnectionRegistry @ 58 NONAME DATA 12 ; #<TI>#
+	_ZTI27CScardAccessControlRegistry @ 59 NONAME DATA 12 ; #<TI>#
+	_ZTI6RScard @ 60 NONAME DATA 24 ; #<TI>#
+	_ZTV10CScardComm @ 61 NONAME DATA 20 ; #<VT>#
+	_ZTV12CScardServer @ 62 NONAME DATA 56 ; #<VT>#
+	_ZTV13CScardSession @ 63 NONAME DATA 52 ; #<VT>#
+	_ZTV14CScardListener @ 64 NONAME DATA 36 ; #<VT>#
+	_ZTV14CScardNotifier @ 65 NONAME DATA 32 ; #<VT>#
+	_ZTV15CScardConnector @ 66 NONAME DATA 52 ; #<VT>#
+	_ZTV16CScardEventStack @ 67 NONAME DATA 20 ; #<VT>#
+	_ZTV17CScardReaderQuery @ 68 NONAME DATA 20 ; #<VT>#
+	_ZTV18CScardCommandTimer @ 69 NONAME DATA 32 ; #<VT>#
+	_ZTV18CScardMessageStack @ 70 NONAME DATA 20 ; #<VT>#
+	_ZTV19CScardAccessControl @ 71 NONAME DATA 32 ; #<VT>#
+	_ZTV20CScardChannelManager @ 72 NONAME DATA 20 ; #<VT>#
+	_ZTV20CScardNotifyRegistry @ 73 NONAME DATA 36 ; #<VT>#
+	_ZTV20CScardReaderRegistry @ 74 NONAME DATA 20 ; #<VT>#
+	_ZTV21CScardConnectionTimer @ 75 NONAME DATA 32 ; #<VT>#
+	_ZTV22CScardResourceRegistry @ 76 NONAME DATA 20 ; #<VT>#
+	_ZTV24CScardConnectionRegistry @ 77 NONAME DATA 20 ; #<VT>#
+	_ZTV27CScardAccessControlRegistry @ 78 NONAME DATA 20 ; #<VT>#
+	_ZTV6RScard @ 79 NONAME DATA 16 ; #<VT>#
+	_ZThn4_N20CScardNotifyRegistry15NotifyCardEventE19TScardServiceStatuss @ 80 NONAME ; #<thunk>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/bwins/SCARDU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,35 @@
+EXPORTS
+	??0CScardListener@@IAE@PAVRScard@@@Z @ 1 NONAME ; CScardListener::CScardListener(class RScard *)
+	??0TScardConnectionRequirement@@QAE@XZ @ 2 NONAME ; TScardConnectionRequirement::TScardConnectionRequirement(void)
+	??1CScardComm@@UAE@XZ @ 3 NONAME ; CScardComm::~CScardComm(void)
+	??1CScardListener@@MAE@XZ @ 4 NONAME ; CScardListener::~CScardListener(void)
+	??1CScardReaderQuery@@UAE@XZ @ 5 NONAME ; CScardReaderQuery::~CScardReaderQuery(void)
+	??1RScard@@UAE@XZ @ 6 NONAME ; RScard::~RScard(void)
+	?CancelTransmit@CScardComm@@QBEXXZ @ 7 NONAME ; void CScardComm::CancelTransmit(void) const
+	?ClearAIDBytesL@TScardConnectionRequirement@@QAEXXZ @ 8 NONAME ; void TScardConnectionRequirement::ClearAIDBytesL(void)
+	?ClearATRL@TScardConnectionRequirement@@QAEXXZ @ 9 NONAME ; void TScardConnectionRequirement::ClearATRL(void)
+	?ClearExcludedL@TScardConnectionRequirement@@QAEXXZ @ 10 NONAME ; void TScardConnectionRequirement::ClearExcludedL(void)
+	?ClearExplicitL@TScardConnectionRequirement@@QAEXXZ @ 11 NONAME ; void TScardConnectionRequirement::ClearExplicitL(void)
+	?DoCancel@CScardListener@@MAEXXZ @ 12 NONAME ; void CScardListener::DoCancel(void)
+	?GetATRL@CScardComm@@QBEXAAV?$TBuf8@$0CB@@@@Z @ 13 NONAME ; void CScardComm::GetATRL(class TBuf8<33> &) const
+	?GetCapabilitiesL@CScardComm@@QBEXJAAVTDes8@@J@Z @ 14 NONAME ; void CScardComm::GetCapabilitiesL(long, class TDes8 &, long) const
+	?ListGroupsL@CScardReaderQuery@@QAEXPAV?$CArrayFixFlat@V?$TBuf@$0CA@@@@@@Z @ 15 NONAME ; void CScardReaderQuery::ListGroupsL(class CArrayFixFlat<class TBuf<32> > *)
+	?ListReadersL@CScardReaderQuery@@QAEXPAV?$CArrayFixFlat@V?$TBuf@$0CA@@@@@ABV?$TBuf@$0CA@@@@Z @ 16 NONAME ; void CScardReaderQuery::ListReadersL(class CArrayFixFlat<class TBuf<32> > *, class TBuf<32> const &)
+	?ListenCardEvents@CScardListener@@QAEHABV?$TBuf@$0CA@@@@Z @ 17 NONAME ; int CScardListener::ListenCardEvents(class TBuf<32> const &)
+	?ManageChannel@CScardComm@@QBEXW4TScChannelManagement@@CAAVTDes8@@AAVTRequestStatus@@J@Z @ 18 NONAME ; void CScardComm::ManageChannel(enum TScChannelManagement, signed char, class TDes8 &, class TRequestStatus &, long) const
+	?NewCardsOnly@TScardConnectionRequirement@@QAEXH@Z @ 19 NONAME ; void TScardConnectionRequirement::NewCardsOnly(int)
+	?NewL@CScardComm@@SAPAV1@PAVRScard@@AAVTScardConnectionRequirement@@AAV?$TBuf@$0CA@@@AAVTRequestStatus@@J@Z @ 20 NONAME ; class CScardComm * CScardComm::NewL(class RScard *, class TScardConnectionRequirement &, class TBuf<32> &, class TRequestStatus &, long)
+	?NewL@CScardNotifyRegistry@@SAPAV1@PAVCScardServer@@@Z @ 21 NONAME ; class CScardNotifyRegistry * CScardNotifyRegistry::NewL(class CScardServer *)
+	?NewL@CScardReaderQuery@@SAPAV1@XZ @ 22 NONAME ; class CScardReaderQuery * CScardReaderQuery::NewL(void)
+	?NewL@RScard@@SAPAV1@XZ @ 23 NONAME ; class RScard * RScard::NewL(void)
+	?NewReadersOnly@TScardConnectionRequirement@@QAEXH@Z @ 24 NONAME ; void TScardConnectionRequirement::NewReadersOnly(int)
+	?NotifyCardEvent@CScardNotifyRegistry@@UAEXW4TScardServiceStatus@@F@Z @ 25 NONAME ; void CScardNotifyRegistry::NotifyCardEvent(enum TScardServiceStatus, short)
+	?RunL@CScardListener@@MAEXXZ @ 26 NONAME ; void CScardListener::RunL(void)
+	?Scard@CScardComm@@QBEPAVRScard@@XZ @ 27 NONAME ; class RScard * CScardComm::Scard(void) const
+	?SetAIDBytesL@TScardConnectionRequirement@@QAEXAAVTDesC8@@@Z @ 28 NONAME ; void TScardConnectionRequirement::SetAIDBytesL(class TDesC8 &)
+	?SetATRL@TScardConnectionRequirement@@QAEXAAV?$TBuf8@$0CB@@@@Z @ 29 NONAME ; void TScardConnectionRequirement::SetATRL(class TBuf8<33> &)
+	?SetExcludedL@TScardConnectionRequirement@@QAEXAAV?$TBuf@$0CA@@@@Z @ 30 NONAME ; void TScardConnectionRequirement::SetExcludedL(class TBuf<32> &)
+	?SetExplicitL@TScardConnectionRequirement@@QAEXAAV?$TBuf@$0CA@@@@Z @ 31 NONAME ; void TScardConnectionRequirement::SetExplicitL(class TBuf<32> &)
+	?StartThread@@YAHXZ @ 32 NONAME ; int StartThread(void)
+	?TransmitToCard@CScardComm@@QBEXABVTDesC8@@AAVTDes8@@AAVTRequestStatus@@JC@Z @ 33 NONAME ; void CScardComm::TransmitToCard(class TDesC8 const &, class TDes8 &, class TRequestStatus &, long, signed char) const
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/group/Scard.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,69 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project build file
+*
+*/
+
+#include <platform_paths.hrh>
+// Uncomment MACRO and define below to enable trace logging
+//MACRO __WIM_ENABLE_TRACES
+//#define __WIM_ENABLE_TRACES
+
+TARGET        Scard.dll
+TARGETTYPE    dll
+UID           0x1000008D  0x101F79DE
+
+CAPABILITY    CAP_GENERAL_DLL
+VENDORID      VID_DEFAULT
+
+SOURCEPATH    ../src
+
+//  API SOURCE FILES
+SOURCE        Scard.cpp
+SOURCE        ScardComm.cpp
+SOURCE        ScardConnectionRequirement.cpp
+SOURCE        ScardListener.cpp
+SOURCE        ScardReaderQuery.cpp
+
+//  SERVER SOURCE FILES
+SOURCE        ScardAccessControl.cpp
+SOURCE        ScardAccessControlRegistry.cpp
+SOURCE        ScardChannelManager.cpp
+SOURCE        ScardCommandTimer.cpp
+SOURCE        ScardConnector.cpp
+SOURCE        ScardConnectionRegistry.cpp
+SOURCE        ScardConnectionTimer.cpp
+SOURCE        ScardEventStack.cpp
+SOURCE        ScardMessageStack.cpp
+SOURCE        ScardNotifier.cpp
+SOURCE        ScardNotifyRegistry.cpp
+SOURCE        ScardReaderRegistry.cpp
+SOURCE        ScardResourceRegistry.cpp
+SOURCE        ScardServer.cpp
+SOURCE        ScardSession.cpp
+
+//  INCLUDE DIRECTORIES
+USERINCLUDE   ../inc
+USERINCLUDE   ../../inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+//  LIBRARIES
+LIBRARY       euser.lib c32.lib
+LIBRARY       efsrv.lib         //Needed for loading SwimReader.dll
+
+DEBUGLIBRARY  flogger.lib
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardAccessControl.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,329 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This object is the one responsible for trafficing between
+*               the Smart Card reader and the sessions.
+*
+*/
+
+
+
+#ifndef CSCARDACCESSCONTROL_H
+#define CSCARDACCESSCONTROL_H
+
+//  INCLUDES
+#include "ScardDefs.h"
+#include "ScardChannelManager.h" // required by inline functions
+
+// FORWARD DECLARATIONS
+class CScardSession;
+class MScardReader;
+class CScardMessageRegistry;
+class CScardAccessControl;
+class CScardAccessControlRegistry;
+class CScardCommandTimer;
+class CScardChannelManager;
+
+// CLASS DECLARATION
+
+/**
+*  Handles traffic between the Smart Card reader and the sessions.
+*  
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardAccessControl : public CActive
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        * @param aReaderID Reader ID
+        * @param aControl Pointer to AccessControlRegistry
+        */
+        static CScardAccessControl* NewL(
+            const TReaderID aReaderID, 
+            CScardAccessControlRegistry* aControl );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CScardAccessControl();
+    
+    public: // New functions
+        
+        /**
+        * Attach a new session to the reader.
+        * @param aSession session
+        * @param aSessionID session ID
+        * @return Pointer to reader.
+        */
+        MScardReader* AttachSessionToReaderL( CScardSession* aSession, 
+                                              TInt &aSessionID );
+
+        /**
+        * Is this session attached to this reader.
+        * @param aSession session
+        * @return true if session is attached.
+        */
+        TBool IsAttached( CScardSession* aSession ) const;
+
+        /**
+        * Detach a connection between reader and session.
+        * @param aSessionID session ID
+        * @return void
+        */
+        void DetachSessionFromReader( const TInt aSessionID );
+    
+        /**
+        * Initialise reader by calling Open.
+        * @param aSessionID session ID
+        * @param aMessage message
+        * @return EFalse if succesful, ETrue if reader is already open.
+        */
+        TBool InitialiseReader( const TInt aSessionID, 
+                                const RMessage2& aMessage );
+    
+        /**
+        * Is the reader available for data transmit
+        * @param aSessionID session ID
+        * @param aChannel channel
+        * @return ETrue if reader is ready for data transmission.
+        */
+        TBool ReaderIsReady( const TInt aSessionID, 
+                             const TInt8 aChannel ) const;
+    
+        /**
+        * Set access control in a state that enables communication with the 
+        * reader. Also sets control object active, and gives iStatus back to 
+        * caller.
+        * @param aSessionID session ID
+        * @param aMessage message
+        * @param aTimeOut time-out in microseconds (0 = no time-out).
+        * @param aChannel Logical channel
+        * @param aAdditionalParameter proprietary parameter sent to reader.
+        * @return ETrue if reader is ready for data transmission.
+        */
+        TRequestStatus& InitiateCommunication(
+            const TInt aSessionID, 
+            const RMessage2& aMessage, 
+            const TInt32 aTimeOut, 
+            const TInt8 aChannel,
+            const TUint8 aAdditionalParameter = 0x00 );
+    
+        /**
+        * Free reader's reservation.
+        * @param aSessionId session ID
+        * @param aChannel channel
+        */
+        void FreeChannelL( const TInt aSessionID, const TInt8 aChannel );
+
+        /**
+        * Stack the given command for completion later.
+        * @param aMessage message
+        * @param aSessionID session ID
+        * @param aTimeOut time-out in milliseconds (0 = no time-out).
+        * @param aChannel channel
+        */
+        void QueueExecution( const RMessage2& aMessage,
+                             const TInt aSessionID, 
+                             const TInt32 aTimeOut,
+                             const TInt8 aChannel, 
+                             const TInt8 aParameter = 0 );
+
+        /**
+        * Stack the given command for completion later with slightly higher 
+        * priority.
+        * @param aMessage message
+        * @param aSessionID session ID
+        * @param aTimeOut time-out in milliseconds (0 = no time-out).
+        * @param aChannel channel
+        */
+        void QueueChannelOperation( const RMessage2& aMessage, 
+                                    const TInt aSessionID,
+                                    const TInt32 aTimeOut, 
+                                    const TInt8 aChannel );
+
+        /**
+        * Remove operations for the session from the stack.
+        * @param aSessionID session ID
+        */
+        void DequeueOperations( const TInt aSessionID );
+
+        /**
+        * Handle a card event.
+        * @param aEvent card event
+        * @param aATR ATR-bytes
+        */
+        void CardEvent( const TScardServiceStatus aEvent, 
+                        const TScardATR& aATR );
+
+        /**
+        * Cancel everything from the session.
+        * @param aSessionID session ID
+        */
+        void CancelTransmissionsL( const TInt aSessionID );
+
+        /**
+        * Cancel an operation because the commands timer has run out.
+        * @param aTimer command timer
+        */
+        inline void CancelByTimeOut( CScardCommandTimer* aTimer );
+
+        /**
+        * ID of the reader this object controls.
+        * @return reader ID
+        */
+        inline const TReaderID ReaderID() const;
+
+        /**
+        * The reader object this object control.
+        * @return pointer to reader object.
+        */
+        inline MScardReader* Reader() const;
+
+        /**
+        * Give a session access rigths to the channel.
+        * @param aChannel channel
+        * @param aSessionID session ID
+        * @return ETrue on success.
+        */
+        inline const TBool AddSessionToChannelL( const TInt8 aChannel, 
+                                                 const TInt aSessionID );
+
+        /**
+        * Remove the session from the channel.
+        * @param aChannel channel
+        * @param aSessionID session ID
+        * @return ETrue on success.
+        */
+        inline const TBool RemoveSessionFromChannelL( const TInt8 aChannel, 
+                                                      const TInt aSessionID );
+
+        /**
+        * Has a channel been opened yet.
+        * @param aChannel channel
+        * @return ETrue if channel has been opened.
+        */
+        inline const TBool ChannelOpenedYet( const TInt8 aChannel );
+
+        /**
+        * Getter for channel status.
+        * @return channel status
+        */
+        inline TUint16 ChannelStatus();
+
+        /**
+        * Is the channel number legal, and is the session on the channel.
+        * @param aChannel channel number
+        * @param aSessionID session id
+        */
+        inline void ValidateChannelL( const TInt8 aChannel, 
+                                      const TInt aSessionID );
+
+        /**
+        * Get next unreserved logical channel.
+        * @return number of next unreserved logical channel
+        */
+        inline const TInt8 UnreservedLogicalChannel() const;
+
+
+    private: // Functions from base classes
+
+        /**
+        * From CActive cancel the request.
+        */
+        void DoCancel();
+
+        /**
+        * From CActive complete the request.
+        */
+        void RunL();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        * @param aReaderID Reader ID
+        * @param aControl Pointer to AccessControlRegistry
+        */
+        CScardAccessControl( const TReaderID aReaderID, 
+                             CScardAccessControlRegistry* aControl );
+    
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+    
+        /**
+        * Get a pointer to the session with ID aSessionID.
+        * @param aSessionID Session ID
+        * @return Pointer to session
+        */
+        CScardSession* SessionBase( const TInt aSessionID );
+
+        /**
+        * Handles next message.
+        * @param aHandle Handle of message
+        */
+        inline void HandleNextMessageL( const TMessageHandle& aHandle );
+
+    private:    // Data
+
+        // Reader session struct
+        struct TReaderSession
+            {
+            CScardSession* SessionBase;
+            TInt SessionID;
+            };
+
+        // Life modes
+        enum TLifeMode
+            {
+            ECanBeDeleted,
+            ECanNotDelete,
+            EDestroyASAP
+            };
+
+        //  Container for the client sessions
+        CArrayFixFlat<TReaderSession>* iSessionRegistry;
+    
+        // state variables for the reader
+        TBool           iReaderActive;
+        TBool           iIsCreated;
+        TBool           iIsOpen;
+        TInt            iNextSessionID;
+
+        //  the actual reader object parameters
+        MScardReader* iReader;
+        TReaderID     iReaderID;
+
+        //  Owner of this object
+        CScardAccessControlRegistry* iControlRegistry;
+
+        //  Internal channel manager
+        CScardChannelManager* iManager;
+    
+        //  ATR bytes of the SC in the reader this object controls
+        TScardATR iATR;
+
+        // Life mode
+        TLifeMode iLifeMode;
+        
+    };
+
+#include "ScardAccessControl.inl"
+
+#endif  // CSCARDACCESSCONTROL_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardAccessControl.inl	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,136 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Inline functions for smart card access control
+*
+*/
+
+
+
+//  INCLUDES
+#include "ScardMessageStack.h"
+#include "ScardSession.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::ReaderID
+// Return reader ID
+// -----------------------------------------------------------------------------
+//
+inline const TReaderID CScardAccessControl::ReaderID() const 
+    {
+    return iReaderID;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::Reader
+// Return reader object
+// -----------------------------------------------------------------------------
+//
+inline MScardReader* CScardAccessControl::Reader() const
+    {
+    return iReader;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::CancelByTimeOut
+// Cancel operations by timeout
+// -----------------------------------------------------------------------------
+//
+void CScardAccessControl::CancelByTimeOut( CScardCommandTimer* aTimer )
+    {
+    iManager->CancelByTimeOut( aTimer );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::ChannelStatus
+// Return channel status
+// -----------------------------------------------------------------------------
+//
+inline TUint16 CScardAccessControl::ChannelStatus()
+    {
+    return iManager->ChannelStatus();
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::ChannelOpenedYet
+// Is channel opened yet. Return ETrue/EFalse
+// -----------------------------------------------------------------------------
+//
+inline const TBool CScardAccessControl::ChannelOpenedYet( const TInt8 aChannel )
+    {
+    return iManager->ChannelOpenedYet( aChannel );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::AddSessionToChannelL
+// Add session to the channel
+// -----------------------------------------------------------------------------
+//
+inline const TBool CScardAccessControl::AddSessionToChannelL(
+    const TInt8 aChannel,
+    const TInt aSessionID )
+    {
+    return iManager->AddSessionToChannelL( aChannel, aSessionID );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::UnreservedLogicalChannel
+// Return unreserved logical channel
+// -----------------------------------------------------------------------------
+//
+inline const TInt8 CScardAccessControl::UnreservedLogicalChannel() const
+    {
+    return iManager->UnreservedLogicalChannel();
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::RemoveSessionFromChannelL
+// Remove Session From Channel
+// -----------------------------------------------------------------------------
+//
+inline const TBool CScardAccessControl::RemoveSessionFromChannelL(
+    const TInt8 aChannel,
+    const TInt aSessionID )
+    {
+    return iManager->RemoveSessionL( aChannel, aSessionID );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::ValidateChannelL
+// Validate channel
+// -----------------------------------------------------------------------------
+//
+inline void CScardAccessControl::ValidateChannelL(
+    const TInt8 aChannel, 
+    const TInt aSessionID )
+    {
+    iManager->ValidateChannelL( aChannel, aSessionID );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::HandleNextMessageL
+// Handle Next Message
+// -----------------------------------------------------------------------------
+//
+inline void CScardAccessControl::HandleNextMessageL(
+    const TMessageHandle& aHandle )
+    {
+    if ( aHandle.iSessionID != ENoSession )
+        {
+        ( SessionBase( aHandle.iSessionID ) )->ServiceL( aHandle );
+        }
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardAccessControlRegistry.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,130 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Handles the creation and destruction of individual access 
+*                controllers
+*
+*/
+
+
+
+#ifndef CSCARDACCESSCONTROLREGISTRY_H
+#define CSCARDACCESSCONTROLREGISTRY_H
+
+//  INCLUDES
+#include "ScardBase.h"
+#include "ScardDefs.h"
+
+//  FORWARD DECLARATIONS
+class CScardAccessControl;
+class CScardServer;
+class MScardReader;
+
+// CLASS DECLARATION
+
+/**
+*  Handles the creation and destruction of individual access controllers.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardAccessControlRegistry : public CBase
+    {
+    public:  // Constructors and destructor
+            
+        /**
+        * Two-phased constructor.
+        * @param aServer Pointer to server object
+        */
+        static CScardAccessControlRegistry* NewL( CScardServer* aServer );
+    
+        /**
+        * Destructor
+        */
+        virtual ~CScardAccessControlRegistry();
+
+    public: // New functions
+
+        /**
+        * Give pointer to the actual access control object for the 
+        * spesified reader
+        * @param aReaderID ReaderID
+        * @return Pointer to found ScardAccessControl object
+        */
+        CScardAccessControl* FindAccessController( const TReaderID aReaderID );
+        
+        /**
+        * Return access controller object
+        * @param aReaderID ReaderID
+        * @return Pointer to CScardAccessControl object
+        */
+        CScardAccessControl* AccessController( const TReaderID aReaderID );
+
+        /**
+        * Used by the server to get a Reader object
+        * @param aReaderID ReaderID
+        * @return Pointer to MScardReader object
+        */
+        MScardReader* Reader( const TReaderID aReaderID ) const;
+    
+        /**
+        * Check if this reader has a controller loaded
+        * @param aReaderID ReaderID
+        * @return ETrue if reader loaded, EFalse if not
+        */
+        TBool ReaderHandlerLoaded( const TReaderID aReaderID ) const;
+
+        /**
+        * Return pointer to CScardServer
+        * @return Pointer to CScardServer object
+        */
+        CScardServer* Server();
+
+        /**
+        * An access controller has been disconnected
+        * @param aControl Pointer to CScardAccessControl object
+        * @return void
+        */
+        void ControllerRetired( CScardAccessControl* aControl );
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CScardAccessControlRegistry();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        * @param aServer Pointer to server object
+        */
+        void ConstructL( CScardServer* aServer );
+
+        //  
+        /**
+        * Destroy a handler object from the registry
+        * @param aIndex Index of access controller in registry
+        * @return void
+        */
+        //  
+        void RemoveAccessController( const TInt aIndex );
+
+    private:    //Data
+        // Array of AccessControllers. Owned.
+        CArrayFixFlat<CScardAccessControl*>* iAccessControllers;
+        // Pointer to Server object. Not owned.
+        CScardServer*                        iServer;
+    };
+
+#endif      // CSCARDACCESSCONTROLREGISTRY_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardChannelManager.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,225 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Handles individual channels on a singular SC 
+*               (which equals one SC reader handler) Can be queried
+*               for information about channels, controls traffic etc.
+*
+*/
+
+
+
+#ifndef CSCARDCHANNELMANAGER_H
+#define CSCARDCHANNELMANAGER_H
+
+// INCLUDES
+#include "ScardServerBase.h"
+#include "ScardDefs.h"
+
+// FORWARD DECLARATIONS
+class CScardAccessControl;
+class CScardMessageStack;
+class CScardCommandTimer;
+
+// CLASS DECLARATION
+
+/**
+*  Scard channel manager.
+*  Handles individual channels on a singular Smart card
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardChannelManager : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CScardChannelManager* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CScardChannelManager();
+
+    public: // New functions
+
+        /**
+        * Give the session the right to use the channel
+        * @param aChannel Channel to be added
+        * @param aSessionID Session ID
+        * @return Always returns ETrue
+        */
+        TBool AddSessionToChannelL( const TInt8 aChannel, 
+                                    const TInt aSessionID );
+
+        /**
+        * Remove session from the given channel
+        * @param aChannel Channel
+        * @param aSessionID Session ID to be removed
+        * @return Always returns EFalse
+        */
+        TBool RemoveSessionL( const TInt8 aChannel, 
+                              const TInt aSessionID );
+
+        /**
+        * Does the session have permission to the channel
+        * @param aChannel Channel
+        * @param aSessionID SessionID
+        * @return ETrue if session is on channel, otherwise EFalse
+        */
+        TBool SessionIsOnChannel( const TInt8 aChannel, 
+                                  const TInt aSessionID ) const;
+
+        /**
+        * This function returns an int16 that spesifies which channels have
+        * been opened and which of them are reserved
+        * @return Two-byte parameter telling:
+        *   b0 - Channel 0 open (should always be set)
+        *   b1 - Channel 0 reserved
+        *   b2 - Channel 1 open
+        *   b3 - Channel 1 reserved
+        *   ...
+        *   b7 - Channel 3 open
+        *   b8 - Channel 3 reserved
+        *                
+        *   b9-b15 Maximum number of channels available (at the moment always 4)
+        */
+        TUint16 ChannelStatus();
+
+        /**
+        * Is the channel reserved? Return ID of session reserving the channel
+        * @param aChannel Channel
+        * @return Reserver session ID of the channel
+        */
+        TInt ChannelReservedL( const TInt8 aChannel ) const;
+
+        /**
+        * Remove the exclusive access from one channel.
+        * @param aChannel Channel
+        * @param aSessionID Session ID
+        * @return void
+        */
+        void FreeChannelL( const TInt8 aChannel,
+                           const TInt aSessionID );
+
+        /**
+        * Remove any exclusive accesses.
+        * @param aChannel Channel
+        * @return void
+        */
+        void FreeChannels( const TInt aSessionID );
+
+        /**
+        * Is the session on the channel, and is the channel number legal.
+        * @param aChannel Channel
+        * @param aSessionID SessionID
+        * @return void
+        */
+        void ValidateChannelL( const TInt8 aChannel,
+                               const TInt aSessionID );
+
+        /**
+        * Get the number of the next unreserved logical channel.
+        * @param aChannel Channel
+        * @return Number of next unreserved channel
+        */
+        TInt8 UnreservedLogicalChannel() const;
+
+        /**
+        * Has the channel been opened yet.
+        * @param aChannel Channel
+        * @return ETrue if channel already reserved, otherwise EFalse
+        */
+        TBool ChannelOpenedYet( const TInt8 aChannel );
+
+        /**
+        * Cancels the message.
+        * @param aTimer Pointer to command timer
+        * @return void
+        */
+        void CancelByTimeOut( CScardCommandTimer* aTimer );
+
+        /**
+        * Cancels all the messages for given session.
+        * @param aSessionID SessionID
+        * @return void
+        */
+        void CancelAll( const TInt aSessionID );
+
+        /**
+        * Puts message on bottom of message stack.
+        * @param aMessage Message to be pushed to bottow of stack
+        * @return void
+        */
+        void PushMessageToBottomL( const TMessageHandle& aMessage );
+        
+        /**
+        * Puts message on top of message stack.
+        * @param aMessage Message to be pushed
+        * @return void
+        */
+        void PushMessageToTopL( const TMessageHandle& aMessage );
+
+        /**
+        * Get message from top of the message stack.
+        * @return TMessageHandle
+        */
+        const TMessageHandle MessageFromTop();
+        
+        /**
+        * Get next message
+        * @return TMessageHandle
+        */
+        const TMessageHandle NextMessageL();
+        
+        /**
+        * NextMessageFromFree
+        * @param aChannel Channel
+        * @return TMessageHandle
+        */
+        const TMessageHandle NextMessageFromFree( const TInt8 aChannel );
+
+        /**
+        * Handle channels when card is removed.
+        * @return void
+        */
+        void CardRemoved();
+    
+    private:
+        
+        /**
+        * C++ default constructor.
+        */
+        CScardChannelManager();
+        
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    private:
+        // The messages
+        CScardMessageStack* iMessageStack;
+    
+        // The sessions that are joined/channel
+        CArrayPtrFlat< CArrayFixFlat<TInt> >* iChannels;
+
+        //  IDs of sessions that are currently reserving the channels
+        TInt iReserverID[KMaxChannels];
+    };
+
+#endif      // CSCARDCHANNELMANAGER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardClsv.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions for client-server communication
+*
+*/
+
+
+
+#ifndef CSCARDCLSV_H
+#define CSCARDCLSV_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+// A version must be specifyed when creating a session with the server
+const TUint KScardServMajorVersionNumber = 0;
+const TUint KScardServMinorVersionNumber = 1;
+const TUint KScardServBuildVersionNumber = 1;
+// server name
+_LIT( KScardServerName, "ScardServer" );
+
+// DATA TYPES
+// opcodes used in message passing between client and server
+enum TScardServRqst
+    {
+    //  CScardComm opcodes
+    EScardServerCloseSession,
+    EScardServerNotifyChange,
+    EScardServerCancelNotifyChange,
+    EScardServerConnectToReader,
+    EScardServerDisconnectFromReader,
+    EScardServerTransmitToCard,
+    EScardServerCancelTransmit,
+    EScardServerGetATR,
+    EScardServerGetCapabilities,
+    EScardServerManageChannel
+    };
+
+// FUNCTION PROTOTYPES
+IMPORT_C TInt StartThread();
+
+#endif      // CSCARDCLSV_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardCommandTimer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Smart card command timer
+*
+*/
+
+
+
+#ifndef CSCARDCOMMANDTIMER_H
+#define CSCARDCOMMANDTIMER_H
+
+// FORWARD DECLARATIONS
+class CScardAccessControl;
+
+// CLASS DECLARATION
+
+/**
+*  Timer class.
+*  Timer class, which is used when smart card is accessed after connection 
+*  is established.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardCommandTimer : public CActive  
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        * @param aTimeOut Timeout
+        * @param aController Pointer to access controller
+        */
+        static CScardCommandTimer* NewL( TInt32 aTimeOut, 
+                                         CScardAccessControl* aController );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CScardCommandTimer();
+
+    public: // New functions
+
+        /**
+        * Starts the timer.
+        * @return void
+        */
+        void StartTiming();
+        
+    public: // Functions from base classes
+    
+        /**
+        * From CActive DoCancel.
+        */
+        void DoCancel();
+
+        /**
+        * From CActive RunL.
+        */
+        void RunL();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CScardCommandTimer();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        * @param aTimeOut Timeout
+        * @param aController Pointer to access controller
+        */
+        void ConstructL( TInt32 aTimeOut,
+                         CScardAccessControl* aController );
+
+    private:
+        // Pointer to RTimer object. Owned.
+        RTimer* iTimer;
+        // Pointer to Controller. Not owned.
+        CScardAccessControl* iController;
+        // Timeout
+        TInt32 iTimeOut;
+    };
+
+#endif      // CSCARDCOMMANDTIMER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardConnectionRegistry.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,141 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Keeps track, creates and destroys connector objects
+*
+*/
+
+
+
+#ifndef CSCARDCONNECTIONREGISTRY_H
+#define CSCARDCONNECTIONREGISTRY_H
+
+// INCLUDE FILES
+#include "ScardDefs.h"
+
+
+//FORWARD DECLARATIONS
+class CScardAccessControlRegistry;
+class CScardAccessControl;
+class CScardServer;
+class CScardConnector;
+class CScardSession;
+class MScardReader;
+
+
+// DATA TYPES
+struct TConnectionHandle
+    {
+    CScardConnector* iConnector;  // This is introduced in forward declarations
+    CScardSession*   iClient;
+    TConnectionHandle()
+        :iConnector( NULL ), iClient( NULL )
+        {}
+    };
+
+// CLASS DECLARATION
+
+/**
+*  Keeps track, creates and destroys connector objects.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardConnectionRegistry : public CBase
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        * @param aServer Pointer to server object
+        */
+        static CScardConnectionRegistry* NewL( CScardServer* aServer );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CScardConnectionRegistry();
+    
+    public: // New functions
+        
+        /**
+        * Creates the connector and instructs it to connect.
+        * @param aSession Pointer to session
+        * @param aMessage Message
+        * @return void
+        */
+        void ConnectToReaderL( CScardSession* aSession, 
+                               const RMessage2& aMessage );
+
+        /**
+        * Finds the connector managing the session and instructs it cancel. 
+        * Panics if the connector is not found.
+        * @param aSession
+        * @return void
+        */
+        void CancelConnection( CScardSession* aSession );
+
+        /**
+        * Connection completed.
+        * @param aConnector Pointer to connector
+        * @param aReaderID Reader ID
+        * @param aErrorCode Error code that is returned in error
+        * @return void
+        */
+        void ConnectDone( CScardConnector* aConnector, 
+                          const TReaderID& aReaderID, 
+                          const TInt& aErrorCode );
+
+        /**
+        * Removes connector from registry.
+        * @param aConnector Pointer to connector to be removed
+        * @return void
+        */
+        void RemoveConnector( CScardConnector* aConnector );
+
+        /**
+        * Return pointer to ScardServer object
+        * @return Pointer to ScardServer object
+        */
+        CScardServer* Server() const;
+
+        /**
+        * Return connection handle
+        * @param aLocation Index in iConnectors array
+        * @return Connection handle
+        */
+        TConnectionHandle& Connection( TInt aLocation ) const;
+
+    private:
+        
+        /**
+        * C++ default constructor.
+        */
+        CScardConnectionRegistry();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        * @param aServer Pointer to server object
+        */
+        void ConstructL( CScardServer* aServer );
+
+    private:    // Data
+        // Pointer to Scard Server. Not owned.
+        CScardServer* iServer;
+        // Array of connectors. Owned.
+        CArrayFixFlat<TConnectionHandle>* iConnectors;
+    };
+
+#endif      // CSCARDCONNECTIONREGISTRY_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardConnectionTimer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,92 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Timer for connections to smartcard.
+*
+*/
+
+
+
+#ifndef CSCARDCONNECTIONTIMER_H
+#define CSCARDCONNECTIONTIMER_H
+
+// INCLUDES
+#include "ScardBase.h"
+
+// FORWARD DECLARATIONS
+class CScardConnector;
+
+/**
+*  Timer class, which is used while establishing connection to smart card.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardConnectionTimer : public CActive
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        * @param aConnector Pointer to connector object
+        * @param aTimeOut Timeout
+        */
+        static CScardConnectionTimer* NewL( CScardConnector* aConnector,
+                                            TInt32 aTimeOut );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CScardConnectionTimer();
+    
+    public: // Functions from base classes        
+        
+        /**
+        * From CActive RunL.
+        */
+        void RunL();
+        
+        /**
+        * From CActive DoCancel.
+        */
+        void DoCancel();
+
+    private:
+        
+        /**
+        * C++ default constructor.
+        * @param aConnector Pointer to connector object
+        * @param aTimeOut Timeout
+        */
+        CScardConnectionTimer( CScardConnector* aConnector,
+                               TInt32 aTimeOut );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    private:    // Data
+        // Timeout
+        TInt32  iTimeOut;
+        
+        // Pointer to timer. Owned.
+        RTimer* iTimer;
+
+        // Pointer to connector. Not owned.
+        CScardConnector* iConnector;
+    };
+
+#endif      // CSCARDCONNECTIONTIMER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardConnector.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,233 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A connection to a smart card.
+*
+*/
+
+
+
+#ifndef CSCARDCONNECTOR_H
+#define CSCARDCONNECTOR_H
+
+// INCLUDE FILES
+#include "ScardSession.h"
+#include "ScardEventStack.h"
+
+// CONSTANTS
+const TUint8 KOpenReader = 0x40;
+
+//FORWARD DECLARATIONS
+class CScardAccessControlRegistry;
+class CScardAccessControl;
+class CScardConnectionRegistry;
+class CScardConnectionTimer;
+//class TScardATR;
+
+// STRUCTURES
+struct TConnectionParameter
+    {
+    TPtr*             iReaderName;
+    TScardReaderName* iExcluded;
+    
+    TScardATR*        iATRBytes;
+    TPtr8*            iAIDBytes;
+    
+    TBool             iNewCardOnly;
+    TBool             iNewReaderOnly;
+
+    TConnectionParameter();
+    };
+
+//  Handle to a complete connection attempt
+struct TConnection
+    {
+    //  Access controller for that reader
+    CScardAccessControl* iCtrl;
+    //  The reader object this connection is attached and it's ID
+    MScardReader*        iReader;
+    TReaderID            iReaderID;
+    //  This connection's session id
+    TInt                 iSessionID;
+    //  Constructor added for convenience    
+    TConnection();
+    };
+
+//  Little shortcut to use when comparing two connections
+TBool operator==( const TConnection&, const TConnection& );
+
+//  The states the connection process can be in
+enum TScardConnectionState
+    {
+    EActive = 1,    //  actively pursuing new connections
+    //  all clear, a clean connection was established (or an error occurred)
+    EConnectionComplete,
+    //  one stage completed, waiting for the client to confirm
+    EWaitingForConfirm,
+    EReconnecting,  // Rrunning the while loop inside ReconnectToReaderL()
+    EInitialising,  // Initialising the reader(s)
+    //  connection was established inside the while loop, 
+    //  imminent suicide as soon as possible
+    EDying,
+    ETimedOut       // Hit a timeout. Die ASAP.
+    };
+
+// CLASS DECLARATION
+
+/**
+*  Actual connector class. 
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardConnector : public CScardSession
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        * @param aConnRegistry Pointer to connection registry
+        * @param aClient Client thread
+        * @param aMessage Client message
+        */ 
+        static CScardConnector* NewL( CScardConnectionRegistry* aConnRegistry,
+                                      RThread& aClient, 
+                                      const RMessage2& aMessage );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CScardConnector();
+
+    public: // New functions
+
+        /**
+        * The timer has sent a signal indicating that this connection 
+        * attempt has timed out
+        * @return void
+        */
+        void ConnectionTimedOut();
+
+        /**
+        * Cancel connection. It appears this connection is not wanted after all.
+        * @return void
+        */
+        void Cancel();
+
+    public: // Functions from base classes
+    
+        /**
+        * From CScardSession Override ConnectToReader.
+        * @return void
+        */
+        void ConnectToReaderL(); 
+
+        /**
+        * From CScardSession Override CardEvent
+        * Handles card events. Panics if there is no connection to reader.
+        * @param aEvent Scard event
+        * @param aATR ATR bytes
+        * @param aReaderID Reader ID
+        * @return void
+        */
+        virtual void CardEvent( const TScardServiceStatus aEvent,
+                                const TScardATR& aATR, 
+                                const TReaderID& aReaderID );
+    
+        /**
+        * From CScardSession All clear, a connection has been established.
+        * @param aReaderID ReaderID
+        * @param aErrorCode Error code
+        * @return void
+        */
+        void ConnectionDone( const TReaderID aReaderID, 
+                             const TInt& aErrorCode );
+        
+
+        /**
+        * From CSharableSession. Return client message.
+        * @return RMessage
+        */
+        RMessage2& Message();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        * @param aConnRegistry Pointer to connection registry
+        * @param aClient Client thread
+        */
+        CScardConnector( CScardConnectionRegistry* aConnRegistry, 
+                         RThread& aClient );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        * @param aMessage Client message
+        */
+        void ConstructL( const RMessage2& aMessage );
+
+        /**
+        * Parse the message to get limiting factors
+        * @return void
+        */
+        void ReadLimitsL();
+
+        /**
+        * Check all conditions set for the new card. This method checks if
+        * ATR bytes and AID bytes match with given values in connection 
+        * requirements. Currently AID and ATR bytes are not supported.
+        * @param aConnection Connection 
+        * @param aATR ATR bytes
+        * @return ETrue if connection conditions are met, else EFalse
+        */
+        TBool CheckConditions( TConnection& aConnection, 
+                               const TScardATR* aATR );
+
+        /**
+        * Make and add to list a new connection.
+        * @param aMessage Client message
+        * @param aReaderID Reader ID
+        * @return ETrue if connectin succesfully created, otherwise EFalse.
+        */
+        TBool NewConnectionL( const RMessage2 aMessage,
+                              const TReaderID aReaderID );
+
+        /**
+        * Find connection for giben reader
+        * @param aReaderID Reader ID
+        * @return Reference to TConnection object
+        */
+        TConnection& FindReaderConnectionL( const TReaderID& aReaderID );
+
+    private:    // Data
+        // Container for all connection attempt handles. Owned.
+        CArrayFixFlat<TConnection>* iConnections;
+        // Pointer to connection registry. Not owned.
+        CScardConnectionRegistry*   iConnectionRegistry;
+        // The message from the client
+        RMessage2*                   iClientMessage;
+        // Storage for card events to be handled later. Owned.
+        CScardEventStack*           iStack;
+        //  Life status indicator
+        TInt                        iState;
+        // Contacting a single reader or many?
+        TBool                       iOneReaderMode;
+        // Timer for this connector. Owned.
+        CScardConnectionTimer*      iTimer;
+        // The parameter block for this connection attempt
+        TConnectionParameter        iParameters;
+    };
+
+#endif      // CSCARDCONNECTOR_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardEventStack.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,90 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A class implementing two stacks. One is a fifo-stack of
+*               reader events, the other a random-access stack of service
+*               providers that are not used with a given reader.
+*
+*/
+
+
+
+#ifndef CSCARDEVENTSTACK_H
+#define CSCARDEVENTSTACK_H
+
+//  INCLUDES
+#include "ScardServerBase.h"
+#include "ScardDefs.h"
+
+//  FORWARD DECLARATIONS
+class CScardConnector;
+
+// CLASS DECLARATION
+
+/**
+*  A class implementing two stacks. 
+*  One is a fifo-stack of reader events, the other a random-access stack of
+*  service providers that are not used with a given reader.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardEventStack : public CBase  
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        * @param aConnector Pointer to connector object
+        */
+        static CScardEventStack* NewL( CScardConnector* aConnector );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CScardEventStack();
+   
+    public: // New functions
+       
+        /**
+        * Queue events
+        * @param aReaderID ReaderID
+        * @param aEventType Event type
+        * @return void
+        */
+        void QueueEvent( const TReaderID aReaderID,
+                         const TScardServiceStatus aEventType );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CScardEventStack();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        * @param aConnector Pointer to connector object
+        */
+        void ConstructL( CScardConnector* aConnector );
+
+    private:    // Data
+        // Array of event. Owned.
+        CArrayFixFlat<TQueueEvent>*  iEvents;
+        // Pointer to connector object. Not owned.
+        CScardConnector* iConnector;
+    };
+
+#endif      // CSCARDEVENTSTACK_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardLogs.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Constans for Scard logging
+*
+*/
+
+
+
+#ifndef CSCARDLOGS_H
+#define CSCARDLOGS_H
+
+// CONSTANTS
+_LIT( KScardLogDir, "Scard" );
+_LIT( KScardLogFileName, "Log.txt" );
+
+#endif      // CSCARDLOGS_H
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardMessageStack.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,173 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Smart card message stack.
+*
+*/
+
+
+
+#ifndef CSCARDMESSAGESTACK_H
+#define CSCARDMESSAGESTACK_H
+
+//  INCLUDES
+#include "ScardServerBase.h"
+#include "ScardClsv.h"
+#include "ScardCommandTimer.h"
+#include "ScardDefs.h"
+
+// FORWARD DECLARATIONS
+class CScardCommandTimer;
+
+// CLASS DECLARATION
+
+/**
+*  Message stack.
+*  This class establishes a connection with a SC reader handler for a session. 
+*  Creates (if necessary) MScardReader objects, and determines when one of 
+*  them satisfies the parameters.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardMessageStack : public CBase
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CScardMessageStack* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CScardMessageStack();
+    
+    public: // New functions 
+        
+        /**
+        * Cancel all messages waiting for service. Delete all others 
+        * except the first one.
+        * @param aReason Reason code for cancellation
+        * @return void
+        */
+        void CancelAll( const TInt aReason );
+        
+        /**
+        * Cancel all operations for this session ID.
+        * @param aSessionID Session ID
+        * @param aReason Reason code for cancellation
+        * @return void
+        */
+        void CancelAll( const TInt aSessionID,
+                        const TInt aReason );
+
+        /**
+        * Effectively the same as CancelAll(const TInt aReason), 
+        * except that does not cancel OpenReader commands.
+        * @return void
+        */
+        void CancelCardOperations();
+
+        /**
+        * Cancels the messages using the given timer.
+        * @param aTimer Timer object
+        * @return void
+        */
+        void CancelByTimeOut( const CScardCommandTimer* aTimer );
+
+        /**
+        * Puts the message to the top of the stack.
+        * @param aMessage Message
+        * @return Error code
+        */
+        TInt PushToTop( const TMessageHandle& aMessage );
+
+        /**
+        * Puts the message to the bottom of the stack.
+        * @param aMessage Message
+        * @return Error code
+        */
+        TInt PushToBottom( const TMessageHandle& aMessage );
+
+        /**
+        * Returns the topmost message from the stack.
+        * @return Handle to topmost message
+        */
+        const TMessageHandle FromTop();
+        
+        /**
+        * This function is called when a channel is freed. It gives priority
+        * for applications who are waiting to reserve either this channel 
+        * or any channel.
+        * @param aChannel Channel
+        * @return Handle to message
+        */        
+        const TMessageHandle NextReservation( const TInt8 aChannel );
+
+        /**
+        * Returns the message from given position in the stack.
+        * @param aPosition Position from which we want the message
+        * @return Handle to message
+        */ 
+        const TMessageHandle FromPositionL( const TInt aPosition );
+
+        /**
+        * Push message to given position in the stack.
+        * @param aPosition Position to which we want to push the msg
+        * @param aHandle Message handle
+        * @return Handle to message
+        */
+        void PushToPositionL( const TInt aPosition,
+                              TMessageHandle& aHandle );
+
+        /**
+        * Returns the number of messages in the stack.
+        * @return Count of messagages in the stack
+        */
+        inline const TInt Count();
+
+    private:
+        
+        /**
+        * C++ default constructor.
+        */
+        CScardMessageStack();
+        
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Cancel one message
+        * @param aIndex Index of message
+        * @param aReason Reason code for cancellation
+        * @param aCancelTimer Do we want to cancel timer
+        * @return void
+        */
+        inline void CancelOne( const TInt aIndex,
+                               const TInt aReason, 
+                               const TBool aCancelTimer = ETrue );
+
+    private:    // Data
+        // Array of messages. Owned.
+        CArrayFixFlat<TMessageHandle>* iMessages;
+    };
+
+#include "ScardMessageStack.inl"
+
+#endif      // CSCARDMESSAGESTACK_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardMessageStack.inl	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,63 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Inline functions for smart card message stack
+*
+*/
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::Count
+// Returns count of messages in the stack.
+// -----------------------------------------------------------------------------
+//
+inline const TInt CScardMessageStack::Count()
+    {
+    return iMessages->Count();
+    }   
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::CancelOne
+// Cancel one message
+// -----------------------------------------------------------------------------
+//
+inline void CScardMessageStack::CancelOne( 
+    const TInt aIndex, 
+    const TInt aReason,
+    const TBool aCancelTimer )
+    {
+    TMessageHandle& tmp = (*iMessages)[aIndex]; 
+
+    // Do not cancel twice
+    if ( !tmp.iCancelled )
+        {
+        tmp.iCancelled = ETrue;
+        //  There are two special types of messages that don't need completing.
+        //  One is a transmission from a connector and the other
+        //  is ConnectToReader
+        if ( ! ( (tmp.iAdditionalParameter & KConnection ) |
+            ( tmp.iMessage.Function() == EScardServerConnectToReader ) ) ) 
+            {
+            tmp.iMessage.Complete( aReason );
+            }
+
+        if ( aCancelTimer && tmp.iTimer )
+            {
+            tmp.iTimer->Cancel();
+            }
+        }
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardNotifier.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,132 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Notifier for SmartCard.
+*
+*/
+
+
+
+#ifndef CSCARDNOTIFIER_H
+#define CSCARDNOTIFIER_H
+
+
+//  INCLUDES
+#include "ScardNotifyRegistry.h"
+
+// CLASS DECLARATION
+
+/**
+*  Used to notify smart card server about card events.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardNotifier : public CActive
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        * @param aRegistry Pointer to notify registry
+        * @param aClient Client thread
+        * @param aClientStatus Client request status
+        * @param aReaderID Reader ID
+        */
+        static CScardNotifier* NewL( CScardNotifyRegistry* aRegistry, 
+                                     RMessage2& aMessage,
+                                     TRequestStatus* aClientStatus, 
+                                     const TReaderID& aReaderID );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CScardNotifier();
+    
+    public: // New functions
+    
+        /**
+        * Complete our own request, or if that's done already, 
+        * store the event until it can be serviced.
+        * @param aEvent Scard event
+        * @param aReaderID Reader ID
+        * @return void
+        */
+        void NotifyCardEvent( TScardServiceStatus aEvent, 
+                              TReaderID aReaderID );
+                              
+        TReaderID ReaderId();
+
+    public: // Functions from base classes    
+        
+        /**
+        * From CActive RunL.
+        */
+        void RunL();
+
+        /**
+        * From CActive DoCancel.
+        */
+        void DoCancel();
+        
+    private:
+        
+        /**
+        * C++ default constructor.
+        * @param aRegistry Pointer to notify registry
+        * @param aClient Client thread
+        * @param aClientStatus Client request status
+        * @param aReaderID Reader ID
+        */
+        CScardNotifier( CScardNotifyRegistry* aRegistry, 
+                        RMessage2& aMessage,
+                        TRequestStatus* aClientStatus,
+                        const TReaderID& aReaderID );
+        
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    public: // Data
+                
+    
+    private:    // Data
+        struct TCardEvent
+            {
+            TScardServiceStatus iEvent;
+            TReaderID           iReaderID;
+            };
+
+        // Pointer to notify registry. Not owned.
+        CScardNotifyRegistry*      iRegistry;
+        // Event stack. Owned.
+        CArrayFixFlat<TCardEvent>* iEventStack;
+        
+        // Client message to be completed when event occurs
+        RMessage2       iMessage;
+
+        // Clients request status. Not owned. 
+        TRequestStatus* iClientStatus; 
+        
+        // Reader ID
+        TReaderID       iReaderID;
+        
+        // Flag to tell if message is already completed
+        TBool           iMessageCompleted;
+ 
+    };
+
+#endif      // CSCARDNOTIFIER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardNotifyRegistry.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,125 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Notification Registry for SmartCard.
+*
+*/
+
+
+
+#ifndef CSCARDNOTIFYREGISTRY_H
+#define CSCARDNOTIFYREGISTRY_H
+
+
+//  INCLUDES
+#include "ScardServerBase.h"
+#include "ScardNotifyObserver.h"
+
+
+// CONSTANTS
+const TReaderID KServerNotifier = -1;
+
+//  FORWARD DECLARATIONS
+class CScardServer;
+class CScardNotifier;
+
+// CLASS DECLARATION
+
+/**
+*  Keeps track of notifiers.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardNotifyRegistry : public CBase, public MScardNotifyObserver
+    {
+
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static  CScardNotifyRegistry* NewL( CScardServer* aServer );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CScardNotifyRegistry();
+   
+    public: // New functions
+        
+        /**
+        * Creates a notifier if necessary.
+        * @param aMessage Message
+        * @return void
+        */
+        void AddReaderEventListenerL( const RMessage2& aMessage );
+
+        /**
+        * Removes the notifier.
+        * @param aMessage Message
+        * @return void
+        */
+        void RemoveReaderEventListener( const RMessage2& aMessage );
+
+        /**
+        * Removes all notifiers for given client.
+        * @param aClient Client thread
+        * @return void
+        */
+        void RemoveReaderEventListeners( const RThread& aClient );
+    
+        /**
+        * Notify clients about card event.
+        * @param aEvent Event
+        * @param aReaderID Reader ID
+        * @return void
+        */
+        IMPORT_C void NotifyCardEvent( TScardServiceStatus aEvent,
+                                       TReaderID aReaderID );
+
+        /**
+        * Return pointer to Server
+        * @return Pointer to the Server object
+        */
+        CScardServer* Server();
+
+        /**
+        * Cancels the request.
+        * @param aStatus Request status
+        * @return void
+        */
+        void Cancel( TRequestStatus& aStatus );
+
+    private:
+        
+        /**
+        * C++ default constructor.
+        */
+        CScardNotifyRegistry(); 
+
+        /**
+        * Symbian 2nd phase constructor.
+        */
+        void ConstructL( CScardServer* aServer);  
+
+    private:    // Data
+        // Array of notifiers. Owned.
+        CArrayPtrFlat<CScardNotifier>* iNotifiers;    
+        // Server object. Not owned.
+        CScardServer*                  iServer;
+    };
+
+#endif      // CSCARDREGISTRY_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardReaderRegistry.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,152 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Registry of smart card readers.
+*
+*/
+
+
+
+#ifndef CSCARDREADERREGISTRY_H
+#define CSCARDREADERREGISTRY_H
+
+//  INCLUDES
+#include "ScardDefs.h"
+#include <f32file.h>    // For RFs
+
+//  FORWARD DECLARATIONS
+class CScardServer;
+class MScardReader;
+class MScardReaderLauncher;
+class CScardAccessControl;
+
+// DATA TYPES
+struct TLauncherStruct
+    {
+    RFs         iSession;
+    RLibrary    iLibrary;
+    TGroupID    iGroupID;
+    TReaderID   iReaderID;
+    MScardReaderLauncher* iLauncher;
+    TLauncherStruct();
+    };
+
+// CLASS DECLARATION
+
+/**
+*  Reader registry.
+*  This class handles all server-side connections to the reader/card database. 
+*  Creates reader handlers, queries whether a given reader is supported and 
+*  gives lists of all the currently open or closed readers.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardReaderRegistry : public CBase
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        * @param aServer Pointer to CScardServer object
+        */
+        static CScardReaderRegistry* NewL( CScardServer* aServer ); 
+
+        /**
+        * Destructor.
+        */
+        virtual ~CScardReaderRegistry();
+
+    public: // New functions
+
+        /**
+        * Loads reader handler module with given ID.
+        * @param aReaderID Reader ID
+        * @return pointer to MScardReader object
+        */
+        MScardReader* LoadReaderL( const TReaderID aReaderID );
+
+        /**
+        * Unload the reader module with given ID.
+        * @param aReaderID Reader ID
+        * @return void
+        */
+        void CloseReader( const TReaderID aReaderID );
+
+        /**
+        * Get ID for name.
+        * @param aReaderName Reader name
+        * @return TReaderID object
+        */
+        TReaderID ReaderID( const TScardReaderName& aReaderName );
+
+        /**
+        * Get name for ID.
+        * @param aReaderID Reader ID
+        * @return TScardDBName object
+        */
+        const TScardReaderName FriendlyName( const TReaderID aReaderID );
+
+        /**
+        * Is reader supported or not?
+        * @param aReaderName Reader name
+        * @return ETrue if supported, else EFalse
+        */
+        TBool IsSupported( const TScardReaderName& aReaderName );
+
+        /**
+        * Lists open readers.
+        * @param aACList (OUT) List of readers
+        * @return void
+        */
+        void ListOpenReadersL( CArrayFix<CScardAccessControl*>* aACList );
+
+        /**
+        * List the readers, which have not opened yet.
+        * @param aACList (OUT) List of readers
+        * @return void
+        */
+        void ListClosedReadersL( CArrayFix<TReaderID>* aIDList );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        * @param aServer Pointer to CScardServer object
+        */
+        CScardReaderRegistry( CScardServer* aServer );
+        
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+    
+        /**
+        * Loads the reader handler dll corresponding to given parameters
+        * @param aGroupID Group ID
+        * @param aReaderID Reader ID
+        * @return Pointer to MScardReaderLauncher object
+        */
+        MScardReaderLauncher* LoadFactoryModuleL( const TGroupID aGroupID,
+                                                  const TReaderID aReaderID );
+
+    private:    // Data
+        // Handle for server. Not owned
+        CScardServer*  iServer; 
+        // Storage to keep track of loaded factories. Owned.
+        CArrayFixFlat<TLauncherStruct>* iLaunchersInUse;
+    };
+
+#endif      // CSCARDREADERREGISTRY_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardResourceRegistry.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,84 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Registry of smart card resources.
+*
+*/
+
+
+
+#ifndef CSCARDRESOURCEREGISTRY_H
+#define CSCARDRESOURCEREGISTRY_H
+
+//  INCLUDES
+#include "ScardDefs.h"
+
+//  FORWARD DECLARATIONS
+class CScardServer;
+class MScardReader;
+
+// CLASS DECLARATION
+
+/**
+*  Manages resources (e.g. cards and service providers).
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardResourceRegistry : public CBase
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        * @param aServer Pointer to CScardServer object
+        */
+        static CScardResourceRegistry* NewL( CScardServer* aServer ); 
+
+        /**
+        * Destructor.
+        */
+        virtual ~CScardResourceRegistry();
+
+    public: // New functions
+
+        /**
+        * Handle card event
+        * @param aEvent Card event
+        * @param aReaderID Reader ID
+        * @return void
+        */
+        void CardEvent( const TScardServiceStatus aEvent, 
+                        const TReaderID aReaderID );
+
+    private:
+        
+        /**
+        * C++ default constructor.
+        */
+        CScardResourceRegistry();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        * @param aServer Pointer to CScardServer object
+        */
+        void ConstructL( CScardServer* aServer );
+ 
+    private:    // Data
+        // Pointer to server object. Not owned.
+        CScardServer* iServer;
+    };
+
+#endif      // CSCARDRESOURCEREGISTRY_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardServer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,227 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  SmartCard server.
+*
+*/
+
+
+
+#ifndef CSCARDSERVER_H
+#define CSCARDSERVER_H
+
+//  INCLUDES
+#include "ScardReaderLauncher.h"
+
+
+//  FORWARD DECLARATIONS
+class CScardAccessControl;
+class CScardAccessControlRegistry;
+class CScardSession;
+class CScardNotifyRegistry;
+class CScardReaderRegistry;
+class CScardResourceRegistry;
+class CScardConnectionRegistry;
+
+
+// CLASS DECLARATION
+
+/**
+*  Server class.
+*  Contains an object container index which provides subsessions with 
+*  object containers.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardServer : public CServer2, public MScardReaderService
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CScardServer* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CScardServer();
+
+    public: // New functions
+
+        /**
+        * Panic server
+        * @param aPanic Panic code 
+        * @return void
+        */
+        static void PanicServer( const TInt aPanic );
+        
+        /**
+        * List the readers, which have not opened yet.
+        * @param aStarted Thread parameter
+        * @return TInt
+        */
+        static TInt ThreadFunction( TAny* aStarted );
+    
+        /**
+        * Opens session.
+        * @param aVersion Version of the server
+        * @return Pointer to created session
+        */
+        virtual CSession2* CScardServer::NewSessionL( 
+            const TVersion& aVersion,
+            const RMessage2& aMessage ) const;
+    
+        /**
+        * Return pointers to registries.
+        * @return Pointer to CScardNotifyRegistry object
+        */
+        inline CScardNotifyRegistry* NotifyRegistry() const;
+
+        /**
+        * Return pointer to reader registry.
+        * @return Pointer to CScardReaderRegistry object
+        */
+        inline CScardReaderRegistry* FactoryRegistry() const;
+
+        /**
+        * Return pointer to an access controller.
+        * @param aReaderID Reader ID
+        * @return Pointer to CScardAccessControl object
+        */
+        inline CScardAccessControl* FindAccessControl(
+            const TReaderID aReaderID ) const;
+
+        /**
+        * Scan through the readers to see if this reader is supported 
+        * (so it is usable).
+        * @param aReaderName Name of the reader
+        * @return ETrue if reader is supported else EFalse
+        */
+        inline const TBool ReaderSupported(
+            const TScardReaderName& aReaderName ) const;
+    
+        /**
+        * Scan the access controllers to see if reader is loaded at the moment.
+        * @param aReaderName Name of the reader
+        * @return ETrue if reader is in use, otherwise EFalse
+        */
+        inline const TBool ReaderInUse( 
+            const TScardReaderName& aReaderName ) const;
+        
+        /**
+        * Scan the database to see if group is loaded at the moment.
+        * @param aGroupName Name of the group
+        * @return ETrue if group is in use, otherwise EFalse
+        */
+        inline const TBool GroupInUse(
+            const TScardReaderName& aGroupName ) const;
+
+        /**
+        * Return pointer to notify observer.
+        * @return Pointer to MScardNotifyObserver object
+        */
+        inline MScardNotifyObserver* NotifyObserver();
+
+        /**
+        * Return pointer to access control registry object.
+        * @return Pointer to CScardAccessControlRegistry object
+        */
+        inline CScardAccessControlRegistry* AccessRegistry() const;
+
+        /**
+        * Return pointer to reader registry object.
+        * @return Pointer to CScardReaderRegistry object
+        */
+        inline CScardReaderRegistry* ReaderRegistry() const;
+
+        /**
+        * Return pointer to connection registry object.
+        * @return Pointer to CScardConnectionRegistry object
+        */
+        inline CScardConnectionRegistry* ConnectionRegistry() const;
+
+        /**
+        * Return pointer to Reader service object
+        * @return Pointer to MScardReaderService object
+        */
+        inline MScardReaderService* ReaderService();
+
+        /**
+        * Scan database to see ID belonging to this name.
+        * @param aFriendlyName DB Name
+        * @return Reader ID for given reader name
+        */
+        inline const TReaderID ReaderID(
+            const TScardReaderName& aFriendlyName ) const;
+
+        /**
+        * Scan the database for the name belonging to this ID.
+        * @param aReaderID Reader ID
+        * @return Name of the given reader ID
+        */
+        inline const TScardReaderName FriendlyName(
+            const TReaderID aReaderID ) const;
+
+        /**
+        * Connect to reader.
+        * @param aSession Pointer to session
+        * @param aMessage Message
+        * @return void
+        */
+        inline void ConnectToReaderL( CScardSession* aSession, 
+                                      const RMessage2& aMessage );
+    
+        /**
+        * If a card is inserted / removed, we need to update the list 
+        * of cards in use.
+        * @param aEvent Card event
+        * @param aReaderID Reader ID
+        * @return void
+        */
+        inline void CardEvent( const TScardServiceStatus aEvent,
+                               const TReaderID aReaderID ); 
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CScardServer();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    private:    // Data
+        // Pointer to connection registry. Owned.
+        CScardConnectionRegistry*    iConnectionRegistry;
+        // Pointer to access control registry. Owned.
+        CScardAccessControlRegistry* iControlRegistry;
+        // Pointer to notify registry. Owned.
+        CScardNotifyRegistry*        iNotifyRegistry;
+        // Pointer to reader registry. Owned.
+        CScardReaderRegistry*        iReaderFactoryRegistry;
+        // Pointer to resource registry. Owned.
+        CScardResourceRegistry*      iResourceRegistry;
+        // Name of the server. Owned.
+        HBufC*                       iName;
+    };
+
+#include "ScardServer.inl"
+
+#endif      // CSCARDSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardServer.inl	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,170 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Inline function for smart card server.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "ScardSession.h"
+#include "ScardNotifyRegistry.h"
+#include "ScardAccessControl.h"
+#include "ScardAccessControlRegistry.h"
+#include "ScardReaderRegistry.h"
+#include "ScardResourceRegistry.h"
+#include "ScardConnectionRegistry.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardServer::NotifyRegistry
+// return pointer to registry
+// -----------------------------------------------------------------------------
+//
+inline CScardNotifyRegistry* CScardServer::NotifyRegistry() const
+    {
+    return iNotifyRegistry;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::FindAccessControl
+// Return the access controller for the reader
+// -----------------------------------------------------------------------------
+//
+inline CScardAccessControl* CScardServer::FindAccessControl(
+    const TReaderID aReaderID ) const
+    {
+    return iControlRegistry->FindAccessController( aReaderID );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::FactoryRegistry
+// Return factory register
+// -----------------------------------------------------------------------------
+//
+inline CScardReaderRegistry* CScardServer::FactoryRegistry() const
+    {
+    return iReaderFactoryRegistry;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::ConnectionRegistry
+// Return pointer to CScardConnectionRegistry
+// -----------------------------------------------------------------------------
+//
+inline CScardConnectionRegistry* CScardServer::ConnectionRegistry() const
+    {
+    return iConnectionRegistry;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::NotifyObserver
+// Return pointer to observer
+// -----------------------------------------------------------------------------
+//
+inline MScardNotifyObserver* CScardServer::NotifyObserver()
+    {
+    return iNotifyRegistry;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::ReaderService
+// Return service pointer
+// -----------------------------------------------------------------------------
+//
+inline MScardReaderService* CScardServer::ReaderService()
+    {
+    return this;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::ReaderID
+// Scan database to see ID belonging to this name
+// -----------------------------------------------------------------------------
+//
+inline const TReaderID CScardServer::ReaderID(
+    const TScardReaderName& aFriendlyName ) const
+    {
+    return iReaderFactoryRegistry->ReaderID( aFriendlyName );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::FriendlyName
+// Scan the database for the name belonging to this ID
+// -----------------------------------------------------------------------------
+//
+inline const TScardReaderName CScardServer::FriendlyName(
+    const TReaderID aReaderID ) const
+    {
+    return iReaderFactoryRegistry->FriendlyName( aReaderID );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::ReaderSupported
+// Scan the database to see if we support this reader type
+// -----------------------------------------------------------------------------
+//
+inline const TBool CScardServer::ReaderSupported(
+    const TScardReaderName& aReaderName ) const
+    {
+    return iReaderFactoryRegistry->IsSupported( aReaderName );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::AccessRegistry
+// Return pointer to CScardAccessControlRegistry
+// -----------------------------------------------------------------------------
+//
+inline CScardAccessControlRegistry* CScardServer::AccessRegistry() const
+    {
+    return iControlRegistry;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::ReaderRegistry
+// Return pointer to server's CScardReaderRegistry
+// -----------------------------------------------------------------------------
+//
+inline CScardReaderRegistry* CScardServer::ReaderRegistry() const
+    {
+    return iReaderFactoryRegistry;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::ConnectToReaderL
+// Connect to reader
+// -----------------------------------------------------------------------------
+//
+inline void CScardServer::ConnectToReaderL(
+    CScardSession* aSession,
+    const RMessage2& aMessage )
+    {
+    iConnectionRegistry->ConnectToReaderL( aSession, aMessage );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::CardEvent
+// Handle card event
+// -----------------------------------------------------------------------------
+//
+inline void CScardServer::CardEvent(
+    const TScardServiceStatus aEvent,
+    const TReaderID aReaderID )
+    {
+    iResourceRegistry->CardEvent( aEvent, aReaderID );
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardServerBase.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions and structures for smart card server.
+*
+*/
+
+
+
+#ifndef CSCARDSERVERBASE_H
+#define CSCARDSERVERBASE_H
+
+// INCLUDE FILES
+#include <e32base.h>
+
+// ENUMERATIONS
+enum TSpecialSessionIDs 
+    {
+    ENoSession      = 0, //-1,
+    EPollSessionID  = -2,
+    EAccessMasterID = -3
+    };
+
+// CONSTANTS
+
+//needed for creating server thread.
+const TUint KDefaultMinHeapSize = 0x1000;
+const TUint KDefaultMaxHeapSize = 0x100000;
+
+const TInt8 KChannel0       = 0;
+const TInt8 KAllChannels    = -1;
+
+const TInt8 KMaxChannels    = 0x04;
+
+const TUint8 KManageChannel = 0x70;
+const TUint8 KOpenChannel   = 0x00;
+const TUint8 KCloseChannel  = 0x80;
+
+const TUint8 KReservation   = 0x01;
+const TUint8 KClosing       = 0x02;
+const TUint8 KConnection    = 0x80;
+
+
+// MACROS
+#define __ASSERT_MEMORY( err ) if ( ( err ) )\
+    User::Panic( _L( "Not enough free memory" ), KScPanicNoMemory )
+
+#endif      // CSCARDSERVERBASE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/inc/ScardSession.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,332 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Session for the Scard server, to a single client-side session.
+*
+*/
+
+
+
+#ifndef CSCARDSESSION_H
+#define CSCARDSESSION_H
+
+//  INCLUDES
+#include "ScardDefs.h"
+#include <f32file.h>    // f32file header needed for loading dlls
+
+//  CONSTANTS  
+const TInt KOpenChannelResponseLength = 3;
+const TInt KApduHeaderLength          = 4;
+
+const TInt KCLA    = 0;    //  class byte
+const TInt KINS    = 1;    //  instruction code
+const TInt KP1     = 2;    //  control parameter 1
+const TInt KP2     = 3;    //  control parameter 2
+const TInt KLcHigh = 4;    //  command length high byte
+const TInt KLcLow  = 5;    //  command length low byte
+
+const TInt8 KNoChannel     = 0;
+const TInt8 KChannelByCard = 1;
+const TInt8 KChannelByCID  = 2;
+
+
+//  FORWARD DECLARATIONS
+class CScardAccessControl;
+class CScardServer;
+class MScardReader;
+class CScardNotifyRegistry;
+
+// CLASS DECLARATION
+
+/**
+*  Session for the Scard server, to a single client-side session
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardSession : public CSession2
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        * @param aServer Pointer to ScardServer object
+        */
+        static CScardSession* NewL( CScardServer* aServer );  
+
+        /**
+        * Destructor.
+        */
+        virtual ~CScardSession();
+    
+    public: // New functions
+
+        /**
+        * Clean up the reader event listeners.
+        * @param aMessage Client message
+        * @return void
+        */
+        void CloseSession( const RMessage2& aMessage );
+
+        /**
+        * Wrapper for the actual ServiceL() (this needed only because of
+        * connector class)
+        * @param aMessageHandle Handle to client message
+        * @return void
+        */
+        virtual void ServiceL( const TMessageHandle& aMessageHandle );
+
+        /**
+        * Asynchronous operation completed
+        * @param aMessageHandle Handle to client message
+        * @param aErrorCode Error code
+        * @return void
+        */
+        virtual void AsynchronousServiceComplete( 
+            const TMessageHandle& aMessageHandle,
+            const TInt aErrorCode );
+    
+        /**
+        * This is here only for derivative class CScardConnector
+        * It implements and needs this function
+        * @param aServiceStatus Service status
+        * @param aATR ATR bytes
+        * @param aReaderID Reader ID from which event comes
+        * @return void
+        */
+        virtual void CardEvent( const TScardServiceStatus aServiceStatus,
+                                const TScardATR& aATR,
+                                const TReaderID& aReaderID );
+
+        /**
+        * A reader has finally been contacted.
+        * @param aReaderID Reader ID
+        * @param aMessage Client essage
+        * @param aErrorCode Error code
+        * @return void
+        */
+        void ConnectionDone( const TReaderID& aReaderID, 
+                             const RMessage2& aMessage,
+                             const TInt aErrorCode );
+    
+        /**
+        * Detach this session from the reader
+        * @return void
+        */
+        void DisconnectFromReader();
+
+    protected:
+   
+        /**
+        * C++ default constructor.
+        */
+        CScardSession();
+    
+    protected:  // Functions from base classes
+        
+        /**
+        * From CSharableSession. Service a request message
+        * @param aMessage Message
+        * @return void
+        */
+        void ServiceL( const RMessage2& aMessage );
+
+    private:
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL( CScardServer* aServer );
+
+        /**
+        * Connect to reader
+        * @param aMessage Message
+        * @return void
+        */
+        void ConnectToReaderL( const RMessage2& aMessage );
+
+        /**
+        * Get reader/card capabilities
+        * @param aMessage Message
+        * @return void
+        */
+        void GetCapabilities( const RMessage2& aMessage );
+
+        /**
+        * Send data to card
+        * @param aMessage Message
+        * @return void
+        */
+        void TransmitToCard( const RMessage2& aMessage );
+    
+        /**
+        * Cancel everything
+        * @return void
+        */
+        void CancelTransmitL();
+
+        /**
+        * Open/close channel, get channel status
+        * @param aMessage Message
+        * @return void
+        */
+        void ManageChannel( const RMessage2& aMessage );
+    
+        /**
+        * Helper function for ManageChannel. Create and send a 
+        * manage channel apdu according to parameters
+        * @param aMessage Message
+        * @param aCommand Command
+        * @param aP2 Control parameter 2
+        * @param aCommandLength Command APDU length
+        * @param aResponseLength Response APDU length
+        * @param aTimeOut Timeout
+        * @param aChannel Channel used to transmit APDU
+        * @return void
+        */
+        void DoCommandAndTransmit( const RMessage2& aMessage,
+                                   const TUint8 aCommand, 
+                                   const TUint8 aP2,
+                                   const TInt8 aCommandLength, 
+                                   const TUint8 aResponseLength,
+                                   const TInt32 aTimeOut,
+                                   const TUint8 aChannel );
+
+        /**
+        * Helper function for ManageChannel. Create and send a 
+        * manage channel apdu according to parameters
+        * @param aMessage Message
+        * @param aCommand Command
+        * @param aP2 Control parameter 2
+        * @param aCommandLength Command APDU length
+        * @param aResponseLength Response APDU length
+        * @param aTimeOut Timeout
+        * @param aChannel Channel used to transmit APDU
+        * @return void
+        */
+        void DoCommandAndTransmitL( const RMessage2& aMessage,
+                                   const TUint8 aCommand, 
+                                   const TUint8 aP2,
+                                   const TInt8 aCommandLength, 
+                                   const TUint8 aResponseLength,
+                                   const TInt32 aTimeOut,
+                                   const TUint8 aChannel );
+
+        /**
+        * Write descriptors to client thread. 8 bit version.
+        * @param aMessage Message
+        * @param aResponseBuffer Response Buffer
+        * @param aPtrIndex Pointer index
+        * @return void
+        */
+        void WriteToClient( const RMessage2& aMessage,
+                            const TDesC8& aResponseBuffer,
+                            const TInt aPtrIndex );
+
+        /**
+        * Read descriptors from client thread. 8 bit version.
+        * @param aMessage Message
+        * @param aBuffer Buffer for data
+        * @param aPointer Pointer to buffer data
+        * @param aPtrIndex Pointer index
+        * @return Symbian or Scard error code
+        */
+        TInt ReadFromClient( const RMessage2& aMessage,
+                                   HBufC8*& aBuffer, 
+                                   TPtr8*& aPointer,
+                                   const TInt aPtrIndex );
+
+        /**
+        * Write descriptors to client thread. 16 bit version.
+        * @param aMessage Message
+        * @param aResponseBuffer
+        * @param aPtrIndex
+        * @return void
+        */
+        void WriteToClient( const RMessage2& aMessage,
+                            const TDesC16& aResponseBuffer,
+                            const TInt aPtrIndex );
+
+        /**
+        * Allocate space for the internal response buffer. The lenght of the
+        * necessary space is deduced from the message.
+        * @param aMessage Message
+        * @param aPtrIndex Pointer index of message.
+        * @return TInt
+        */
+        TInt AllocateResponse( const RMessage2& aMessage,
+                                     const TInt aPtrIndex );
+
+        /**
+        * Allocate space for the internal response buffer. The lenght of the
+        * necessary space is deduced from the message.
+        * @param aDesLen Length of buffer to be allocated.
+        * @return void
+        */
+        void AllocateResponseL( TInt aDesLen );
+
+        /**
+        * Delete all internal buffers
+        * @return void
+        */
+        void DeleteBuffers();
+
+        /**
+        * Return pointer to wanted slot of client message 
+        * @param aMessage Message
+        * @param aPtrIndex Pointer index of message.
+        * @return Pointer to message slot
+        */
+        TAny* MessagePointer( const RMessage2& aMessage, const TInt aPtrIndex );
+        
+        /**
+        * Return length of descriptor in client message 
+        * @param aMessage Message
+        * @param aPtrIndex Pointer index of message.
+        * @param aMaxLength ETrue: get maxlength of descriptor
+        *                   EFalse: get length of descriptor
+        * @return Length of descriptor (MaxLength or just Length)
+        */
+        TInt DesLength( const RMessage2& aMessage,
+                        const TInt aPtrIndex, 
+                        const TBool aMaxLength  );
+
+    private:    // Data
+        // Pointer to owning server. Not owned.
+        CScardServer*         iServer; 
+        //  Pointer to notify registry. Owned by server
+        CScardNotifyRegistry* iNotifyRegistry;
+        //  Reader handler associated with this session
+        MScardReader*         iReader;
+        //  Reader access controller for this session's reader
+        CScardAccessControl*  iAccessCtrl; 
+        //  This is, obviously, the session's ID number
+        TInt                  iSessionID;
+        //  Pointers to command and response parameters. Owned.
+        TPtr8*                iResponse;
+        TPtr8*                iCommand;
+
+        //  Heap pointers containing the buffers. Owned.
+        HBufC8*               iResponseBuffer;
+        HBufC8*               iCommandBuffer;
+
+        // Flag to tell if connected to readed
+        TBool                 iConnectedToReader;
+        
+        // Client thread
+        RThread iClient;
+
+    };
+
+#endif      // CSCARDSESSION_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/Scard.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,97 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Main smard card object
+*
+*/
+
+
+// INCLUDE FILES
+#include    "ScardClsv.h"
+#include    "Scard.h"
+#include    "WimTrace.h"
+
+// CONSTANTS
+const TUint KDefaultMessageSlots = 4;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// RSCard::RScard
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+RScard::RScard()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// RScard::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void RScard::ConstructL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScard::ConstructL|Begin"));
+    TInt error = StartThread();
+    if ( error == KErrNone )    
+        {
+        error = CreateSession( KScardServerName,
+                               Version(),
+                               KDefaultMessageSlots );
+        }
+
+    if ( error )
+        {
+        User::Leave( error );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// RScard::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C RScard* RScard::NewL()
+    {
+    _WIMTRACE(_L("WIM|Scard|RScard::NewL|Begin"));
+    RScard* self = new( ELeave ) RScard;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// Destructor
+EXPORT_C RScard::~RScard()
+    {
+    _WIMTRACE(_L("WIM|Scard|RScard::~CScard|Begin"));
+    TIpcArgs args( TIpcArgs::ENothing );
+    SendReceive( EScardServerCloseSession, args );
+    RHandleBase::Close();
+    }
+
+// -----------------------------------------------------------------------------
+// RScard::Version
+// Returns version of the Scard Server
+// -----------------------------------------------------------------------------
+//
+TVersion RScard::Version() const
+    {
+    _WIMTRACE(_L("WIM|Scard|RScard::Version|Begin"));
+    return ( TVersion( KScardServMajorVersionNumber, 
+        KScardServMinorVersionNumber, KScardServBuildVersionNumber ) );
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardAccessControl.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,775 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This object is the one responsible for trafficing between
+*                the Smart Card reader and the sessions.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardServer.h"
+#include    "ScardReaderRegistry.h"
+#include    "ScardAccessControl.h"
+#include    "ScardAccessControlRegistry.h"
+#include    "ScardCommandTimer.h"
+#include    "ScardConnector.h"
+#include    <c32comm.h>         // Needed for RCommServ in WINS
+#include    "WimTrace.h"
+
+#ifdef _DEBUG // for logging
+#include    "ScardLogs.h"
+#include    <flogger.h> 
+#endif
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// TMessageHandle::TMessageHandle
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+TMessageHandle::TMessageHandle(
+    const RMessage2& aMessage,
+    const TInt aSessionID,
+    const TReaderID aReaderID,
+    const TInt8 aChannel,
+    const TInt8 aAddition)
+    : iMessage( aMessage ),
+      iSessionID( aSessionID ),
+      iReaderID( aReaderID ), 
+      iCancelled( EFalse ),
+      iChannel( aChannel ),
+      iTimer( NULL ), 
+      iAdditionalParameter( aAddition )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// TMessageHandle::TMessageHandle
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+TMessageHandle::TMessageHandle()
+    : iMessage(), 
+      iSessionID( ENoSession ),
+      iReaderID( 0 ),
+      iCancelled( EFalse ), 
+      iChannel( 0 ),
+      iTimer( NULL ),
+      iAdditionalParameter( 0 )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::CScardAccessControl
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardAccessControl::CScardAccessControl(
+    const TReaderID aReaderID, 
+    CScardAccessControlRegistry* aControlRegistry )
+    : CActive( EPriorityNormal ), 
+      iSessionRegistry( NULL ),
+      iReaderActive( EFalse ),
+      iIsCreated( EFalse ),
+      iIsOpen( EFalse ),
+      iNextSessionID( 1 ),
+      iReader( NULL ),
+      iReaderID( aReaderID ),
+      iControlRegistry( aControlRegistry ),
+      iManager( NULL ),
+      iLifeMode( ECanBeDeleted )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::CScardAccessControl|Begin"));
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardAccessControl::ConstructL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::ConstructL|Begin"));
+    iSessionRegistry = new( ELeave ) CArrayFixFlat<TReaderSession>( 1 );
+    iManager = CScardChannelManager::NewL();
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardAccessControl* CScardAccessControl::NewL(
+    const TReaderID aReaderID, 
+    CScardAccessControlRegistry* aControl )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::NewL|Begin"));
+    CScardAccessControl* self = new( ELeave ) CScardAccessControl( aReaderID, 
+        aControl );
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "Access controller created.\n" ) );
+#endif
+    return self;
+    }
+
+    
+// Destructor
+CScardAccessControl::~CScardAccessControl()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::~CScardAccessControl|Begin"));
+    Cancel();
+
+    if ( iIsCreated )
+        {
+        DetachSessionFromReader( EAccessMasterID );
+        }
+    if ( iControlRegistry )
+        {
+        iControlRegistry->ControllerRetired( this );
+        }
+    delete iSessionRegistry;
+    delete iManager;
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "Access controller destroyed.\n" ) );
+#endif
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::InitiateCommunication
+// Set the reader as active. Prevents polling and other sessions 
+// from using the reader. Returns the request status of this object.
+// -----------------------------------------------------------------------------
+//
+TRequestStatus& CScardAccessControl::InitiateCommunication(
+    const TInt aSessionID,
+    const RMessage2& aMessage, 
+    const TInt32 aTimeOut,
+    const TInt8 aChannel,
+    const TUint8 aAdditionalParameter )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::InitiateCommunication|Begin"));
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CScardAccessControl::InitiateCommunication session: %d, channel:\
+        %d, reader: %d\n" ), aSessionID, aChannel, iReaderID );
+#endif
+    iReaderActive = ETrue;
+
+    TMessageHandle handle( aMessage, aSessionID, iReaderID, aChannel, 
+        aAdditionalParameter );
+    if ( aTimeOut )
+        {
+#ifdef _DEBUG    
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardAccessControl::InitiateCommunication create command\
+            timer\n" ) );
+#endif
+        TRAPD( err, 
+            handle.iTimer = CScardCommandTimer::NewL( aTimeOut, this ) );
+        if ( err )
+            {
+            return iStatus;
+            }
+        handle.iTimer->StartTiming();
+        }
+
+    TRAPD( err, iManager->PushMessageToTopL( handle ) );
+    if ( !err )
+        {
+        SetActive();
+        }
+    iStatus = err;
+    _WIMTRACE2(_L("WIM|Scard|CScardAccessControl::InitiateCommunication|End|iStatus=%d"), err);
+    return iStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::ReaderIsReady
+// Ask if the reader is available to use for aSessionID.
+// -----------------------------------------------------------------------------
+//
+TBool CScardAccessControl::ReaderIsReady(
+    const TInt aSessionID, 
+    const TInt8 aChannel ) const 
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::ReaderIsReady|Begin"));
+    TInt res( 0 );
+
+    TRAPD( err, res = iManager->ChannelReservedL( aChannel ) );
+    if ( err )
+        {
+        return EFalse;
+        }
+    if ( res )
+        {
+        if ( res != aSessionID && aSessionID != EAccessMasterID )
+            {
+#ifdef _DEBUG    
+            RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardAccessControl::ReaderIsReady: Channel reserved by\
+            another session.\n" ) );
+#endif
+            return EFalse;
+            }
+        }
+    
+    if ( iReaderActive ) 
+        {
+#ifdef _DEBUG    
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardAccessControl::ReaderIsReady: Reader active.\n" ) );
+#endif
+        return EFalse;
+        }
+    else
+        {
+        return ETrue;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::FreeChannelL
+// Free current reservation (if this session has a reservation)
+// If there are messages in the stack, service them.
+// -----------------------------------------------------------------------------
+//
+void CScardAccessControl::FreeChannelL(
+    const TInt aSessionID, 
+    const TInt8 aChannel )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::FreeChannelL|Begin"));
+    if ( aChannel == KAllChannels )
+        {
+        iManager->FreeChannels( aSessionID );
+        }
+    else
+        {
+        iManager->FreeChannelL( aChannel, aSessionID );
+        }
+
+    if ( !iReaderActive )
+        {
+        HandleNextMessageL( iManager->NextMessageFromFree( aChannel ) );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::RunL
+// Handle completed reader messages by finding the caller, and calling 
+// the complete function. Also take the next message from the stack (if 
+// present) and start handling it.
+// -----------------------------------------------------------------------------
+//
+void CScardAccessControl::RunL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::RunL|Begin"));
+#ifdef _DEBUG        
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+        EFileLoggingModeAppend, 
+        _L( "CScardAccessControl::RunL\n" ) );
+#endif
+    iLifeMode = ECanNotDelete;
+
+    //  reader has finished, mark it as inactive
+    iReaderActive = EFalse;
+    
+    //  Get the message that was serviced, and the session that made the 
+    //  request
+    TMessageHandle msgHandle = iManager->MessageFromTop();
+
+    //  Controller needs to know if a connection has been successful
+    if ( msgHandle.iAdditionalParameter == KOpenReader ) 
+        {
+        // If connection was succesful, ConnectionDone() is called from
+        // notifier. Otherwise, call it from here.
+        if ( iStatus == KErrNone )
+            {
+            iIsOpen = ETrue;
+            }
+        else 
+            {
+            iControlRegistry->Server()->ConnectionRegistry()->
+                Connection( 0 ).iConnector->ConnectionDone( 
+                msgHandle.iReaderID, iStatus.Int() );
+            }
+        }
+
+    //  Handle result in appropriate session
+    //  In case the operation was cancelled, continue from the next operation
+    //  w/o completing the last one.
+    //  In case of connecting to reader, ConnectionDone() takes care of 
+    //  completing the message. 
+    if ( !msgHandle.iCancelled &&
+        msgHandle.iAdditionalParameter != KOpenReader )
+        {
+        CScardSession* session = SessionBase( msgHandle.iSessionID );
+        if ( !session )
+            {
+            User::Panic( _L( "Message stack fault" ), 
+                KScServerPanicInternalError );
+            }
+#ifdef _DEBUG    
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardAccessControl::RunL: Message %x completed with status\
+            %d.\n" ), msgHandle.iAdditionalParameter, iStatus.Int() );
+#endif
+        session->AsynchronousServiceComplete( msgHandle, iStatus.Int() );
+        }
+
+    //  The session may have indicated that it's about time for this 
+    //  object to destroy itself
+    if ( iLifeMode == EDestroyASAP )
+        {
+        delete this;
+        return;
+        }
+
+    iLifeMode = ECanBeDeleted;
+
+    //  Check for queued messages. 
+    HandleNextMessageL( iManager->NextMessageL() );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::DoCancel
+// Instruct the reader to cancel
+// -----------------------------------------------------------------------------
+//
+void CScardAccessControl::DoCancel()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::DoCancel|Begin"));
+    if ( iReader )
+        {
+#ifdef _DEBUG    
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardAccessControl::DoCancel: Canceling transmissions.\n" ) );
+#endif
+        TRAPD( err, CancelTransmissionsL( EAccessMasterID ) );
+        
+        if ( err != KErrNone )
+            {
+            // Do nothing
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::QueueExecution
+// Queue the execution of a command until it can be serviced
+// -----------------------------------------------------------------------------
+//
+void CScardAccessControl::QueueExecution(
+    const RMessage2& aMessage, 
+    const TInt aSessionID,
+    const TInt32 aTimeOut, 
+    const TInt8 aChannel, 
+    const TInt8 aParameter )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::QueueExecution|Begin"));
+    TMessageHandle tmp( aMessage, aSessionID, iReaderID, aChannel, aParameter );
+    TInt err;
+    if ( aTimeOut )
+        {
+        TRAP( err, tmp.iTimer = CScardCommandTimer::NewL( aTimeOut, this ) );
+        if ( err )
+            {
+            tmp.iMessage.Complete( err );
+            }
+        tmp.iTimer->StartTiming();
+        }
+
+    TRAP( err, iManager->PushMessageToBottomL( tmp ) );
+    if ( err )
+        {
+        tmp.iMessage.Complete( err );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::QueueChannelOperation
+// Queue channel operation
+// -----------------------------------------------------------------------------
+//
+void CScardAccessControl::QueueChannelOperation(
+    const RMessage2& aMessage, 
+    const TInt aSessionID, 
+    const TInt32 aTimeOut, 
+    const TInt8 aChannel )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::QueueChannelOperation|Begin"));
+    TMessageHandle tmp( aMessage, aSessionID, iReaderID, aChannel,
+        KReservation );
+    if ( aTimeOut )
+        {
+        TRAPD( err, tmp.iTimer = CScardCommandTimer::NewL( aTimeOut, this ) );
+        if ( err )
+            {
+            tmp.iMessage.Complete( err );
+            }
+        tmp.iTimer->StartTiming();
+        }
+
+    TRAPD( err, iManager->PushMessageToBottomL( tmp ) );
+    if ( err )
+        {
+        tmp.iMessage.Complete( err );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::IsAttached
+// Is this session attached to the reader yet?
+// -----------------------------------------------------------------------------
+//
+TBool CScardAccessControl::IsAttached( CScardSession* aSession ) const
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::IsAttached|Begin"));
+    TInt sessionCount = iSessionRegistry->Count();
+    for ( TInt i( 0 ); i < sessionCount; i++ )
+        {
+        if ( (*iSessionRegistry)[i].SessionBase == aSession )
+            {
+            return ETrue;
+            }
+        }
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::SessionBase
+// Returns CScardSession* belonging to this session id
+// -----------------------------------------------------------------------------
+//
+CScardSession* CScardAccessControl::SessionBase( const TInt aSessionID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::SessionBase|Begin"));
+    TInt sessionCount = iSessionRegistry->Count();
+    for ( TInt i( 0 ); i < sessionCount; i++ )
+        {
+        if ( (*iSessionRegistry)[i].SessionID == aSessionID )
+            {
+            return (*iSessionRegistry)[i].SessionBase;
+            }
+        }
+    return NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::CardEvent
+// Handle card event
+// -----------------------------------------------------------------------------
+//
+void CScardAccessControl::CardEvent(
+    const TScardServiceStatus aEvent, 
+    const TScardATR& aATR )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::CardEvent|Begin"));
+
+    if ( aATR.Length() )
+        {
+        iATR = aATR;
+        }
+
+    if ( aEvent == EScardRemoved )
+        {
+        iManager->CardRemoved();
+        }
+
+    TInt sessionCount = iSessionRegistry->Count();
+
+    for ( TInt index( 0 ); index < sessionCount ; index++ )
+        {
+        iSessionRegistry->At( index ).SessionBase->CardEvent( aEvent, aATR, 
+            iReaderID );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::CancelTransmissionsL
+// Cancel Transmissions
+// -----------------------------------------------------------------------------
+//
+void CScardAccessControl::CancelTransmissionsL( const TInt aSessionID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::CancelTransmissions|Begin"));
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+        EFileLoggingModeAppend, 
+        _L( "CScardAccessControl::CancelTransmissions: Purge messages from \
+        stack.\n" ) );
+#endif
+    //  First purge the messages from the stack
+    iManager->CancelAll( aSessionID );
+
+    //  If the message currently served is for the calling session, cancel it 
+    //  from the reader also and put it back
+    TMessageHandle tmp = iManager->MessageFromTop();
+    if ( tmp.iSessionID == aSessionID || aSessionID == EAccessMasterID )
+        {
+#ifdef _DEBUG    
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+            EFileLoggingModeAppend, 
+            _L( "CScardAccessControl::CancelTransmissions: Cancel message from\
+            reader.\n" ) );
+#endif
+     
+        iReader->CancelTransmit();
+        
+        if ( aSessionID == EAccessMasterID )
+            {
+            // reader not active anymore
+            iReaderActive = EFalse;
+            }    
+        }
+
+    if ( tmp.iSessionID != ENoSession && aSessionID != EAccessMasterID )
+        {
+        iManager->PushMessageToTopL( tmp );
+        }
+
+    //  Finish by clearing any reservations the cancelling session has done
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+        EFileLoggingModeAppend, 
+        _L( "CScardAccessControl::CancelTransmissions: Free reserved\
+        channels.\n" ) );
+#endif
+    iManager->FreeChannels( aSessionID );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::DetachSessionFromReader
+// Detach session from reader
+// -----------------------------------------------------------------------------
+//
+void CScardAccessControl::DetachSessionFromReader( const TInt aSessionID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::DetachSessionFromReader|Begin"));
+    if ( aSessionID == EAccessMasterID )
+        {
+#ifdef _DEBUG    
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardAccessControl::DetachSessionFromReader: Detach all\
+            sessions...\n" ) );
+#endif
+
+        //  detach all sessions and delete all their messages
+        DequeueOperations( EAccessMasterID );
+        while ( iSessionRegistry->Count() )
+            {
+            iSessionRegistry->Delete( 0 );
+            }
+
+        //  all sessions have been detached, so kill the reader (if it's around)
+        if ( iReader )
+            {
+            iReader->Close();
+            }
+        iControlRegistry->Server()->FactoryRegistry()->CloseReader(
+                iReaderID );
+        iReader = NULL;
+        iIsOpen = EFalse;
+        iIsCreated = EFalse;
+        }
+    
+    else
+        {
+#ifdef _DEBUG    
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardAccessControl::DetachSessionFromReader: Detach session\
+            %d...\n" ), aSessionID );
+#endif
+        TInt i( 0 );
+        if ( !IsAttached( SessionBase( aSessionID ) ) ) 
+            {
+#ifdef _DEBUG    
+            RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "CScardAccessControl::DetachSessionFromReader: Session not\
+                attached!!!\n" ), aSessionID );
+#endif
+            return;
+            }
+        
+        //  locate the session to be detached
+        for ( ; (*iSessionRegistry)[i].SessionID != aSessionID; i++ )
+            {;}
+        
+        iSessionRegistry->Delete( i );
+
+        //  pop out all messages queued to it
+        DequeueOperations( aSessionID );
+
+        //  Free any possible transactions with the smart card
+        TRAPD( error, FreeChannelL( aSessionID, KAllChannels ) );
+
+        if ( error != KErrNone )
+            {
+            // Do nothing
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::DequeueOperations
+// Cancel all pending messages
+// -----------------------------------------------------------------------------
+//
+void CScardAccessControl::DequeueOperations( const TInt aSessionID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::DequeueOperations|Begin"));
+    iManager->CancelAll( aSessionID );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::InitialiseReader
+// Initialise reader handler
+// -----------------------------------------------------------------------------
+//
+TBool CScardAccessControl::InitialiseReader(
+    const TInt aSessionID, 
+    const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::InitialiseReader|Begin"));
+    if ( iIsOpen )
+        {
+#ifdef _DEBUG    
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardAccessControl::InitialiseReader: Reader already\
+            open.\n" ) );
+#endif
+        return ETrue;
+        }
+
+    if ( ReaderIsReady( EAccessMasterID, 0 ) )
+        {
+        InitiateCommunication( aSessionID, aMessage, static_cast< TInt32>( 0 ),
+            0, KOpenReader );
+#if defined (__WINS__)
+        RCommServ commServer;
+        TInt error = commServer.Connect();
+        if ( error == KErrNone)
+            {
+            commServer.Close();         	
+            }
+#endif
+#ifdef _DEBUG    
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardAccessControl::InitialiseReader: Opening Reader\n" ) );
+#endif
+        iReader->Open( iStatus );
+        }
+#ifdef _DEBUG    
+    else 
+        {
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+          EFileLoggingModeAppend, 
+          _L( "CScardAccessControl::InitialiseReader: Reader not ready!.\n" ) );
+        }
+#endif
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControl::AttachSessionToReaderL
+// Attach session to reader
+// -----------------------------------------------------------------------------
+//
+MScardReader* CScardAccessControl::AttachSessionToReaderL(
+    CScardSession* aSession, 
+    TInt &aSessionID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControl::AttachSessionToReaderL|Begin"));
+    TReaderSession newSession;
+    newSession.SessionID = iNextSessionID;
+    newSession.SessionBase = aSession;
+
+    TInt readerCreationError( 0 );  
+
+    //  If no other session has connected yet or the reader launcher has been
+    //  unable to create the reader object, go here...
+    if ( !iIsCreated )
+        {
+#ifdef _DEBUG    
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardAccessControl::AttachSessionToReader: reader not\
+            created!\n" ) );
+#endif
+        //  ... and ask the launcher to create the reader object
+        CScardReaderRegistry* reg = 
+            iControlRegistry->Server()->FactoryRegistry();
+        TRAP( readerCreationError, iReader = reg->LoadReaderL( iReaderID ) );
+        }
+    
+#ifdef _DEBUG        
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+        EFileLoggingModeAppend, 
+        _L( "CScardAccessControl::AttachSessionToReader: session ID %d\n" ),
+        newSession.SessionID );
+#endif
+
+    iSessionRegistry->AppendL( newSession );
+    
+    // Place session ID and increment the next ID
+    aSessionID = iNextSessionID++;
+
+    //  All sessions are immediately on channel 0
+    iManager->AddSessionToChannelL( KChannel0, aSessionID );
+
+    if ( !readerCreationError && iReader )
+        {
+        iIsCreated = ETrue;
+        return iReader;
+        }
+    else
+        {
+#ifdef _DEBUG    
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardAccessControl::AttachSessionToReader: reader creation\
+            failed!!!\n" ) );
+#endif
+        iIsCreated = EFalse;
+        User::Leave( readerCreationError );
+        return NULL;
+        }
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardAccessControlRegistry.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,254 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Handles the creation and destruction of individual access 
+*                controllers
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardAccessControlRegistry.h"
+#include    "ScardAccessControl.h"
+#include    "WimTrace.h"
+
+#ifdef _DEBUG // for logging
+#include    "ScardLogs.h"
+#include    <flogger.h> 
+#endif
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardAccessControlRegistry::CScardAccessControlRegistry
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardAccessControlRegistry::CScardAccessControlRegistry()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControlRegistry::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardAccessControlRegistry::ConstructL( CScardServer* aServer )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControlRegistry::ConstructL|Begin"));
+    iAccessControllers = new( ELeave ) CArrayFixFlat<CScardAccessControl*>( 1 );
+    iServer = aServer;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControlRegistry::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardAccessControlRegistry* CScardAccessControlRegistry::NewL(
+    CScardServer* aServer )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControlRegistry::NewL|Begin"));
+    CScardAccessControlRegistry* self = 
+        new( ELeave ) CScardAccessControlRegistry;
+    
+    CleanupStack::PushL( self );
+    self->ConstructL( aServer );
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CScardAccessControlRegistry::~CScardAccessControlRegistry()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControlRegistry::~CScardAccessControlRegistry|Begin"));
+    while ( iAccessControllers->Count() )
+        {
+        RemoveAccessController( 0 );
+        }
+    delete iAccessControllers;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CScardAccessControlRegistry::ControllerRetired
+// An access controller has been disconnected
+// -----------------------------------------------------------------------------
+//
+void CScardAccessControlRegistry::ControllerRetired(
+    CScardAccessControl* aControl )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControlRegistry::ControllerRetired|Begin"));
+    for ( TInt i( 0 ); i < iAccessControllers->Count(); i++ )
+        {
+        if ( iAccessControllers->At( i ) == aControl )
+            {
+            iAccessControllers->Delete( i );
+            return;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControlRegistry::RemoveAccessController
+// Remove Access controller from registry
+// -----------------------------------------------------------------------------
+//
+void CScardAccessControlRegistry::RemoveAccessController(
+    const TInt aIndex )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControlRegistry::RemoveAccessController|Begin"));
+    __ASSERT_ALWAYS( aIndex < iAccessControllers->Count(), 
+        User::Panic( _L( "Registry corruption" ), 
+            KScServerPanicInternalError ) );
+
+    //  we allocated the controller, so we must also delete it..
+    delete ( (*iAccessControllers)[aIndex] );
+    
+    //  ...and remove it from the registy as well
+    //Check first it is not removed yet...
+    if ( aIndex < iAccessControllers->Count() )
+        {
+        iAccessControllers->Delete( aIndex );
+        }
+    return;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControlRegistry::Reader
+// Get reader object by Reader ID
+// -----------------------------------------------------------------------------
+//
+MScardReader* CScardAccessControlRegistry::Reader(
+    const TReaderID aReaderID) const
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControlRegistry::Reader|Begin"));
+    for ( TInt i( 0 ); i < iAccessControllers->Count(); i++ )
+        {
+        if ( (*iAccessControllers)[i]->ReaderID() == aReaderID )
+            {
+            return (*iAccessControllers)[i]->Reader();
+            }
+        }
+    return NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControlRegistry::FindAccessController
+// Returns the access controller for given reader. 
+// Returns NULL if access controlled is not created
+// -----------------------------------------------------------------------------
+//
+CScardAccessControl* CScardAccessControlRegistry::FindAccessController(
+    const TReaderID aReaderID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControlRegistry::FindAccessController|Begin"));
+    for ( TInt i( 0 ); i < iAccessControllers->Count(); i++ )
+        {
+        if ( (*iAccessControllers)[i]->ReaderID() == aReaderID )
+            {
+            return (*iAccessControllers)[i];
+            }
+        }
+    return NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControlRegistry::ReaderHandlerLoaded
+// Check if this reader has a controller loaded
+// -----------------------------------------------------------------------------
+//
+TBool CScardAccessControlRegistry::ReaderHandlerLoaded(
+    const TReaderID aReaderID ) const 
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControlRegistry::ReaderHandlerLoaded|Begin"));
+    for ( TInt i( 0 ); i < iAccessControllers->Count(); i++ )
+        {
+        if ( (*iAccessControllers)[i]->ReaderID() == aReaderID )
+            {
+            return ETrue;
+            }
+        }
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControlRegistry::Server
+// Returns the server
+// -----------------------------------------------------------------------------
+//
+CScardServer* CScardAccessControlRegistry::Server()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControlRegistry::Server|Begin"));
+    return iServer;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardAccessControlRegistry::AccessController
+// Creates access controller if necessary
+// -----------------------------------------------------------------------------
+//
+CScardAccessControl* CScardAccessControlRegistry::AccessController(
+    const TReaderID aReaderID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardAccessControlRegistry::AccessController|Begin"));
+#ifdef _DEBUG
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CScardAccessControlRegistry::GetAccessController entered.\n" ) );
+#endif
+    //  If a controller is already made for the reader, just return it
+    CScardAccessControl* ctrl = FindAccessController( aReaderID );
+    if ( ctrl )
+        {
+#ifdef _DEBUG
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardAccessControlRegistry::GetAccessController access\
+            controller found.\n" ) );
+#endif
+        return ctrl;
+        }
+        
+    //  If we're here, the controller has not yet been made, so create it
+#ifdef _DEBUG
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CScardAccessControlRegistry::GetAccessController create new access\
+        controller.\n" ) );
+#endif
+    TRAPD( err,  ctrl = CScardAccessControl::NewL( aReaderID, this ) );
+    if ( !ctrl || err )
+        {
+#ifdef _DEBUG
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardAccessControlRegistry::GetAccessController access\
+            controller creation failed: %d.\n" ), err );
+#endif
+        return NULL;
+        }
+
+    TRAP( err, iAccessControllers->AppendL( ctrl ) );
+    if ( err )
+        {
+        return NULL;
+        }
+
+    return ctrl;
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardChannelManager.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,513 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Handles individual channels on a singular SC (which equals one
+*                Smart Card reader handler). Can be queried for information 
+*                about channels, controls traffic etc.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardAccessControl.h"
+#include    "ScardBase.h"
+#include    "ScardChannelManager.h"
+#include    "ScardMessageStack.h"
+#include    "WimTrace.h"
+
+
+// MACROS
+//  Assert that a session is on a channel  
+#define __ASSERT_SESSION( a, b ) if ( !SessionIsOnChannel( (a), (b) ) )\
+    User::Leave( KScServerErrIllegalChannel );
+//  Assert that the channel number is legal, or leave
+#define __ASSERT_CHANNEL_LEAVE( a ) if ( (a) < 0 || (a) > KMaxChannels - 1 )\
+    User::Leave( KScServerErrIllegalChannel )
+
+//  Assert that the channel number is legal, or return false
+#define __ASSERT_CHANNEL_FALSE( a ) if ( (a) < 0 || (a) > KMaxChannels - 1 )\
+    return EFalse
+
+// LOCAL FUNCTION PROTOTYPES
+TUint8 pow2( const TInt aPower );
+
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// pow2
+// Returns: 2 powered to given value
+// -----------------------------------------------------------------------------
+//
+
+TUint8 pow2( const TInt aPower )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::pow2|Begin"));
+    TUint8 result = 1;
+    for ( TInt i = 0; i < aPower; i++ )
+        {
+        result *= 2;
+        }
+    return result;
+    }
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::CScardChannelManager
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardChannelManager::CScardChannelManager()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::CScardChannelManager|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardChannelManager::ConstructL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::ConstructL|Begin"));
+    iChannels = new( ELeave ) CArrayPtrFlat<CArrayFixFlat<TInt> >( 1 );
+
+    //  Channel 0 is always open
+    CArrayFixFlat<TInt>* zeroChannel = new( ELeave ) CArrayFixFlat<TInt>( 1 );
+    CleanupStack::PushL( zeroChannel );
+    iChannels->AppendL( zeroChannel );
+
+    // others are opened as the need arises
+    iChannels->AppendL( static_cast< CArrayFixFlat<TInt>* >( NULL ) );
+    iChannels->AppendL( static_cast< CArrayFixFlat<TInt>* >( NULL ) );
+    iChannels->AppendL( static_cast< CArrayFixFlat<TInt>* >( NULL ) );
+
+    iMessageStack = CScardMessageStack::NewL();
+    CleanupStack::Pop( zeroChannel );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardChannelManager* CScardChannelManager::NewL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::NewL|Begin"));
+    CScardChannelManager* self = new( ELeave ) CScardChannelManager;
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CScardChannelManager::~CScardChannelManager()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::~CScardChannelManager|Begin"));
+    if ( iChannels )
+        {
+        iChannels->ResetAndDestroy();
+        }
+    delete iChannels;
+    delete iMessageStack;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::ChannelStatus
+// Give available channels
+// Returns two-byte parameter telling:
+// b0 - Channel 0 open (should always be set)
+// b1 - Channel 0 reserved
+// b2 - Channel 1 open
+// b3 - Channel 1 reserved
+// ...
+// b7 - Channel 3 open
+// b8 - Channel 3 reserved
+//                
+// b9-b15 Maximum number of channels available (at the moment always 4)
+//
+// -----------------------------------------------------------------------------
+//
+TUint16 CScardChannelManager::ChannelStatus()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::ChannelStatus|Begin"));
+    TUint16 free( 0 );
+    free = static_cast< TUint16 >( 0x04 << 8 ); // 4 channels available
+
+    //  Get the status for each individual channel, and set the according bits
+    for ( TInt i = 0; i < KMaxChannels; i++ )
+        {
+        if ( iChannels->At( i ) )    
+            {
+            free |= pow2( 2 * i );
+            }
+        if ( iReserverID[i] )
+            {
+            free |= pow2( 2 * i + 1 );
+            }
+        }
+    return free;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::SessionIsOnChannel
+// Does the session have permission to the channel.
+// -----------------------------------------------------------------------------
+//
+TBool CScardChannelManager::SessionIsOnChannel(
+    const TInt8 aChannel, 
+    const TInt aSessionID ) const
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::SessionIsOnChannel|Begin"));
+    __ASSERT_CHANNEL_FALSE( aChannel );
+    if ( iChannels->At( aChannel ) )
+        {
+        TInt count = iChannels->At( aChannel )->Count();
+        for ( TInt j( 0 ); j < count; j++ )
+            {
+            if ( iChannels->At( aChannel )->At( j ) == aSessionID )
+                {
+                _WIMTRACE(_L("WIM|Scard|CScardChannelManager::SessionIsOnChannel|Permission granted"));
+                return ETrue;
+                }
+            }
+        }
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::SessionIsOnChannel|Permission denied"));
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::AddSessionToChannelL
+// Give the session the right to use the channel
+// -----------------------------------------------------------------------------
+//
+TBool CScardChannelManager::AddSessionToChannelL(
+    const TInt8 aChannel, 
+    const TInt aSessionID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::AddSessionToChannelL|Begin"));
+    __ASSERT_CHANNEL_FALSE( aChannel );
+    if ( !SessionIsOnChannel( aChannel, aSessionID ) )
+        {
+        // if the channel is not yet opened...
+        if ( !iChannels->At( aChannel ) )
+            {
+            CArrayFixFlat<TInt>* channel = NULL;
+            channel = new( ELeave ) CArrayFixFlat<TInt>( 1 );
+            iChannels->At( aChannel ) = channel;
+            }
+        iChannels->At( aChannel )->AppendL( aSessionID );
+        }
+    return ETrue;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::RemoveSessionL
+// Remove session entries from the channel.
+// -----------------------------------------------------------------------------
+//
+TBool CScardChannelManager::RemoveSessionL(
+    const TInt8 aChannel, 
+    const TInt aSessionID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::RemoveSessionL|Begin"));
+    __ASSERT_CHANNEL_LEAVE( aChannel );
+    if ( SessionIsOnChannel( aChannel, aSessionID ) )
+        {
+        for ( TInt i( 0 ); i < iChannels->At( aChannel )->Count(); i++ )
+            {
+            // remove the indivídual from the channel
+            if ( iChannels->At( aChannel )->At( i ) == aSessionID )
+                {
+                iChannels->At( aChannel )->Delete( i );
+                i = iChannels->At( aChannel )->Count(); // Stop loop
+                }
+            }
+        //  if the channel is empty (except channel 0), delete it
+        if ( aChannel != 0 && !iChannels->At( aChannel )->Count() )
+            {
+            delete iChannels->At( aChannel );
+            iChannels->At( aChannel ) = NULL;
+            return EFalse;
+            }
+        }
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::PushMessageToBottomL
+// Push message to bottom of message stack
+// -----------------------------------------------------------------------------
+//
+void CScardChannelManager::PushMessageToBottomL(
+    const TMessageHandle& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::PushMessageToBottomL|Begin"));
+    __ASSERT_CHANNEL_LEAVE( aMessage.iChannel );
+    __ASSERT_SESSION( aMessage.iChannel, aMessage.iSessionID );
+    __ASSERT_MEMORY( iMessageStack->PushToBottom( aMessage ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::PushMessageToTopL
+// Push message to top of message stack
+// -----------------------------------------------------------------------------
+//
+void CScardChannelManager::PushMessageToTopL(
+    const TMessageHandle& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::PushMessageToTopL|Begin"));
+    __ASSERT_CHANNEL_LEAVE( aMessage.iChannel );
+    __ASSERT_SESSION( aMessage.iChannel, aMessage.iSessionID );
+    __ASSERT_MEMORY( iMessageStack->PushToTop( aMessage ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::NextMessageL
+// Get the next available message from the stack (preserving
+// the order of other messages)
+// -----------------------------------------------------------------------------
+//
+const TMessageHandle CScardChannelManager::NextMessageL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::NextMessage|Begin"));
+    TInt count = iMessageStack->Count();
+    TInt index( 0 );
+    while ( index < count )
+        {
+        TMessageHandle tmp = iMessageStack->FromPositionL( index );
+
+        // If the channel is reserved (for someone else), 
+        // put message back to wait
+        if ( iReserverID[tmp.iChannel] && iReserverID[tmp.iChannel] != 
+            tmp.iSessionID )
+            {
+            iMessageStack->PushToPositionL( index, tmp );
+            index++;
+            }
+        else
+            {
+            return tmp;
+            }
+        }
+    TMessageHandle noMessage;
+    return noMessage;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::MessageFromTop
+// Get message from top of message stack
+// -----------------------------------------------------------------------------
+//
+const TMessageHandle CScardChannelManager::MessageFromTop()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::MessageFromTop|Begin"));
+    return iMessageStack->FromTop();
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::CancelAll
+// Cancel all messages from the stack that match the criteria
+// -----------------------------------------------------------------------------
+//
+void CScardChannelManager::CancelAll( const TInt aSessionID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::CancelAll|Begin"));
+    if ( aSessionID == EAccessMasterID )
+        {
+        iMessageStack->CancelAll( KScErrCancelled );
+        }
+    else
+        {
+        iMessageStack->CancelAll( aSessionID, KScErrCancelled );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::ChannelReservedL
+// Return reserver session of the channel
+// -----------------------------------------------------------------------------
+//
+TInt CScardChannelManager::ChannelReservedL(
+    const TInt8 aChannel ) const
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::ChannelReservedL|Begin"));
+    __ASSERT_CHANNEL_LEAVE( aChannel );
+    return iReserverID[aChannel];
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::FreeChannelL
+// Free channel
+// -----------------------------------------------------------------------------
+//
+void CScardChannelManager::FreeChannelL(
+    const TInt8 aChannel, 
+    const TInt aSessionID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::FreeChannelL|Begin"));
+    __ASSERT_CHANNEL_LEAVE( aChannel );
+    if ( iReserverID[aChannel] == aSessionID )
+        {
+        iReserverID[aChannel] = ENoSession;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::FreeChannels
+// Free all channels this session has reserved
+// -----------------------------------------------------------------------------
+//
+void CScardChannelManager::FreeChannels( const TInt aSessionID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::FreeChannels|Begin"));
+    for ( TInt i( 0 ); i < KMaxChannels; i++ )
+        {
+        if ( iReserverID[i] == aSessionID )
+            {
+            iReserverID[i] = 0;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::ChannelOpenedYet
+// Return ETrue if channel is allready opened, otherwise return EFalse
+// -----------------------------------------------------------------------------
+//
+TBool CScardChannelManager::ChannelOpenedYet( const TInt8 aChannel )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::ChannelOpenedYet|Begin"));
+    __ASSERT_CHANNEL_LEAVE( aChannel );
+    if ( iChannels->At( aChannel ) )
+        {
+        _WIMTRACE(_L("WIM|Scard|CScardChannelManager::ChannelOpenedYet|True"));
+        return ETrue;
+        }
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::ChannelOpenedYet|False"));
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::UnreservedLogicalChannel
+// First channel w/o a reservation
+// -----------------------------------------------------------------------------
+//
+TInt8 CScardChannelManager::UnreservedLogicalChannel() const
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::UnreservedLogicalChannel|Begin"));
+    for ( TInt8 i( 0 ); i < KMaxChannels; i++ )
+        {
+        if ( !iReserverID[i] )
+            {
+            return i;
+            }
+        }
+    return -1;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::NextMessageFromFree
+// Return next message from free 
+// -----------------------------------------------------------------------------
+//
+const TMessageHandle CScardChannelManager::NextMessageFromFree(
+    const TInt8 aChannel)
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::NextMessageFromFree|Begin"));
+    TMessageHandle tmp = iMessageStack->NextReservation( aChannel );
+    if ( tmp.iSessionID != ENoSession )
+        {
+        return tmp;
+        }
+    
+    TMessageHandle nextMessage;
+
+    TRAPD( err, nextMessage = NextMessageL() );
+    
+    if ( err != KErrNone )
+        {
+        TMessageHandle noMessage;
+        return noMessage;
+        }
+    else
+        {
+        return nextMessage;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::ValidateChannelL
+// Channel is legal & open for this session
+// -----------------------------------------------------------------------------
+//
+void CScardChannelManager::ValidateChannelL(
+    const TInt8 aChannel, 
+    const TInt aSessionID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::ValidateChannelL|Begin"));
+    __ASSERT_CHANNEL_LEAVE( aChannel );
+    if ( iChannels->At( aChannel ) )
+        {
+        for ( TInt j( 0 ); j < iChannels->At( aChannel )->Count(); j++ )
+            {
+            if ( iChannels->At( aChannel )->At( j ) == aSessionID )
+                {
+                return;
+                }
+            }
+        }
+    _WIMTRACE(_L("WIM|Scard|CScardSession::ValidateChannelL|Leave"));
+    User::Leave( KScErrNotFound );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::CardRemoved
+// Card removed. Clear all card-spesific data & transmissions
+// -----------------------------------------------------------------------------
+//
+void CScardChannelManager::CardRemoved()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::CardRemoved|Begin"));
+    // Cancel all card operations
+    iMessageStack->CancelCardOperations();
+
+    // remove all session entries from channel registers
+    for ( TInt i( 1 ); i < iChannels->Count(); i++ )
+        {
+        delete iChannels->At( i );
+        iChannels->At( i ) = static_cast< CArrayFixFlat<TInt>* >( NULL );
+        iReserverID[i] = ENoSession;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardChannelManager::CancelByTimeOut
+// Cancel messages by timeout
+// -----------------------------------------------------------------------------
+//
+void CScardChannelManager::CancelByTimeOut( CScardCommandTimer* aTimer )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardChannelManager::CancelByTimeOut|Begin"));
+    iMessageStack->CancelByTimeOut( aTimer );
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardComm.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,362 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Core class for all Smart Card aware applications to use when 
+*                communicating with the card.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "Scard.h"
+#include    "ScardBase.h"
+#include    "ScardClsv.h"
+#include    "ScardComm.h"
+#include    "ScardConnectionRequirement.h"
+#include    "WimTrace.h"
+
+#ifdef _DEBUG   // for logging
+#include    "ScardLogs.h"
+#include    <flogger.h> 
+#endif
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardComm::CScardComm
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardComm::CScardComm( RScard* aScard )
+    : iScard( aScard )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardComm::CScardComm|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardComm::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardComm::ConstructL(
+    TScardConnectionRequirement& aRequirement,
+    TScardReaderName& aReaderName,
+    TRequestStatus& aStatus,
+    const TInt32 aTimeOut )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardComm::ConstructL|Begin"));
+    aStatus = KRequestPending;
+    TAny* p[KMaxMessageArguments];
+    p[0] = p[1] = p[2] = p[3] = reinterpret_cast<TAny*>( 0 );
+
+    p[3] = reinterpret_cast<TAny*>( aTimeOut );
+
+    TInt mode( 0 );
+    
+    if ( aRequirement.iNewReaders )
+        {
+        mode |= KNewReadersOnly;
+        }
+    if ( aRequirement.iNewCards )
+        {
+        mode |= KNewCardsOnly;
+        }
+
+    //  Reader requirements
+    if ( aRequirement.iExplicitReader )
+        {
+        mode |= KExplicitReader;
+        aReaderName.Copy( *aRequirement.iExplicitReader );
+        }
+    else if ( aRequirement.iExcludedReader )
+        {
+        mode |= KExcludedReader;
+        aReaderName.Copy( *aRequirement.iExcludedReader );
+        }
+    else
+        {
+        mode |= KAnyReader;
+        aReaderName.Copy( _L( "" ) );
+        }
+    
+    p[1] = static_cast<TAny*>( &aReaderName );
+    
+    //  Card requirements
+    if ( aRequirement.iATRBytes )
+        {
+        mode |= KATRSpesified;
+        p[2] = reinterpret_cast<TAny*>( aRequirement.iATRBytes );
+        }
+    else if ( aRequirement.iAIDBytes )
+        {
+        mode |= KApplicationSpesified;
+        p[2] = reinterpret_cast<TAny*>( aRequirement.iAIDBytes );
+        }
+    else
+        {
+        mode |= KAnyCard;
+        }
+#ifdef _DEBUG
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, _L( "CScardComm::ConstructL mode: 0x%x \n" ), 
+        mode );
+#endif
+
+    //  Set the connection mode
+    p[0] = reinterpret_cast<TAny*>( mode );
+    TIpcArgs args( p[0], &aReaderName, p[2], p[3] ); 
+    iScard->SendReceive( EScardServerConnectToReader, args, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardComm::NewL
+// Two-phased constructor, asynchronous version.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScardComm* CScardComm::NewL(
+    RScard* aScard,
+    TScardConnectionRequirement& aRequirement,
+    TScardReaderName& aReaderName,
+    TRequestStatus& aStatus,
+    const TInt32 aTimeOut )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardComm::NewL|Begin"));
+    __ASSERT_ALWAYS( aScard, 
+        User::Panic( _L( "Null pointer" ), KScPanicNullPointer ) );
+    __ASSERT_ALWAYS( aTimeOut >= 0, User::Leave( KScErrBadArgument ) );
+    
+    CScardComm* self = new( ELeave ) CScardComm( aScard );
+    
+    CleanupStack::PushL( self );
+    self->ConstructL( aRequirement, aReaderName, aStatus, aTimeOut );
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+ 
+// Destructor
+EXPORT_C CScardComm::~CScardComm()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardComm::~CScardComm|Begin"));
+    if ( iScard )
+        {
+        DisconnectFromReader();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardComm::TransmitToCard
+// Transmit data to the card
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CScardComm::TransmitToCard(
+    const TDesC8& aCommand,
+    TDes8& aResponse,
+    TRequestStatus& aStatus,
+    const TInt32 aTimeOut,
+    const TInt8 aChannel ) const
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardComm::TransmitToCard|Begin"));
+#ifdef _DEBUG
+    RFileLogger::HexDump( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _S( "CScardComm::TransmitToCard command APDU:\n" ), 0,
+        aCommand.Ptr(), aCommand.Length() );
+#endif
+    
+    if ( aTimeOut < 0 ) // Check if timeout value is valid
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete( status, KErrArgument );
+        return; // Return right away
+        }
+
+    aStatus = KRequestPending;
+    
+    TIpcArgs args( &aCommand,
+                   &aResponse,
+                   aTimeOut,
+                   aChannel );
+
+    iScard->SendReceive( EScardServerTransmitToCard, args, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardComm::CancelTransmit
+// Cancel transmitting
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CScardComm::CancelTransmit() const
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardComm::CancelTransmit|Begin"));
+    TIpcArgs args( TIpcArgs::ENothing );
+    iScard->SendReceive( EScardServerCancelTransmit, args );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardComm::GetATRL
+// This function fetches the answer-to-reset bytes of the SC currently in the 
+// card reader. If an error occurs during the operation, the  length of the 
+// ATR bytes is set to zero. 
+// -----------------------------------------------------------------------------
+//
+
+EXPORT_C void CScardComm::GetATRL( TScardATR& aATR ) const
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardComm::GetATRL|Begin"));
+
+    TIpcArgs args( ( TAny* )&aATR );
+    TInt err = iScard->SendReceive( EScardServerGetATR, args );
+
+    if ( err )
+        {
+        User::Leave( err );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardComm::GetCapabilitiesL
+// Get proprietary parameters from the reader handler. 
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CScardComm::GetCapabilitiesL(
+    const TInt32 aTag,
+    TDes8& aValue,
+    const TInt32 aTimeOut ) const
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardComm::GetCapabilitiesL|Begin"));
+    __ASSERT_ALWAYS( aTimeOut >= 0, User::Leave( KScErrBadArgument ) );
+    TAny* p[KMaxMessageArguments];
+    p[0] = reinterpret_cast<TAny*>( 
+        static_cast<TInt>( ( ( aTag & 0xff00L ) >> 8 ) ) ); //Bits 8-15 from tag
+    p[1] = reinterpret_cast<TAny*>( 
+        static_cast<TInt>( ( aTag & 0x00ffL ) ) );  //First 8 bits from tag
+    p[2] = static_cast<TAny*>( &aValue );
+    p[3] = reinterpret_cast<TAny*>( aTimeOut );
+    
+    TIpcArgs args( p[0], p[1], &aValue, p[3] );
+    
+    TInt err = iScard->SendReceive( EScardServerGetCapabilities, args );
+    
+    if ( err ) // Scard error code may be positive
+        {
+        User::Leave( err );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardComm::Scard
+// Return Scard object contained within this object.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C RScard* CScardComm::Scard() const
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardComm::Scard|Begin"));
+    return iScard;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardComm::ManageChannel
+// Channel management function.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CScardComm::ManageChannel(
+    const TScChannelManagement aCommand,
+    const TInt8 aArgument,
+    TDes8& aResponseBuffer,
+    TRequestStatus& aStatus,
+    const TInt32 aTimeOut ) const
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardComm::ManageChannel|Begin"));
+    
+    if ( aTimeOut < 0 ) // Check if timeout value is valid
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete( status, KErrArgument );
+        return; // Return right away
+        }
+
+    TAny* p[KMaxMessageArguments];
+    
+    p[0] = p[1] = p[2] = p[3] = reinterpret_cast<TAny*>( 0 );
+
+    p[0] = reinterpret_cast<TAny*>( aCommand );
+
+    TIpcArgs args( p[0], p[1], p[2], p[3] );    
+    
+    switch ( aCommand )
+        {
+        case EOpenAnyChannel:
+            {
+#ifdef _DEBUG
+            RFileLogger::Write( KScardLogDir, KScardLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "CScardComm::ManageChannel -- Open Any channel" ) );
+#endif
+
+            args.Set( 1, &aResponseBuffer );
+            args.Set( 2, aTimeOut );
+            break;
+            }
+        
+        case ECloseChannel:
+            {
+#ifdef _DEBUG
+            RFileLogger::Write( KScardLogDir, KScardLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "CScardComm::ManageChannel -- Close channel" ) );
+#endif
+
+            args.Set( 1, aArgument );
+            args.Set( 2, aTimeOut );
+            
+            break;
+            }
+        
+        case EChannelStatus:
+            {
+            args.Set( 1, &aResponseBuffer );
+            break;
+            }
+        
+        default:
+            {
+            User::Panic( _L( "Command not supported" ), 
+                KScPanicNotSupported );
+            break;
+            }
+        }
+
+    iScard->SendReceive( EScardServerManageChannel, args, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardComm::DisconnectFromReader
+// Close connection
+// -----------------------------------------------------------------------------
+//
+void CScardComm::DisconnectFromReader() const
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardComm::DisconnectFromReader|Begin"));
+#ifdef _DEBUG
+    RFileLogger::Write( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, _L( "CScardComm::DisconnectFromReader" ) );
+#endif
+
+    TIpcArgs args( TIpcArgs::ENothing );
+    iScard->SendReceive( EScardServerDisconnectFromReader, args );
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardCommandTimer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,144 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Smart card command timer
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardAccessControl.h"
+#include    "ScardBase.h"
+#include    "ScardCommandTimer.h"
+#include    "WimTrace.h"
+
+#ifdef _DEBUG // for logging
+#include    "ScardLogs.h"
+#include    <flogger.h> 
+#endif
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardCommandTimer::CScardCommandTimer
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardCommandTimer::CScardCommandTimer()
+    : CActive( EPriorityNormal )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardCommandTimer::CScardCommandTimer|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardCommandTimer::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardCommandTimer::ConstructL(
+    TInt32 aTimeOut, 
+    CScardAccessControl* aController )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardCommandTimer::ConstructL|Begin"));
+    iTimeOut = aTimeOut;
+    iController = aController;
+    iTimer = new( ELeave ) RTimer;
+    iTimer->CreateLocal();
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardCommandTimer::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardCommandTimer* CScardCommandTimer::NewL(
+    TInt32 aTimeOut, 
+    CScardAccessControl* aController )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardCommandTimer::NewL|Begin"));
+    __ASSERT_ALWAYS( aTimeOut >= 0, User::Leave( KScErrBadArgument ) );
+    CScardCommandTimer* self = new( ELeave ) CScardCommandTimer;
+    
+    CleanupStack::PushL( self );
+    self->ConstructL( aTimeOut, aController );
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CScardCommandTimer::~CScardCommandTimer()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardCommandTimer::~CScardCommandTimer|Begin"));
+    if ( iTimer )
+        {
+        Cancel();
+        delete iTimer;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardCommandTimer::StartTiming
+// Start the clock
+// -----------------------------------------------------------------------------
+//
+void CScardCommandTimer::StartTiming()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardCommandTimer::StartTiming|Begin"));
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CScardCommandTimer: start timer\n" ) );
+#endif
+    iTimer->After( iStatus, iTimeOut );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CScardCommandTimer::RunL
+// The timer finished, i.e. the command has timed out
+// -----------------------------------------------------------------------------
+//
+void CScardCommandTimer::RunL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardCommandTimer::RunL|Begin"));
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CScardCommandTimer: timer expired\n" ) );
+#endif
+    iController->CancelByTimeOut( this );
+    delete iTimer;
+    iTimer = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardCommandTimer::DoCancel
+// -----------------------------------------------------------------------------
+//
+void CScardCommandTimer::DoCancel()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardCommandTimer::DoCancel|Begin"));
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CScardCommandTimer: cancel timer\n" ) );
+#endif
+    iTimer->Cancel();
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardConnectionRegistry.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,277 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Keeps track, creates and destroys connector objects
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardConnectionRegistry.h"
+#include    "ScardServer.h"
+#include    "ScardConnector.h"
+#include    "ScardServerBase.h"
+#include    "WimTrace.h"
+
+#ifdef _DEBUG // for logging
+#include    "ScardLogs.h"
+#include    <flogger.h> 
+#endif
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardConnectionRegistry::CScardConnectionRegistry
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardConnectionRegistry::CScardConnectionRegistry()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionRegistry::CScardConnectionRegistry|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnectionRegistry::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardConnectionRegistry::ConstructL( CScardServer* aServer )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionRegistry::ConstructL|Begin"));
+    iServer = aServer;
+    iConnectors = new( ELeave ) CArrayFixFlat<TConnectionHandle>( 1 );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnectionRegistry::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardConnectionRegistry* CScardConnectionRegistry::NewL(
+    CScardServer* aServer )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionRegistry::NewL|Begin"));
+    CScardConnectionRegistry* self = new( ELeave ) CScardConnectionRegistry();
+    
+    CleanupStack::PushL( self );
+    self->ConstructL( aServer );
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CScardConnectionRegistry::~CScardConnectionRegistry()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionRegistry::~CScardConnectionRegistry|Begin"));
+    while ( iConnectors->Count() )
+        {
+        TConnectionHandle& handle = iConnectors->At( 0 );
+        delete handle.iConnector;
+        iConnectors->Delete( 0 );
+        }
+    delete iConnectors;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CScardConnectionRegistry::ConnectToReaderL
+// Connect to reader
+// -----------------------------------------------------------------------------
+//
+void CScardConnectionRegistry::ConnectToReaderL(
+    CScardSession* aClient, 
+    const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionRegistry::ConnectToReaderL|Begin"));
+#ifdef _DEBUG
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+        EFileLoggingModeAppend, 
+        _L( "CScardConnectionRegistry::ConnectToReaderL entered.\n" ) );
+#endif
+    TConnectionHandle handle;
+    handle.iClient = aClient;
+    CScardConnector* conn = NULL;
+    RThread thread;
+    
+    TInt err1 = thread.Open( KScardServerName );
+    
+    if ( err1 != KErrNone )
+        {
+        _WIMTRACE(_L("WIM|Scard|CScardConnectionRegistry::ConnectToReaderL|Thread open failed"));
+        }
+
+    TRAPD( err, conn = CScardConnector::NewL( this, thread, aMessage ) );
+    if ( err )
+        {
+#ifdef _DEBUG
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardConnectionRegistry::ConnectToReaderL: creating connector\
+            failed: %d \n" ), err );
+#endif
+        aMessage.Complete( err );
+        return;
+        }
+    CleanupStack::PushL( conn );
+    handle.iConnector = conn;
+    iConnectors->AppendL( handle );
+    conn->ConnectToReaderL();
+    CleanupStack::Pop(conn);
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnectionRegistry::ReconnectToReader
+// Find the connector managing the session, and instruct it to reconnect.
+// If the connector is not found, panic will occur.
+// -----------------------------------------------------------------------------
+//
+/*
+void CScardConnectionRegistry::ReconnectToReaderL(
+    CScardSession* aClient, 
+    const RMessage& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionRegistry::ReconnectToReader|Begin"));
+    for ( TInt i( 0 ); i < iConnectors->Count(); i++ )
+        {
+        if ( iConnectors->At( i ).iClient == aClient )
+            {
+            //  The session needs to be detached from the previous reader 
+            //  (it wasn't the one we wanted after all)
+            aClient->DisconnectFromReader();
+
+            //  Now tell the connector to start reconnecting
+            iConnectors->At( i ).iConnector->ReconnectToReaderL( aMessage );
+            return;
+            }
+        }
+    User::Panic( _L( "Connector registry failure" ), 
+        KScServerPanicInternalError );
+    }
+*/
+
+// -----------------------------------------------------------------------------
+// CScardConnectionRegistry::CancelConnection
+// Cancel connection
+// -----------------------------------------------------------------------------
+//
+void CScardConnectionRegistry::CancelConnection( CScardSession* aSession )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionRegistry::CancelConnection|Begin"));
+    for ( TInt i( 0 ); i < iConnectors->Count(); i++ )
+        {
+        if ( iConnectors->At( i ).iClient == aSession )
+            {
+            iConnectors->At( i ).iConnector->Cancel();
+            return;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnectionRegistry::ConnectDone
+// Connection has been established. Complete client message.
+// -----------------------------------------------------------------------------
+//
+void CScardConnectionRegistry::ConnectDone(
+    CScardConnector* aConnector,
+    const TReaderID& aReaderID, 
+    const TInt& aErrorCode )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionRegistry::ConnectDone|Begin"));
+#ifdef _DEBUG
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+        EFileLoggingModeAppend, 
+        _L( "CScardConnectionRegistry::ConnectDone to reader %d with status\
+        %d.\n" ), aReaderID, aErrorCode );
+#endif
+    for ( TInt i( 0 ); i < iConnectors->Count(); i++ )
+        {
+#ifdef _DEBUG
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+            EFileLoggingModeAppend, 
+            _L( "CScardConnectionRegistry::ConnectDone finding correct\
+            connector out of %d.\n" ), iConnectors->Count() );
+#endif
+        TConnectionHandle& connection = iConnectors->At( i );
+        if ( connection.iConnector == aConnector )
+            {
+#ifdef _DEBUG
+            RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+                EFileLoggingModeAppend, 
+                _L( "CScardConnectionRegistry::ConnectDone connector\
+                found.\n" ) );
+#endif
+            connection.iClient->ConnectionDone( aReaderID, 
+                connection.iConnector->Message(), aErrorCode );
+            connection.iConnector->Message().Complete( aErrorCode );
+            return;
+            }
+        }
+    User::Panic( _L( "Registry failure" ), KScServerPanicInternalError );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnectionRegistry::RemoveConnector
+// Remove connector.
+// -----------------------------------------------------------------------------
+//
+void CScardConnectionRegistry::RemoveConnector( CScardConnector* aConnector )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionRegistry::RemoveConnector|Begin"));
+#ifdef _DEBUG
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+        EFileLoggingModeAppend, 
+        _L( "CScardConnectionRegistry::RemoveConnector.\n" ) );
+#endif
+    for ( TInt i( 0 ); i < iConnectors->Count(); i++ )
+        {
+        if ( iConnectors->At( i ).iConnector == aConnector )
+            {
+#ifdef _DEBUG
+            RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+                EFileLoggingModeAppend, 
+                _L( "CScardConnectionRegistry::RemoveConnector connector\
+                found.\n" ) );
+#endif
+            iConnectors->Delete( i );
+            return;
+            }
+        }
+    User::Panic( _L( "Registry failure" ), KScServerPanicInternalError );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnectionRegistry::Server
+// Return pointer to Scard server object
+// -----------------------------------------------------------------------------
+//
+CScardServer* CScardConnectionRegistry::Server() const
+    {
+    return iServer;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnectionRegistry::Connection
+// Return connection handle
+// -----------------------------------------------------------------------------
+//
+TConnectionHandle& CScardConnectionRegistry::Connection( TInt aLocation ) const
+    { 
+    return iConnectors->At( aLocation ); 
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardConnectionRequirement.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,204 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  For describing required Smart Card reader connections
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardConnectionRequirement.h"
+#include    "ScardServerBase.h"
+#include    "ScardBase.h"
+#include    "WimTrace.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// TScardConnectionRequirement::TScardConnectionRequirement
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TScardConnectionRequirement::TScardConnectionRequirement()
+    : iExplicitReader( NULL ),
+      iExcludedReader( NULL ),
+      iATRBytes( NULL ),
+      iAIDBytes( NULL ),
+      iParameterCount( 0 ), 
+      iNewCards( EFalse ),
+      iNewReaders( EFalse )
+    {
+    _WIMTRACE(_L("WIM|Scard|TScardConnectionRequirement::TScardConnectionRequirement|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// TScardConnectionRequirement::SetExplicitL
+// Set explicit reader
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void TScardConnectionRequirement::SetExplicitL(
+    TScardReaderName& aExplicitName )
+    {
+    _WIMTRACE(_L("WIM|Scard|TScardConnectionRequirement::SetExplicitL|Begin"));
+    __ASSERT_ALWAYS( iParameterCount < 2, User::Leave( KScErrFull ) );
+    __ASSERT_ALWAYS( !iExcludedReader, User::Leave( KErrNotSupported ) );
+    iExplicitReader = &aExplicitName;
+    iParameterCount++;
+    }
+
+// -----------------------------------------------------------------------------
+// TScardConnectionRequirement::SetExcludedL
+// Set exluded reader
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void TScardConnectionRequirement::SetExcludedL(
+    TScardReaderName& aExcludedName )
+    {
+    _WIMTRACE(_L("WIM|Scard|TScardConnectionRequirement::SetExcludedL|Begin"));
+    __ASSERT_ALWAYS( iParameterCount < 2, User::Leave( KScErrFull ) );
+    __ASSERT_ALWAYS( !iExplicitReader, User::Leave( KErrNotSupported ) );
+    iExcludedReader = &aExcludedName;
+    iParameterCount++;
+    }
+
+// -----------------------------------------------------------------------------
+// TScardConnectionRequirement::SetATRL
+// Set ATR bytes
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void TScardConnectionRequirement::SetATRL( TScardATR& aATR )
+    {
+    _WIMTRACE(_L("WIM|Scard|TScardConnectionRequirement::SetATRL|Begin"));
+    __ASSERT_ALWAYS( iParameterCount < 2, User::Leave( KScErrFull ) );
+    __ASSERT_ALWAYS( !(iAIDBytes), User::Leave( KErrNotSupported ) );
+    iATRBytes = &aATR;
+    iParameterCount++;
+    }
+
+// -----------------------------------------------------------------------------
+// TScardConnectionRequirement::SetAIDBytesL
+// Set AID bytes
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void TScardConnectionRequirement::SetAIDBytesL( TDesC8& aAID )
+    {
+    _WIMTRACE(_L("WIM|Scard|TScardConnectionRequirement::SetAIDBytesL|Begin"));
+    __ASSERT_ALWAYS( iParameterCount < 2, User::Leave( KScErrFull ) );
+    __ASSERT_ALWAYS( !(iATRBytes), User::Leave( KErrNotSupported ) );
+    iAIDBytes = &aAID;
+    iParameterCount++;
+    }
+
+// -----------------------------------------------------------------------------
+// TScardConnectionRequirement::ClearExplicitL
+// Clear explicit requirement
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void TScardConnectionRequirement::ClearExplicitL()
+    {
+    _WIMTRACE(_L("WIM|Scard|TScardConnectionRequirement::ClearExplicitL|Begin"));
+    if ( !iExplicitReader )
+        {
+        User::Leave( KScErrEmpty );
+        }
+    if ( iParameterCount && iExplicitReader )
+        {
+        iParameterCount--;
+        }
+    iExplicitReader = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// TScardConnectionRequirement::ClearExcludedL
+// Clear exluded requirement
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void TScardConnectionRequirement::ClearExcludedL()
+    {
+    _WIMTRACE(_L("WIM|Scard|TScardConnectionRequirement::ClearExcludedL|Begin"));
+    if ( !iExcludedReader )
+        {
+        User::Leave( KScErrEmpty );
+        }
+
+    if ( iParameterCount && iExcludedReader )
+        {
+        iParameterCount--;
+        }
+
+    iExcludedReader = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// TScardConnectionRequirement::ClearATRL
+// Clear ATR
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void TScardConnectionRequirement::ClearATRL()
+    {
+    _WIMTRACE(_L("WIM|Scard|TScardConnectionRequirement::ClearATRL|Begin"));
+    if ( !iATRBytes )
+        {
+        User::Leave( KScErrEmpty );
+        }
+    if ( iParameterCount && iATRBytes )
+        {
+        iParameterCount--;
+        }
+    iATRBytes = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// TScardConnectionRequirement::ClearAIDBytesL
+// Clear AID bytes
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void TScardConnectionRequirement::ClearAIDBytesL()
+    {
+    _WIMTRACE(_L("WIM|Scard|TScardConnectionRequirement::ClearAIDBytesL|Begin"));
+    if ( !iAIDBytes )
+        {
+        User::Leave( KScErrEmpty );
+        }
+    if ( iParameterCount && iAIDBytes )
+        {
+        iParameterCount--;
+        }
+    iAIDBytes = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// TScardConnectionRequirement::NewCardsOnly
+// Set New cards only flag
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void TScardConnectionRequirement::NewCardsOnly( const TBool aNewOnly )
+    {
+    _WIMTRACE(_L("WIM|Scard|TScardConnectionRequirement::NewCardsOnly|Begin"));
+    iNewCards = aNewOnly;
+    }
+
+// -----------------------------------------------------------------------------
+// TScardConnectionRequirement::NewReadersOnly
+// Set new readers only flag
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void TScardConnectionRequirement::NewReadersOnly( const TBool aNewOnly )
+    {
+    _WIMTRACE(_L("WIM|Scard|TScardConnectionRequirement::NewReadersOnly|Begin"));
+    iNewReaders = aNewOnly;
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardConnectionTimer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,135 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Timer for connections to smartcard
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardConnector.h"
+#include    "ScardConnectionTimer.h"
+#include    "WimTrace.h"
+
+#ifdef _DEBUG // for logging
+#include    "ScardLogs.h"
+#include    <flogger.h> 
+#endif
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardConnectionTimer::CScardConnectionTimer
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardConnectionTimer::CScardConnectionTimer(
+    CScardConnector* aConnector, 
+    TInt32 aTimeOut )
+    : CActive( EPriorityNormal ), 
+      iTimeOut( aTimeOut ), 
+      iConnector( aConnector )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionTimer::CScardConnectionTimer|Begin"));
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnectionTimer::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardConnectionTimer::ConstructL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionTimer::ConstructL|Begin"));
+    iTimer = new( ELeave ) RTimer;
+    iTimer->CreateLocal();
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CScardConnectionTimer::ConstructL\n" ) );
+#endif
+    iTimer->After( iStatus, iTimeOut );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnectionTimer::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardConnectionTimer* CScardConnectionTimer::NewL(
+    CScardConnector* aConnector, 
+    TInt32 aTimeOut )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionTimer::NewL|Begin"));
+    __ASSERT_ALWAYS( aTimeOut >= 0, User::Leave( KScErrBadArgument ) );
+    CScardConnectionTimer* self = new( ELeave ) CScardConnectionTimer(
+        aConnector, aTimeOut );
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CScardConnectionTimer::~CScardConnectionTimer()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionTimer::~CScardConnectionTimer|Begin"));
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CScardConnectionTimer::Destructor\n" ) );
+#endif
+    Cancel();
+    delete iTimer;    
+    }
+
+
+// -----------------------------------------------------------------------------
+// CScardConnectionTimer::RunL
+// -----------------------------------------------------------------------------
+//
+void CScardConnectionTimer::RunL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionTimer::RunL|Begin"));
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CScardConnectionTimer::RunL\n" ) );
+#endif
+    iConnector->ConnectionTimedOut();
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnectionTimer::DoCancel
+// -----------------------------------------------------------------------------
+//
+void CScardConnectionTimer::DoCancel()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnectionTimer::DoCancel|Begin"));
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CScardConnectionTimer::DoCancel\n" ) );
+#endif
+    iTimer->Cancel();
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardConnector.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,796 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A connection to a smart card
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardConnector.h"
+#include    "ScardConnectionRegistry.h"
+#include    "ScardAccessControl.h"
+#include    "ScardAccessControlRegistry.h"
+#include    "ScardConnectionTimer.h"
+#include    "ScardServer.h"
+#include    "ScardServerBase.h"
+#include    "WimTrace.h"
+
+#ifdef _DEBUG // for logging
+#include    "ScardLogs.h"
+#include    <flogger.h> 
+#endif
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// TConnectionParameter::TConnectionParameter
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+TConnectionParameter::TConnectionParameter()
+    : iReaderName( NULL ), 
+      iExcluded( NULL ), 
+      iATRBytes( NULL ),
+      iAIDBytes( NULL ),
+      iNewCardOnly( EFalse ), 
+      iNewReaderOnly( EFalse )
+    {
+    _WIMTRACE(_L("WIM|Scard|TConnectionParameter::TConnectionParameter|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// TConnection::TConnection
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+TConnection::TConnection()
+    : iCtrl( NULL ), 
+      iReader( NULL ), 
+      iReaderID( 0 ), 
+      iSessionID( ENoSession )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// Compare two connections
+// -----------------------------------------------------------------------------
+//
+TBool operator==(
+    const TConnection& aConnection1, 
+    const TConnection& aConnection2 )
+    {
+    if ( aConnection1.iReader == aConnection2.iReader && 
+        aConnection1.iCtrl == aConnection2.iCtrl &&
+        aConnection1.iSessionID == aConnection2.iSessionID &&
+        aConnection1.iReaderID == aConnection2.iReaderID )
+        {
+        return ETrue;
+        }
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnector::CScardConnector
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardConnector::CScardConnector(
+    CScardConnectionRegistry* aConnRegistry, 
+    RThread& /*aClient*/ )
+    : CScardSession(),
+      iConnectionRegistry( aConnRegistry ),
+      iState( EActive )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnector::CScardConnector|Begin"));
+    }
+
+
+// -----------------------------------------------------------------------------
+// CScardConnector::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardConnector::ConstructL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnector::ConstructL|Begin"));
+    iConnections = new( ELeave ) CArrayFixFlat<TConnection>( 1 );
+    iStack = CScardEventStack::NewL( this );
+    iClientMessage = new( ELeave ) RMessage2( aMessage ); 
+    iState = EActive;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnector::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardConnector* CScardConnector::NewL(
+    CScardConnectionRegistry* aConnRegistry, 
+    RThread& aClient, 
+    const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnector::NewL|Begin"));
+    CScardConnector* self = new( ELeave ) CScardConnector( aConnRegistry, 
+        aClient );
+    
+    CleanupStack::PushL( self );
+    self->ConstructL( aMessage );
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CScardConnector::~CScardConnector()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnector::~CScardConnector|Begin"));
+    delete iTimer;
+    
+    //  Delete members of the parameter block
+    delete iParameters.iReaderName;
+    delete iParameters.iExcluded;
+    delete iParameters.iATRBytes;
+    delete iParameters.iAIDBytes;
+
+    //  Detach from all connections
+    if ( iConnections->Count() )
+        {
+        TConnection& connection = iConnections->At( 0 );
+        //  Detach and delete all connections
+        while ( iConnections->Count() )
+            {
+            connection = iConnections->At( 0 );
+            TInt err = KErrNone;
+            TRAP( err, connection.iCtrl->CancelTransmissionsL(
+                                                      connection.iSessionID ) );
+            connection.iCtrl->DetachSessionFromReader( connection.iSessionID );
+            iConnections->Delete( 0 );
+            }
+        }
+
+    iConnections->Reset();
+    delete iConnections;
+    delete iClientMessage;
+    delete iStack;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CScardConnector::ConnectToReaderL
+// The connection is attempted and if it is successful
+// the session requesting the connection is notified. If the connection
+// can not yet be made, this object will remain waiting until all the
+// required parameters are matched or a timeout occurs.
+// -----------------------------------------------------------------------------
+//
+void CScardConnector::ConnectToReaderL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnector::ConnectToReaderL|Begin"));
+    // Get the limit factors
+    TRAPD( messageError, ReadLimitsL() ); 
+    if ( messageError == KScErrBadArgument || 
+        messageError == KScErrNotSupported )
+        {
+#ifdef _DEBUG
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardConnector::ConnectToReader: ReadLimits failed: %d \n" ), 
+            messageError );
+#endif
+        iConnectionRegistry->ConnectDone( this, 0, messageError );
+        iConnectionRegistry->RemoveConnector( this );
+        delete this;
+        return;
+        }
+    else if ( messageError != KErrNone )
+        {
+        User::Panic( _L( "Not enough free memory" ), KScPanicNoMemory );
+        }
+
+    //  Now go to all the ACs you need and attach to them. If the reader 
+    //  is spesific, only one entry is required. Otherwise all are.
+    if ( iParameters.iReaderName )
+        {
+#ifdef _DEBUG
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+            EFileLoggingModeAppend, 
+            _L( "CScardConnector::ConnectToReader Connecting to specific\
+            reader: %S\n" ),
+           iParameters.iReaderName);
+#endif
+        iOneReaderMode = ETrue;
+        //  Is the chosen one supported ??
+        if ( !( iConnectionRegistry->Server()->ReaderSupported( 
+            *iParameters.iReaderName ) ) )
+            {
+#ifdef _DEBUG
+            RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "CScardConnector::ConnectToReader ReaderSupported\
+                failed: \n" ) );
+#endif
+            iConnectionRegistry->ConnectDone( this, 0, KScErrUnknownReader );
+            iConnectionRegistry->RemoveConnector( this );
+            delete this;
+            return;
+            }
+
+        //  Grab the reader id (this shouldn't fail if the previous step 
+        //  went ok)
+        const TReaderID readerID = 
+            iConnectionRegistry->Server()->ReaderID( *iParameters.iReaderName );
+
+        //  If the reader can't be open when connecting, check it
+        if ( iParameters.iNewReaderOnly )
+            {
+            if ( iConnectionRegistry->Server()->AccessRegistry()->
+                ReaderHandlerLoaded( readerID ) )
+                {
+#ifdef _DEBUG
+                RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+                    EFileLoggingModeAppend, 
+                    _L( "CScardConnector::ConnectToReader Failed! Only new\
+                    readers allowed!\n" ) );
+#endif
+                iConnectionRegistry->ConnectDone( this, 0, 
+                    KScErrAlreadyExists );
+                iConnectionRegistry->RemoveConnector( this );
+                delete this;
+                return;
+                }
+            }
+        //  Create the access controller and the reader
+        TBool opened( EFalse );
+        TRAPD( readerError, opened = NewConnectionL( (*iClientMessage), 
+            readerID ) );
+        
+        //  If the reader object could not be created, look no further, 
+        //  we're in trouble
+        if ( readerError != KErrNone )
+            {
+#ifdef _DEBUG
+            RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "CScardConnector::ConnectToReader NewConnectionL failed:\
+                %d \n" ), readerError );
+#endif
+            iConnectionRegistry->ConnectDone( this, 0, readerError );
+            iConnectionRegistry->RemoveConnector( this );
+            delete this;
+            return;
+            }
+
+        //  The reader was created successfully.
+
+        //  1.  If the reader is open and if old cards are acceptable, 
+        //  check conditions
+
+        if ( opened && !iParameters.iNewCardOnly )
+            {
+            TScardATR atr;
+            iConnections->At( 0 ).iReader->GetATR( atr );
+            const TBool ok( CheckConditions( iConnections->At( 0 ), &atr ) );
+            if ( ok )
+                {
+#ifdef _DEBUG
+                RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+                    EFileLoggingModeAppend, 
+                    _L( "CScardConnector::ConnectToReader: Connection\
+                    succesfully established.\n" ) );
+#endif
+                ConnectionDone( iConnections->At( 0 ).iReaderID, KErrNone );
+                return;
+                }
+#ifdef _DEBUG
+            RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "CScardConnector::ConnectToReader CheckConditions\
+                failed! \n" ) );
+#endif
+            }
+
+        //  2.  In other cases, just stay waiting for either the OpenReader 
+        //  or condition checking to go through or for a card event to occur.
+        return;
+        }
+    else
+        {
+        //  Contact (almost) all readers, dead or alive...
+#ifdef _DEBUG
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+            EFileLoggingModeAppend, 
+           _L("CScardConnector::ConnectToReader Connecting to all readers.\n") );
+#endif
+        CScardReaderRegistry* rr = 
+            iConnectionRegistry->Server()->ReaderRegistry();
+
+        //  First list the ones not yet opened
+        CArrayFixFlat<TReaderID>* closelist = NULL;
+        closelist = new( ELeave ) CArrayFixFlat<TReaderID>( 1 );
+        CleanupStack::PushL( closelist );
+        rr->ListClosedReadersL( closelist );
+
+        //  then list the ones that are currently open (if necessary)
+        CArrayPtrFlat<CScardAccessControl>* openlist = NULL;
+        if ( !iParameters.iNewReaderOnly )
+            {
+            openlist = new( ELeave ) CArrayPtrFlat<CScardAccessControl>( 1 );
+            CleanupStack::PushL( openlist );
+            rr->ListOpenReadersL( openlist );
+            }
+
+        TReaderID excludeID( -1 );
+        if ( iParameters.iExcluded )
+            {
+#ifdef _DEBUG
+            RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+                EFileLoggingModeAppend, 
+               _L( "CScardConnector::ConnectToReader Get ID of excluded\
+               reader.\n" ) );
+#endif
+            excludeID = iConnectionRegistry->Server()->ReaderID( 
+                *iParameters.iExcluded );
+            }
+        
+        //  Attach to open readers
+        if ( !iParameters.iNewReaderOnly )
+            {
+#ifdef _DEBUG
+            RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+                EFileLoggingModeAppend, 
+               _L( "CScardConnector::ConnectToReader Attach to open readers" ) );
+#endif
+            for ( TInt i( 0 ); i < openlist->Count(); i++ )
+                {
+                TReaderID next = openlist->At( i )->ReaderID();
+                if ( next != excludeID )
+                    {
+                    TBool open( EFalse );
+                    //  Create the connection
+                    TRAPD( readerError, 
+                        open = NewConnectionL( *iClientMessage, next ) );
+
+                    //  If the reader is already open and old cards are 
+                    //  acceptable, check SC for the parameters.
+
+                    if ( !readerError && open && !iParameters.iNewCardOnly )
+                        {
+                        const TInt index = iConnections->Count() - 1;
+                        TScardATR atr;
+                        iConnections->At( index ).iReader->GetATR( atr );
+                        TBool ok = CheckConditions( iConnections->At( 
+                            iConnections->Count() - 1 ), &atr );
+                        if ( ok )
+                            {
+                            //delete openlist & closelist
+                            CleanupStack::PopAndDestroy( 2 ); 
+                            ConnectionDone( next, KErrNone );
+                            return;
+                            }
+                        }
+                    else if ( open && iParameters.iNewCardOnly )
+                        {
+                        //delete openlist & closelist
+                        CleanupStack::PopAndDestroy( 2 ); 
+                        // old cards are not acceptable, return error
+                        ConnectionDone( next, KScErrNotFound );
+                        return;
+                        }    
+                    }
+                }
+            CleanupStack::PopAndDestroy( openlist );  //  delete openlist
+            }
+        
+        //  attach to new readers
+        for ( TInt i( 0 ); i < closelist->Count(); i++ )
+            {
+#ifdef _DEBUG
+            RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+                EFileLoggingModeAppend, 
+               _L( "CScardConnector::ConnectToReader Attach to new readers" ) );
+#endif
+            TReaderID next = closelist->At( i );
+            if ( next != excludeID )
+                {
+                TInt err = KErrNone;
+                TRAP( err, NewConnectionL( (*iClientMessage), next ) );
+                }
+            }
+
+        CleanupStack::PopAndDestroy( closelist );  //  delete closelist
+        }
+
+    //  If no readers could be contacted at all ( == the handlers could not be 
+    //  created) why continue?
+    if ( !iConnections->Count() )
+        {
+        iState = EConnectionComplete;
+        ConnectionDone( 0, KScErrNotFound );
+        return;
+        }
+
+    if ( iConnections->Count() == 1 )
+        {
+        iOneReaderMode = ETrue;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnector::CardEvent
+// Handle card event
+// -----------------------------------------------------------------------------
+//
+void CScardConnector::CardEvent(
+    const TScardServiceStatus aEvent, 
+    const TScardATR& aATR, 
+    const TReaderID& aReaderID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnector::CardEvent|Begin"));
+    //  Card event handling is postponed if waiting for confirmation on
+    //  a connection attempt
+    if ( iState == EWaitingForConfirm )
+        {
+        iStack->QueueEvent( aReaderID, aEvent );
+        return;
+        }
+
+    //  Find the connection handling the reader and see if it meets the 
+    //  criteria
+    TConnection* conn = NULL;
+    TRAPD( err, conn = &( FindReaderConnectionL( aReaderID ) ) );
+
+    //  The connection must be found...
+    __ASSERT_ALWAYS( !err, User::Panic( _L( "Connector stack failure" ), 
+        KScServerPanicInternalError ) );
+
+    //  Now see what kind of event has occurred
+    switch ( aEvent )
+        {
+        case EScardRemoved: // Flow through
+        case EReaderRemoved:
+            {
+            break;
+            }
+        case EScardInserted:
+            {
+            //  A new card has been inserted, match it against the parameters
+            const TBool ok = CheckConditions( *conn, &aATR );
+            if ( ok )
+                {
+                ConnectionDone( conn->iReaderID, KErrNone );
+                }
+            break;
+            }
+        default:
+            {
+            break;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnector::ReadLimitsL
+// Extract the limit parameters for this connection attempt
+// -----------------------------------------------------------------------------
+//
+void CScardConnector::ReadLimitsL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnector::ReadLimitsL|Begin"));
+    TInt limiters = (*iClientMessage).Int0();
+
+    //  Check out the limiting factors
+    
+    //  The name of the reader is specified
+    if ( limiters & KExplicitReader )
+        {
+        TInt desLen = (*iClientMessage).GetDesLength( 1 );
+        HBufC* name = HBufC::NewL( desLen );
+        CleanupStack::PushL( name );
+        iParameters.iReaderName = new( ELeave ) TPtr( name->Des() );
+        TRAPD( err, (*iClientMessage).ReadL( 1, *iParameters.iReaderName ) );
+        if ( err != KErrNone )
+            {
+            (*iClientMessage).Panic( _L( "SCardServer" ), 
+                KScServerPanicBadDescriptor );
+            User::Leave( KScErrBadArgument );
+            }
+        CleanupStack::Pop( name );
+        }
+
+    //  The specified must not be contacted
+    else if ( limiters & KExcludedReader )
+        {
+        TInt desLen = (*iClientMessage).GetDesLength( 1 );
+        HBufC* bytes = HBufC::NewL( desLen );
+        CleanupStack::PushL( bytes );
+        iParameters.iExcluded = new( ELeave ) TScardReaderName( bytes->Des() );
+        TRAPD( err, (*iClientMessage).ReadL( 1, *iParameters.iExcluded ) );
+        if ( err != KErrNone )
+            {
+            (*iClientMessage).Panic( _L( "SCardServer" ), 
+                KScServerPanicBadDescriptor );
+            User::Leave( KScErrBadArgument );
+            }
+        CleanupStack::Pop( bytes );
+        }
+
+    //  Only newly inserted cards are acceptable
+    if ( limiters & KNewReadersOnly )
+        {
+        iParameters.iNewReaderOnly = ETrue;
+        }
+
+    //  The ATR bytes of the card are spesified
+    if ( limiters & KATRSpesified )
+        {
+        User::Leave( KScErrNotSupported );
+        }
+
+    //  The spesified application must be located within the SC
+    else if ( limiters & KApplicationSpesified )
+        {
+        User::Leave( KScErrNotSupported );
+        }
+
+    //  Only newly inserted cards are acceptable
+    if ( limiters & KNewCardsOnly )
+        {
+        iParameters.iNewCardOnly = ETrue;
+        }
+
+    //  Is there a time limit as well ?
+    TInt32 timeOut = reinterpret_cast< TInt32 >( iClientMessage->Ptr3() );
+
+    if ( timeOut )
+        {
+        iTimer = CScardConnectionTimer::NewL( this, timeOut );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnector::CheckConditions
+// Check if connection conditions are met.
+// -----------------------------------------------------------------------------
+//
+TBool CScardConnector::CheckConditions(
+    TConnection& /*aConnection*/, 
+    const TScardATR* aATR )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnector::CheckConditions|Begin"));
+    //  If no parameters are spesified, announce a match
+    if ( !(iParameters.iATRBytes || iParameters.iAIDBytes ) )
+        {
+#ifdef _DEBUG
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardConnector::CheckConditions: no parameters\
+            specified.\n" ) );
+#endif
+
+        iState = EConnectionComplete;
+        return ETrue;
+        }
+
+    //  Now check the parameters one by one
+
+    //  ATR match ?
+    if ( iParameters.iATRBytes )
+        {
+        if ( aATR )
+            {
+            if ( *iParameters.iATRBytes == *aATR )
+                {
+#ifdef _DEBUG
+                RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+                    EFileLoggingModeAppend, 
+                    _L( "CScardConnector::CheckConditions: ATR match." ) );
+#endif
+
+                iState = EConnectionComplete;
+                return ETrue;
+                }
+            }
+#ifdef _DEBUG
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+            EFileLoggingModeAppend, 
+            _L( "CScardConnector::CheckConditions: ATR mismatch!\n" ) );
+#endif
+
+        return EFalse;
+        }
+
+    //  The card has the requiered application ?
+    else if ( iParameters.iAIDBytes )
+        {
+#ifdef _DEBUG
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,     
+            EFileLoggingModeAppend, 
+            _L( "CScardConnector::CheckConditions: AIDBytes not supported!\n" ) );
+#endif
+        return EFalse;
+        }
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnector::NewConnectionL
+// Create new connection to the reader.
+// -----------------------------------------------------------------------------
+//
+TBool CScardConnector::NewConnectionL(
+    const RMessage2 aMessage, 
+    const TReaderID aReaderID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnector::NewConnectionL|Begin"));
+    TConnection conn;
+
+    conn.iReaderID = aReaderID;
+
+    //  Assign an access controller to this connection
+    conn.iCtrl = iConnectionRegistry->Server()->AccessRegistry()->
+        AccessController( aReaderID );
+    
+    //  Make sure there was enough memory for the access controller
+    __ASSERT_MEMORY( !(conn.iCtrl) );
+
+    //  attempt to create the connection's reader
+    TRAPD( readerError, conn.iReader = conn.iCtrl->AttachSessionToReaderL( 
+        this, conn.iSessionID ) );
+
+    //  If creating the reader succeeds, attempt to initialise the reader
+    if ( readerError == KErrNone )
+        {
+#ifdef _DEBUG    
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardConnector::NewConnectionL: Reader (ID: %d)\
+            succesfully created.\n" ), aReaderID );
+#endif
+        const TBool ok( conn.iCtrl->InitialiseReader( conn.iSessionID, 
+            aMessage ) );
+        iConnections->AppendL( conn );
+        return ok;
+        }
+
+#ifdef _DEBUG
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName,         
+        EFileLoggingModeAppend, 
+        _L( "CScardConnector::NewConnectionL: FAILED! error: %d\n" ),
+        readerError );
+#endif
+
+    conn.iCtrl->DetachSessionFromReader( conn.iSessionID );
+    User::Leave( readerError );
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnector::FindReaderConnectionL
+// Find connection for given reader.
+// -----------------------------------------------------------------------------
+//
+TConnection& CScardConnector::FindReaderConnectionL(
+    const TReaderID& aReaderID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnector::FindReaderConnectionL|Begin"));
+    TInt count = iConnections->Count();
+    for ( TInt i( 0 ); i < count; i++ )
+        {
+        if ( iConnections->At( i ).iReaderID == aReaderID )
+            {
+            return iConnections->At( i );
+            }
+        }
+    User::Leave( KScErrNotFound );
+    return iConnections->At( 0 ); //just to satisfy compiler
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnector::ConnectionDone
+// Connection has been established. Remove connector.
+// -----------------------------------------------------------------------------
+//
+void CScardConnector::ConnectionDone(
+    const TReaderID aReaderID, 
+    const TInt& aErrorCode )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnector::ConnectionDone|Begin"));
+#ifdef _DEBUG
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, _L( "CScardConnector::ConnectionDone \
+        status: %d \n" ), aErrorCode );
+#endif
+    if ( aErrorCode != KErrNone )
+        {
+        iState = EConnectionComplete;
+        }
+    if ( iTimer )
+        {
+#ifdef _DEBUG
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, _L( "CScardConnector::ConnectionDone Cancel\
+            timer. \n" ) );
+#endif
+        iTimer->Cancel();
+        }
+
+    if ( aErrorCode == KScErrTimeOut )
+        {
+        iConnectionRegistry->Server()->
+            FindAccessControl( aReaderID )->Cancel();
+      
+        }
+
+    iConnectionRegistry->ConnectDone( this, aReaderID, aErrorCode );
+    if ( iState == EConnectionComplete )
+        {
+        iConnectionRegistry->RemoveConnector( this );
+        delete this;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnector::Cancel
+// Cancel connection. Call ConnectionDone with error code KScErrCancelled.
+// -----------------------------------------------------------------------------
+//
+void CScardConnector::Cancel()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnector::Cancel|Begin"));
+    iState = EConnectionComplete;
+    ConnectionDone( 0, KScErrCancelled );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnector::Message
+// Return client message.
+// -----------------------------------------------------------------------------
+//
+RMessage2& CScardConnector::Message()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnector::Message|Begin"));
+    return *iClientMessage;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardConnector::ConnectionTimedOut
+// Timeout has occurred. Connectin done with KScErrTimeOut.
+// -----------------------------------------------------------------------------
+//
+void CScardConnector::ConnectionTimedOut()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardConnector::ConnectionTimedOut|Begin"));
+#ifdef _DEBUG
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CScardConnector::ConnectionTimedOut state=%d\n" ), iState );
+#endif
+    if ( iState == EWaitingForConfirm )
+        {
+        iState = ETimedOut;
+        return;
+        }
+    else
+        {
+        iState = EConnectionComplete;
+        ConnectionDone( iConnections->At( 0 ).iReaderID, KScErrTimeOut );
+        }
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardEventStack.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,110 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A class implementing two stacks. One is a fifo-stack of
+*               reader events, the other a random-access stack of service
+*               providers that are not used with a given reader
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardBase.h"
+#include    "ScardEventStack.h"
+#include    "ScardConnector.h"
+#include    "WimTrace.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardEventStack::CScardEventStack
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardEventStack::CScardEventStack()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CScardEventStack::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardEventStack::ConstructL( CScardConnector* aConnector )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardEventStack::ConstructL|Begin"));
+    iConnector = aConnector;
+    iEvents = new ( ELeave ) CArrayFixFlat<TQueueEvent>( 1 );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardEventStack::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardEventStack* CScardEventStack::NewL( CScardConnector* aConnector )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardEventStack::NewL|Begin"));
+    CScardEventStack* self = new( ELeave ) CScardEventStack;
+    
+    CleanupStack::PushL( self );
+    self->ConstructL( aConnector );
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CScardEventStack::~CScardEventStack()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardEventStack::~CScardEventStack|Begin"));
+    if ( iEvents )
+        {
+        iEvents->Reset();
+        }
+    delete iEvents;    
+    }
+
+// -----------------------------------------------------------------------------
+// CScardEventStack::QueueEvent
+// Queue event
+// -----------------------------------------------------------------------------
+//
+void CScardEventStack::QueueEvent(
+    const TReaderID aReaderID, 
+    const TScardServiceStatus aEventType )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardEventStack::QueueEvent|Begin"));
+    //  Remove any old events for this reader to ensure that no out-of-date 
+    //  events are in the stack
+    for ( TInt i( 0 ); i < iEvents->Count(); i++ )
+        {
+        if ( iEvents->At( i ).iReaderID == aReaderID )
+            {
+            iEvents->Delete( i );
+            break;
+            }
+        }
+
+    //  Add event to the stack
+    TQueueEvent event;
+    event.iEventType = aEventType;
+    event.iReaderID = aReaderID;
+    TRAPD( mem_ok, iEvents->AppendL( event ) );
+    __ASSERT_MEMORY( mem_ok );
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardListener.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,148 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Listens for smard card events
+*
+*/
+
+
+// INCLUDE FILES
+#include    "Scard.h"
+#include    "ScardBase.h"
+#include    "ScardListener.h"
+#include    "ScardClsv.h"
+#include    "WimTrace.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScardListener::CScardListener( RScard* aScard ) 
+    : CActive( CActive::EPriorityStandard )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardListener::CScardListener|Begin"));
+    __ASSERT_ALWAYS( aScard, User::Panic( _L( "NULL pointer" ), 
+        KErrArgument ) );
+    iScard = aScard;
+    CActiveScheduler::Add( this );
+    }
+
+// Destructor
+EXPORT_C CScardListener::~CScardListener()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardListener::~CScardListener|Begin"));
+    Cancel(); // Make sure we're cancelled
+    _WIMTRACE(_L("WIM|Scard|CScardListener::~CScardListener|End"));
+    }
+
+
+// -----------------------------------------------------------------------------
+// CScardListener::ListenCardEvents
+// Start listening card events
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CScardListener::ListenCardEvents(
+    const TScardReaderName& aReaderName )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardListener::ListenCardEvents|Begin"));
+    iReaderName.Copy( aReaderName );
+    TInt err = NotifyChange( iStatus, aReaderName );
+    SetActive();
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardListener::DoCancel
+// Listening cancelled
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CScardListener::DoCancel()
+    {   
+    _WIMTRACE(_L("WIM|Scard|CScardListener::DoCancel|Begin"));
+    CancelNotifyChange(iReaderName );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardListener::RunL
+// Handle event we have got
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CScardListener::RunL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardListener::RunL|Begin"));
+    TScardServiceStatus event = (TScardServiceStatus) iStatus.Int();
+    //iStatus = KRequestPending;
+    //SetActive();
+    ProcessEvent( event );
+    _WIMTRACE(_L("WIM|Scard|CScardListener::RunL|END"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardListener::NotifyChange
+// Send NotifyChange opcode to server
+// -----------------------------------------------------------------------------
+//
+TInt CScardListener::NotifyChange(
+    TRequestStatus& aStatus,
+    const TScardReaderName& aFriendlyName )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardListener::NotifyChange|Begin"));
+    aStatus = KRequestPending;
+    iPckg = &aStatus;
+    //TPckgBuf<TRequestStatus*> pckg( &aStatus );
+
+    TIpcArgs args( &iPckg, &aFriendlyName );
+    iScard->SendReceive( EScardServerNotifyChange, args, aStatus );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardListener::CancelNotifyChange
+// Send CancelNotifyChange opcode to server
+// -----------------------------------------------------------------------------
+//
+/*void CScardListener::CancelNotifyChange(
+    TRequestStatus& aStatus,
+    const TScardReaderName& aFriendlyName )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardListener::CancelNotifyChange|Begin"));
+    
+    //TPckgBuf<TRequestStatus*> pckg( &aStatus );
+    iPckg = &aStatus;
+    
+    TIpcArgs args( &iPckg, &aFriendlyName );
+    
+    iScard->SendReceive( EScardServerCancelNotifyChange, args );
+    _WIMTRACE(_L("WIM|Scard|CScardListener::CancelNotifyChange|End"));
+    }*/
+    
+
+TInt CScardListener::CancelNotifyChange( const TScardReaderName& aFriendlyName )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardListener::CancelNotifyChange|Begin"));
+    
+    //this parameter is not used in server side
+    //It will be useful if there is a multiple scard listener
+    //currently only wimserver is the scard listener, so by calling
+    //this function, the array of listener will be cleaned.
+    TIpcArgs args( &iPckg, &aFriendlyName );
+    
+    return iScard->SendReceive( EScardServerCancelNotifyChange, args );
+    _WIMTRACE(_L("WIM|Scard|CScardListener::CancelNotifyChange|End"));
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardMessageStack.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,303 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Handles messaging with stack
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardBase.h"
+#include    "ScardMessageStack.h"
+#include    "ScardConnector.h"
+#include    "WimTrace.h"
+
+#ifdef _DEBUG // for logging
+#include    "ScardLogs.h"
+#include    <flogger.h> 
+#endif
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::CScardMessageStack
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardMessageStack::CScardMessageStack()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardMessageStack::CScardMessageStack|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardMessageStack::ConstructL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardMessageStack::ConstructL|Begin"));
+    iMessages = new( ELeave ) CArrayFixFlat<TMessageHandle>( 3 );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardMessageStack* CScardMessageStack::NewL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardMessageStack::NewL|Begin"));
+    CScardMessageStack* self = new( ELeave ) CScardMessageStack();
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CScardMessageStack::~CScardMessageStack()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardMessageStack::~CScardMessageStack|Begin"));
+    CancelAll( KScErrCancelled );
+    delete iMessages;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::CancelAll
+// Cancel all operations for this session ID.
+// -----------------------------------------------------------------------------
+//
+void CScardMessageStack::CancelAll(
+    const TInt aSessionID, 
+    const TInt aReason )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardMessageStack::CancelAll|Begin"));
+    if ( iMessages->Count() )
+        {
+        //  First check if the message currently serviced is one of 
+        //  the cancelled ones (it requires special treatment)
+        if ( (*iMessages)[0].iSessionID == aSessionID ) 
+            {
+            CancelOne( 0, aReason );
+            }
+        //  Then pop out all the others
+        for ( TInt i( 1 ); i < iMessages->Count(); i++ ) 
+            {
+            if ( (*iMessages)[i].iSessionID == aSessionID )
+                {
+                CancelOne( i, aReason );
+                iMessages->Delete( i );
+                i--;
+                } // if
+            } // for
+        } // if
+    }
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::CancelAll
+// Cancel all messages waiting for service. Delete all others except the 
+// first one
+// -----------------------------------------------------------------------------
+//
+void CScardMessageStack::CancelAll( const TInt aReason )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardMessageStack::CancelAll|Begin"));
+    if ( iMessages->Count() )
+        {
+        //  Just cancel the first
+        CancelOne( 0, aReason );
+    
+        //  Then pop out all the others
+        for ( TInt i( 1 ); i < iMessages->Count(); i++ )
+            {
+            CancelOne( i, aReason );
+            iMessages->Delete( i );
+            i--;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::CancelCardOperations
+// Effectively the same as the above, except that does not cancel 
+// OpenReader commands...
+// -----------------------------------------------------------------------------
+//
+void CScardMessageStack::CancelCardOperations()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardMessageStack::CancelCardOperations|Begin"));
+    if ( iMessages->Count() )
+        {
+        //  Just cancel the first
+        if ( iMessages->At( 0 ).iAdditionalParameter != KOpenReader )
+            {
+            CancelOne( 0, KScReaderErrNoCard );
+            }
+    
+        //  Then pop out all the others
+        for ( TInt i( 1 ); i < iMessages->Count(); i++ )
+            {
+            if ( iMessages->At( i ).iAdditionalParameter != KOpenReader )
+                {
+                CancelOne( i, KScReaderErrNoCard );
+                iMessages->Delete( i );
+                i--;
+                }
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::CancelByTimeOut
+// Cancel message by timeout
+// -----------------------------------------------------------------------------
+//
+void CScardMessageStack::CancelByTimeOut( const CScardCommandTimer* aTimer )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardMessageStack::CancelByTimeOut|Begin"));
+#ifdef _DEBUG
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, _L( "CScardMessageStack::CancelByTimeOut\n" ) );
+#endif
+
+    if ( iMessages->Count() )
+        {
+        //  First check if the message currently serviced is the cancelled one
+        //  (it requires special treatment)
+        if ( (*iMessages)[0].iTimer == aTimer )
+            {
+            CancelOne( 0, KScErrTimeOut, EFalse );
+            return;
+            }
+
+        //  Then check out all the others
+        for ( TInt i( 1 ); i < iMessages->Count(); i++ )
+            {
+            if ( (*iMessages)[i].iTimer == aTimer )
+                {
+                CancelOne( i, KScErrTimeOut, EFalse );
+                iMessages->Delete( i );
+                return;
+                } // if
+            } // for
+        } // if
+    }
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::PushToTop
+// Push message to top
+// -----------------------------------------------------------------------------
+//
+TInt CScardMessageStack::PushToTop( const TMessageHandle& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardMessageStack::PushToTop|Begin"));
+    TRAPD( err, iMessages->InsertL( 0, aMessage ) );
+    _WIMTRACE2(_L("WIM|Scard|CScardMessageStack::PushToTop|End|err=%d"), err);
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::FromTop
+// Message from top
+// -----------------------------------------------------------------------------
+//
+const TMessageHandle CScardMessageStack::FromTop()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardMessageStack::FromTop|Begin"));
+    if ( !iMessages->Count() )
+        {
+        //  returns the default, which is interpreted as an error
+        TMessageHandle a;
+        return a;
+        }
+    TMessageHandle tmp = (*iMessages)[0];
+    iMessages->Delete( 0 );
+    return tmp;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::PushToBottom
+// Push message to bottom
+// -----------------------------------------------------------------------------
+//
+TInt CScardMessageStack::PushToBottom( const TMessageHandle& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardMessageStack::PushToBottom|Begin"));
+    TRAPD( err, iMessages->AppendL( aMessage ) );
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::NextReservation
+// This function is called when a channel is freed. It gives priority
+// for applications who are waiting to reserve either this channel or
+// any channel
+// -----------------------------------------------------------------------------
+//
+const TMessageHandle CScardMessageStack::NextReservation( const TInt8 aChannel )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardMessageStack::NextReservation|Begin"));
+    TMessageHandle tmp;
+    for ( TInt i( 0 ); i < iMessages->Count(); i++ )
+        {
+        tmp = (*iMessages)[i];
+        if ( ( tmp.iAdditionalParameter & KReservation ) && 
+           ( tmp.iChannel == aChannel || tmp.iChannel == KAllChannels ) )
+            {
+            iMessages->Delete( i );
+            return tmp;
+            }
+        }
+    tmp.iSessionID = ENoSession;
+    return tmp;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::FromPositionL
+// Get message from given position
+// -----------------------------------------------------------------------------
+//
+const TMessageHandle CScardMessageStack::FromPositionL( const TInt aPosition )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardMessageStack::FromPositionL|Begin"));
+    __ASSERT_ALWAYS( aPosition >= 0 && aPosition < iMessages->Count(), 
+        User::Leave( KScErrBadArgument ) );
+    TMessageHandle r = iMessages->At( aPosition );
+    iMessages->Delete( aPosition );
+    return r;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardMessageStack::PushToPositionL
+// Push message to given position
+// -----------------------------------------------------------------------------
+//
+void CScardMessageStack::PushToPositionL(
+    const TInt aPosition, 
+    TMessageHandle& aHandle )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardMessageStack::PushToPositionL|Begin"));
+    __ASSERT_ALWAYS( aPosition >= 0 && aPosition <= iMessages->Count(), 
+        User::Leave( KScErrBadArgument ) );
+    iMessages->InsertL( aPosition, aHandle );
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardNotifier.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,246 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Notification of events
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardServer.h"
+#include    "ScardNotifier.h"
+#include    "WimTrace.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardNotifier::CScardNotifier
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardNotifier::CScardNotifier(
+    CScardNotifyRegistry* aRegistry, 
+    RMessage2& aMessage,
+    TRequestStatus* aClientStatus,
+    const TReaderID& aReaderID )
+    : CActive( EPriorityNormal ), 
+      iRegistry( aRegistry ),
+      iMessage( aMessage ),
+      iClientStatus( aClientStatus ),
+      iReaderID( aReaderID ),
+      iMessageCompleted( EFalse )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardNotifier::CScardNotifier|Begin"));
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardNotifier::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardNotifier::ConstructL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardNotifier::ConstructL|Begin"));
+    //if the notifier is regular, no need to activate the ActiveObject.
+    //since the notifier can only be used once and will be deleted after
+    //the one-time notification is done.
+    if(!iClientStatus)
+       {
+       iEventStack = new( ELeave ) CArrayFixFlat<TCardEvent>( 1 );
+       iStatus = KRequestPending; 	
+       SetActive();
+       }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardNotifier::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardNotifier* CScardNotifier::NewL(
+    CScardNotifyRegistry* aRegistry,
+    RMessage2& aMessage,
+    TRequestStatus* aClientStatus,
+    const TReaderID& aReaderID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardNotifier::NewL|Begin"));
+    CScardNotifier* self = new( ELeave ) CScardNotifier( 
+        aRegistry, aMessage, aClientStatus, aReaderID );
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CScardNotifier::~CScardNotifier()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardNotifier::~CScardNotifier|Begin"));
+    if(!iClientStatus)
+       {
+       delete iEventStack;
+       Cancel();
+       }
+    else
+       {
+       if ( !iMessageCompleted ) 
+          {
+          iMessage.Complete( KErrNone );
+          }	
+       }
+    _WIMTRACE(_L("WIM|Scard|CScardNotifier::~CScardNotifier|End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardNotifier::NotifyCardEvent
+// Complete our own request, or if that's done already, store the event
+// until it can be serviced...
+// -----------------------------------------------------------------------------
+//
+void CScardNotifier::NotifyCardEvent(
+    TScardServiceStatus aEvent,
+    TReaderID aReaderID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardNotifier::NotifyCardEvent|Begin"));
+    
+    //regular notifier
+    if( iClientStatus )
+       {
+       _WIMTRACE(_L("WIM|Scard|CScardNotifier::NotifyCardEvent| a regular notifier"));
+       if(iMessageCompleted )
+          {
+       	  return;
+          }
+       _WIMTRACE(_L("WIM|Scard|CScardNotifier::NotifyCardEvent|iMessage not used"));   
+       _WIMTRACE(_L("WIM|Scard|CScardNotifier::NotifyCardEvent|Notify client"));
+       iMessage.Complete( aEvent );
+       iMessageCompleted = ETrue;
+       _WIMTRACE(_L("WIM|Scard|CScardNotifier::NotifyCardEvent|Notify client DONE"));
+       return;	
+       }
+    
+    _WIMTRACE(_L("WIM|Scard|CScardNotifier::NotifyCardEvent| Server notifier"));   
+    //  No need to store the event, just notify it
+    if ( iStatus == KRequestPending )
+        {
+        TUint code( 0 );
+        
+        //  If this is the server notifier, 
+        //  it needs a different event encoding
+        if ( !iClientStatus )
+            {
+            //  The server needs to know both the event code and 
+            //  the reader ID, because it listens to all readers
+
+            //  Place the reader ID in the higher bytes...
+            code = aReaderID;
+            code <<= 4;
+            //  ...and the event code in the low 4 bytes
+            code |= aEvent;
+            }
+        TRequestStatus* sp = &iStatus;
+        User::RequestComplete( sp, code );
+        }
+    //  Well, previous notify hasn't finished, so store the event
+    else
+        {
+        TCardEvent event;
+        event.iEvent = aEvent;
+        event.iReaderID = aReaderID;
+        TRAPD( err, iEventStack->AppendL( event ) );
+
+        if ( err != KErrNone ) // No reason to continue
+            {
+            User::Panic( _L( "Memory allocation error" ), err );
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardNotifier::RunL
+// Asynchronous request has finished
+// -----------------------------------------------------------------------------
+//
+void CScardNotifier::RunL()
+    {
+    _WIMTRACE2(_L("WIM|Scard|CScardNotifier::RunL|Begin, iClientStatus=%d"), iClientStatus);
+    //  if this is a regular notifier, 
+    //  then some thing goes wrong.
+    //  only server notifier should come to RunL().
+    if ( iClientStatus )
+        {
+        _WIMTRACE(_L("WIM|Scard|CScardNotifier::RunL|Only server notifer will come to RunL"));
+        }
+    //  Otherwise this is the server notifier, so tell the server
+    else
+        {
+        _WIMTRACE(_L("WIM|Scard|CScardNotifier::RunL|server notifer"));
+        // the bit-shifting that was done when notifying is now reversed
+        TScardServiceStatus event = static_cast< TScardServiceStatus >
+                                                ( iStatus.Int() & 0x0f );
+        TReaderID readerID = static_cast< TReaderID >( iStatus.Int() >> 4 );
+        iRegistry->Server()->CardEvent( event, readerID );
+        _WIMTRACE(_L("WIM|Scard|CScardNotifier::RunL|Server notification DONE"));
+        }
+    iStatus = KRequestPending;
+    SetActive();
+
+    //  If there are any queued events, notify (first one of) them now
+    if ( iEventStack->Count() )
+        {
+        _WIMTRACE(_L("WIM|Scard|CScardNotifier::RunL| Some queued event in server notifier"));
+        iRegistry->NotifyCardEvent( iEventStack->At( 0 ).iEvent, 
+            iEventStack->At( 0 ).iReaderID );
+        iEventStack->Delete( 0 );
+        }
+    _WIMTRACE(_L("WIM|Scard|CScardNotifier::RunL|Exit"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardNotifier::DoCancel
+// Active object cancelled
+// -----------------------------------------------------------------------------
+//
+void CScardNotifier::DoCancel()
+    {
+    _WIMTRACE3(_L("WIM|Scard|CScardNotifier::DoCancel|Begin, status=%d"),
+    iStatus.Int(), iClientStatus );
+    iRegistry->Cancel( iStatus );
+    _WIMTRACE(_L("WIM|Scard|CScardNotifier::DoCancel|Cancel called"));
+
+    // If message not already completed do it here
+    if ( !iMessageCompleted && iClientStatus ) 
+        {
+        iMessage.Complete( KErrCancel );
+        _WIMTRACE(_L("WIM|Scard|CScardNotifier::DoCancel|Message completed"));
+        }
+    
+    _WIMTRACE(_L("WIM|Scard|CScardNotifier::DoCancel|End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardNotifier::ReaderID
+// Return readerID
+// -----------------------------------------------------------------------------
+//
+TReaderID CScardNotifier::ReaderId()
+    {
+    return iReaderID;
+    }
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardNotifyRegistry.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,241 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Notification Registry for SmartCard
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardBase.h"
+#include    "ScardNotifyRegistry.h"
+#include    "ScardServer.h"
+#include    "ScardNotifier.h"
+#include    "WimTrace.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardNotifyRegistry::CScardNotifyRegistry
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardNotifyRegistry::CScardNotifyRegistry() 
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::CScardNotifyRegistry|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardNotifyRegistry::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardNotifyRegistry::ConstructL( CScardServer* aServer )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::ConstructL|Begin"));
+    iNotifiers = new( ELeave ) CArrayPtrFlat<CScardNotifier>( 1 );
+
+    //  The server is notified of all reader events. 
+    RMessage2 message; // Empty message
+    CScardNotifier* serverNotifier = CScardNotifier::NewL( this, 
+                                                           message,
+                                                           NULL,
+                                                           KServerNotifier );
+
+    iNotifiers->AppendL( serverNotifier );
+
+    iServer = aServer;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardNotifyRegistry::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardNotifyRegistry* CScardNotifyRegistry::NewL( CScardServer* aServer )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::NewL|Begin"));
+    CScardNotifyRegistry* self = new( ELeave ) CScardNotifyRegistry;
+    
+    CleanupStack::PushL( self );
+    self->ConstructL( aServer );
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CScardNotifyRegistry::~CScardNotifyRegistry() 
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::~CScardNotifyRegistry|Begin"));
+    if ( iNotifiers )
+        {
+        iNotifiers->ResetAndDestroy();
+        }
+    delete iNotifiers;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CScardNotifyRegistry::NotifyCardEvent
+// Notify all notifiers when event occurs
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CScardNotifyRegistry::NotifyCardEvent(
+    TScardServiceStatus aEvent,
+    TReaderID aReaderID )
+    {
+    _WIMTRACE2(_L("WIM|Scard|CScardNotifyRegistry::NotifyCardEvent|Begin, notifierCount=%d"), iNotifiers->Count());
+    // Tell the server of the event
+    CScardNotifier* notifier = (*iNotifiers)[0];
+    notifier->NotifyCardEvent( aEvent, aReaderID );
+
+    // notify clients (if any)
+    for ( TInt i( 1 ); i < iNotifiers->Count(); i++ )
+        {
+        notifier = (*iNotifiers)[i];
+        if ( notifier->ReaderId() == aReaderID )
+            {
+            _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::NotifyCardEvent|NotifyCardEvent Regular starts"));
+            notifier->NotifyCardEvent( aEvent, aReaderID );
+            _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::NotifyCardEvent|NotifyCardEvent Regular DONE"));
+
+            // when creating notifier in AddReaderEventListenerL,
+            // the RMessage pointer is passed as parameter to notifier.
+            // that will be used later to notify the client about smart 
+            // card event.
+            // So that each notifier can only be used once.
+            // so we must remove the notifier from the array.
+            // the scard server's notified can be kept.
+            iNotifiers->Delete( i );
+            delete notifier;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardNotifyRegistry::Server
+// Return CScardServer object
+// -----------------------------------------------------------------------------
+//
+CScardServer* CScardNotifyRegistry::Server()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::Server|Begin"));
+    return iServer;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardNotifyRegistry::Cancel
+//
+// -----------------------------------------------------------------------------
+//
+void CScardNotifyRegistry::Cancel( TRequestStatus& aStatus )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::Cancel|Begin"));
+    TRequestStatus* sp = &aStatus;
+    User::RequestComplete( sp, KScErrCancelled );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardNotifyRegistry::RemoveReaderEventListeners
+// Remove event listener from registry and delete it
+// -----------------------------------------------------------------------------
+//
+void CScardNotifyRegistry::RemoveReaderEventListeners(
+    const RThread& /*aClient*/ )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::RemoveReaderEventListeners|Begin"));
+    //find and delete from array
+    TInt numOfItems = iNotifiers->Count();
+
+    //do while better here EPR
+    for ( TInt i( 1 ); i < numOfItems; i++ )
+        {
+        iNotifiers->Delete( i );
+        }
+    _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::RemoveReaderEventListeners|End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardNotifyRegistry::RemoveReaderEventListener
+// Remove event listener from registry and delete it
+// -----------------------------------------------------------------------------
+//
+void CScardNotifyRegistry::RemoveReaderEventListener(
+    const RMessage2& /*aMessage*/ )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::RemoveReaderEventListener|Begin"));
+
+    TInt notifierCount = iNotifiers->Count();
+
+    _WIMTRACE2(_L("WIM|Scard|CScardNotifyRegistry::RemoveReaderEventListener|Notifier count=%d"), notifierCount);
+
+    //Delete all but our own listener which is the first
+    for ( TInt i( 1 ); i < notifierCount; i++ )
+        {
+        CScardNotifier* notifier = (*iNotifiers)[i];
+        delete notifier;
+        iNotifiers->Delete( i );
+        break;
+        }
+    _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::RemoveReaderEventListener|END"));
+
+    }
+
+// -----------------------------------------------------------------------------
+// CScardNotifyRegistry::AddReaderEventListenerL
+// Add new event listener
+// -----------------------------------------------------------------------------
+//
+void CScardNotifyRegistry::AddReaderEventListenerL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::AddReaderEventListenerL|Begin"));
+
+    RMessage2 message( aMessage );
+    // extract the TRequestStatus from message
+    TPckgBuf<TRequestStatus*> pckg;
+
+    aMessage.ReadL( 0, pckg );
+
+    TRequestStatus* status = pckg();
+    _WIMTRACE2(_L("WIM|Scard|CScardNotifyRegistry::AddReaderEventListenerL|status=%d"), status);
+    
+    //  extract the reader's friendly name
+    TScardReaderName name;
+    aMessage.ReadL( 1, name );
+
+    const TReaderID readerID = iServer->ReaderID( name );
+
+    if ( !readerID )
+        {
+        aMessage.Complete( KScErrUnknownReader );
+        _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::AddReaderEventListenerL|Leave"));
+        User::Leave( KScErrNotSupported );
+        }
+
+    // add item to listener table
+    CScardNotifier* notifier2 = CScardNotifier::NewL( this,
+                                                      message,
+                                                      status,
+                                                      readerID );
+    CleanupStack::PushL( notifier2 );
+    iNotifiers->AppendL( notifier2 );
+    CleanupStack::Pop( notifier2 );
+    _WIMTRACE(_L("WIM|Scard|CScardNotifyRegistry::AddReaderEventListenerL|End"));
+    }
+
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardReaderQuery.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,107 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This class returns all supported readers and reader groups.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardBase.h"
+#include    "ScardReaderQuery.h"
+#include    "WimTrace.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardReaderQuery::CScardReaderQuery
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardReaderQuery::CScardReaderQuery()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CScardReaderQuery::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardReaderQuery::ConstructL( )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderQuery::ConstructL|Begin"));
+    }
+    
+// -----------------------------------------------------------------------------
+// CScardReaderQuery::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScardReaderQuery* CScardReaderQuery::NewL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderQuery::NewL|Begin"));
+    CScardReaderQuery* self = new( ELeave ) CScardReaderQuery;
+    
+    CleanupStack::PushL( self );
+    //  ReaderQuery does not need writing access
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+EXPORT_C CScardReaderQuery::~CScardReaderQuery()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderQuery::~CScardReaderQuery|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardReaderQuery::ListReadersL
+// List card readers belonging to given group
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CScardReaderQuery::ListReadersL(
+    CArrayFixFlat<TScardReaderName>* aReaderList,
+    const TScardReaderName& aGroupName )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderQuery::ListReadersL|Begin"));
+    TScardReaderName groupName( KGroupName );
+
+    if ( !aGroupName.Compare( groupName ) ) //Check if group name is as given
+        {
+        TScardReaderName readerName( KReaderName );
+        aReaderList->AppendL( readerName );
+        }
+    else // Group name is not what we expected 
+        {
+        User::Leave( KScErrNotSupported );
+        }
+    }
+// -----------------------------------------------------------------------------
+// CScardReaderQuery::ListGroupsL
+// List reader groups supported by Scard
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CScardReaderQuery::ListGroupsL(
+   CArrayFixFlat<TScardReaderName>* aGroupList )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderQuery::ListGroupsL|Begin"));
+    TScardReaderName groupName( KGroupName );
+    aGroupList->AppendL( groupName );
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardReaderRegistry.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,348 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Registry of Smart Card readers
+*
+*/
+
+
+
+// INCLUDE FILES
+
+#include    "ScardReaderRegistry.h"
+#include    "ScardReaderLauncher.h"
+#include    "ScardServer.h"
+#include    "ScardAccessControlRegistry.h"
+#include    "WimTrace.h"
+
+#ifdef _DEBUG // for logging
+#include    "ScardLogs.h"
+#include    <flogger.h> 
+#endif
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// TLauncherStruct::TLauncherStruct
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+TLauncherStruct::TLauncherStruct()
+    : iGroupID( 0 ),
+      iReaderID( 0 ),
+      iLauncher( NULL ) 
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CScardReaderRegistry::CScardReaderRegistry
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardReaderRegistry::CScardReaderRegistry( CScardServer* aServer )
+    : iServer( aServer ),
+      iLaunchersInUse( NULL )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderRegistry::CScardReaderRegistry|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardReaderRegistry::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardReaderRegistry::ConstructL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderRegistry::ConstructL|Begin"));
+    iLaunchersInUse = new( ELeave ) CArrayFixFlat<TLauncherStruct>( 1 );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardReaderRegistry::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardReaderRegistry* CScardReaderRegistry::NewL( 
+    CScardServer *aServer )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderRegistry::NewL|Begin"));
+    CScardReaderRegistry* self = new( ELeave ) CScardReaderRegistry( aServer );
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CScardReaderRegistry::~CScardReaderRegistry()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderRegistry::~CScardReaderRegistry|Begin"));
+    //  remove all currently used readers
+    while ( iLaunchersInUse->Count() )
+        {
+        delete (*iLaunchersInUse)[0].iLauncher;
+        (*iLaunchersInUse)[0].iLibrary.Close();
+        (*iLaunchersInUse)[0].iSession.Close();
+        iLaunchersInUse->Delete( 0 );
+        }
+
+    delete iLaunchersInUse;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CScardReaderRegistry::ReaderID
+// Get ID for name
+// -----------------------------------------------------------------------------
+//
+TReaderID CScardReaderRegistry::ReaderID(
+    const TScardReaderName& aReaderName )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderRegistry::ReaderID|Begin"));
+    TReaderID readerID( 0 );
+
+    TScardReaderName readerName( KReaderName ); //Only supported is "SwimReader"
+
+    if ( aReaderName.Compare( readerName ) ) //Compare names
+        {
+        readerID = 0; //Not equal
+        }
+    else
+        {
+        readerID = KReaderID;
+        }
+
+    return readerID;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardReaderRegistry::CloseReaderL
+// Unload the reader module with given ID. Also unloads the launcher 
+// module if it's no longer needed
+// -----------------------------------------------------------------------------
+//
+void CScardReaderRegistry::CloseReader( const TReaderID aReaderID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderRegistry::CloseReaderL|Begin"));
+    //  first retrieve the launcher structure
+    TLauncherStruct launcher;
+    TInt index( 0 );
+    for ( ; index < iLaunchersInUse->Count(); index++ )
+        {
+        if ( iLaunchersInUse->At( index ).iReaderID == aReaderID )
+            {
+            launcher = iLaunchersInUse->At( index );
+            break;
+            }
+        }
+
+    //  Couldn't find it!! (So assume it's closed ok)
+    if ( index >= iLaunchersInUse->Count() )
+        {
+        return;
+        }
+
+    //  Instuct the launcher to cleanup the reader..
+    launcher.iLauncher->DeleteReader( aReaderID );
+
+    //  ..and never mind any error codes, just close the library...
+    delete launcher.iLauncher;
+    launcher.iLibrary.Close();
+    launcher.iSession.Close();
+    
+    //  Finally remove the launcher from our records
+    iLaunchersInUse->Delete( index );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardReaderRegistry::IsSupported
+// Is the given reader supported
+// -----------------------------------------------------------------------------
+//
+TBool CScardReaderRegistry::IsSupported(
+    const TScardReaderName& aReaderName )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderRegistry::IsSupported|Begin"));
+    TScardReaderName readerName( KReaderName ); //Only supported is "SwimReader"
+
+    if ( aReaderName.Compare( readerName ) ) //Compare names
+        {
+        return EFalse;
+        }
+    else
+        {
+        return ETrue;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardReaderRegistry::ListOpenReaders
+// List all open readers
+// -----------------------------------------------------------------------------
+//
+void CScardReaderRegistry::ListOpenReadersL(
+    CArrayFix<CScardAccessControl*>* aACList )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderRegistry::ListOpenReadersL|Begin"));
+    CScardAccessControl* ac =
+        iServer->AccessRegistry()->FindAccessController( KReaderID );
+    if ( ac )
+        {
+        aACList->AppendL( ac );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardReaderRegistry::ListClosedReaders
+// List closed readers
+// -----------------------------------------------------------------------------
+//
+void CScardReaderRegistry::ListClosedReadersL( CArrayFix<TReaderID>* aIDList )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderRegistry::ListClosedReadersL|Begin"));
+    // See if it has already an access controller (aka it's been opened already)
+    CScardAccessControl* ac = 
+        iServer->AccessRegistry()->FindAccessController( KReaderID );
+    if ( !ac )
+        {
+        aIDList->AppendL( KReaderID );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardReaderRegistry::FriendlyName
+// Get friendly name of reader
+// -----------------------------------------------------------------------------
+//
+const TScardReaderName CScardReaderRegistry::FriendlyName(
+    const TReaderID aReaderID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderRegistry::FriendlyName|Begin"));
+    TScardReaderName name;
+    if ( aReaderID == KReaderID ) //Only supported is 1
+        {
+        name.Copy( KReaderName );
+        }
+    return name;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CScardReaderRegistry::LoadReaderL
+// Load reader
+// -----------------------------------------------------------------------------
+//
+MScardReader* CScardReaderRegistry::LoadReaderL( const TReaderID aReaderID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderRegistry::LoadReaderL|Begin"));
+    TGroupID groupID( 0 );
+    if ( aReaderID == KReaderID )
+        {
+        groupID = KGroupID;
+        }
+
+    //  load the group launcher's module
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L("CScardReaderRegistry::LoadReaderL loading launcher module...\n") );
+#endif
+    MScardReaderLauncher* launcher = NULL;
+    
+    launcher = LoadFactoryModuleL( groupID, aReaderID );
+
+    MScardReader* reader = NULL;
+
+    //  create the reader
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CScardReaderRegistry::LoadReaderL creating reader...\n" ) );
+#endif
+    reader = (/*(CSwimReaderLauncher*)*/launcher)->CreateReaderL( aReaderID );
+
+    return reader;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardReaderRegistry::LoadFactoryModuleL
+// Load factory module (SwimReader.dll)
+// -----------------------------------------------------------------------------
+//
+MScardReaderLauncher* CScardReaderRegistry::LoadFactoryModuleL(
+    const TGroupID aGroupID, 
+    const TReaderID aReaderID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardReaderRegistry::LoadFactoryModuleL|Begin"));
+    //Check ID's, only supported ID's in Series 60 are
+    // KGroupID and KReaderID
+    if ( aGroupID != KGroupID || aReaderID != KReaderID )
+        {
+        User::Leave( KErrArgument );
+        }
+    TLauncherStruct launcher;
+    launcher.iGroupID = KGroupID; //This is always 1
+    launcher.iReaderID = KReaderID; //This is always 1
+    launcher.iSession.Connect();
+
+    User::LeaveIfError( launcher.iLibrary.Load( KSwimReaderDLL ) );
+
+    //  Create the actual CScardReaderLauncher object
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CScardReaderRegistry::LoadFactoryModuleL creating\
+        CScardReaderLauncher object...\n" ) );
+#endif
+    TLibraryFunction entry = launcher.iLibrary.Lookup( 1 );
+
+    if ( entry ) // entry found
+        {
+        launcher.iLauncher = reinterpret_cast< MScardReaderLauncher* >
+                                ( entry() );
+        }
+        else
+        {
+        //delete launcher.iLauncher; // (?) why delete
+        launcher.iLibrary.Close();
+        launcher.iSession.Close();
+        User::Leave( KErrNotFound );
+        }
+
+    //  Initialise the launcher and append it to the list
+#ifdef _DEBUG    
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CScardReaderRegistry::LoadFactoryModuleL initialising\
+        launcher...\n" ) );
+#endif
+    TRAPD( initialisationError, launcher.iLauncher->ConstructL( 
+        iServer->ReaderService() ) );
+    if ( initialisationError )
+        {
+        delete launcher.iLauncher;
+        launcher.iLibrary.Close();
+        launcher.iSession.Close();
+        User::Leave( initialisationError );
+        }
+
+    iLaunchersInUse->AppendL( launcher );
+    return launcher.iLauncher;
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardResourceRegistry.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,129 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Registry of smart card resources
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardResourceRegistry.h"
+#include    "ScardServer.h"
+#include    "WimTrace.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardResourceRegistry::CScardResourceRegistry
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardResourceRegistry::CScardResourceRegistry()
+    : iServer( NULL )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardResourceRegistry::CScardResourceRegistry|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardResourceRegistry::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardResourceRegistry::ConstructL( CScardServer* aServer )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardResourceRegistry::ConstructL|Begin"));
+    iServer = aServer;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardResourceRegistry::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardResourceRegistry* CScardResourceRegistry::NewL( CScardServer* aServer )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardResourceRegistry::NewL|Begin"));
+    CScardResourceRegistry* self = new( ELeave ) CScardResourceRegistry;
+    
+    CleanupStack::PushL( self );
+    self->ConstructL( aServer );
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CScardResourceRegistry::~CScardResourceRegistry()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardResourceRegistry::~CScardResourceRegistry|Begin"));
+    }
+
+
+// -----------------------------------------------------------------------------
+// CScardResourceRegistry::CardEventL
+// If a card is inserted / removed, we need to update the list of cards in use
+// -----------------------------------------------------------------------------
+//
+void CScardResourceRegistry::CardEvent(
+    const TScardServiceStatus aEvent, 
+    const TReaderID aReaderID )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardResourceRegistry::CardEventL|Begin"));
+    //  First get the access controller for the reader
+    CScardAccessControl* control = iServer->FindAccessControl( aReaderID );
+
+    // Due to asynchronity, some readers may have closed before the events 
+    // are processed
+    if ( !control )
+        {
+        return;
+        }
+
+    //  Then the actual reader
+    MScardReader* reader = control->Reader();
+    __ASSERT_ALWAYS( reader, User::Panic( _L( "Unknown reader" ), 
+        KScServerPanicBadRequest ) );
+
+    switch ( aEvent )
+        {
+        case EScardRemoved: // Flow through 
+        case EReaderRemoved:
+            {
+            TScardATR atr;
+
+            //  Inform the sessions attached to the reader
+            control->CardEvent( aEvent, atr );
+
+            break;
+            }
+        case EScardInserted:
+            {
+            //  A new card was inserted, so get the atr bytes
+            TScardATR atr;
+            TInt err = reader->GetATR( atr );
+            if ( !err )
+                {
+                }
+            //  Inform sessions
+            control->CardEvent( aEvent, atr );
+            break;
+            }
+        default:
+            break;
+        }
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardServer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,254 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Smart card server
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardBase.h"
+#include    "ScardClsv.h"
+#include    "ScardServerBase.h"
+#include    "ScardServer.h"
+#include    "WimTrace.h"
+
+// MODULE DATA STRUCTURES
+struct TThreadParameter
+    {
+    RSemaphore  iSemaphore;
+    TInt        iPanicCode;
+    };
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardServer::CScardServer
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardServer::CScardServer()
+    : CServer2( EPriorityStandard )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardServer::CScardServer|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardServer::ConstructL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardServer::ConstructL|Begin"));
+    iNotifyRegistry = CScardNotifyRegistry::NewL( this );
+    iControlRegistry = CScardAccessControlRegistry::NewL( this );
+    iReaderFactoryRegistry = CScardReaderRegistry::NewL( this );
+    iResourceRegistry = CScardResourceRegistry::NewL( this );
+    iConnectionRegistry = CScardConnectionRegistry::NewL( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardServer* CScardServer::NewL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardServer::NewL|Begin"));
+    CScardServer* self = new( ELeave ) CScardServer;
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    TPtrC tempName;
+    tempName.Set( KScardServerName );
+    HBufC* pName = tempName.Alloc();
+    //Again these panics EPR
+    __ASSERT_ALWAYS( pName,
+        PanicServer( KScServerPanicSvrCreateServer ) );
+    
+    self->iName = pName; // Ownership moves
+
+    // Start the server
+    TPtr name = self->iName->Des();     
+    TInt r = self->Start( name );
+    __ASSERT_ALWAYS( r == KErrNone,
+        PanicServer( KScServerPanicSvrCreateServer ) );
+
+    return self;
+    }
+
+    
+// Destructor
+CScardServer::~CScardServer()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardServer::~CScardServer|Begin"));
+    delete iNotifyRegistry;
+    delete iControlRegistry;
+    delete iReaderFactoryRegistry;
+    delete iResourceRegistry;
+    delete iConnectionRegistry;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CScardServer::PanicServer
+// Panics the server
+// -----------------------------------------------------------------------------
+//
+void CScardServer::PanicServer( const TInt aPanic )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardServer::PanicServer|Begin"));
+    User::Panic( _L( "ScardServer" ), aPanic );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::NewSessionL
+// Create a new client session for this server.
+// -----------------------------------------------------------------------------
+//
+CSession2* CScardServer::NewSessionL(
+    const TVersion& aVersion, const RMessage2& /*aMessage*/ ) const
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardServer::NewSessionL|Begin"));
+    // check version is ok
+    TVersion v( KScardServMajorVersionNumber, KScardServMinorVersionNumber, 
+        KScardServBuildVersionNumber );
+    if ( !User::QueryVersionSupported( v, aVersion ) )
+        {
+        User::Leave( KErrNotSupported );
+        }
+
+    // make new session
+    return CScardSession::NewL( const_cast< CScardServer* >( this ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardServer::ThreadFunction
+// Start active scheduler and do other new thread things
+// -----------------------------------------------------------------------------
+//
+GLDEF_C TInt CScardServer::ThreadFunction( TAny* aStarted )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardServer::ThreadFunction|Begin"));
+    //  convert argument to initial data
+    TThreadParameter& data = *(static_cast< TThreadParameter* >( aStarted ) );
+    RSemaphore& started = data.iSemaphore;
+
+    data.iPanicCode = KErrNone;
+    
+    // create cleanup stack
+    if ( !CTrapCleanup::New() )
+        {
+        data.iPanicCode = KScServerPanicCreateTrapCleanup;
+        started.Signal();
+        PanicServer( KScServerPanicCreateTrapCleanup );
+        }
+
+    // construct and install active scheduler
+    if ( !CActiveScheduler::Current() ) //Check if scheduler already started
+        {
+        CActiveScheduler* scheduler = new CActiveScheduler;
+        if ( !scheduler )
+            {
+            data.iPanicCode = KScServerPanicMainSchedulerError;
+            started.Signal();
+            PanicServer( KScServerPanicMainSchedulerError );
+            }
+        CActiveScheduler::Install( scheduler );
+        }
+    // construct server, an active object
+    TRAPD( err, CScardServer::NewL() );
+
+    if ( err )
+        {
+        data.iPanicCode = KScServerPanicSvrCreateServer;
+        started.Signal();
+        PanicServer( KScServerPanicSvrCreateServer );
+        }
+
+    // signal everything has started
+    started.Signal(); // now started ok
+
+    // start handling requests
+    CActiveScheduler::Start();
+    return KErrNone;
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// StartThread Starts the server thread.
+// Returns: TInt:   error code
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt StartThread()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardServer::StartThread|Begin"));
+    TInt res = KErrNone;
+
+    // check server not already started
+    TFindServer findSCardServer( KScardServerName );
+    TFullName name;
+    if ( findSCardServer.Next( name ) != KErrNone )
+        {
+        // create server thread
+        RThread thread;
+        TThreadParameter threadData;
+        threadData.iSemaphore.CreateLocal( 0 );
+
+        res = thread.Create(
+            KScardServerName, // name of thread
+            CScardServer::ThreadFunction, // thread function
+            KDefaultStackSize,
+            KDefaultMinHeapSize,
+            KDefaultMaxHeapSize,
+            &threadData // parameter to thread function
+            );
+
+        //  If creation was successful, try starting the server
+        if ( res == KErrNone )
+            {
+            // now start thread
+            thread.SetPriority( EPriorityNormal ); // set its priority
+            thread.Resume(); // kick it into life
+            threadData.iSemaphore.Wait(); // wait until it's got going
+
+            if ( threadData.iPanicCode )   
+                {
+                //  The server did not start properly
+                thread.Kill( threadData.iPanicCode );
+                res = threadData.iPanicCode; // set the response
+                return res;
+                }
+
+            // tidy up
+            thread.Close(); // no longer interested in that thread
+            }
+        else
+            {
+            thread.Close();         
+            }
+
+        threadData.iSemaphore.Close(); // or semaphore
+        }
+
+    // all well
+    return res;
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/Scard/src/ScardSession.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1126 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Session for the Scard server, to a single client-side session
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardBase.h"
+#include    "ScardReader.h"
+#include    "ScardClsv.h"
+#include    "ScardNotifyRegistry.h"
+#include    "ScardSession.h"
+#include    "ScardServer.h"
+#include    "ScardAccessControl.h"
+#include    "WimTrace.h"
+
+#ifdef _DEBUG // for logging
+#include    "ScardLogs.h"
+#include    <flogger.h> 
+#endif
+
+// LOCAL CONSTANTS AND MACROS
+const TInt KResponseLengthCloseChannel = 0;
+const TInt KResponseLengthOpenChannel  = 1;
+const TInt KCommandLengthCloseChannel  = 4;
+const TInt KCommandLengthOpenChannel   = 6;
+
+// Assert that the channel has been opened for this session, and if not, leave
+#define __ASSERT_CHANNEL_OPEN( a ) TRAPD( channelClosed,\
+                    iAccessCtrl->ValidateChannelL( ( a ), iSessionID ) );\
+                    if ( channelClosed )\
+                        {\
+                        aMessage.Complete( KScServerErrIllegalChannel );\
+                        return;\
+                        }
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScardSession::CScardSession
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CScardSession::CScardSession()
+    : CSession2()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::CScardSession|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CScardSession::ConstructL( CScardServer* aServer )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::ConstructL|Begin"));
+    iServer         = aServer;
+    iNotifyRegistry = iServer->NotifyRegistry();
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CScardSession* CScardSession::NewL( CScardServer* aServer )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::NewL|Begin"));
+    CScardSession* self = new( ELeave ) CScardSession;
+    
+    CleanupStack::PushL( self );
+    self->ConstructL( aServer );
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+// Destructor
+CScardSession::~CScardSession()
+    {
+    DeleteBuffers();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CScardSession::ServiceL
+// Handle the client message
+// -----------------------------------------------------------------------------
+//
+void CScardSession::ServiceL( const TMessageHandle& aMessageHandle )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::ServiceL|Begin"));
+    ServiceL( aMessageHandle.iMessage );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::CloseSession
+// Clean up the reader event listeners
+// -----------------------------------------------------------------------------
+//
+void CScardSession::CloseSession( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::CloseSession|Begin"));
+    if ( iAccessCtrl && iAccessCtrl->IsAttached( this ) )
+        {
+        iAccessCtrl->DetachSessionFromReader( iSessionID );
+        }
+
+    RThread client;
+    aMessage.Client( client );
+    iNotifyRegistry->RemoveReaderEventListeners( client );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::AsynchronousServiceComplete
+// An asynchronous service has been completed by the reader.
+// -----------------------------------------------------------------------------
+//
+void CScardSession::AsynchronousServiceComplete(
+    const TMessageHandle& aMessageHandle, 
+    const TInt aErrorCode )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::AsynchronousServiceComplete|Begin"));
+    const RMessage2& aMessage = aMessageHandle.iMessage;
+    //  In all cases, if the operation has encountered a problem, ignore 
+    //  results and just complain to the client that something went wrong.
+    if ( aErrorCode != KErrNone )
+        {
+#ifdef _DEBUG
+         RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardSession::AsynchronousServiceComplete ERROR: %d.\n" ),
+            aErrorCode );
+#endif
+
+        DeleteBuffers();
+        aMessage.Complete( aErrorCode );
+        return;
+        }
+
+    //  Now, see what got serviced
+    _WIMTRACE2(_L("WIM|Scard|CScardSession::AsynchronousServiceComplete|Event=%d"), aMessage.Function());
+    switch ( aMessage.Function() )
+        {
+        case EScardServerTransmitToCard:
+            {
+#ifdef _DEBUG
+             RFileLogger::Write( KScardLogDir, KScardLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "Transmit to card completed.\n" ) );
+#endif
+            //  Write response to client and cleanup
+            WriteToClient( aMessage, *iResponse, 1 );
+            DeleteBuffers();
+            aMessage.Complete( KErrNone );
+            break;
+            }
+
+        case EScardServerGetCapabilities:
+            {
+#ifdef _DEBUG
+             RFileLogger::Write( KScardLogDir, KScardLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "Get capabilities completed.\n" ) );
+#endif
+            //  Write response to client and cleanup
+            WriteToClient( aMessage, *iResponse, 2 );
+            DeleteBuffers();
+            aMessage.Complete( KErrNone );
+            break;
+            }
+
+        case EScardServerManageChannel:
+            {
+#ifdef _DEBUG
+             RFileLogger::Write( KScardLogDir, KScardLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "Manage channel completed.\n" ) );
+#endif
+
+            //  Which type of channel management got serviced?
+            switch ( aMessage.Int0() )
+                {
+                case EOpenAnyChannel:
+                    {
+                    //  Was there a proper response 
+                    //  (aka. the command was successful)
+                    if ( iResponse->Length() == KOpenChannelResponseLength )
+                        {
+                        //  Add this session to the newly opened channel
+                        TBool ok( EFalse );
+                        TRAPD( mem, ok = iAccessCtrl->AddSessionToChannelL( 
+                            (*iResponse)[0], iSessionID ) ); 
+                        __ASSERT_MEMORY( mem );
+                        if ( !ok )
+                            {
+                            aMessage.Complete( KScErrNotSupported );
+                            return;
+                            }
+                        }
+                    //  Then write the card's response back to the client 
+                    //  and cleanup
+                    WriteToClient( aMessage, *iResponse, 1 );
+                    DeleteBuffers();                    
+                    aMessage.Complete( KErrNone );
+                    break;
+                    }
+                case ECloseChannel:
+                    {
+                    //  Channel closed, OK
+                    aMessage.Complete( KErrNone );
+                    DeleteBuffers();
+                    break;
+                    }
+                default:
+                    {
+                    break;
+                    }
+                }
+            return;
+            }
+
+        default:
+            {
+            User::Panic( _L( "Message Stack Corrupted" ), 
+                KScServerPanicInternalError );
+            break;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::ServiceL
+// Message handler for the session.
+// Dispatches requests to the appropriate handler
+// Trap harness for dispatcher
+// -----------------------------------------------------------------------------
+//
+void CScardSession::ServiceL( const RMessage2& aMessage )
+    {
+    _WIMTRACE2(_L("WIM|Scard|CScardSession::ServiceL|Begin|Event=%d"), aMessage.Function());
+    //  Divide the operation to the handler functions
+    switch ( aMessage.Function() )
+        {
+        //  These functions are synchronous, and don't use message stack,
+        //  so we can complete the messages here.
+        case EScardServerNotifyChange:
+            {
+            iNotifyRegistry->AddReaderEventListenerL( aMessage );
+            // Does not complete message because it is completed when card
+            // event occurs
+            break;
+            }
+        case EScardServerCancelNotifyChange:
+            {
+            iNotifyRegistry->RemoveReaderEventListener( aMessage );
+            aMessage.Complete( KErrNone );
+            break;
+            }
+        case EScardServerCloseSession:
+            {
+            CloseSession( aMessage );
+            aMessage.Complete( KErrNone );
+            break;
+            }
+        case EScardServerDisconnectFromReader:
+            {
+            DisconnectFromReader();
+            aMessage.Complete( KErrNone );
+            break;
+            }
+        case EScardServerCancelTransmit:
+            {
+            CancelTransmitL();
+            aMessage.Complete( KErrNone );
+            break;
+            }
+        //  These functions are asynchronous, and (may) put their messages
+        //  in the message stack, so they do completion internally.
+        case EScardServerConnectToReader:
+            {
+            TInt desLen = aMessage.GetDesMaxLength( 1 );
+            _WIMTRACE2(_L( "WIM|Scard|EScardServerConnectToReader desLen %d" ), desLen );
+            if ( desLen <= 0 )
+               {
+               _WIMTRACE(_L(" WIM|Scard|EScardServerConnectToReader Descriptor is bad"));
+               aMessage.Panic( _L( "ScardServer" ), KErrBadDescriptor );
+               break;
+               }
+            ConnectToReaderL( aMessage );
+            break;
+            }
+         case EScardServerGetATR:
+            {
+            aMessage.Complete( KErrNotSupported );
+            break;
+            }
+        case EScardServerTransmitToCard:
+            {
+            TransmitToCard( aMessage );
+            break;
+            }
+        case EScardServerGetCapabilities:
+            {
+            GetCapabilities( aMessage );
+            break;
+            }
+        case EScardServerManageChannel:
+            {
+            ManageChannel( aMessage );
+            break;
+            }
+        
+        //  A corrupt request
+        default:
+            aMessage.Panic( _L( "ScardServer" ), KScServerPanicBadRequest );
+            break;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::ConnectToReaderL
+// Ask Access Control to add this session to registry, and update session ID
+// -----------------------------------------------------------------------------
+//
+void CScardSession::ConnectToReaderL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::ConnectToReaderL|Begin"));
+#ifdef _DEBUG
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend,
+        _L( "CScardSession::ConnectToReaderL entered.\n" ) );
+#endif
+    //  If already connected, what more could the client want??
+    if ( iConnectedToReader )
+        {
+#ifdef _DEBUG
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+         EFileLoggingModeAppend, 
+         _L( "CScardSession::ConnectToReaderL FAILED: already connected.\n" ) );
+#endif
+        aMessage.Complete( KScErrAlreadyExists );
+        return;
+        }
+    // Store client thread from message to member to be used in PanicClient().
+    aMessage.Client( iClient );
+    // If not, get on with it...            
+    iServer->ConnectToReaderL( this, aMessage );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::DisconnectFromReader
+// Ask Access Control to detach this session from the reader.
+// -----------------------------------------------------------------------------
+//
+void CScardSession::DisconnectFromReader()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::DisconnectFromReader|Begin"));
+    //  If connected at all, disconnect
+    if ( iConnectedToReader )
+        {
+        iAccessCtrl->DetachSessionFromReader( iSessionID );
+        iConnectedToReader = EFalse;
+        iAccessCtrl = NULL;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::GetCapabilities
+// Get capabilities of the card
+// -----------------------------------------------------------------------------
+//
+void CScardSession::GetCapabilities( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::GetCapabilities|Begin"));
+    if ( !iConnectedToReader )
+        {
+        aMessage.Panic( _L( "Reader not contacted" ), 
+            KScPanicNoResourceConnection );
+        return;
+        }
+    const TInt8 channel( 0 );
+
+    if ( iAccessCtrl->ReaderIsReady( iSessionID, channel ) )
+        {
+        TRequestStatus& status =
+            iAccessCtrl->InitiateCommunication( iSessionID, aMessage,
+                reinterpret_cast< TInt32>( aMessage.Ptr3() ), channel );
+        __ASSERT_MEMORY( status.Int() );
+        TInt32 commandCode( 0 );
+        commandCode = aMessage.Int1();
+        commandCode |= ( aMessage.Int0() << 8 ) & 0xff00;
+
+        //  Get the response buffer
+        TInt error = AllocateResponse( aMessage, 2 );
+        if ( error )
+            {
+            aMessage.Complete( error );
+            return;
+            }
+
+        TInt32 timeout = reinterpret_cast< TInt32>( aMessage.Ptr3() );
+        //  ...do the control command
+        iReader->GetCapabilities( status, commandCode, *iResponse, timeout );
+        }
+    //  The reader was busy, queue
+    else
+        {
+#ifdef _DEBUG
+        RFileLogger::Write( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L("CScardSession::GetCapabilities()-reader busy, message queued.\n") );
+#endif
+
+        iAccessCtrl->QueueExecution( aMessage, iSessionID,
+            reinterpret_cast< TInt32 >( aMessage.Ptr3() ), channel );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::TransmitToCard
+// Transmit data to the card
+// -----------------------------------------------------------------------------
+//
+void CScardSession::TransmitToCard( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::TransmitToCard|Begin"));
+    if ( !iConnectedToReader )
+        {
+        aMessage.Panic( _L( "Reader not contacted" ), 
+            KScPanicNoResourceConnection );
+        return;
+        }
+
+    // check if this client has the access rights for the reader
+    // and reader is ready
+    const TInt8 channel( static_cast< TInt8>( aMessage.Int3() ) );
+    __ASSERT_CHANNEL_OPEN( channel );
+
+    if ( iAccessCtrl->ReaderIsReady( iSessionID, channel ) )
+        {
+        //  Read the command APDU from the client
+        TInt error = ReadFromClient( aMessage, iCommandBuffer, iCommand, 0 );
+        if ( error )
+            {
+#ifdef _DEBUG
+    RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+        EFileLoggingModeAppend, 
+        _L("CScardSession::TransmitToCard()-Cmd APDU couldn't be read from\
+        client. Error: %d.\n"), error );
+#endif
+            return;
+            }
+
+        //  If the channel number is not the same one as asked for
+        //  in the parameter 3 of the message, adjust the command...
+        if ( ( (*iCommand)[KCLA] & 0x0f) != channel )
+            {
+#ifdef _DEBUG
+            RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L("CScardSession::TransmitToCard() -- Channel changed from %d\
+             to: %d.\n"), (*iCommand)[KCLA] & 0x0f, channel & 0x0f );
+#endif
+            (*iCommand)[KCLA] &= 0xf0;
+            (*iCommand)[KCLA] |= channel;
+            }
+
+        //  No manage channel apdu's are allowed. 
+        //  Use CScardComm::ManageChannel() instead.
+        if ( (*iCommand)[KINS] == KManageChannel )
+            {
+#ifdef _DEBUG
+            RFileLogger::Write( KScardLogDir, KScardLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "CScardSession::TransmitToCard() -- Error! Manage channel\
+                APDU.\n" ) );
+#endif
+            delete iCommand;
+            iCommand = NULL;
+            aMessage.Complete( KScServerErrIllegalOperation );
+            return;
+            }
+
+        //  Alloc response 
+        error = AllocateResponse( aMessage, 1 );
+        if ( error )
+            {
+#ifdef _DEBUG
+            RFileLogger::Write( KScardLogDir, KScardLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "CScardSession::TransmitToCard() -- Could not allocate\
+                response.\n" ) );
+#endif
+            return;
+            }
+
+        //  Transfer APDU
+        TRequestStatus& sr =
+            iAccessCtrl->InitiateCommunication( iSessionID, aMessage,
+                reinterpret_cast< TInt32>( aMessage.Ptr2() ), channel );
+        __ASSERT_MEMORY( sr.Int() );
+        const TInt32 timeout = static_cast< TInt32>( aMessage.Int2() );
+#ifdef _DEBUG
+        RFileLogger::HexDump( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _S( "CScardSession::TransmitToCard() command APDU:\n" ), 0,
+            iCommand->Ptr(), iCommand->Length() );
+#endif
+        iReader->TransmitToCard( sr, *iCommand, *iResponse, timeout );
+        }
+    //  The reader was busy, queue
+    else
+        {
+#ifdef _DEBUG
+        RFileLogger::Write( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardSession::TransmitToCard() -- reader busy. message\
+            queued.\n" ) );
+#endif
+        iAccessCtrl->QueueExecution( aMessage, iSessionID, 
+            static_cast< TInt32>( aMessage.Int2() ), channel );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::CancelTransmit
+// Cancel all transmissions belonging to this session
+// -----------------------------------------------------------------------------
+//
+void CScardSession::CancelTransmitL()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::CancelTransmit|Begin"));
+    // It is not clear if this session is attempting to connect, so cancel any
+    // connection attempts as well... If this session is not connecting at the
+    // moment, this does nothing.
+    iServer->ConnectionRegistry()->CancelConnection( this );
+
+    if ( iAccessCtrl )
+        {
+        //  Cancel from the reader
+        iAccessCtrl->CancelTransmissionsL( iSessionID );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::ManageChannel
+// Manage logical channel
+// -----------------------------------------------------------------------------
+//
+void CScardSession::ManageChannel( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::ManageChannel|Begin"));
+    if ( !iConnectedToReader )
+        {
+        aMessage.Panic( _L( "Reader not contacted" ), 
+            KScPanicNoResourceConnection );
+        return;
+        }
+    
+    const TUint8 maxChannels( 4 );
+
+    //  What exactly does the client want to do?
+    const TInt operationCode = aMessage.Int0();
+    _WIMTRACE2(_L("WIM|Scard|CScardSession::ManageChannel|operationCode=%d"), operationCode);
+    switch ( operationCode )
+        {
+        //  Open a channel and the card will assign the channel number
+        case EOpenAnyChannel:
+            {
+            //  If we're already on all the channels, return error indicating 
+            //  that no more channels are available
+            TBool allOpen( ETrue );
+            TInt8 i( 0 );
+            for ( i = 1; i < maxChannels; i++ )
+                {
+                TRAPD( closed, iAccessCtrl->ValidateChannelL( i, iSessionID ) );
+                if ( closed )
+                    {
+                    allOpen = EFalse;
+                    break;
+                    }
+                }
+            if ( allOpen )
+                {
+#ifdef _DEBUG
+                RFileLogger::Write( KScardLogDir, KScardLogFileName, 
+                    EFileLoggingModeAppend, 
+                    _L( "CScardSession::ManageChannel() -- Open any channel:\
+                    all channels open.\n" ) );
+#endif
+                _WIMTRACE(_L("WIM|Scard|CScardSession::ManageChannel|no more channels available"));
+                aMessage.Complete( KScErrFull );
+                return;
+                }
+
+            //  Check if all channels have already been opened.
+            //  (Of course this session is not yet on all of them)
+            allOpen = ETrue;
+            for ( i = 1 ; i < maxChannels ; i++ ) 
+                {
+                if ( !( iAccessCtrl->ChannelOpenedYet( i ) ) )  
+                    {
+                    allOpen = EFalse;
+                    break;
+                    }
+                }
+
+            //  If all channels have been opened, get the first unreserved
+            //  one and assign the session to it. If no unreserved channels
+            //  are found, put the message on hold for the next available channel.
+            if ( allOpen )
+                {
+                _WIMTRACE(_L("WIM|Scard|CScardSession::ManageChannel|all channels open"));
+                const TInt8 channel = iAccessCtrl->UnreservedLogicalChannel();
+                if ( channel > 0 )
+                    {
+                    _WIMTRACE(_L("WIM|Scard|CScardSession::ManageChannel|unreserved channels found"));
+                    TRAPD( err, iAccessCtrl->AddSessionToChannelL( 
+                        channel, iSessionID ) ); 
+                    __ASSERT_MEMORY( err );
+                    _WIMTRACE(_L("WIM|Scard|CScardSession::ManageChannel|session added to channel"));
+                    aMessage.Complete( KErrNone );
+                    return;
+                    }
+                else
+                    {
+                    _WIMTRACE(_L("WIM|Scard|CScardSession::ManageChannel|no unreserved channels found"));
+                    iAccessCtrl->QueueChannelOperation( aMessage, iSessionID,
+                        reinterpret_cast< TInt32>( aMessage.Ptr2() ),
+                        KAllChannels );
+                    return;
+                    }
+                }
+            _WIMTRACE(_L("WIM|Scard|CScardSession::ManageChannel|some channels not open"));
+            //  The card has logical channels available that have not been 
+            //  yet opened. Make the command and send it to the SC
+            if ( iAccessCtrl->ReaderIsReady( iSessionID, KChannel0 ) )
+                {
+                _WIMTRACE(_L("WIM|Scard|CScardSession::ManageChannel|reader ready"));
+                DoCommandAndTransmit( 
+                    aMessage,
+                    KOpenChannel,
+                    0,
+                    KCommandLengthOpenChannel,
+                    KResponseLengthOpenChannel,
+                    reinterpret_cast< TInt32 >( aMessage.Ptr2() ),
+                    KChannel0 );
+                return;
+                }
+            //  The reader was busy, queue
+            else
+                {
+#ifdef _DEBUG
+                RFileLogger::Write( KScardLogDir, KScardLogFileName, 
+                    EFileLoggingModeAppend, 
+                    _L( "CScardSession::ManageChannel() -- reader busy.\
+                    message queued.\n" ) );
+#endif
+                _WIMTRACE(_L("WIM|Scard|CScardSession::ManageChannel|reader busy"));
+                iAccessCtrl->QueueExecution( aMessage, iSessionID,
+                    reinterpret_cast< TInt32>( aMessage.Ptr2() ), KChannel0 );
+                return;
+                }
+            //break; //unreachable
+            }
+
+        //  Close a channel
+        case ECloseChannel:
+            {
+            const TUint8 channel( static_cast< TUint8>( aMessage.Int1() ) );
+            TBool stillOpen( EFalse );
+            //  Remove this session from the channel
+            TRAPD( err, stillOpen = iAccessCtrl->RemoveSessionFromChannelL( 
+                channel, iSessionID ) );
+            if ( err != KErrNone )
+                {
+#ifdef _DEBUG
+                RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+                    EFileLoggingModeAppend, 
+                    _L( "CScardSession::ManageChannel() -- Close channel:\
+                    Error %d in removing session.\n" ), err );
+#endif
+                aMessage.Complete( err );
+                return;
+                }
+
+            //  If no one else is using the channel send CloseChannel to card
+            if ( !stillOpen )
+                {
+                if ( iAccessCtrl->ReaderIsReady( iSessionID, KChannel0 ) )
+                    {
+                    //  If possible send the close channel APDU
+                    DoCommandAndTransmit( 
+                        aMessage,
+                        KCloseChannel,
+                        channel, 
+                        KCommandLengthCloseChannel,
+                        KResponseLengthCloseChannel,
+                        reinterpret_cast< TInt32>( aMessage.Ptr2() ),
+                        KChannel0 );
+                    return;
+                    }
+
+                //  The reader is busy, queue
+                else
+                    {
+#ifdef _DEBUG
+                    RFileLogger::Write( KScardLogDir, KScardLogFileName, 
+                        EFileLoggingModeAppend, 
+                        _L( "CScardSession::ManageChannel() -- reader busy.\
+                        message queued.\n" ) );
+#endif
+                    iAccessCtrl->QueueExecution( aMessage, iSessionID, 0, 
+                        KChannel0 );
+                    return;
+                    }
+                }
+            //  Some one else is still on the channel, so we can't physically 
+            //  close it from the SC
+            else
+                {
+                aMessage.Complete( KErrNone );
+                return;
+                }
+            //break; //unreachable
+            }
+
+        //  Check channel status
+        case EChannelStatus:
+            {
+            //  Get status
+            TUint16 status = iAccessCtrl->ChannelStatus();
+            TBuf8<2> buf(2);
+            // Split the 16 bit integer to two 8-bit bytes
+            buf[0] = static_cast< TInt8 >( status & 0x00ff );
+            buf[1] = static_cast< TInt8 >( ( status & 0xff00 ) >> 8 );
+
+            //  Inform client
+            WriteToClient( aMessage, buf, 1 );
+            aMessage.Complete( KErrNone );
+            break;
+            }
+        //  Something's gotten warped
+        default:
+            aMessage.Complete( KScErrBadArgument );
+            break;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::DoCommandAndTransmit
+// Create a command APDU for ManageChannel operations, and send it
+// -----------------------------------------------------------------------------
+//
+void CScardSession::DoCommandAndTransmit(
+    const RMessage2& aMessage, 
+    const TUint8 aCommand, 
+    const TUint8 aP2,
+    const TInt8 aCommandLength,
+    const TUint8 aResponseLength, 
+    const TInt32 aTimeOut, 
+    const TUint8 aChannel )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::DoCommandAndTransmit|Begin"));
+
+    TRAPD( memFail, DoCommandAndTransmitL( aMessage,
+                                           aCommand,
+                                           aP2,
+                                           aCommandLength,
+                                           aResponseLength,
+                                           aTimeOut,
+                                           aChannel ) );
+    __ASSERT_MEMORY( memFail );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::DoCommandAndTransmitL
+// Create a command APDU for ManageChannel operations, and send it
+// -----------------------------------------------------------------------------
+//
+void CScardSession::DoCommandAndTransmitL(
+    const RMessage2& aMessage,
+    const TUint8 aCommand,
+    const TUint8 aP2,
+    const TInt8 aCommandLength,
+    const TUint8 aResponseLength,
+    const TInt32 aTimeOut,
+    const TUint8 aChannel )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::DoCommandAndTransmitL|Begin"));
+    TRequestStatus& status = iAccessCtrl->InitiateCommunication( iSessionID,
+        aMessage, aTimeOut, static_cast< TInt8 >( aChannel ) );
+    __ASSERT_MEMORY( status.Int() );
+
+    // allocate and assert the command
+    iCommandBuffer = HBufC8::NewL( aCommandLength );
+    iCommand = new( ELeave ) TPtr8( iCommandBuffer->Des() );
+
+    // Allocate and assert the response
+
+    // response + 2 status bytes
+    iResponseBuffer = HBufC8::NewL( aResponseLength + 2 );
+    iResponse = new( ELeave ) TPtr8( iResponseBuffer->Des() );
+
+    //  Make the command APDU
+    iCommand->SetLength( 4 );
+    (*iCommand)[KCLA] = aChannel;
+    (*iCommand)[KINS] = KManageChannel;
+    (*iCommand)[KP1] = aCommand;
+    (*iCommand)[KP2] = aP2;
+
+    if ( aResponseLength )
+        {
+        //  one byte length
+        iCommand->SetLength( 5 );
+        (*iCommand)[KLcHigh] = aResponseLength;
+        }
+
+    //  Transmit the APDU to the SC
+#ifdef _DEBUG
+    RFileLogger::HexDump( KScardLogDir, KScardLogFileName,
+        EFileLoggingModeAppend,
+        _S( "CScardSession::DoCommandAndTransmit() command APDU:\n" ), 0,
+        iCommand->Ptr(), iCommand->Length() );
+#endif
+
+    iReader->TransmitToCard( status, *iCommand, *iResponse, aTimeOut );
+    _WIMTRACE(_L("WIM|Scard|CScardSession::DoCommandAndTransmitL|End"));
+    return;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::WriteToClient
+// Write the provided descriptor to the client thread, 8 bit version.
+// -----------------------------------------------------------------------------
+//
+void CScardSession::WriteToClient(
+    const RMessage2& aMessage, 
+    const TDesC8& aResponseBuffer, 
+    const TInt aPtrIndex )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::WriteToClient|Begin"));
+
+    TInt desLen = DesLength( aMessage, aPtrIndex, ETrue ); //Len of descriptor;
+
+    //  Make sure there is always enough space for the response
+    __ASSERT_ALWAYS( desLen >= aResponseBuffer.Length(), 
+        aMessage.Panic( _L( "Response space too short" ), 
+            KScServerPanicBadDescriptor ) );
+
+    //  Write
+    TRAPD( desError, aMessage.WriteL( aPtrIndex, aResponseBuffer ) );
+
+    if ( desError )
+        {
+        aMessage.Panic( _L( "ScardServer" ), KScServerPanicBadDescriptor );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::WriteToClient
+// Write the provided descriptor to the client thread, 16 bit version.
+// -----------------------------------------------------------------------------
+//
+void CScardSession::WriteToClient(
+    const RMessage2& aMessage, 
+    const TDesC16& aResponseBuffer, 
+    const TInt aPtrIndex )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::|Begin"));
+    TInt desLen = DesLength( aMessage, aPtrIndex, ETrue ); //Len of descriptor
+    _WIMTRACE2(_L("WIM|Scard|CScardSession:: %d "), desLen );
+    _WIMTRACE2(_L("WIM|Scard|CScardSession:: %d "), aResponseBuffer.Length() );
+
+    //  Make sure there is always enough space for the response
+    __ASSERT_ALWAYS( desLen >= aResponseBuffer.Length(), 
+        aMessage.Panic( _L( "Response space too short" ), 
+            KScServerPanicBadDescriptor ) );
+
+    //  Write
+    TRAPD( desError, aMessage.WriteL( aPtrIndex, aResponseBuffer ) );
+
+    if ( desError )
+        {
+        aMessage.Panic( _L( "ScardServer" ), KScServerPanicBadDescriptor );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::ReadFromClient
+// 8 bit version
+// -----------------------------------------------------------------------------
+//
+TInt CScardSession::ReadFromClient(
+    const RMessage2& aMessage, 
+    HBufC8*& aBuffer, 
+    TPtr8*& aPointer, 
+    const TInt aPtrIndex )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::ReadFromClient|Begin"));
+    TInt desLen = DesLength( aMessage, aPtrIndex, EFalse );
+
+    //  Allocate the buffer and pointer to it
+    TRAPD( memFail, aBuffer = HBufC8::NewL( desLen ) );
+    __ASSERT_MEMORY( memFail );
+
+    aPointer = new TPtr8( aBuffer->Des() );
+    __ASSERT_MEMORY( !aPointer );
+
+    //  Read the descriptor and that's it
+    TRAPD( desError, aMessage.ReadL( aPtrIndex, *aPointer ) );
+    if ( desError )
+        {
+        aMessage.Panic( _L( "ScardServer" ), KScServerPanicBadDescriptor );
+        return KScErrGeneral;
+        }
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::AllocateResponse
+// Allocate space for the internal response buffer. The lenght of the 
+// necessary space is deduced from the message.
+// -----------------------------------------------------------------------------
+//
+TInt CScardSession::AllocateResponse( const RMessage2& aMessage,
+                                      const TInt aPtrIndex )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::AllocateResponse|Begin"));
+    TInt desLen = DesLength( aMessage, aPtrIndex, ETrue ); //Len of descriptor;
+
+    //  If no space is needed, why bother
+    if ( desLen <= 0 )
+        {
+        return -1;
+        }
+
+    //  Allocate and assert the response buffer
+    TRAPD( memFail, AllocateResponseL( desLen ) );
+    __ASSERT_MEMORY( memFail );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::AllocateResponse
+// Allocate space for the internal response buffer. The lenght of the
+// necessary space is deduced from the message.
+// -----------------------------------------------------------------------------
+//
+void CScardSession::AllocateResponseL( TInt aDesLen )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::AllocateResponseL|Begin"));
+
+    //  Allocate the response buffer
+    iResponseBuffer = HBufC8::NewL( aDesLen );
+    iResponse = new( ELeave ) TPtr8( iResponseBuffer->Des() );
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::DeleteBuffers
+// Delete all reserved buffers
+// -----------------------------------------------------------------------------
+//
+void CScardSession::DeleteBuffers()
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::DeleteBuffers|Begin"));
+    delete iCommand; 
+    delete iResponse;
+    iCommand = NULL; 
+    iResponse = NULL;
+    delete iCommandBuffer; 
+    delete iResponseBuffer;
+    iCommandBuffer = NULL; 
+    iResponseBuffer = NULL;
+    _WIMTRACE(_L("WIM|Scard|CScardSession::DeleteBuffers|End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::ConnectionDone
+// Connection has established (maybe with error)
+// -----------------------------------------------------------------------------
+//
+void CScardSession::ConnectionDone(
+    const TReaderID& aReaderID, 
+    const RMessage2& aMessage, 
+    const TInt aErrorCode )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::ConnectionDone|Begin"));
+    //  Connection successfully completed, attach to the reader and write the
+    //  reader's name to the client thread
+    if ( aErrorCode == KErrNone )
+        {
+        iAccessCtrl = iServer->FindAccessControl( aReaderID );
+        __ASSERT_MEMORY( !iAccessCtrl );
+        TRAPD( readerError, iReader = iAccessCtrl->AttachSessionToReaderL(
+            this, iSessionID ) );
+        if ( readerError == KErrNone )
+            {
+            iConnectedToReader = ETrue;
+            TScardReaderName name( iServer->FriendlyName( aReaderID ) );
+            WriteToClient( aMessage, name, 1 );
+            }
+        else 
+            {
+#ifdef _DEBUG
+            RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "CScardSession::ConnectionDone() -- Error %d when attaching\
+                session to reader: \n" ), readerError );
+#endif
+            iConnectedToReader = EFalse;
+            }
+        }
+    //  No connection could be established
+    else
+        {
+#ifdef _DEBUG
+        RFileLogger::WriteFormat( KScardLogDir, KScardLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CScardSession::ConnectionDone() -- ERROR: %d.\n" ), 
+            aErrorCode );
+#endif
+        iConnectedToReader = EFalse;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::DesLength
+// Return length of descriptor in client message
+// -----------------------------------------------------------------------------
+//
+TInt CScardSession::DesLength(
+    const RMessage2& aMessage,
+    const TInt aPtrIndex,
+    const TBool aMaxLength )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::DesLength|Begin"));
+    TInt desLen( 0 );
+
+    if ( aMaxLength ) //Get max length
+        {
+        desLen = aMessage.GetDesMaxLength( aPtrIndex );
+        }
+    else
+        {
+        desLen = aMessage.GetDesLength( aPtrIndex );
+        }
+
+    return desLen;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::MessagePointer
+// Return pointer to wanted block of client message 
+// -----------------------------------------------------------------------------
+//
+TAny* CScardSession::MessagePointer(
+    const RMessage2& aMessage,
+    const TInt aPtrIndex )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::MessagePointer|Begin"));
+    TAny* messagePointer = NULL;
+    
+    //  See from which pointer we are reading and set parameters accordingly
+    switch ( aPtrIndex )
+        {
+        case 0:
+            {
+            messagePointer = ( TAny* )aMessage.Ptr0();
+            break;
+            }
+        case 1:
+            {
+            messagePointer = ( TAny* )aMessage.Ptr1();
+            break;
+            }
+        case 2:
+            {
+            messagePointer = ( TAny* )aMessage.Ptr2();
+            break;
+            }
+        case 3:
+            {
+            messagePointer = ( TAny* )aMessage.Ptr3();
+            break;
+            }
+        default:
+            {
+            User::Panic( _L( "Bad index" ), KScServerPanicInternalError );
+            }
+        }
+    return messagePointer;
+    }
+
+// -----------------------------------------------------------------------------
+// CScardSession::CardEvent
+// This is here only for derivative class CScardConnector
+// It implements and needs this function
+// -----------------------------------------------------------------------------
+//
+void CScardSession::CardEvent(
+    const TScardServiceStatus, 
+    const TScardATR&, 
+    const TReaderID& )
+    {
+    _WIMTRACE(_L("WIM|Scard|CScardSession::CardEvent|Begin"));
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/EABI/SwimReaderU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,11 @@
+EXPORTS
+	_Z11NewServiceLv @ 1 NONAME
+	_ZTI11CSwimReader @ 2 NONAME DATA 12 ; #<TI>#
+	_ZTI13CSwimReaderIF @ 3 NONAME DATA 32 ; #<TI>#
+	_ZTI19CSwimReaderLauncher @ 4 NONAME DATA 32 ; #<TI>#
+	_ZTI21CSwimSysAgentObserver @ 5 NONAME DATA 12 ; #<TI>#
+	_ZTV11CSwimReader @ 6 NONAME DATA 32 ; #<VT>#
+	_ZTV13CSwimReaderIF @ 7 NONAME DATA 88 ; #<VT>#
+	_ZTV19CSwimReaderLauncher @ 8 NONAME DATA 48 ; #<VT>#
+	_ZTV21CSwimSysAgentObserver @ 9 NONAME DATA 32 ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/bwins/SWIMREADERU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,4 @@
+EXPORTS
+	?NewServiceL@@YAPAVCSwimReaderLauncher@@XZ @ 1 NONAME ; class CSwimReaderLauncher * NewServiceL(void)
+	?PanicClient@@YAXH@Z @ 2 NONAME ; void PanicClient(int)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/group/SwimReader.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project build file
+*
+*/
+
+
+#include <platform_paths.hrh>
+// Uncomment MACRO and define below to enable trace logging
+//MACRO           __WIM_ENABLE_TRACES
+//#define         __WIM_ENABLE_TRACES
+
+TARGET          SwimReader.dll
+TARGETTYPE      dll
+UID             0x1000086e 0x101F79DF
+
+CAPABILITY      CAP_GENERAL_DLL
+VENDORID        VID_DEFAULT
+
+SOURCEPATH      ../src
+SOURCE          SwimApduReqHeader.cpp
+SOURCE          SwimApduRespHeader.cpp
+SOURCE          SwimLauncher.cpp
+SOURCE          SwimReaderIF.cpp
+SOURCE          SwimEtelApdu.cpp
+SOURCE          SwimReader.cpp
+SOURCE          SwimSysAgentObserver.cpp
+
+USERINCLUDE     ../inc
+USERINCLUDE     ../../inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         etel.lib etelmm.lib // Etel
+LIBRARY         customapi.lib       // CustomAPI
+
+DEBUGLIBRARY    flogger.lib
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/inc/SwimApduReqHeader.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,120 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  SWIM APDU Request header
+*
+*/
+
+
+#ifndef SWIMAPDUREQHEADER_H
+#define SWIMAPDUREQHEADER_H
+
+//  INCLUDES
+#include "SwimReaderConsts.h"
+
+
+// CLASS DECLARATION
+
+/**
+*  Services for creating Request APDU header
+*  Used by class CSwimReader
+*
+*  @lib SwimReader.lib
+*  @since Series60 2.1
+*/
+class TSwimApduReqHeader  
+    {
+    
+    public:  // Constructors and destructor
+
+        /**
+        * C++ default constructor.
+        */
+        TSwimApduReqHeader();
+
+    public: // New functions
+
+        /**
+        * Return APDU data
+        * @return Data
+        */
+        TDes8* Data();
+
+        /**
+        * Set Application type byte
+        * @param aApp Application type
+        * @return void
+        */
+        void SetAppType( TUint8 aApp );
+        
+        /**
+        * Set CardReader byte
+        * @param aCardReader Card reader byte
+        * @return void
+        */
+        void SetCardReader( TUint8 aCardReader );
+        
+        /**
+        * Set header
+        * @param aServiceType Service type
+        * @param aCardReader Card reader
+        * @param aAppType Applicatin type
+        * @param aPaddingByte Padding type
+        * @return void
+        */
+        void SetHeader( TUint8 aServiceType = KSendApdu,
+                        TUint8 aCardReader = KNoPreferredReader,
+                        TUint8 aAppType = KAPDUAppTypeWIM,
+                        TUint8 aPaddingByte = 0 );
+
+        /**
+        * operator=
+        * @param aData
+        * @return void
+        */
+        void operator=( const TDesC8& aData );
+        
+        /**
+        * Return Padding Byte
+        * @return Padding Byte
+        */
+        TUint8 PaddingByte();
+        
+        /**
+        * Return ServiceType byte
+        * @return Service Type
+        */
+        TUint8 ServiceType();
+        
+        /**
+        * Set PaddingByte
+        * @param aPaddingByte Padding type
+        * @return void
+        */
+        void SetPaddingByte( TUint8 aPaddingByte );
+        
+        /**
+        * Set ServiceType
+        * @param aServiceType Service type
+        * @return void
+        */
+        void SetServiceType( TUint8 aServiceType );
+        
+    private:  // Data
+        // APDU data
+        TBuf8<KMaxApduHeaderLen> iData;
+    };
+
+#endif      // SWIMAPDUREQHEADER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/inc/SwimApduRespHeader.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  SWIM APDU Response Header
+*
+*/
+
+
+#ifndef SWIMAPDURESPHEADER_H
+#define SWIMAPDURESPHEADER_H
+
+//  INCLUDES
+#include "SwimReaderConsts.h"
+
+// CLASS DECLARATION
+
+/**
+*  Services for parse APDU responce header
+*  Used by class CSwimReader
+*
+*  @lib SwimReader.lib
+*  @since Series60 2.1
+*/
+class TSwimApduRespHeader  
+    {
+    
+    public:  // Constructors and destructor
+
+        /**
+        * C++ default constructor.
+        @ param aData Data
+        */
+        TSwimApduRespHeader( const TDesC8& aData );
+
+    public: // New functions
+
+        /**
+        * operator=
+        * @param aData Data to be assigned
+        * @return void
+        */
+        void operator=( const TDesC8& aData );
+        
+        /**
+        * Return byte in given index
+        * @param aIndex Index of byte
+        * @return TUint8
+        */
+        TUint8 AnyByte( TUint8 aIndex );
+
+        /**
+        * Copy data
+        * @param aData
+        * @return void
+        */
+        void Copy( const TDesC8& aData );
+        
+        /**
+        * Return Data length
+        * @return Data Length
+        */
+        TUint16 DataLength();
+
+        /**
+        * Return Service type byte
+        * @return TUint8
+        */
+        TUint8 ServiceType();
+
+        /**
+        * Return short data length
+        * @return Lenght
+        */
+        TUint8 ShortDataLength();
+        
+        /**
+        * Return Status byte
+        * @return Status byte
+        */
+        TUint8 Status();
+
+    private:  //Data
+        // APDU data
+        TBuf8<KMaxApduHeaderLen> iData;
+    };
+
+#endif      // SWIMAPDURESPHEADER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/inc/SwimEtelApdu.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,106 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Etel references
+*
+*/
+
+
+
+#ifndef ETELAPDU_H
+#define ETELAPDU_H
+
+//  INCLUDES
+#include <rmmcustomapi.h>   // For CustomAPI services
+
+//  CONSTANTS 
+// For logging
+#ifdef _DEBUG
+_LIT( KSwimReaderLogDir, "Scard" );
+_LIT( KSwimReaderLogFileName, "Log.txt" );
+#endif
+
+// FORWARD DECLARATIONS
+class RTelServer;
+
+
+// CLASS DECLARATION
+
+/**
+*  Functionality to send Apdus through Etel
+*  
+*
+*  @lib SwimReader.lib
+*  @since Series60 2.1
+*/
+class RApdu : public RTelSubSessionBase
+    {
+    public: // Constructors and destructor
+    
+        /**
+        * C++ default constructor.
+        */
+        RApdu();
+    
+    public: // New functions
+        
+        /**
+        * Open Etel connection
+        * @param aSession RTelServer session
+        * @param aName    Name of the phone
+        * @return S60 error code
+        */
+        TInt Open( RTelServer& aSession, const TDesC& aName );
+
+        /**
+        * Close connection to Etel server
+        * @return void
+        */
+        void Close();
+        
+        /**
+        * Transmit message through Etel (via CustomAPI)
+        * @param  aStatus Request's status
+        * @param  aMsg    Message to be transmitted
+        * @return void
+        */
+        void APDUReq( TRequestStatus& aStatus, RMmCustomAPI::TApdu& aMsg );
+        
+        /**
+        * Cancel transmit message through Etel (via CustomAPI)
+        * @return void
+        */
+        void CancelAPDUReq();
+        
+    private:
+
+        /**
+        * Symbian 2nd phase constructor
+        */
+        void ConstructL();
+
+        /**
+        * Destruct 
+        * @return void
+        */
+        void Destruct();
+
+    private:    // Data
+        //pointer to customAPI instance. Owned.
+        RMmCustomAPI* iCustomApi;
+        RMobilePhone iPhone;
+    };
+
+#endif      // ETELAPDU_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/inc/SwimLauncher.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,76 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  For launching SwimReader
+*
+*/
+
+
+#ifndef CSWIMREADERLAUNCHER_H
+#define CSWIMREADERLAUNCHER_H
+
+//  INCLUDES
+#include "ScardReaderLauncher.h"
+
+/**
+*  Launcher class
+*  
+*
+*  @lib SwimReader.lib
+*  @since Series60 2.1
+*/
+class CSwimReaderLauncher : public MScardReaderLauncher, public CBase 
+    {
+    public: // Constructors and destructor
+     
+        /**
+        * C++ default constructor.
+        */
+        CSwimReaderLauncher();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSwimReaderLauncher();
+    
+    public: // New functions
+        
+        /**
+        * Symbian 2nd phase constructor
+        */
+        void ConstructL( MScardReaderService* aService );
+
+        /**
+        * Delete reader 
+        * @param  aReader Reader ID to be deleted
+        * @return void
+        */
+        void DeleteReader( TReaderID aReaderID );
+        
+        /**
+        * Create new reader object
+        * @param aReaderID reader's ID 
+        * @return pointer to created Scard reader
+        */    
+        MScardReader* CreateReaderL( TReaderID aReaderID );
+ 
+    private:    // Data
+        // Pointer to reader object. Owned.
+        MScardReader*        iReader;
+        // Pointer to reader service object. Not owned.
+        MScardReaderService* iService;
+    };
+
+#endif      // CSWIMREADERLAUNCHER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/inc/SwimReader.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,247 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  For reading SWIM
+*
+*/
+
+
+#ifndef CSWIMREADER_H
+#define CSWIMREADER_H
+
+//  INCLUDES
+#include "ScardDefs.h"          // KMaxATRHistoricalBytes
+#include "SwimEtelApdu.h"       // RApdu
+#include "SwimReaderConsts.h"
+#include "SwimApduRespHeader.h"
+#include "SwimApduReqHeader.h"
+
+
+//  FORWARD DECLARATIONS
+class CSwimReaderIF;
+
+// CLASS DECLARATION
+
+/**
+*  Functional level of SwimReader
+*  
+*
+*  @lib SwimReader.lib
+*  @since Series60 2.1
+*/
+class CSwimReader : public CActive
+    {
+    public:  // Constructors and destructor
+    
+        /**
+        * Two-phased constructor.
+        * @param aInterface Pointer to SwimReaderIF
+        */
+        static CSwimReader* NewL( CSwimReaderIF* aInterface );
+         
+        /**
+        * Destructor.
+        */
+        virtual ~CSwimReader();
+        
+    public: // New functions
+
+        /**
+        * APDU Request
+        * @param aStatus Status of request
+        * @param aCommandAPDU Command APDU 
+        * @param aResponseAPDU Response APDU
+        * @param aServiceType Service type
+        * @param aCardReader Card reader
+        * @param aAppType Application type
+        * @param aPaddingByte Padding byte
+        * @return
+        */
+        void APDUReqL( TRequestStatus& aStatus,
+                       const TPtrC8& aCommandAPDU,
+                       TPtr8& aResponseAPDU,
+                       TUint8 aServiceType = KSendApdu,
+                       TUint8 aCardReader = KNoPreferredReader,
+                       TUint8 aAppType = KAPDUAppTypeWIM,
+                       TUint8 aPaddingByte = 0 );
+        
+        /**
+        * Close Etel and CustomAPI connection
+        * @return void
+        */
+        void Close();
+        
+        /**
+        * Get preferred reader status from PreferredReaderStatus member
+        * @param aReaderStatus Reader's status
+        * @return void
+        */
+        void PreferredReaderStatus( TUint8& aReaderStatus );
+        
+        /**
+        * From given status bytes, select a card reader,
+        * which is present, and card is also present in the reader.
+        * @param aReaderStatuses Reader statys bytes
+        * @param aPreferredReaderStatus Preferred reader status
+        * @param aOldPreferredReader Old preferred reader
+        * @return Reader number which was selected
+        */
+        static TUint8 SelectCardReader(
+            TDesC8&  aReaderStatuses,
+            TUint8& aPreferredReaderStatus,
+            TUint8  aOldPreferredReader = KNoPreferredReader );
+        
+        /**
+        * Sets iCardInserted member variable according the attribute.
+        * @param aIsInserted is the card inserted (ETrue / EFalse)
+        * @return void
+        */
+        void SetCardInserted( TBool aIsInserted );
+        
+        /**
+        * Initializes the reader. Also make APDU_LIST to get all 
+        * statuses of card readers attached to the device.
+        * @param aStatus Request status
+        * @param aHistoricals Historical ATR bytes
+        * @return void
+        */
+        void WakeUpL( TRequestStatus& aStatus, TDes8& aHistoricals );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        * @param aInterface Pointer to SwimReaderIF
+        */
+        CSwimReader( CSwimReaderIF* aInterface );
+         
+        /**
+        * Symbian 2nd phase constructor.
+        */
+        void ConstructL();
+
+        /**
+        * APDU request
+        * @param aCommandAPDU Command APDU
+        * @param aResponseAPDU Response APDU
+        * @param aServiceType Service type
+        * @param aCardReader Card reader number
+        * @param aAppType Application type
+        * @param aPaddingByte Padding byte
+        * @return void
+        */
+        void APDUReqL( const TPtrC8& aCommandAPDU,
+                       TPtr8& aResponseAPDU,
+                       TUint8 aServiceType = KSendApdu,
+                       TUint8 aCardReader = KNoPreferredReader,
+                       TUint8 aAppType = KAPDUAppTypeWIM,
+                       TUint8 aPaddingByte = 0 );
+
+        /**
+        * APDU request
+        * @param aCommandAPDU Command APDU
+        * @param aResponseAPDU Response APDU
+        * @param aReqHeader APDU request header
+        * @return void
+        */
+        void APDUReqL( const TPtrC8& aCommandAPDU,
+                       TPtr8& aResponseAPDU,
+                       TSwimApduReqHeader& aReqHeader );
+
+        /**
+        * Cleanup all allocated stuff
+        * @return void
+        */
+        void CleanUp();
+        
+        /**
+        * Handle APDU request
+        * @return Scard error code
+        */
+        TInt HandleAPDUReq();
+        
+        /**
+        * Handle open APDU request
+        * @return Scard error code
+        */
+        TInt HandleOpenAPDUReq();
+        
+        /**
+        * From CActive RunL
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * From CActive Cancel request 
+        * @return void
+        */
+        void DoCancel();
+
+    private:    // Data
+        // Enumerator for reader phase
+        enum TReaderPhase
+            {
+            EWakeUpAPDURequest,
+            EAPDURequest
+            };
+
+        // RApdu class
+        RApdu                       iApdu;
+        // Status for Apdu
+        TUint8                      iApduStatus;
+        // Is the card inserted
+        TBool                       iCardInserted;
+        // Pointer for client status. Not owned.
+        TRequestStatus*             iClientStatus;
+        // Cmd bytes
+        TBufC8<1>                   iCmdBytes;
+        // Pointer to Etel server. Owned.
+        RTelServer*                 iEtelServer;
+        // Header for APDU
+        TSwimApduReqHeader          iHeader;
+        //
+        TBuf8<KMaxATRHistoricalBytes> iHistoricals;
+        // Pointer for SwimReaderIF object. Not owned.
+        CSwimReaderIF*              iInterface;
+        // Phase of reader operations
+        TReaderPhase                iPhase;
+        // Max length of APDU
+        TInt                        iMaxLen;
+        // Pointer to TApdu message. Owned.
+        RMmCustomAPI::TApdu*        iMsg;
+        // Is reader open
+        TBool                       iOpen;
+        // Prefferred reader
+        TUint8                      iPreferredReader;
+        // Prefferred reader status
+        TUint8                      iPreferredReaderStatus;
+        // Is reader attached
+        TBool                       iReaderAttached;
+        // Buffer for reader statusses
+        HBufC8*                     iReaderStatuses;
+        // Pointer to reader statusses. Owned.
+        TPtr8*                      iReaderStatusesPtr;
+        // Request header
+        TSwimApduReqHeader*         iReqHeader;
+        // Pointer to Response APDU. Not owned.
+        TPtr8*                      iResponseAPDU;
+        // Temporary buffer. Owned.
+        HBufC8*                     iTempBuf;
+        // Pointer to Temporary buffer
+        TPtr8*                      iTempPtr;
+    };
+
+#endif      // CSWIMREADER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/inc/SwimReaderConsts.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,90 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Constans for SwimReader
+*
+*/
+
+
+#ifndef SWIMREADERCONSTS_H
+#define SWIMREADERCONSTS_H
+
+//  INCLUDES
+#include <e32base.h>
+
+
+//  CONSTANTS
+
+/* APDUs */
+const TUint8 KSendApdu       = 79;
+const TUint8 KGetATR         = 80;
+const TUint8 KList           = 81;
+const TUint8 KAPDUAppTypeWIM = 1;
+
+const TUint8 KApduOK         = 0x3d;
+
+// Error byte values
+const TUint8 KApduTransmissionError = 0x3e;
+const TUint8 KApduCardMute          = 0x3f;
+const TUint8 KApduCardDisconnected  = 0x40;
+const TUint8 KApduError             = 0x41;
+const TUint8 KApduReaderNotValid    = 0x42;
+const TUint8 KApduFormatError       = 0x43;
+const TUint8 KApduTypeNotValid      = 0x44;
+
+const TUint8 KSimServNoservice      = 0xFA; 
+const TUint8 KSimServNotready       = 0xFB; 
+const TUint8 KSimServError          = 0xFC; 
+
+//
+// Check APDU list chapter to understand these.
+const TUint8 KMaxReaderAmount       = 8;
+const TUint8 KListAllReaders        = 0xff;
+
+//
+// Reader status bits.
+const TUint8 KIdentityMask          = 0x07;
+const TUint8 KCardReaderRemovable   = 0x08;//0x10;
+const TUint8 KCardReaderPresent     = 0x10;//0x08;
+const TUint8 KCardReaderID1Size     = 0x20;
+const TUint8 KCardPresent           = 0x40;//0x02;
+const TUint8 KCardPowered           = 0x80;//0x01;
+
+const TUint8 KMaxApduHeaderLen      = 16;
+
+const TUint8 KSendApduHeaderLen     = 4;
+const TUint8 KGetListHeaderLen      = 2;
+
+const TUint8 KSendApduRespHeaderLen = 14;
+const TUint8 KListRespHeaderLen     = 13;
+const TUint8 KGetAtrRespHeaderLen   = 16;
+
+const TUint8 KNoPreferredReader     = 254;
+
+//APDU request bytes
+const TInt KIndexServiceType = 0;
+const TInt KIndexCardReader  = 1;
+const TInt KIndexAppType     = 2;
+const TInt KIndexPaddingByte = 3;
+
+//APDU response bytes
+const TInt KIndexRespTransActionID = 8;
+const TInt KIndexRespMessageID     = 9;
+const TInt KIndexRespServiceType   = 10;
+const TInt KIndexRespStatus        = 11;
+const TInt KIndexRespPaddingByte   = 12;
+const TInt KIndexRespSDataLength   = 15;
+
+#endif      // SWIMREADERCONSTS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/inc/SwimReaderIF.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,194 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  SWIM reader interface
+*
+*/
+
+
+
+#ifndef CSWIMREADERIF_H
+#define CSWIMREADERIF_H
+
+//  INCLUDES
+#include "ScardReader.h"
+#include "ScardNotifyObserver.h"
+
+//  CONSTANTS  
+const TUint8 KGetStatus = 0xf0;
+
+//  FORWARD DECLARATIONS
+class CSwimReader;
+class CSwimReaderLauncher;
+class CSwimSysAgentObserver;
+
+// CLASS DECLARATION
+
+/**
+*  Implements SwimReader interface class
+*  
+*
+*  @lib SwimReader.lib
+*  @since Series60 2.1
+*/
+class CSwimReaderIF : public CActive, public MScardReader
+    {
+    public: // Constructors and destructor
+       
+        /**
+        * Two-phased constructor.
+        * @param aNotifyObserver Pointer to notify observer
+        * @param aReaderID Reader ID
+        * @param aLauncher Pointer to reader launcher
+        */    
+        static CSwimReaderIF* NewL( MScardNotifyObserver* aNotifyObserver,
+                                    TReaderID aReaderID,
+                                    CSwimReaderLauncher* aLauncher );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CSwimReaderIF();
+    
+
+    public: // New functions
+        
+        /**
+        * Cancel transmit
+        * @return void
+        */
+        void CancelTransmit();
+        
+        /**
+        * Close SwimReader IF
+        * @return KErrNone
+        */
+        TInt Close();
+        
+        /**
+        * Get the ATR bytes
+        * @param aAtr ATR bytes
+        * @return KScErrNotSupported
+        */
+        TInt GetATR( TScardATR& aAtr );
+        
+        /**
+        * Get card status or presence bits according to aTag parameter
+        * @param aStatus Clients request status
+        * @param aTag Tag for request type
+        * @param aValue Value of tag
+        * @param aTimeout Timeout for GetCapabilities request
+        * @return ETrue
+        */        
+        TBool GetCapabilities( TRequestStatus& aStatus,
+                               const TInt32 aTag,
+                               TPtr8& aValue,
+                               const TInt32 aTimeout );
+        
+        /**
+        * Notifies Scard Server about card event
+        * @param aStatus TScardServiceStatus
+        * @return void
+        */
+        void Notify( TScardServiceStatus aStatus );
+        
+        /**
+        * Open connection to Etel server
+        * @param  aStatus TRequestStatus
+        * @return void 
+        */            
+        void Open( TRequestStatus& aStatus );
+
+        /**
+        * Send a CommandAPDU on a slot and return ResponseAPDU from slot
+        * @param aStatus TRequestStatus
+        * @param aCommandAPDU Command APDU
+        * @param aResponceAPDU Response APDU
+        * @param aTimeout Timeout
+        * @return void
+        */
+        void TransmitToCard( TRequestStatus& aStatus,
+                             const TPtrC8& aCommandAPDU,
+                             TPtr8& aResponseAPDU,
+                             const TInt32 aTimeout);
+
+    private:
+        
+        /**
+        * C++ default constructor.
+        * @param aNotifyObserver Pointer to notify observer
+        * @param aReaderID Reader ID
+        * @param aLauncher Pointer to reader launcher
+        */ 
+        CSwimReaderIF( MScardNotifyObserver* aNotifyObserver, 
+                       TReaderID aReaderID,
+                       CSwimReaderLauncher* aLauncher );
+        
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Handle open APDU
+        * @return void
+        */
+        void HandleOpen();
+
+        /**
+        * From CActive, RunL
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * Cancel the asyncronous request
+        * @return void
+        */
+        void DoCancel();
+    
+    private: // Data
+        // Enumerator for reader IF phases
+        enum TReaderIFPhase
+            {
+            EOpen,
+            EGetATR,
+            ETransmitToCard
+            };
+        // error code
+        TInt                            iErr;
+        // Pointer to client status. Not owned.
+        TRequestStatus*                 iClientStatus;
+        // Pointer to SwimReader object. Owned.
+        CSwimReader*                    iFunctionalLevel;
+        // Historical bytes
+        TBuf8<KMaxATRHistoricalBytes>   iHistoricals;
+        // Reader ID
+        TReaderID                       iID;
+        // Reader IF phase
+        TReaderIFPhase                  iIFPhase;
+        // Pointer to ReaderLauncher object. Not owned. 
+        CSwimReaderLauncher*            iLauncher;
+        // Pointer to NotifyObserver object
+        MScardNotifyObserver*           iNotifyObserver;
+         // Pointer to System Agent Observer. Owned.
+        CSwimSysAgentObserver*          iSysAgentObserver;
+        
+    private:    // Friend classes
+        friend class CSwimReaderLauncher;
+    
+    };
+
+#endif      // CSWIMREADERIF_H
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/inc/SwimSysAgentObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,102 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implement SIM state observer for card removed event
+*
+*/
+
+
+
+#ifndef CSWIMSYSAGENTOBSERVER_H
+#define CSWIMSYSAGENTOBSERVER_H
+
+
+//  INCLUDES
+#include <e32base.h>
+#include <e32property.h> // RProperty
+
+//  FORWARD DECLARATIONS
+class CSwimReaderIF;
+
+// CLASS DECLARATION
+
+/**
+*  Publish and subscribe Observer class
+*  This class listens P/S events
+*
+*  @lib SwimReader.lib
+*  @since Series60 1.2
+*/
+class CSwimSysAgentObserver : public CActive
+    {
+    public: // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        * @param aReaderIF Pointer to ReaderIF owning this observer
+        */ 
+        static CSwimSysAgentObserver* NewL( CSwimReaderIF* aReaderIF );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSwimSysAgentObserver();
+
+    public: // New functions
+        
+        /**
+        * Starts listener
+        * @return void 
+        */
+        void Start();
+
+    private: 
+
+        /**
+        * C++ default constructor.
+        * @param aReaderIF Pointer to ReaderIF owning this observer
+        */ 
+        CSwimSysAgentObserver( CSwimReaderIF* aReaderIF );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * This function starts listening card state from System agent
+        * @return void
+        */
+        void StartListening();
+        /**
+        * From CActive. Handle asyncronous event response
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * From CActive. Handle Cancel call
+        * @return void
+        */
+        void DoCancel();
+
+    private:    // Data
+        // SIM status property
+        RProperty       iProperty;
+        // Pointer to ReaderIF owning this observer. Not owned.
+        CSwimReaderIF*  iReaderIF;
+    };
+
+#endif      // CSWIMSYSAGENTOBSERVER_H
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/src/SwimApduReqHeader.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,160 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class for APDU request header
+*
+*/
+
+
+
+// INCLUDE FILES 
+#include    "SwimApduReqHeader.h"
+#include    "WimTrace.h"            // for trace logging
+
+#ifdef _DEBUG
+#include    <flogger.h>
+#endif
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// TSwimApduReqHeader::TSwimApduReqHeader
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+TSwimApduReqHeader::TSwimApduReqHeader()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduReqHeader::TSwimApduReqHeader|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// TSwimApduReqHeader::Data
+// Return APDU data
+// -----------------------------------------------------------------------------
+//
+TDes8* TSwimApduReqHeader::Data()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduReqHeader::Data|Begin"));
+    return &iData;
+    }
+
+// -----------------------------------------------------------------------------
+// TSwimApduReqHeader::operator=
+// Operator =
+// -----------------------------------------------------------------------------
+//
+void TSwimApduReqHeader::operator=( const TDesC8& /*aData*/ )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduReqHeader::operator=|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// TSwimApduReqHeader::SetAppType
+// Set Application type byte
+// -----------------------------------------------------------------------------
+//
+void TSwimApduReqHeader::SetAppType( TUint8 aAppType )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduReqHeader::SetAppType|Begin"));
+    iData[KIndexAppType] = aAppType;
+    }
+
+// -----------------------------------------------------------------------------
+// TSwimApduReqHeader::SetCardReader
+// Set CardReader byte
+// -----------------------------------------------------------------------------
+//
+void TSwimApduReqHeader::SetCardReader( TUint8 aCardReader )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduReqHeader::SetCardReader|Begin"));
+    iData[KIndexCardReader] = aCardReader;
+    }
+
+// -----------------------------------------------------------------------------
+// TSwimApduReqHeader::SetHeader
+// Set header for ADPU
+// -----------------------------------------------------------------------------
+//
+void TSwimApduReqHeader::SetHeader(
+    TUint8 aServiceType,
+    TUint8 aCardReader, 
+    TUint8 aAppType,
+    TUint8 aPaddingByte )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduReqHeader::SetHeader|Begin"));
+    // Initialize data buffer so it can be accessed byte by byte.
+    for ( TInt i = 0; i < KMaxApduHeaderLen; i++ )
+        {
+        if ( iData.Length() < iData.MaxLength() )
+            {
+            iData.Append( 0 );
+            }
+        else
+            {
+            iData[i] = 0;
+            }
+        }
+
+    // Service type and card reader are used in all types of APDUs.
+    SetServiceType( aServiceType );
+    SetCardReader( aCardReader );
+
+    switch ( aServiceType )
+        {
+        case KSendApdu:
+            {
+            // App type and padding byte are used only with SEND_APDU msg.
+            SetAppType( aAppType );
+            SetPaddingByte( aPaddingByte );
+
+            iData.SetLength( KSendApduHeaderLen );
+            break;
+            }
+        case KList:
+            {
+            iData.SetLength( KGetListHeaderLen );
+            break;
+            }
+        default:
+            {
+            iData.SetLength( KMaxApduHeaderLen );
+            break;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// TSwimApduReqHeader::SetPaddingByte
+// Set padding byte
+// -----------------------------------------------------------------------------
+//
+void TSwimApduReqHeader::SetPaddingByte( TUint8 aPaddingByte )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduReqHeader::SetPaddingByte|Begin"));
+    iData[KIndexPaddingByte] = aPaddingByte;
+    }
+
+// -----------------------------------------------------------------------------
+// TSwimApduReqHeader::SetServiceType
+// Set ServiceType byte
+// -----------------------------------------------------------------------------
+//
+void TSwimApduReqHeader::SetServiceType( TUint8 aServiceType )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduReqHeader::SetServiceType|Begin"));
+    iData[KIndexServiceType] = aServiceType;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/src/SwimApduRespHeader.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,157 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class for APDU response header
+*
+*/
+
+
+
+// INCLUDE FILES 
+#include    "SwimApduRespHeader.h"
+#include    "WimTrace.h"            // for trace logging
+
+#ifdef _DEBUG
+#include <flogger.h>
+#endif
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// TSwimApduRespHeader::TSwimApduRespHeader
+// Constructor
+// -----------------------------------------------------------------------------
+//
+TSwimApduRespHeader::TSwimApduRespHeader( const TDesC8& aData )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduRespHeader::TSwimApduRespHeader|Begin"));
+    Copy( aData );
+    }
+
+// -----------------------------------------------------------------------------
+// TSwimApduRespHeader::AnyByte
+// Return byte in given index
+// -----------------------------------------------------------------------------
+//
+TUint8 TSwimApduRespHeader::AnyByte( TUint8 aIndex )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduRespHeader::AnyByte|Begin"));
+    if ( iData.Length() > aIndex )
+        {
+        return iData[aIndex];
+        }
+    else
+        {
+        return 0;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// TSwimApduRespHeader::Copy
+// Copy data
+// -----------------------------------------------------------------------------
+//
+void TSwimApduRespHeader::Copy( const TDesC8& aData )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduRespHeader::Copy|Begin"));
+    // If max length is shorter than length of given data,
+    // copy only max length amount of data.
+    if ( KMaxApduHeaderLen >= aData.Length() ) 
+        {
+        iData = aData;
+        }
+    else
+        {
+        iData = aData.Left( KMaxApduHeaderLen );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// TSwimApduRespHeader::DataLength
+// Return data length
+// -----------------------------------------------------------------------------
+//
+TUint16 TSwimApduRespHeader::DataLength()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduRespHeader::DataLength|Begin"));
+    TUint8  serviceType, shortRet;
+    TUint16 ret = 0;
+
+    serviceType = ServiceType();
+
+    if ( serviceType == KList )
+        {
+        shortRet = ShortDataLength();
+        ret = shortRet;
+        }
+    else if ( iData.Length() > 13 )
+        {
+        ret = TUint16( iData[12] << 8 );
+        ret = TUint16( ret | iData[13] );
+        }
+
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// TSwimApduRespHeader::operator=
+// Operator =
+// -----------------------------------------------------------------------------
+//
+void TSwimApduRespHeader::operator=( const TDesC8& aData )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduRespHeader::operator=|Begin"));
+    Copy( aData );
+    }
+
+// -----------------------------------------------------------------------------
+// TSwimApduRespHeader::ServiceType
+// Return Service type byte
+// -----------------------------------------------------------------------------
+//
+TUint8 TSwimApduRespHeader::ServiceType()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduRespHeader::ServiceType|Begin"));
+    return AnyByte( KIndexRespServiceType );
+    }
+
+// -----------------------------------------------------------------------------
+// TSwimApduRespHeader::ShortDataLength
+// Return ShortDataLength byte
+// -----------------------------------------------------------------------------
+//
+TUint8 TSwimApduRespHeader::ShortDataLength()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|TSwimApduRespHeader::ShortDataLength|Begin"));
+    if ( ServiceType() == KSendApdu )
+        {
+        return 0;
+        }
+    else
+        {
+        return AnyByte( KIndexRespSDataLength );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// TSwimApduRespHeader::Status
+// Return status byte
+// -----------------------------------------------------------------------------
+//
+TUint8 TSwimApduRespHeader::Status()
+    {
+    _WIMTRACE2(_L("WIM|SwimReader|TSwimApduRespHeader::Status|status=%d"), AnyByte(KIndexRespStatus));
+    return AnyByte( KIndexRespStatus );
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/src/SwimEtelApdu.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,180 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implements the functionality of RApdu class
+*
+*/
+
+
+
+// INCLUDE FILES 
+#include    "SwimEtelApdu.h"
+#include    "etelext.h"         // EEtelPanicNullHandle
+#include    "WimTrace.h"        // for trace logging
+ 
+#ifdef _DEBUG
+#include    <flogger.h>
+#endif
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// RApdu::RApdu
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+RApdu::RApdu()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|RApdu::RApdu|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// RApdu::ConstructL
+// Symbian 2nd phase constructor can leave. 
+// Virtual function which extensions may overload. Called in Open()
+// -----------------------------------------------------------------------------
+//
+void RApdu::ConstructL()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|RApdu::ConstructL|Begin"));
+    //Create new CustomAPI instance
+    iCustomApi = new( ELeave ) RMmCustomAPI;
+    }
+
+
+// -----------------------------------------------------------------------------
+// RApdu::APDUReq
+// Message Transmission
+// -----------------------------------------------------------------------------
+//
+void RApdu::APDUReq( TRequestStatus& aStatus, RMmCustomAPI::TApdu& aMsg )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|RApdu::APDUReq|Begin"));
+    aStatus = KRequestPending;
+    // Send APDU to Etel through CustomAPI
+    iCustomApi->SendAPDUReq( aStatus, aMsg );
+    }
+
+// -----------------------------------------------------------------------------
+// RApdu::CancelAPDUReq
+// Cancel Message Transmission
+// -----------------------------------------------------------------------------
+//
+void RApdu::CancelAPDUReq()
+    {
+	iCustomApi->CancelAsyncRequest( ECustomSendAPDUReqIPC );
+    }
+
+// -----------------------------------------------------------------------------
+// RApdu::Destruct
+// Destructor. Called in Close()
+// -----------------------------------------------------------------------------
+//
+void RApdu::Destruct()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|RApdu::Destruct|Begin"));
+    if ( iCustomApi )
+    	{
+    	iCustomApi->Close();
+        delete iCustomApi;
+        iCustomApi = NULL;
+    	} 
+    }
+
+// -----------------------------------------------------------------------------
+// RApdu::Close
+// Close a phone and connection to CustomAPI
+// -----------------------------------------------------------------------------
+//
+void RApdu::Close()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|RApdu::Close|Begin"));
+    CloseSubSession( EEtelClose );
+    iPhone.Close();
+    if ( iCustomApi )
+    	{
+        iCustomApi->Close();
+    	}   
+    Destruct();
+    }
+
+// -----------------------------------------------------------------------------
+// RApdu::Open
+// Open a phone by name and CustomAPI session
+// -----------------------------------------------------------------------------
+//
+TInt RApdu::Open( RTelServer& aServer, const TDesC &aName )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|RApdu::Open|Begin"));
+    __ASSERT_ALWAYS( aServer.Handle() != 0, 
+        PanicClient( EEtelPanicNullHandle ) );
+    __ASSERT_ALWAYS( aName.Length() != 0, PanicClient( KErrBadName ) );
+
+    TRAPD( ret, ConstructL() );
+    if ( ret )
+        {
+        Destruct();
+        return ret;
+        }
+
+    //RMobilePhone phone;
+
+    // Open phone
+    ret = iPhone.Open( aServer, aName );
+            
+    if ( ret != KErrNone )
+        {
+#ifdef _DEBUG        
+        RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName,
+        EFileLoggingModeAppend, 
+        _L( "EtelApdu::Open: phone open failed: %d" ), 
+        ret );
+#endif
+        Destruct();
+        iPhone.Close();
+        return ret;
+        }
+    
+    // Open new CustomAPI session for phone
+    ret = iCustomApi->Open( iPhone );
+    
+    if ( ret != KErrNone )
+        {
+#ifdef _DEBUG        
+        RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName,
+        EFileLoggingModeAppend, 
+        _L( "EtelApdu::Open: CustomAPI open failed: %d" ), 
+        ret );
+#endif
+        Destruct();
+        iPhone.Close();
+        return ret;
+        }
+
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// PanicClient
+// Panic the client on client side
+// -----------------------------------------------------------------------------
+//
+void PanicClient( TInt aFault )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|RApdu::PanicClient|Begin"));
+    _LIT( KETelClientFault,"Etel Client Fault" );
+    User::Panic( KETelClientFault, aFault );
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/src/SwimLauncher.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,96 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  SWIM launcher. Creates new instance of SwimReader.
+*
+*/
+
+
+
+// INCLUDE FILES 
+#include    "SwimLauncher.h"
+#include    "SwimReaderIF.h"
+#include    "ScardBase.h"
+#include    "WimTrace.h"        // for trace logging
+
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// NewServiceL
+// New CSwimReaderLauncher
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CSwimReaderLauncher* NewServiceL()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderLauncher::NewServiceL|Begin"));
+    return new( ELeave ) CSwimReaderLauncher;
+    }
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CSwimReaderLauncher::CSwimReaderLauncher
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CSwimReaderLauncher::CSwimReaderLauncher()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderLauncher::CSwimReaderLauncher|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReaderLauncher::ConstructL
+// Symbian 2nd phase constructor can leave. 
+// -----------------------------------------------------------------------------
+//
+void CSwimReaderLauncher::ConstructL( MScardReaderService* aService )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderLauncher::ConstructL|Begin"));
+    iService = aService;
+    }
+
+// Detructor
+CSwimReaderLauncher::~CSwimReaderLauncher()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderLauncher::~CSwimReaderLauncher|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReaderLauncher::CreateReaderL
+// Create reader
+// -----------------------------------------------------------------------------
+//
+MScardReader* CSwimReaderLauncher::CreateReaderL( TReaderID aReaderID )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderLauncher::CreateReaderL|Begin"));
+    iReader = CSwimReaderIF::NewL( iService->NotifyObserver(), 
+                                   aReaderID, this );  
+    return iReader;
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReaderLauncher::DeleteReader
+// Delete reader
+// -----------------------------------------------------------------------------
+//
+void CSwimReaderLauncher::DeleteReader( TReaderID /*aReaderID*/ )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderLauncher::DeleteReaderL|Begin"));
+    delete iReader;
+    iReader = NULL;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/src/SwimReader.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,699 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implements the functional and communication levels of module
+*
+*/
+
+
+// INCLUDE FILES 
+#include    "SwimReader.h"
+#include    "SwimReaderIF.h"
+#include    "rmmcustomapi.h"    // TApdu
+#include    "WimTrace.h"        // For trace logging
+#include    <mmtsy_names.h>     // TSY and Phone name
+
+#ifdef _DEBUG
+#include    <flogger.h>
+#endif
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CSwimReader::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CSwimReader* CSwimReader::NewL( CSwimReaderIF* aInterface )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::NewL|Begin"));
+    CSwimReader* self = new( ELeave ) CSwimReader( aInterface );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader::CSwimReader
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CSwimReader::CSwimReader( CSwimReaderIF* aInterface )
+    : CActive( EPriorityNormal )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::CSwimReader|Begin"));
+    CActiveScheduler::Add( this );
+    iInterface = aInterface;
+    iReaderAttached = ETrue;
+    
+    // Currently (and probably always) APDU interface and forecoming
+    // APDU server will support only one reader, which number is 0.
+    iPreferredReader = 0;
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CSwimReader::ConstructL()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::ConstructL|Begin"));
+#ifdef _DEBUG        
+    RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName,     
+        EFileLoggingModeAppend, 
+        _L( "CSwimReader::ConstructL: Creating new RTelServer object...\n" ) );
+#endif
+    iEtelServer = new( ELeave ) RTelServer();    
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader:: ~CSwimReader
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CSwimReader::~CSwimReader()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::~CSwimReader|Begin"));
+    Close();
+    CleanUp();
+    delete iMsg;
+    delete iEtelServer;
+    delete iTempBuf;
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader::APDUReqL
+// Send APDU command aCommandAPDU to the ETEL server.
+// Response is set to aResponseAPDU.
+// -----------------------------------------------------------------------------
+//
+void CSwimReader::APDUReqL(
+    TRequestStatus& aStatus,
+    const TPtrC8&   aCommandAPDU,
+    TPtr8&          aResponseAPDU,    
+    TUint8          aServiceType,
+    TUint8          aCardReader,
+    TUint8          aAppType,
+    TUint8          aPaddingByte )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::APDUReqL1|Begin"));
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+    APDUReqL( aCommandAPDU, aResponseAPDU, aServiceType, aCardReader, 
+              aAppType, aPaddingByte );
+    iPhase = EAPDURequest;
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader::Close
+// Close ETEL connection and connection to CustomAPI.
+// -----------------------------------------------------------------------------
+//
+void CSwimReader::Close()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::Close|Begin"));
+    Cancel();
+    if ( iOpen )
+        {
+        iApdu.Close();
+        iEtelServer->Close();
+        iOpen = EFalse;
+        }
+    }
+    
+// -----------------------------------------------------------------------------
+// CSwimReader::DoCancel
+// Asynchronous request cancelled
+// -----------------------------------------------------------------------------
+//
+void CSwimReader::DoCancel()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::DoCancel|Begin"));
+    
+    if( iPhase == EAPDURequest )
+        {
+    	iApdu.CancelAPDUReq();
+        }
+        
+#ifdef _DEBUG            
+    RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName,         
+        EFileLoggingModeAppend, 
+        _L( "CSwimReader::DoCancel: Clean up.\n" ) );
+#endif
+    CleanUp();
+#ifdef _DEBUG            
+    RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName,         
+        EFileLoggingModeAppend, 
+        _L( "CSwimReader::DoCancel: Complete request with status %d.\n" ),
+            iStatus.Int() );
+#endif
+    User::RequestComplete( iClientStatus, iStatus.Int() );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader::PreferredReaderStatus
+// Get preferred reader statuses from the iPreferredReaderStatus member.
+// -----------------------------------------------------------------------------
+//
+void CSwimReader::PreferredReaderStatus( TUint8& aReaderStatus )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::PreferredReaderStatus|Begin"));
+    aReaderStatus = iPreferredReaderStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader::SelectCardReader
+// From given status bytes, select a card reader, which
+// is present and card is also present in the reader.
+// -----------------------------------------------------------------------------
+//
+TUint8 CSwimReader::SelectCardReader(
+    TDesC8&  aReaderStatuses,
+    TUint8& aPreferredReaderStatus,
+    TUint8  aOldPreferredReader /* = NO_PREFERRED_READER */ )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::SelectCardReader|Begin"));
+    TInt i;
+    TInt size;
+    TUint8 readerStatus;
+
+    size = aReaderStatuses.Length();
+
+    for ( i = 0; i < size; i++ )
+        {
+        readerStatus = aReaderStatuses[i];
+
+        _WIMTRACE2(_L("WIM|SwimReader|CSwimReader::SelectCardReader|ReaderStatus=%d"), 
+            (TUint8)aReaderStatuses[i]);
+
+        // First check that this isn't the reader the caller has
+        // already tried to use and find inappropriate for some reason.
+        if ( i != aOldPreferredReader )
+            {
+            // If reader and card are present, this reader is good for us.
+            if ( (readerStatus & KCardReaderPresent) &&
+                (readerStatus & KCardPresent) )
+                {
+                aPreferredReaderStatus = readerStatus;
+                _WIMTRACE2(_L("WIM|SwimReader|CSwimReader::SelectCardReader|PreferredReaderStatus1=%d"),
+                    readerStatus);
+
+                // Reader number is stored in first three bits,
+                // so return only them.
+                return ( static_cast< TUint8 >( readerStatus & KIdentityMask ) );
+                }
+            }
+        }
+
+    // If not found, use a one where reader is present.
+    for ( i = 0; i < size; i++ )
+        {
+        readerStatus = aReaderStatuses[i];
+
+        // First check that this isn't the reader the caller has
+        // already tried to use and find inappropriate for some reason.
+        if ( i != aOldPreferredReader )
+            {
+            // If reader is present, this reader is good for us.
+            if ( readerStatus & KCardReaderPresent )
+                {
+                _WIMTRACE2(_L("WIM|SwimReader|CSwimReader::SelectCardReader|PreferredReaderStatus2=%d"),
+                    readerStatus);
+                aPreferredReaderStatus = readerStatus;
+
+                // Reader number is stored in first three bits,
+                // so return only them.
+                return ( static_cast< TUint8 >( readerStatus & KIdentityMask ) );
+                }
+            }
+        }
+
+    // If nothing found, return a one caller gave to us.
+    return aOldPreferredReader;
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader::SetCardInserted
+// Set card inserted
+// -----------------------------------------------------------------------------
+//
+void CSwimReader::SetCardInserted( TBool aIsInserted )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::SetCardInserted|Begin"));
+    iCardInserted = aIsInserted;
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader::WakeUpL
+// Initializes the reader. Also make APDU_LIST to get
+// all statuses of card readers attached to the device.
+// -----------------------------------------------------------------------------
+//
+void CSwimReader::WakeUpL( TRequestStatus& aStatus, TDes8& aHistoricals )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::WakeUpL|Begin"));
+    iHistoricals = aHistoricals;
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+
+    // Set reader not open
+    iOpen = EFalse;
+
+    _WIMTRACE2(_L("WIM|SwimReader|CSwimReader::WakeUpL|iPreferredReader=%d"),
+        iPreferredReader);
+
+    // If WakeUp failed last time, preferred reader might be initialized
+    // wrong, use reader 0
+    if ( iPreferredReader == KNoPreferredReader )
+        {
+        iPreferredReader = 0;
+        _WIMTRACE(_L("WIM|SwimReader|CSwimReader::WakeUpL|iPreferredReader changed to 0"));
+        }
+    
+    TInt ret = 0;
+
+    // Connect to the Etel server.
+    ret = iEtelServer->Connect();
+    if ( ret != KErrNone )
+        {
+#ifdef _DEBUG        
+        RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName,
+            EFileLoggingModeAppend, 
+            _L( "CSwimReader::WakeUpL: connection to etel server failed: %d" ),
+            ret );
+#endif
+        User::Leave( ret );
+        }
+
+    // Load phone module.
+    ret = iEtelServer->LoadPhoneModule( KMmTsyModuleName );
+    
+    if ( ret != KErrNone )
+        {
+#ifdef _DEBUG        
+        RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName,
+            EFileLoggingModeAppend, 
+            _L( "CSwimReader::WakeUpL: loading phone module failed: %d" ), 
+            ret );
+#endif
+        User::Leave( ret );
+        }
+
+    // Open CustomAPI connection
+    ret = iApdu.Open( *iEtelServer, KMmTsyPhoneName );
+
+    if ( ret != KErrNone )
+        {
+#ifdef _DEBUG        
+        RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName,
+            EFileLoggingModeAppend, 
+            _L( "CSwimReader::WakeUpL: phone open failed: %d" ), 
+            ret );
+#endif
+        iEtelServer->Close();
+        User::Leave( ret );
+        }
+
+    // Make LIST to get status of only available reader.
+    if ( iReaderStatuses )
+        {
+        delete iReaderStatuses;
+        iReaderStatuses = NULL;
+        }
+    if ( iReaderStatusesPtr )
+        {
+        delete iReaderStatusesPtr;
+        iReaderStatusesPtr = NULL;
+        }
+    iReaderStatuses = HBufC8::NewL( KMaxReaderAmount );
+    iReaderStatusesPtr = new ( ELeave ) TPtr8( iReaderStatuses->Des() );
+
+#ifdef _DEBUG        
+        RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName,
+            EFileLoggingModeAppend, 
+            _L( "CSwimReader::WakeUpL: Getting list..." ) );
+#endif
+    _WIMTRACE2(_L("WIM|SwimReader|CSwimReader::WakeUpL|iPreferredReader=%d"),
+        iPreferredReader);
+
+    TRAPD( err, APDUReqL( iCmdBytes, *iReaderStatusesPtr, KList,
+                          iPreferredReader ) );
+
+    if ( err )
+        {
+#ifdef _DEBUG        
+        RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName,
+            EFileLoggingModeAppend, 
+            _L( "CSwimReader::WakeUpL: get list failed: %d" ), err );
+#endif
+        iInterface->Notify( EReaderRemoved );
+        iApdu.Close();
+        iEtelServer->Close();
+        User::RequestComplete( iClientStatus, err );
+        }
+    else
+        {
+        _WIMTRACE2(_L("WIM|SwimReader|CSwimReader::WakeUpL|*iReaderStatusesPtr=%d"),
+            *iReaderStatusesPtr);
+        iPhase = EWakeUpAPDURequest;
+        SetActive();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader::APDUReqL
+// Send APDU command aCommandAPDU to the ETEL server.
+// Response is set to aResponseAPDU.
+// -----------------------------------------------------------------------------
+//
+void CSwimReader::APDUReqL(
+    const TPtrC8& aCommandAPDU,
+    TPtr8&        aResponseAPDU,    
+    TUint8        aServiceType,
+    TUint8        aCardReader,
+    TUint8        aAppType,
+    TUint8        aPaddingByte )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::CSwimReaderLauncher|Begin"));
+    // If reader not given, use preferred reader,
+    if ( aCardReader == KNoPreferredReader )
+        {
+        // If preferred reader is not set, quess 0.
+        if ( iPreferredReader != KNoPreferredReader )
+            {
+            aCardReader = iPreferredReader;
+            }
+        else
+            {
+            aCardReader = 0;
+            }
+        }
+
+    iHeader.SetHeader( aServiceType, aCardReader, aAppType, aPaddingByte );
+
+    // ...and call next function.
+    APDUReqL( aCommandAPDU, aResponseAPDU, iHeader );
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader::APDUReqL
+// Send APDU command aCommandAPDU to the ETEL server.
+// Response is set to aResponseAPDU.
+// -----------------------------------------------------------------------------
+//
+void CSwimReader::APDUReqL(
+    const TPtrC8&       aCommandAPDU,
+    TPtr8&              aResponseAPDU,
+    TSwimApduReqHeader& aReqHeader )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::APDUReqL|Begin"));
+    iReqHeader = &aReqHeader;
+    iResponseAPDU = &aResponseAPDU; 
+    iTempBuf = 0;
+    
+    if ( iMsg )
+    {
+    delete iMsg;
+    iMsg = NULL;	
+    }
+    
+    iMsg = new( ELeave ) RMmCustomAPI::TApdu();   
+ 
+    // Set APDU header to APDU message.
+    iMsg->iInfo = aReqHeader.Data();
+
+    // Copy command APDU to response APDU and use it to both
+    // transfer request to lower levels and to receive response.
+    if ( &aCommandAPDU )
+        {
+        iMaxLen = aResponseAPDU.MaxLength();
+
+        if ( iMaxLen >= aCommandAPDU.Length() )
+            {
+            aResponseAPDU = aCommandAPDU;
+
+            iMsg->iData = &aResponseAPDU;
+            }
+        else
+            {
+            // Response APDU isn't long enough for Command APDU,
+            // which makes a situation a little more complicated.
+            // Create a new buffer with enough space.
+            if( iTempBuf )
+            {
+            delete iTempBuf;
+            iTempBuf = NULL;
+            }
+            if( iTempPtr )
+            {
+            delete iTempPtr;
+            iTempPtr = NULL;
+            }
+            
+	    iTempBuf = HBufC8::NewL( aCommandAPDU.Length() );
+            iTempPtr = new( ELeave )TPtr8( iTempBuf->Des() );
+	    iTempPtr->Copy( aCommandAPDU );
+	    iMsg->iData = iTempPtr;
+            }
+        }
+    iApdu.APDUReq( iStatus, *iMsg );
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader::CleanUp
+// Clean up allocated buffers
+// -----------------------------------------------------------------------------
+//
+void CSwimReader::CleanUp()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::CleanUp|Begin"));
+    delete iReaderStatusesPtr;
+    iReaderStatusesPtr = NULL;
+    delete iReaderStatuses;
+    iReaderStatuses = NULL;
+    delete iTempBuf;
+    iTempBuf = NULL;
+    delete iMsg;
+    iMsg = NULL;
+    delete iTempPtr;
+    iTempPtr = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader::RunL
+// Handle asyncronous APDU requests
+// -----------------------------------------------------------------------------
+//
+void CSwimReader::RunL()
+    {
+    _WIMTRACE3(_L("WIM|SwimReader|CSwimReader::RunL|iPhase=%d, iStatus=%d"),
+        iPhase, iStatus.Int() );
+
+    if ( iStatus.Int() == 0 )
+        {
+        switch ( iPhase )
+            {
+            case EWakeUpAPDURequest:
+                {
+                TInt error = HandleOpenAPDUReq();
+
+                iOpen = ETrue;
+#ifdef _DEBUG        
+                RFileLogger::WriteFormat( KSwimReaderLogDir, 
+                    KSwimReaderLogFileName, EFileLoggingModeAppend, 
+                    _L( "CSwimReader::RunL: WakeUp completed: %d" ), 
+                    error );
+#endif
+
+                User::RequestComplete( iClientStatus, error );
+
+                break;
+                }
+            case EAPDURequest:
+                {
+                TInt error = HandleAPDUReq();
+
+#ifdef _DEBUG        
+                RFileLogger::WriteFormat( KSwimReaderLogDir, 
+                    KSwimReaderLogFileName, EFileLoggingModeAppend, 
+                    _L( "CSwimReader::RunL: APDU request completed: %d" ), 
+                    error );
+#endif
+                User::RequestComplete( iClientStatus, error );
+                break;
+                }
+
+            }
+        }
+    else
+        {
+#ifdef _DEBUG                
+        RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName,
+            EFileLoggingModeAppend, 
+            _L( "CSwimReader::RunL: Error, iPhase: %d iStatus: %d" ),
+            iPhase, iStatus.Int() );
+#endif
+        iApdu.Close();
+        iEtelServer->Close();
+        CleanUp();
+        User::RequestComplete( iClientStatus, iStatus.Int() );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader::HandleAPDUReq
+// Handle APDU responses
+// -----------------------------------------------------------------------------
+//
+TInt CSwimReader::HandleAPDUReq()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::HandleAPDUReq|Begin"));
+    TInt retValue;
+
+    delete iMsg;
+    iMsg = NULL;
+
+    // If we had to use temp buffer, copy response from
+    // temp buffer to response buffer given by a caller.
+    if ( iTempBuf != 0 )
+        {
+        iMaxLen = iResponseAPDU->MaxLength();
+
+        if ( iMaxLen >= iTempBuf->Length() )
+            {
+            *iResponseAPDU = iTempBuf->Des();
+            }
+        else
+            {
+            *iResponseAPDU = iTempBuf->Left( iMaxLen );
+            }
+
+        delete iTempBuf;
+        }
+
+    // Create TSwimApduRespHeader from response info.
+    TSwimApduRespHeader respHeader( *(iReqHeader->Data()) );
+
+    // Get APDU status from response header...
+    iApduStatus = respHeader.Status();
+
+#ifdef _DEBUG        
+    RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName,
+        EFileLoggingModeAppend, 
+        _L( "CSwimReader::HandleAPDUReq: response status: %d" ),
+        iApduStatus );
+
+    RFileLogger::HexDump( KSwimReaderLogDir, KSwimReaderLogFileName,
+        EFileLoggingModeAppend, 
+        _S( "CSwimReader:: HandleAPDUReq APDU received:\n" ), 0,
+        iResponseAPDU->Ptr(), iResponseAPDU->Length() );
+#endif
+
+    // ...and switch it to SCard error codes.
+    switch ( iApduStatus )
+        {
+        case KApduOK:
+        case KErrNone: // Accept also KErrNone
+            {
+            retValue = KErrNone;
+            break;
+            }
+        case KApduTransmissionError:
+            {
+            retValue = KScReaderErrCommunicationFailure;
+            break;
+            }
+        case KApduCardMute:
+            {
+            retValue = KScReaderErrResponseTimeout;
+            break;
+            }
+        case KApduCardDisconnected:
+            {
+            retValue = KScReaderErrNoCard;
+            break;
+            }
+        case KApduError:
+            {
+            retValue = KScReaderErrCardFailure;
+            break;
+            }
+        case KApduReaderNotValid:
+            {
+            retValue = KScReaderErrNoReader;
+            break;
+            }
+        case KApduFormatError:
+            {
+            retValue = KScErrBadArgument;
+            break;
+            }
+        case KApduTypeNotValid:
+            {
+            retValue = KScErrBadArgument;
+            break;
+            }
+        // DOS SIM server errors
+        case KSimServError:
+        case KSimServNotready:
+        case KSimServNoservice:
+            {
+            retValue = KScReaderErrReaderFailure;
+            break;
+            }
+        default:
+            retValue = KScErrUnknown;
+            break;
+        }
+
+        // Check actual length of the data received and compare it to
+        // the length of the response buffer allocated by the caller.
+        if ( respHeader.DataLength() > iResponseAPDU->MaxLength() 
+             && !retValue )
+            {
+            // If there was more data than fitted to the buffer, tell to the 
+            // caller that the buffer was insufficient.
+            retValue = KScErrInsufficientBuffer;
+            }
+        _WIMTRACE2(_L("WIM|SwimReader|CSwimReader::HandleAPDUReq|return %d"),
+            retValue);
+        return retValue;
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReader::HandleOpenAPDUReq
+// Handle APDU request for GetReaderList request 
+// -----------------------------------------------------------------------------
+//
+TInt CSwimReader::HandleOpenAPDUReq()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReader::HandleOpenAPDUReq|Begin"));
+    TInt error = HandleAPDUReq();
+
+    if ( error == KErrNone )
+        {
+        // Select one reader, which looks like a most promising
+        // candidate to contain something useful.
+        iPreferredReader = SelectCardReader( *iReaderStatuses, 
+                                             iPreferredReaderStatus );
+        }
+    return error;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/src/SwimReaderIF.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,391 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of SIM/WIM reader interface class
+*
+*/
+
+
+// INCLUDE FILES  
+#include    "SwimReaderIF.h"
+#include    "SwimReader.h"
+
+#ifdef _TIMER_TRIGGERED_EVENT   // Timer triggered card event simulation enabled
+#include    "SwimSysAgentObserver_TimerTriggered.h"
+#else
+#include    "SwimSysAgentObserver.h"
+#endif
+
+#include    "WimTrace.h" // for trace logging
+
+#ifdef _DEBUG
+#include <flogger.h>
+#endif
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CSwimReaderIF::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CSwimReaderIF* CSwimReaderIF::NewL(
+    MScardNotifyObserver* aNotifyObserver, 
+    TReaderID aReaderID, 
+    CSwimReaderLauncher* aLauncher )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderIF::NewL|Begin"));
+    CSwimReaderIF* self = new( ELeave ) CSwimReaderIF( aNotifyObserver, 
+                                                       aReaderID, aLauncher );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+
+// Destructor
+CSwimReaderIF::~CSwimReaderIF() 
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderIF::~CSwimReaderIF|Begin"));
+    delete iFunctionalLevel;
+    if ( iSysAgentObserver )
+        {
+        iSysAgentObserver->Cancel();
+        }
+    delete iSysAgentObserver;
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReaderIF::CSwimReaderIF
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CSwimReaderIF::CSwimReaderIF(
+    MScardNotifyObserver* aNotifyObserver, 
+    TReaderID aReaderID, 
+    CSwimReaderLauncher* aLauncher )
+    : CActive( EPriorityNormal )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderIF::CSwimReaderIF|Begin"));
+    CActiveScheduler::Add( this );
+    iLauncher = aLauncher;
+    iNotifyObserver = aNotifyObserver;
+    iID = aReaderID; 
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReaderIF::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CSwimReaderIF::ConstructL()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderIF::ConstructL|Begin"));
+    iFunctionalLevel = CSwimReader::NewL( this );
+    iSysAgentObserver = CSwimSysAgentObserver::NewL( this );
+    iSysAgentObserver->Start(); //Start Listening
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReaderIF::CancelTransmit
+// Cancel transmit
+// -----------------------------------------------------------------------------
+//
+void CSwimReaderIF::CancelTransmit()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderIF::CancelTransmit|Begin"));
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReaderIF::CancelTransmit
+// Close ETEL server connection.
+// -----------------------------------------------------------------------------
+//
+TInt CSwimReaderIF::Close()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderIF::Close|Begin"));
+    Cancel();
+    iFunctionalLevel->Close();
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReaderIF::DoCancel
+// Asyncronous call cancelled
+// -----------------------------------------------------------------------------
+//
+void CSwimReaderIF::DoCancel()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderIF::DoCancel|Begin"));
+    iFunctionalLevel->Cancel();
+    User::RequestComplete( iClientStatus, KErrCancel );
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReaderIF::GetATR
+// Not supported in Series 60
+// -----------------------------------------------------------------------------
+//
+TInt CSwimReaderIF::GetATR( TScardATR& /*anATR*/ )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderIF::GetATR|Begin"));
+    return KScErrNotSupported;
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReaderIF::GetCapabilities
+// Get card status or precense bits according to aTag parameter
+// -----------------------------------------------------------------------------
+//
+TBool CSwimReaderIF::GetCapabilities(
+    TRequestStatus& aStatus,
+    const TInt32   aTag,
+    TPtr8&         aValue,
+    const TInt32 /*aTimeout*/ )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderIF::GetCapabilities|Begin"));
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+    
+    switch ( aTag )  
+        {
+        case KCardPrecence:
+            {
+            TUint8 tempstatus;
+            iFunctionalLevel->PreferredReaderStatus( tempstatus );
+            tempstatus = tempstatus && 0x02;
+            aValue.Copy( &tempstatus, 1 );
+            aValue.SetLength( 1 );
+            User::RequestComplete( iClientStatus, KErrNone );
+            break;
+            }
+        case KCardStatus:
+            {
+            TUint8 temp;
+            iFunctionalLevel->PreferredReaderStatus( temp );
+#ifdef _DEBUG        
+            RFileLogger::WriteFormat( KSwimReaderLogDir, 
+                KSwimReaderLogFileName, EFileLoggingModeAppend, 
+                _L( "CSwimReaderIF::GetCapabilities: %d" ), temp );
+#endif
+            aValue.Copy( &temp, 1 );
+            aValue.SetLength( 1 );
+            User::RequestComplete( iClientStatus, KErrNone );
+            break;
+            }
+        default:
+            {
+#ifdef _DEBUG        
+            RFileLogger::WriteFormat( KSwimReaderLogDir, 
+                KSwimReaderLogFileName, EFileLoggingModeAppend, 
+                _L( "CSwimReaderIF::GetCapabilities: unsupported tag 0x%x" ), 
+                aTag );
+#endif
+            User::RequestComplete( iClientStatus, KErrNotSupported );
+            }
+        }
+    return ETrue;   
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReaderIF::Notify
+// Notify notifyObserver about card event
+// -----------------------------------------------------------------------------
+//
+void CSwimReaderIF::Notify( TScardServiceStatus aStatus )
+    {
+    _WIMTRACE2(_L("WIM|SwimReader|CSwimReaderIF::Notify|Begin aStatus = %d"), aStatus);
+    iNotifyObserver->NotifyCardEvent( aStatus, iID );
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReaderIF::Open
+// Uses CSwimReader::WakeUpL to initialize a connection to the ETEL server.
+// -----------------------------------------------------------------------------
+//
+void CSwimReaderIF::Open( TRequestStatus& aStatus )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderIF::Open|Begin"));
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+    
+#ifdef _DEBUG        
+    RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName, 
+        EFileLoggingModeAppend, 
+        _L( "CSwimReaderIF::Open: Opening Reader..." ) );
+#endif
+
+    TRAPD( err, iFunctionalLevel->WakeUpL( iStatus, iHistoricals ) );
+    if ( err )
+        {
+#ifdef _DEBUG        
+        RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CSwimReaderIF::Open: WakeUpL leaves with %d !!!" ), err );
+#endif
+        User::RequestComplete( iClientStatus, err );
+        }
+    else
+        {
+        iIFPhase = EOpen;
+        SetActive();
+        }
+
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReaderIF::TransmitToCard
+// Transmits given CommandAPDU message to card and
+// gets response to ResponseAPDU message.
+// -----------------------------------------------------------------------------
+//
+void CSwimReaderIF::TransmitToCard(
+    TRequestStatus& aStatus,
+    const TPtrC8&   aCommandAPDU,
+    TPtr8&          aResponseAPDU,
+    const TInt32 /*aTimeout*/ )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderIF::TransmitToCard|Begin"));
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+
+#ifdef _DEBUG        
+        RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CSwimReaderIF::TransmitToCard: Sending APDU to card..." ) );
+#endif
+    TRAPD( err, iFunctionalLevel->APDUReqL( iStatus, aCommandAPDU, 
+                                            aResponseAPDU ) );
+    if ( err )
+        {
+#ifdef _DEBUG        
+        RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName, 
+            EFileLoggingModeAppend, 
+            _L( "CSwimReaderIF::TransmitToCard: APDUReqL leaves with %d !!!" ), 
+            err );
+#endif
+        User::RequestComplete( iClientStatus, err );
+        }
+    else
+        {
+        iIFPhase = ETransmitToCard;
+        SetActive();
+        }
+    }
+
+// PRIVATE FUNCTIONS:
+
+// -----------------------------------------------------------------------------
+// CSwimReaderIF::HandleOpen
+// Handle open request
+// -----------------------------------------------------------------------------
+//
+void CSwimReaderIF::HandleOpen()
+    {
+    _WIMTRACE2(_L("WIM|SwimReader|CSwimReaderIF::HandleOpen|Begin iStatus=%d"), iStatus.Int() );
+    if ( iStatus.Int() != KErrNone ) // a system-spes. error has occ, map to own
+        {
+        switch ( iStatus.Int() )
+            {
+            //  The reader or smart card did not respond in time
+            case KErrTimedOut:
+                iErr = KScReaderErrResponseTimeout;
+                break;
+            //  Access denied occurs if the comm port could not be opened, i.e.
+            //  someone else is using it.
+            case KErrAccessDenied:
+                iErr = KScReaderErrCommunicationFailure;
+                break;
+            //  (Some of the) memory allocations failed
+            case KErrNoMemory:
+                iErr = KScErrNoMemory;
+                break;
+            //  Something else happened...
+            default:
+                iErr = KScErrGeneral;
+                break;
+            }
+        }
+    else
+        {
+        iErr = KErrNone;
+        }
+    User::RequestComplete( iClientStatus, iStatus.Int() );
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimReaderIF::RunL
+// Handle asyncronous response
+// -----------------------------------------------------------------------------
+//
+void CSwimReaderIF::RunL()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimReaderIF::RunL|Begin"));
+    switch ( iIFPhase )
+        {
+        case EOpen:
+            {
+#ifdef _DEBUG        
+            RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "CSwimReaderIF::RunL: Open completed with %d" ), 
+                iStatus.Int() );
+#endif
+            HandleOpen();
+            if ( iErr == KErrNone )
+                {
+                Notify( EScardInserted );
+                iFunctionalLevel->SetCardInserted( ETrue );
+                }
+            else 
+                {
+                Notify( EScardRemoved );
+                iFunctionalLevel->SetCardInserted( EFalse );
+                }
+                
+            break;
+            }
+        case ETransmitToCard:
+            {
+#ifdef _DEBUG        
+            RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "CSwimReaderIF::RunL: TransmitToCard completed with %d" ), 
+                iStatus.Int() );
+#endif
+            User::RequestComplete( iClientStatus, iStatus.Int() );
+            break;
+            }
+
+        default:
+            {
+#ifdef _DEBUG        
+            RFileLogger::WriteFormat( KSwimReaderLogDir, KSwimReaderLogFileName, 
+                EFileLoggingModeAppend, 
+                _L( "CSwimReaderIF::RunL: Invalid phase %d!" ), 
+                iIFPhase );
+#endif
+            User::RequestComplete( iClientStatus, iStatus.Int() );
+            break;
+            }
+        }   
+    _WIMTRACE3(_L("WIM|SwimReader|CSwimReaderIF::RunL|End iIFPhase=%d iErr=%d"), iIFPhase, iErr);
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/SwimReader/src/SwimSysAgentObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,199 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observer class for System Agent events
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "SwimSysAgentObserver.h"
+#include    "SwimReaderIF.h"
+#include    "WimTrace.h"
+
+#ifdef RD_STARTUP_CHANGE
+#include    <startupdomainpskeys.h> // Property values
+#else
+#include    <PSVariables.h>         // Property values
+#endif
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CSwimSysAgentObserver::CSwimSysAgentObserver
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CSwimSysAgentObserver::CSwimSysAgentObserver( CSwimReaderIF* aReaderIF )
+    : CActive( EPriorityNormal )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimSysAgentObserver::CSwimSysAgentObserver|Begin"));
+    CActiveScheduler::Add( this );
+    iReaderIF = aReaderIF;
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimSysAgentObserver::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CSwimSysAgentObserver::ConstructL()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimSysAgentObserver::ConstructL|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimSysAgentObserver::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CSwimSysAgentObserver* CSwimSysAgentObserver::NewL( CSwimReaderIF* aReaderIF )
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimSysAgentObserver::NewL|Begin"));
+    CSwimSysAgentObserver* self = new( ELeave ) CSwimSysAgentObserver ( aReaderIF );
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CSwimSysAgentObserver::~CSwimSysAgentObserver()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimSysAgentObserver::~CSwimSysAgentObserver|Begin"));
+    Cancel();
+    iProperty.Close();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CSwimSysAgentObserver::Start
+// Start listening System agent events
+// -----------------------------------------------------------------------------
+//
+void CSwimSysAgentObserver::Start()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimSysAgentObserver::Start|Begin"));
+    StartListening( ); //Start listening
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimSysAgentObserver::StartListening
+// Start listening card status from System Agent
+// -----------------------------------------------------------------------------
+//
+void CSwimSysAgentObserver::StartListening()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimSysAgentObserver::StartListening|Begin"));
+    iStatus = KRequestPending;
+#ifdef RD_STARTUP_CHANGE
+    TInt err = iProperty.Attach( KPSUidStartup, KPSSimStatus );
+#else
+    TInt err = iProperty.Attach( KUidSystemCategory, KPSUidSIMStatusValue );
+#endif    
+    if ( err == KErrNone )
+        {
+        iProperty.Subscribe( iStatus );
+        }
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CSwimSysAgentObserver::RunL
+// Got card state event
+// -----------------------------------------------------------------------------
+//
+void CSwimSysAgentObserver::RunL()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimSysAgentObserver::RunL|Begin"));
+    //Notify on card event
+    TInt simState;
+    iProperty.Get( simState );
+#ifdef RD_STARTUP_CHANGE
+    switch ( simState )
+          {
+        case ESimUsable: //Card OK, no actions
+            {
+            StartListening();
+            break;
+            }
+
+        // In these states, the SIM card cannot be used by WIM. Notify.
+        // 
+        case ESimReadable:
+        case ESimNotReady:
+        case ESimNotPresent:
+            {
+            iReaderIF->Notify( EScardRemoved ); //Notify Scard server
+            StartListening(); //Start listening again
+            break;
+            }
+
+        // The device does not support any SIM card. WIM cannot be used.
+        //
+        case ESimNotSupported:
+            {
+            break;
+            }
+
+        // These states are considered as fatal errors.
+        //
+        case ESimStatusUninitialized:
+        default:
+            {
+            // __ASSERT_DEBUG( PANIC )
+            break;
+            }
+        }
+#else
+    switch ( simState )
+          {
+        case EPSSimOk: //Card OK, no actions
+            {
+            StartListening();
+            break;
+            }
+        case EPSSimNotPresent: //Flow trough
+        case EPSSimRejected: // Card removed
+            {
+            iReaderIF->Notify( EScardRemoved ); //Notify Scard server
+            StartListening(); //Start listening again
+            break;
+            }
+        default:
+            {
+            break;
+            }
+        }
+#endif // RD_STARTUP_CHANGE
+    }
+
+
+// -----------------------------------------------------------------------------
+// CSwimSysAgentObserver::DoCancel
+// Cancel asynchronous request
+// -----------------------------------------------------------------------------
+//
+void CSwimSysAgentObserver::DoCancel()
+    {
+    _WIMTRACE(_L("WIM|SwimReader|CSwimSysAgentObserver::DoCancel|Begin"));
+    iProperty.Cancel();
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/EABI/WIMCLIENTU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,142 @@
+EXPORTS
+	_ZN11CWimOMAProv10InitializeER14TRequestStatus @ 1 NONAME
+	_ZN11CWimOMAProv13CancelGetSizeEv @ 2 NONAME
+	_ZN11CWimOMAProv14CancelRetrieveEv @ 3 NONAME
+	_ZN11CWimOMAProv16CancelInitializeEv @ 4 NONAME
+	_ZN11CWimOMAProv4NewLEv @ 5 NONAME
+	_ZN11CWimOMAProv7GetSizeERiRK8TOMATypeR14TRequestStatus @ 6 NONAME
+	_ZN11CWimOMAProv8RetrieveERK8TOMATypeR5TDes8R14TRequestStatus @ 7 NONAME
+	_ZN11CWimOMAProvD0Ev @ 8 NONAME
+	_ZN11CWimOMAProvD1Ev @ 9 NONAME
+	_ZN11CWimOMAProvD2Ev @ 10 NONAME
+	_ZN13CWimSecModule10CloseAfterEv @ 11 NONAME
+	_ZN13CWimSecModule11TokenNumberEv @ 12 NONAME
+	_ZN13CWimSecModule12ManufacturerEv @ 13 NONAME
+	_ZN13CWimSecModule12SerialNumberEv @ 14 NONAME
+	_ZN13CWimSecModule13PinNrEntriesLERPK13CArrayPtrFlatI7CWimPinE @ 15 NONAME
+	_ZN13CWimSecModule13PinNrEntriesLERPK13CArrayPtrFlatI7CWimPinER14TRequestStatus @ 16 NONAME
+	_ZN13CWimSecModule13SetCloseAfterEj @ 17 NONAME
+	_ZN13CWimSecModule13TimeRemainingEv @ 18 NONAME
+	_ZN13CWimSecModule15NotifyOnRemovalER14TRequestStatus @ 19 NONAME
+	_ZN13CWimSecModule21CancelNotifyOnRemovalEv @ 20 NONAME
+	_ZN13CWimSecModule4NewLEm @ 21 NONAME
+	_ZN13CWimSecModule5CloseEv @ 22 NONAME
+	_ZN13CWimSecModule5LabelEv @ 23 NONAME
+	_ZN13CWimSecModule6IsOpenEv @ 24 NONAME
+	_ZN13CWimSecModule7VersionEv @ 25 NONAME
+	_ZN13CWimSecModuleD0Ev @ 26 NONAME
+	_ZN13CWimSecModuleD1Ev @ 27 NONAME
+	_ZN13CWimSecModuleD2Ev @ 28 NONAME
+	_ZN14CWimKeyDetails10CancelListEv @ 29 NONAME
+	_ZN14CWimKeyDetails10CancelSignEv @ 30 NONAME
+	_ZN14CWimKeyDetails10GetKeyListER13RPointerArrayI10CCTKeyInfoER13CArrayFixFlatIhER14TRequestStatus @ 31 NONAME
+	_ZN14CWimKeyDetails12CancelExportEv @ 32 NONAME
+	_ZN14CWimKeyDetails16ExportPublicKeyLER6TDesC8RP6HBufC8R14TRequestStatus @ 33 NONAME
+	_ZN14CWimKeyDetails4NewLER8MCTToken @ 34 NONAME
+	_ZN14CWimKeyDetails4SignERK6TDesC8RS0_RP6HBufC8R14TRequestStatus @ 35 NONAME
+	_ZN14CWimKeyDetailsD0Ev @ 36 NONAME
+	_ZN14CWimKeyDetailsD1Ev @ 37 NONAME
+	_ZN14CWimKeyDetailsD2Ev @ 38 NONAME
+	_ZN16CWimSecModuleMgr10CancelListEv @ 39 NONAME
+	_ZN16CWimSecModuleMgr10GetEntriesER14RCPointerArrayI7HBufC16ER14TRequestStatus @ 40 NONAME
+	_ZN16CWimSecModuleMgr16WimLabelByIndexLEi @ 41 NONAME
+	_ZN16CWimSecModuleMgr22WimTokenNumberByIndexLEi @ 42 NONAME
+	_ZN16CWimSecModuleMgr23GetWimSecModuleByIndexLEi @ 43 NONAME
+	_ZN16CWimSecModuleMgr4NewLEv @ 44 NONAME
+	_ZN16CWimSecModuleMgr8WimCountEv @ 45 NONAME
+	_ZN16CWimSecModuleMgrD0Ev @ 46 NONAME
+	_ZN16CWimSecModuleMgrD1Ev @ 47 NONAME
+	_ZN16CWimSecModuleMgrD2Ev @ 48 NONAME
+	_ZN17CWimCertConverter12CancelRemoveEv @ 49 NONAME
+	_ZN17CWimCertConverter13CancelRestoreEv @ 50 NONAME
+	_ZN17CWimCertConverter14AddCertificateERK7TDesC1618TCertificateFormat21TCertificateOwnerTypeRK5TBuf8ILi20EES8_RK6TDesC8R14TRequestStatus @ 51 NONAME
+	_ZN17CWimCertConverter14CancelRetrieveEv @ 52 NONAME
+	_ZN17CWimCertConverter20CancelAddCertificateEv @ 53 NONAME
+	_ZN17CWimCertConverter20RetrieveCertByIndexLEiR5TDes8R14TRequestStatus @ 54 NONAME
+	_ZN17CWimCertConverter4NewLER8MCTToken @ 55 NONAME
+	_ZN17CWimCertConverter7RemoveLEiR14TRequestStatus @ 56 NONAME
+	_ZN17CWimCertConverter7RestoreER13RPointerArrayI12CWimCertInfoER14TRequestStatus @ 57 NONAME
+	_ZN17CWimCertConverterD0Ev @ 58 NONAME
+	_ZN17CWimCertConverterD1Ev @ 59 NONAME
+	_ZN17CWimCertConverterD2Ev @ 60 NONAME
+	_ZN20CWimTrustSettingsAPI11CancelDoingEv @ 61 NONAME
+	_ZN20CWimTrustSettingsAPI16GetTrustSettingsERK12CWimCertInfoRiR6RArrayI4TUidER14TRequestStatus @ 62 NONAME
+	_ZN20CWimTrustSettingsAPI16SetApplicabilityERK12CWimCertInfoRK6RArrayI4TUidER14TRequestStatus @ 63 NONAME
+	_ZN20CWimTrustSettingsAPI19RemoveTrustSettingsERK12CWimCertInfoR14TRequestStatus @ 64 NONAME
+	_ZN20CWimTrustSettingsAPI23SetDefaultTrustSettingsERK12CWimCertInfoiR14TRequestStatus @ 65 NONAME
+	_ZN20CWimTrustSettingsAPI4NewLEv @ 66 NONAME
+	_ZN20CWimTrustSettingsAPI5CloseEv @ 67 NONAME
+	_ZN20CWimTrustSettingsAPI8SetTrustERK12CWimCertInfoiR14TRequestStatus @ 68 NONAME
+	_ZN20CWimTrustSettingsAPID0Ev @ 69 NONAME
+	_ZN20CWimTrustSettingsAPID1Ev @ 70 NONAME
+	_ZN20CWimTrustSettingsAPID2Ev @ 71 NONAME
+	_ZN7CWimPin10UnblockPinER14TRequestStatus @ 72 NONAME
+	_ZN7CWimPin14EnablePinQueryER14TRequestStatus @ 73 NONAME
+	_ZN7CWimPin15CancelChangePinEv @ 74 NONAME
+	_ZN7CWimPin15CancelVerifyPinEv @ 75 NONAME
+	_ZN7CWimPin15DisablePinQueryER14TRequestStatus @ 76 NONAME
+	_ZN7CWimPin16CancelUnblockPinEv @ 77 NONAME
+	_ZN7CWimPin20CancelEnablePinQueryEv @ 78 NONAME
+	_ZN7CWimPin21CancelDisablePinQueryEv @ 79 NONAME
+	_ZN7CWimPin4NewLE7TWimPinmR7TDesC16 @ 80 NONAME
+	_ZN7CWimPin5LabelEv @ 81 NONAME
+	_ZN7CWimPin9ChangePinER14TRequestStatus @ 82 NONAME
+	_ZN7CWimPin9PinNumberEv @ 83 NONAME
+	_ZN7CWimPin9PinStatusEv @ 84 NONAME
+	_ZN7CWimPin9VerifyPinER14TRequestStatus @ 85 NONAME
+	_ZN7CWimPinD0Ev @ 86 NONAME
+	_ZN7CWimPinD1Ev @ 87 NONAME
+	_ZN7CWimPinD2Ev @ 88 NONAME
+	_ZN8CWimCert10InitializeER14TRequestStatus @ 89 NONAME
+	_ZN8CWimCert15CancelGetExtrasEv @ 90 NONAME
+	_ZN8CWimCert16CancelInitializeEv @ 91 NONAME
+	_ZN8CWimCert4NewLEv @ 92 NONAME
+	_ZN8CWimCert9GetExtrasERK6TDesC8R14RCPointerArrayI7HBufC16ER13TCertLocationR14TRequestStatus @ 93 NONAME
+	_ZN8CWimCertD0Ev @ 94 NONAME
+	_ZN8CWimCertD1Ev @ 95 NONAME
+	_ZN8CWimCertD2Ev @ 96 NONAME
+	_ZTI10RWimClient @ 97 NONAME ; #<TI>#
+	_ZTI11CWimOMAProv @ 98 NONAME ; #<TI>#
+	_ZTI12RWimCertMgmt @ 99 NONAME ; #<TI>#
+	_ZTI13CWimSecModule @ 100 NONAME ; #<TI>#
+	_ZTI14CWimKeyDetails @ 101 NONAME ; #<TI>#
+	_ZTI16CWimSecModuleMgr @ 102 NONAME ; #<TI>#
+	_ZTI17CWimCertConverter @ 103 NONAME ; #<TI>#
+	_ZTI20CWimTrustSettingsAPI @ 104 NONAME ; #<TI>#
+	_ZTI21RWimTrustSettingsMgmt @ 105 NONAME ; #<TI>#
+	_ZTI7CWimPin @ 106 NONAME ; #<TI>#
+	_ZTI8CWimCert @ 107 NONAME ; #<TI>#
+	_ZTI8RWimMgmt @ 108 NONAME ; #<TI>#
+	_ZTV10RWimClient @ 109 NONAME ; #<VT>#
+	_ZTV11CWimOMAProv @ 110 NONAME ; #<VT>#
+	_ZTV12RWimCertMgmt @ 111 NONAME ; #<VT>#
+	_ZTV13CWimSecModule @ 112 NONAME ; #<VT>#
+	_ZTV14CWimKeyDetails @ 113 NONAME ; #<VT>#
+	_ZTV16CWimSecModuleMgr @ 114 NONAME ; #<VT>#
+	_ZTV17CWimCertConverter @ 115 NONAME ; #<VT>#
+	_ZTV20CWimTrustSettingsAPI @ 116 NONAME ; #<VT>#
+	_ZTV21RWimTrustSettingsMgmt @ 117 NONAME ; #<VT>#
+	_ZTV7CWimPin @ 118 NONAME ; #<VT>#
+	_ZTV8CWimCert @ 119 NONAME ; #<VT>#
+	_ZTV8RWimMgmt @ 120 NONAME ; #<VT>#
+	_ZN13CWimJavaUtils10GetACFSizeERiRK6TDesC8R14TRequestStatus @ 121 NONAME
+	_ZN13CWimJavaUtils10InitializeER14TRequestStatus @ 122 NONAME
+	_ZN13CWimJavaUtils11GetACIFSizeERiR14TRequestStatus @ 123 NONAME
+	_ZN13CWimJavaUtils15GetAuthObjsInfoERK6RArrayIiERS0_I14TJavaPINParamsER14TRequestStatus @ 124 NONAME
+	_ZN13CWimJavaUtils16CancelGetACFSizeEv @ 125 NONAME
+	_ZN13CWimJavaUtils16CancelInitializeEv @ 126 NONAME
+	_ZN13CWimJavaUtils17CancelGetACIFSizeEv @ 127 NONAME
+	_ZN13CWimJavaUtils18RetrieveACFContentER5TDes8RK6TDesC8R14TRequestStatus @ 128 NONAME
+	_ZN13CWimJavaUtils19RetrieveACIFContentER5TDes8R14TRequestStatus @ 129 NONAME
+	_ZN13CWimJavaUtils21CancelGetAuthObjsInfoEv @ 130 NONAME
+	_ZN13CWimJavaUtils23RetrieveWimLabelAndPathER5TDes8S1_R14TRequestStatus @ 131 NONAME
+	_ZN13CWimJavaUtils24CancelRetrieveACFContentEv @ 132 NONAME
+	_ZN13CWimJavaUtils25CancelRetrieveACIFContentEv @ 133 NONAME
+	_ZN13CWimJavaUtils29CancelRetrieveWimLabelAndPathEv @ 134 NONAME
+	_ZN13CWimJavaUtils4NewLEv @ 135 NONAME
+	_ZN13CWimJavaUtilsD0Ev @ 136 NONAME
+	_ZN13CWimJavaUtilsD1Ev @ 137 NONAME
+	_ZN13CWimJavaUtilsD2Ev @ 138 NONAME
+	_ZTI13CWimJavaUtils @ 139 NONAME ; #<TI>#
+	_ZTV13CWimJavaUtils @ 140 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/bwins/WIMCLIENTU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,98 @@
+EXPORTS
+	??1CWimCert@@UAE@XZ @ 1 NONAME ; CWimCert::~CWimCert(void)
+	??1CWimCertConverter@@UAE@XZ @ 2 NONAME ; CWimCertConverter::~CWimCertConverter(void)
+	??1CWimKeyDetails@@UAE@XZ @ 3 NONAME ; CWimKeyDetails::~CWimKeyDetails(void)
+	??1CWimOMAProv@@UAE@XZ @ 4 NONAME ; CWimOMAProv::~CWimOMAProv(void)
+	??1CWimPin@@UAE@XZ @ 5 NONAME ; CWimPin::~CWimPin(void)
+	??1CWimSecModule@@UAE@XZ @ 6 NONAME ; CWimSecModule::~CWimSecModule(void)
+	??1CWimSecModuleMgr@@UAE@XZ @ 7 NONAME ; CWimSecModuleMgr::~CWimSecModuleMgr(void)
+	??1CWimTrustSettingsAPI@@UAE@XZ @ 8 NONAME ; CWimTrustSettingsAPI::~CWimTrustSettingsAPI(void)
+	?AddCertificate@CWimCertConverter@@QAEXABVTDesC16@@W4TCertificateFormat@@W4TCertificateOwnerType@@ABV?$TBuf8@$0BE@@@3ABVTDesC8@@AAVTRequestStatus@@@Z @ 9 NONAME ; void CWimCertConverter::AddCertificate(class TDesC16 const &, enum TCertificateFormat, enum TCertificateOwnerType, class TBuf8<20> const &, class TBuf8<20> const &, class TDesC8 const &, class TRequestStatus &)
+	?CancelAddCertificate@CWimCertConverter@@QAEXXZ @ 10 NONAME ; void CWimCertConverter::CancelAddCertificate(void)
+	?CancelChangePin@CWimPin@@QAEXXZ @ 11 NONAME ; void CWimPin::CancelChangePin(void)
+	?CancelDisablePinQuery@CWimPin@@QAEXXZ @ 12 NONAME ; void CWimPin::CancelDisablePinQuery(void)
+	?CancelDoing@CWimTrustSettingsAPI@@QAEXXZ @ 13 NONAME ; void CWimTrustSettingsAPI::CancelDoing(void)
+	?CancelEnablePinQuery@CWimPin@@QAEXXZ @ 14 NONAME ; void CWimPin::CancelEnablePinQuery(void)
+	?CancelExport@CWimKeyDetails@@QAEXXZ @ 15 NONAME ; void CWimKeyDetails::CancelExport(void)
+	?CancelGetExtras@CWimCert@@QAEXXZ @ 16 NONAME ; void CWimCert::CancelGetExtras(void)
+	?CancelGetSize@CWimOMAProv@@QAEXXZ @ 17 NONAME ; void CWimOMAProv::CancelGetSize(void)
+	?CancelInitialize@CWimCert@@QAEXXZ @ 18 NONAME ; void CWimCert::CancelInitialize(void)
+	?CancelInitialize@CWimOMAProv@@QAEXXZ @ 19 NONAME ; void CWimOMAProv::CancelInitialize(void)
+	?CancelList@CWimKeyDetails@@QAEXXZ @ 20 NONAME ; void CWimKeyDetails::CancelList(void)
+	?CancelList@CWimSecModuleMgr@@QAEXXZ @ 21 NONAME ; void CWimSecModuleMgr::CancelList(void)
+	?CancelNotifyOnRemoval@CWimSecModule@@QAEXXZ @ 22 NONAME ; void CWimSecModule::CancelNotifyOnRemoval(void)
+	?CancelRemove@CWimCertConverter@@QAEXXZ @ 23 NONAME ; void CWimCertConverter::CancelRemove(void)
+	?CancelRestore@CWimCertConverter@@QAEXXZ @ 24 NONAME ; void CWimCertConverter::CancelRestore(void)
+	?CancelRetrieve@CWimCertConverter@@QAEXXZ @ 25 NONAME ; void CWimCertConverter::CancelRetrieve(void)
+	?CancelRetrieve@CWimOMAProv@@QAEXXZ @ 26 NONAME ; void CWimOMAProv::CancelRetrieve(void)
+	?CancelSign@CWimKeyDetails@@QAEXXZ @ 27 NONAME ; void CWimKeyDetails::CancelSign(void)
+	?CancelUnblockPin@CWimPin@@QAEXXZ @ 28 NONAME ; void CWimPin::CancelUnblockPin(void)
+	?CancelVerifyPin@CWimPin@@QAEXXZ @ 29 NONAME ; void CWimPin::CancelVerifyPin(void)
+	?ChangePin@CWimPin@@QAEXAAVTRequestStatus@@@Z @ 30 NONAME ; void CWimPin::ChangePin(class TRequestStatus &)
+	?Close@CWimSecModule@@QAEHXZ @ 31 NONAME ; int CWimSecModule::Close(void)
+	?Close@CWimTrustSettingsAPI@@QAEXXZ @ 32 NONAME ; void CWimTrustSettingsAPI::Close(void)
+	?CloseAfter@CWimSecModule@@QAEHXZ @ 33 NONAME ; int CWimSecModule::CloseAfter(void)
+	?DisablePinQuery@CWimPin@@QAEXAAVTRequestStatus@@@Z @ 34 NONAME ; void CWimPin::DisablePinQuery(class TRequestStatus &)
+	?EnablePinQuery@CWimPin@@QAEXAAVTRequestStatus@@@Z @ 35 NONAME ; void CWimPin::EnablePinQuery(class TRequestStatus &)
+	?ExportPublicKeyL@CWimKeyDetails@@QAEXAAVTDesC8@@AAPAVHBufC8@@AAVTRequestStatus@@@Z @ 36 NONAME ; void CWimKeyDetails::ExportPublicKeyL(class TDesC8 &, class HBufC8 * &, class TRequestStatus &)
+	?GetEntries@CWimSecModuleMgr@@QAEXAAV?$RCPointerArray@VHBufC16@@@@AAVTRequestStatus@@@Z @ 37 NONAME ; void CWimSecModuleMgr::GetEntries(class RCPointerArray<class HBufC16> &, class TRequestStatus &)
+	?GetExtras@CWimCert@@QAEXABVTDesC8@@AAV?$RCPointerArray@VHBufC16@@@@AAW4TCertLocation@@AAVTRequestStatus@@@Z @ 38 NONAME ; void CWimCert::GetExtras(class TDesC8 const &, class RCPointerArray<class HBufC16> &, enum TCertLocation &, class TRequestStatus &)
+	?GetKeyList@CWimKeyDetails@@QAEXAAV?$RPointerArray@VCCTKeyInfo@@@@AAV?$CArrayFixFlat@E@@AAVTRequestStatus@@@Z @ 39 NONAME ; void CWimKeyDetails::GetKeyList(class RPointerArray<class CCTKeyInfo> &, class CArrayFixFlat<unsigned char> &, class TRequestStatus &)
+	?GetSize@CWimOMAProv@@QAEXAAHABW4TOMAType@@AAVTRequestStatus@@@Z @ 40 NONAME ; void CWimOMAProv::GetSize(int &, enum TOMAType const &, class TRequestStatus &)
+	?GetTrustSettings@CWimTrustSettingsAPI@@QAEXABVCWimCertInfo@@AAHAAV?$RArray@VTUid@@@@AAVTRequestStatus@@@Z @ 41 NONAME ; void CWimTrustSettingsAPI::GetTrustSettings(class CWimCertInfo const &, int &, class RArray<class TUid> &, class TRequestStatus &)
+	?GetWimSecModuleByIndexL@CWimSecModuleMgr@@QAEPAVCWimSecModule@@H@Z @ 42 NONAME ; class CWimSecModule * CWimSecModuleMgr::GetWimSecModuleByIndexL(int)
+	?Initialize@CWimCert@@QAEXAAVTRequestStatus@@@Z @ 43 NONAME ; void CWimCert::Initialize(class TRequestStatus &)
+	?Initialize@CWimOMAProv@@QAEXAAVTRequestStatus@@@Z @ 44 NONAME ; void CWimOMAProv::Initialize(class TRequestStatus &)
+	?IsOpen@CWimSecModule@@QAEHXZ @ 45 NONAME ; int CWimSecModule::IsOpen(void)
+	?Label@CWimPin@@QAE?AVTPtrC16@@XZ @ 46 NONAME ; class TPtrC16 CWimPin::Label(void)
+	?Label@CWimSecModule@@QAE?AVTPtrC16@@XZ @ 47 NONAME ; class TPtrC16 CWimSecModule::Label(void)
+	?Manufacturer@CWimSecModule@@QAEABVTDesC16@@XZ @ 48 NONAME ; class TDesC16 const & CWimSecModule::Manufacturer(void)
+	?NewL@CWimCert@@SAPAV1@XZ @ 49 NONAME ; class CWimCert * CWimCert::NewL(void)
+	?NewL@CWimCertConverter@@SAPAV1@AAVMCTToken@@@Z @ 50 NONAME ; class CWimCertConverter * CWimCertConverter::NewL(class MCTToken &)
+	?NewL@CWimKeyDetails@@SAPAV1@AAVMCTToken@@@Z @ 51 NONAME ; class CWimKeyDetails * CWimKeyDetails::NewL(class MCTToken &)
+	?NewL@CWimOMAProv@@SAPAV1@XZ @ 52 NONAME ; class CWimOMAProv * CWimOMAProv::NewL(void)
+	?NewL@CWimPin@@SAPAV1@W4TWimPin@@KAAVTDesC16@@@Z @ 53 NONAME ; class CWimPin * CWimPin::NewL(enum TWimPin, unsigned long, class TDesC16 &)
+	?NewL@CWimSecModule@@SAPAV1@K@Z @ 54 NONAME ; class CWimSecModule * CWimSecModule::NewL(unsigned long)
+	?NewL@CWimSecModuleMgr@@SAPAV1@XZ @ 55 NONAME ; class CWimSecModuleMgr * CWimSecModuleMgr::NewL(void)
+	?NewL@CWimTrustSettingsAPI@@SAPAV1@XZ @ 56 NONAME ; class CWimTrustSettingsAPI * CWimTrustSettingsAPI::NewL(void)
+	?NotifyOnRemoval@CWimSecModule@@QAEXAAVTRequestStatus@@@Z @ 57 NONAME ; void CWimSecModule::NotifyOnRemoval(class TRequestStatus &)
+	?PinNrEntriesL@CWimSecModule@@QAEHAAPBV?$CArrayPtrFlat@VCWimPin@@@@@Z @ 58 NONAME ; int CWimSecModule::PinNrEntriesL(class CArrayPtrFlat<class CWimPin> const * &)
+	?PinNrEntriesL@CWimSecModule@@QAEHAAPBV?$CArrayPtrFlat@VCWimPin@@@@AAVTRequestStatus@@@Z @ 59 NONAME ; int CWimSecModule::PinNrEntriesL(class CArrayPtrFlat<class CWimPin> const * &, class TRequestStatus &)
+	?PinNumber@CWimPin@@QAEEXZ @ 60 NONAME ; unsigned char CWimPin::PinNumber(void)
+	?PinStatus@CWimPin@@QAEEXZ @ 61 NONAME ; unsigned char CWimPin::PinStatus(void)
+	?RemoveL@CWimCertConverter@@QAEXHAAVTRequestStatus@@@Z @ 62 NONAME ; void CWimCertConverter::RemoveL(int, class TRequestStatus &)
+	?RemoveTrustSettings@CWimTrustSettingsAPI@@QAEXABVCWimCertInfo@@AAVTRequestStatus@@@Z @ 63 NONAME ; void CWimTrustSettingsAPI::RemoveTrustSettings(class CWimCertInfo const &, class TRequestStatus &)
+	?Restore@CWimCertConverter@@QAEXAAV?$RPointerArray@VCWimCertInfo@@@@AAVTRequestStatus@@@Z @ 64 NONAME ; void CWimCertConverter::Restore(class RPointerArray<class CWimCertInfo> &, class TRequestStatus &)
+	?Retrieve@CWimOMAProv@@QAEXABW4TOMAType@@AAVTDes8@@AAVTRequestStatus@@@Z @ 65 NONAME ; void CWimOMAProv::Retrieve(enum TOMAType const &, class TDes8 &, class TRequestStatus &)
+	?RetrieveCertByIndexL@CWimCertConverter@@QAEXHAAVTDes8@@AAVTRequestStatus@@@Z @ 66 NONAME ; void CWimCertConverter::RetrieveCertByIndexL(int, class TDes8 &, class TRequestStatus &)
+	?SerialNumber@CWimSecModule@@QAEABVTDesC16@@XZ @ 67 NONAME ; class TDesC16 const & CWimSecModule::SerialNumber(void)
+	?SetApplicability@CWimTrustSettingsAPI@@QAEXABVCWimCertInfo@@ABV?$RArray@VTUid@@@@AAVTRequestStatus@@@Z @ 68 NONAME ; void CWimTrustSettingsAPI::SetApplicability(class CWimCertInfo const &, class RArray<class TUid> const &, class TRequestStatus &)
+	?SetCloseAfter@CWimSecModule@@QAEXI@Z @ 69 NONAME ; void CWimSecModule::SetCloseAfter(unsigned int)
+	?SetDefaultTrustSettings@CWimTrustSettingsAPI@@QAEXABVCWimCertInfo@@HAAVTRequestStatus@@@Z @ 70 NONAME ; void CWimTrustSettingsAPI::SetDefaultTrustSettings(class CWimCertInfo const &, int, class TRequestStatus &)
+	?SetTrust@CWimTrustSettingsAPI@@QAEXABVCWimCertInfo@@HAAVTRequestStatus@@@Z @ 71 NONAME ; void CWimTrustSettingsAPI::SetTrust(class CWimCertInfo const &, int, class TRequestStatus &)
+	?Sign@CWimKeyDetails@@QAEXABVTDesC8@@AAV2@AAPAVHBufC8@@AAVTRequestStatus@@@Z @ 72 NONAME ; void CWimKeyDetails::Sign(class TDesC8 const &, class TDesC8 &, class HBufC8 * &, class TRequestStatus &)
+	?TimeRemaining@CWimSecModule@@QAEHXZ @ 73 NONAME ; int CWimSecModule::TimeRemaining(void)
+	?TokenNumber@CWimSecModule@@QAEEXZ @ 74 NONAME ; unsigned char CWimSecModule::TokenNumber(void)
+	?UnblockPin@CWimPin@@QAEXAAVTRequestStatus@@@Z @ 75 NONAME ; void CWimPin::UnblockPin(class TRequestStatus &)
+	?VerifyPin@CWimPin@@QAEXAAVTRequestStatus@@@Z @ 76 NONAME ; void CWimPin::VerifyPin(class TRequestStatus &)
+	?Version@CWimSecModule@@QAEABVTDesC16@@XZ @ 77 NONAME ; class TDesC16 const & CWimSecModule::Version(void)
+	?WimCount@CWimSecModuleMgr@@QAEHXZ @ 78 NONAME ; int CWimSecModuleMgr::WimCount(void)
+	?WimLabelByIndexL@CWimSecModuleMgr@@QAE?AVTPtrC16@@H@Z @ 79 NONAME ; class TPtrC16 CWimSecModuleMgr::WimLabelByIndexL(int)
+	?WimTokenNumberByIndexL@CWimSecModuleMgr@@QAEHH@Z @ 80 NONAME ; int CWimSecModuleMgr::WimTokenNumberByIndexL(int)
+	??1CWimJavaUtils@@UAE@XZ @ 81 NONAME ; CWimJavaUtils::~CWimJavaUtils(void)
+	?CancelGetACFSize@CWimJavaUtils@@QAEXXZ @ 82 NONAME ; void CWimJavaUtils::CancelGetACFSize(void)
+	?CancelGetACIFSize@CWimJavaUtils@@QAEXXZ @ 83 NONAME ; void CWimJavaUtils::CancelGetACIFSize(void)
+	?CancelGetAuthObjsInfo@CWimJavaUtils@@QAEXXZ @ 84 NONAME ; void CWimJavaUtils::CancelGetAuthObjsInfo(void)
+	?CancelInitialize@CWimJavaUtils@@QAEXXZ @ 85 NONAME ; void CWimJavaUtils::CancelInitialize(void)
+	?CancelRetrieveACFContent@CWimJavaUtils@@QAEXXZ @ 86 NONAME ; void CWimJavaUtils::CancelRetrieveACFContent(void)
+	?CancelRetrieveACIFContent@CWimJavaUtils@@QAEXXZ @ 87 NONAME ; void CWimJavaUtils::CancelRetrieveACIFContent(void)
+	?CancelRetrieveWimLabelAndPath@CWimJavaUtils@@QAEXXZ @ 88 NONAME ; void CWimJavaUtils::CancelRetrieveWimLabelAndPath(void)
+	?GetACFSize@CWimJavaUtils@@QAEXAAHABVTDesC8@@AAVTRequestStatus@@@Z @ 89 NONAME ; void CWimJavaUtils::GetACFSize(int &, class TDesC8 const &, class TRequestStatus &)
+	?GetACIFSize@CWimJavaUtils@@QAEXAAHAAVTRequestStatus@@@Z @ 90 NONAME ; void CWimJavaUtils::GetACIFSize(int &, class TRequestStatus &)
+	?GetAuthObjsInfo@CWimJavaUtils@@QAEXABV?$RArray@H@@AAV?$RArray@UTJavaPINParams@@@@AAVTRequestStatus@@@Z @ 91 NONAME ; void CWimJavaUtils::GetAuthObjsInfo(class RArray<int> const &, class RArray<struct TJavaPINParams> &, class TRequestStatus &)
+	?Initialize@CWimJavaUtils@@QAEXAAVTRequestStatus@@@Z @ 92 NONAME ; void CWimJavaUtils::Initialize(class TRequestStatus &)
+	?NewL@CWimJavaUtils@@SAPAV1@XZ @ 93 NONAME ; class CWimJavaUtils * CWimJavaUtils::NewL(void)
+	?RetrieveACFContent@CWimJavaUtils@@QAEXAAVTDes8@@ABVTDesC8@@AAVTRequestStatus@@@Z @ 94 NONAME ; void CWimJavaUtils::RetrieveACFContent(class TDes8 &, class TDesC8 const &, class TRequestStatus &)
+	?RetrieveACIFContent@CWimJavaUtils@@QAEXAAVTDes8@@AAVTRequestStatus@@@Z @ 95 NONAME ; void CWimJavaUtils::RetrieveACIFContent(class TDes8 &, class TRequestStatus &)
+	?RetrieveWimLabelAndPath@CWimJavaUtils@@QAEXAAVTDes8@@0AAVTRequestStatus@@@Z @ 96 NONAME ; void CWimJavaUtils::RetrieveWimLabelAndPath(class TDes8 &, class TDes8 &, class TRequestStatus &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/group/WimClient.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Contains information for building project & dll
+*
+*/
+
+
+#include <platform_paths.hrh>
+TARGET WIMCLIENT.dll
+TARGETTYPE dll
+UID             0x1000008d 0x101f79d5
+
+CAPABILITY      CAP_GENERAL_DLL
+VENDORID        VID_DEFAULT
+
+//MACRO           __WIM_ENABLE_TRACES
+//#define         __WIM_ENABLE_TRACES
+
+SOURCE          ../src/WimClient.cpp
+SOURCE          ../src/WimMgmt.cpp
+SOURCE          ../src/WimCertMgmt.cpp
+SOURCE          ../src/WimPin.cpp
+SOURCE          ../src/WimSecModuleMgr.cpp
+SOURCE          ../src/WimSecModule.cpp
+SOURCE          ../src/WimCertConverter.cpp
+SOURCE          ../src/WimKeyDetails.cpp
+SOURCE          ../src/WimCert.cpp
+SOURCE          ../src/ProvSC.cpp
+SOURCE          ../src/WimTrustSettingsAPI.cpp
+SOURCE          ../src/WimTrustSettingsMgmt.cpp
+SOURCE          ../src/JavaUtils.cpp
+
+
+USERINCLUDE     ../inc
+USERINCLUDE     ../../inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         c32.lib efsrv.lib ctframework.lib
+LIBRARY         Wimutil.lib
+LIBRARY         euser.lib
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/inc/WimCertMgmt.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,446 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Certificate & key -management class.
+*
+*/
+
+
+#ifndef WIMCERTMGMT_H
+#define WIMCERTMGMT_H
+
+//  INCLUDES
+#include "WimClient.h"
+#include "WimCertTClassWrappers.h"
+#include "JavaUtils.h"
+
+
+// CLASS DECLARATION
+
+/**
+*  RWimCertMgmt 
+*  This class handle certificate handling and KeyInformation handling
+*  related traffic between client and server.
+*  @lib WimClient
+*  @since Series 60 2.1
+*/
+class RWimCertMgmt: public RWimClient
+    {
+    public:
+
+        /**
+        * A Static method to get the client Session
+        * @Return RWimCertMgmt*
+        */  
+        static RWimCertMgmt* ClientSessionL();
+
+        /**
+        * Destructor.
+        * Allocated memory is released.
+        */  
+        virtual ~RWimCertMgmt();
+        
+        /**
+        * Returns the count of certificates
+        * @param aType  -The type of certificates to be counted.
+        * @return TUint8 -The count of certificates
+        */
+        TUint8 CertCount( TWimEntryType aType );
+
+        /**
+        * Returns certificate list on the WIM.
+        * @param aCertAddrLst - to hold references to certificates
+        * @param aCertInfoArr -address of the certlist address
+        * @param aCount       -the count of certificates
+        * @param aCertEntryType -What type of certificates is wanted:
+        *                ECrEntryTypeAll, ECrEntryTypeCA or ECrEntryTypePersonal  
+        * @param aStatus -Caller's status 
+        * @return void
+        */  
+        void  CertRefLst( TCertificateAddressList aCertAddrLst,
+                          TWimCertInfo* aCertInfoArr, 
+                          TUint8 aCount, 
+                          TWimEntryType aCertEntryType, 
+                          TRequestStatus& aStatus );
+      
+        /**
+        * Returns certificate list on the WIM.
+        * @param aCertAddrLst - to hold references to certificates
+        * @param aCertInfoArr -address of the certlist address
+        * @param aCount       -the count of certificates
+        * @param aCertEntryType -What type of certificates is wanted:
+        *                ECrEntryTypeAll, ECrEntryTypeCA or ECrEntryTypePersonal  
+        * @return TInt -Errorcode from server.
+        */          
+        TInt CertRefLst( TCertificateAddressList aCertAddrLst, 
+                         TWimCertInfo* aCertInfoArr, 
+                         TUint8 aCount, 
+                         TWimEntryType aCertEntryType );
+        /**
+        * Stores the certificate to WIM.
+        * @param aCertificate- certificate
+        * @param aParams - TWimCertAddParameters params to the certificate
+        * @param aLocation  -Location where we want to store. In this case:
+                            EWimCertLocationWIMCard
+        * @return void
+        */
+        void StoreCertificateL( const TDes8& aCertificate, 
+                               TWimCertAddParameters& aParams, 
+                               TWimCertLocation aLocation,
+                               TRequestStatus& aStatus );
+        
+        /**
+        * Removes a certificate from WIM.
+        * @param aWimCertRemoveAddr - reference to the certificate
+        * @param aStatus    -Status from caller
+        * @return void
+        */  
+        void RemoveL( TWimCertRemoveAddr aWimCertRemoveAddr,
+                      TRequestStatus& aStatus );
+
+        /**
+        * Returns certificate details.
+        * @param aCertAddr - reference to the certificate
+        * @param aWimCertDetails -Preallocated structure to hold 
+        *                        the certificate info
+        * @param aStatus    -Caller's status
+        * @return void
+        */  
+        void CertDetailsL( const TCertificateAddress aCertAddr, 
+                           TWimCertDetails& aWimCertDetails,
+                           TRequestStatus& aStatus );
+
+        /**
+        * Gets certificate extra information from one certificate
+        * @param aKeyId - identifies needed certificate
+        * @param aCertExtrasInfo -Preallocated structure to hold 
+        *                        the certificate extra info
+        * @param aUsage     -Identifies the usage of certificate, User or CA
+        * @param aStatus    -Caller's status
+        * @return void
+        */  
+        void GetCertExtrasL(  const TPtr8* aKeyId, 
+                              TCertExtrasInfo& aCertExtrasInfo,
+                              TUint aUsage,
+                              TRequestStatus& aStatus );
+
+        /** 
+        * Returns KeyList from the WIM.
+        * @param aKeyList   -KeyReferences are listed to this
+        * @param aKeyCount  -The number of keys is put to this
+        * @param aStatus    -Caller's status
+        */
+        void KeyList( TDes8& aKeyList,
+                      TDes8& aKeyCount, 
+                      TRequestStatus& aStatus );
+
+        /** 
+        * Gets keyInfo for single key.
+        * @param aKeyReference  -Unique identifier for key.
+        * @param aKeyInfo   -Struct for other key information.
+        */
+        TInt GetKeyInfo( const TInt32 aKeyReference,
+                         TKeyInfo& aKeyInfo );
+
+        /** 
+        * Signs some data
+        * @param aSignParameters -holds data for signing operation
+        * @param aStatus         -Caller's status
+        */
+        void SignL( TKeySignParameters& aSignParameters, 
+                   TRequestStatus& aStatus );
+
+        /** 
+        * Export public key
+        * @param aPublicKeyParams -struct which holds publickeyPtr and Key 
+        *                          identifier.
+        *                          pointer.
+        * @param aStatus        -Caller's Status.
+        */
+        void ExportPublicKeyL( TExportPublicKey& aPublicKeyParams, 
+                              TRequestStatus& aStatus );
+ 
+
+        /**
+        * Retrieves data for OMA Provisioning support. Data can be data size,
+        * type or the actual binary data.
+        * @param aOmaProvStruct -Struct to hold OMA Provisioning data.
+        * @param aStatus        -Caller's status
+        * @param aOpCode        -Code of operation ( EGetOMAFileSize or 
+        *                                            EGetOMAFile
+        *
+        */
+        void RetrieveOmaDataL( TOmaProv& aOmaProvStruct,
+                               TRequestStatus& aStatus,
+                               const TWimServRqst aOpCode );
+       
+       /**
+        * Retrieves ACIF data.
+        *
+        * @since S60 3.2
+        * @param aJavaProvStruct Struct to hold Java data.
+        * @param aStatus Caller's status
+        * @param aOpCode Code of operation 
+        * @return                                            
+        *
+        */
+        void RetrieveACIFDataL( TJavaProv& aJavaProvStruct,
+                               TRequestStatus& aStatus,
+                               const TWimServRqst aOpCode );
+        
+        /**
+        * Retrieves ACF data.
+        *
+        * @since S60 3.2
+        * @param aJavaProvStruct Struct to hold Java data.
+        * @param aStatus Caller's status
+        * @param aOpCode Code of operation 
+        * @return                                           
+        *
+        */                        
+        void RetrieveACFDataL( TJavaProv& aJavaProvStruct,
+                               TRequestStatus& aStatus,
+                               const TWimServRqst aOpCode );   
+        
+        /**
+        * Retrieves Authtication object data.
+        *
+        * @since S60 3.2
+        * @param aAuthIdList 
+        * @param aAuthObjsInfoList 
+        * @param aStatus Caller's status
+        * @param aOpCode Code of operation 
+        * @return                                           
+        *
+        */                       
+        void RetrieveAuthObjsInfoL(const RArray<TInt>& aAuthIdList,
+                              RArray<TJavaPINParams>& aAuthObjsInfoList,
+                              TRequestStatus& aStatus,
+                              const TWimServRqst aOpCode );  
+        
+        
+        /**
+        * Retrieves Label and Path.
+        *
+        * @since S60 3.2
+        * @param aLabel
+        * @param aPath 
+        * @param aStatus Caller's status
+        * @param aOpCode Code of operation 
+        * @return                                           
+        *
+        */                         
+        void RetrieveLabelAndPathL( TDes8& aLabel,
+        	                        TDes8& aPath, 
+                                    TRequestStatus& aStatus,
+                                    const TWimServRqst aOpCode );                      
+                                                                                    
+        /** 
+        * Deallocates memory from iPckgCertDetails.
+        * @return void
+        */
+        void DeallocWimCertPckgBuf();
+
+        /** 
+        * Deallocates memory from iPckgAddCerts.
+        * @return void
+        */
+        void DeallocCertAddParametersPckgBuf();
+
+        /** 
+        * Deallocates memory from iPckgRemoveCert.
+        * @return void
+        */
+        void DeallocRemoveCertPckgBuf();
+
+        /**
+        * Deallocates memory from iPckgGetExtrasAllocated.
+        * @return void
+        */
+        void DeallocGetExtrasPckgBuf();
+
+        /**
+        * Deallocates memory from iPckgKeySignParameters.
+        * @return void
+        */
+        void DeallocKeySignPckgBuf();
+
+        /**
+        * Deallocates memory from iPckgBufExportPublicKey.
+        * @return void
+        */
+        void DeallocExportPublicKeyPckgBuf();
+
+        /** 
+        * Deallocates memory from iPckgBufOmaProv
+        * @return void
+        */
+        void DeallocOmaDataPckgBuf();
+        
+        /** 
+        * Deallocates memory from iPckgBufJavaProv
+        * @return void
+        */
+        void DeallocJavaDataPckgBuf();
+
+        /** 
+        * Return CWimCertPckgBuf<TCertExtrasInfo> pointer to caller
+        * @return CWimCertPckgBuf<TCertExtrasInfo>* 
+        */
+        CWimCertPckgBuf<TCertExtrasInfo>* CertExtrasPckgBuf();
+
+        /** 
+        * Return CWimCertPckgBuf<TOmaProv> pointer to caller
+        * @return CWimCertPckgBuf<TOmaProv>* 
+        */
+        CWimCertPckgBuf<TOmaProv>* TOmaProvPckgBuf();
+        
+        /** 
+        * Return CWimCertPckgBuf<TJavaProv> pointer to caller
+        * @return CWimCertPckgBuf<TJavaProv>* 
+        */
+        CWimCertPckgBuf<TJavaProv>* TJavaProvPckgBuf();
+        
+    private:
+        
+        /**
+        * Constructor 
+        */
+        RWimCertMgmt();
+
+        /** 
+        * Copy constructor
+        * @param aSource -Reference to class object.
+        */
+        RWimCertMgmt( const RWimCertMgmt& aSource );
+
+        /** 
+        * Assignment operator
+        * @param aParam -Reference to class object.
+        */
+        RWimCertMgmt& operator = ( const RWimCertMgmt& aParam );
+
+    private:
+      
+        //Used to point data when listing every certificate from WIM.
+        TPtr8                                   iCertLst;
+
+        //Used to point data when listing every certificate from WIM.
+        TPtr8                                   iCertInfoLst;
+
+        //PckgBuffer wrapper which is used when retrieving certificate.Owned.
+        CWimCertPckgBuf<TWimCertDetails>*       iPckgBufCertDetails;
+
+        //PckgBuffer wrapper which is used when adding a certificate.Owned.
+        CWimCertPckgBuf<TWimCertAddParameters>* iPckgBufAddCerts;
+
+        //PckgBuffer wrapper which is used when removing a certificate.Owned.
+        CWimCertPckgBuf<TWimCertRemoveAddr>*    iPckgBufRemoveCert;
+
+        //PckgBuffer wrapper which is used when getting certificate extra 
+        //information from server.Owned.
+        CWimCertPckgBuf<TCertExtrasInfo>*       iPckgBufGetExtras;
+
+        //Pckgbuffer wrapper which is used when signing data.Owned.
+        CWimCertPckgBuf<TKeySignParameters>*    iPckgBufKeySignParameters;
+
+        //Pckgbuffer wrapper which is used when exporting public key.Owned.
+        CWimCertPckgBuf<TExportPublicKey>*      iPckgBufExportPublicKey;
+
+        //Pckgbuffer wrapper which is used when getting data for 
+        //OMA Provisioning.Owned.
+        CWimCertPckgBuf<TOmaProv>*              iPckgBufOmaProv;
+        
+        //Pckgbuffer wrapper which is used when getting data for 
+        //Java Provisioning.Owned.
+        CWimCertPckgBuf<TJavaProv>*             iPckgBufJavaProv;
+        
+        //Flag to indicate whether certificate details package is allocated or 
+        //not.
+        TBool                                   iPckgBufCertDetailsAllocated;
+        
+        //Flag to indicate whether add certificate package is allocated or not.
+        TBool                                   iPckgBufAddCertsAllocated;
+
+        //Flag to indicate whether remove certificate package is allocated or 
+        //not.
+        TBool                                   iPckgBufRemoveCertAllocated;
+
+        //Flag to indicate whether extra information package is allocated or 
+        //not
+        TBool                                   iPckgBufGetExtrasAllocated;
+
+        //Flag to indicate whether signing package is allocated or not.
+        TBool                                   iPckgBufKeySignAllocated;
+    
+        //Flag to indicate whether export public key package is allocated or 
+        //not
+        TBool                                   iPckgBufExportPublicKeyAllocated;
+
+        //Flag to indicate whether OMA Provisioning package is allocated or 
+        //not
+        TBool                                   iPckgBufOmaProvAllocated;
+        
+        //Flag to indicate whether Java Provisioning package is allocated or 
+        //not
+        TBool                                   iPckgBufJavaProvAllocated;
+        
+        TPtr8*                                  iAuthObjsInfoLstPtr;
+	    
+	    TPtrC8*                                 iAuthIdLstPtr;
+
+    };
+
+#endif //WIMCERTMGMT_H
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/inc/WimCertTClassWrappers.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,106 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  These wrappers are used when we need to fetch/insert 
+*               certificate data asyncronously.
+*
+*/
+
+
+#ifndef WIMCERTCLASSWRAPPERS_H
+#define WIMCERTCLASSWRAPPERS_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// CLASS DECLARATION
+
+/**
+*  Class which wraps a TPckg -buffer. 
+*
+*  @lib WimClient
+*  @since Series60 2.1
+*/
+template <class T>
+class CWimCertPckg : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * C++ constructor.
+        */
+        inline CWimCertPckg( const T& aRef );
+        
+        /**
+        * Destructor.
+        */
+        inline virtual ~CWimCertPckg();
+
+    public: // New functions
+        
+        /**
+        * @return TPckg<T>* Pointer to TPckg<T> typed member
+        */
+        inline TPckg<T>* Pckg();
+
+    private:    // Data
+        // Wrapped TPckg<T>
+        TPckg<T>    iPckg;
+    };
+
+
+/**
+*  Class which wraps a TPckgBuf -buffer. 
+*
+*  @WimClient
+*  @since Series60 2.1
+*/
+template <class T>
+class CWimCertPckgBuf : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * C++ default constructor.
+        */
+        inline CWimCertPckgBuf();
+
+        /**
+        * C++ constructor.
+        */
+        inline CWimCertPckgBuf( const T& aRef );
+        
+        /**
+        * Destructor.
+        */
+        inline virtual ~CWimCertPckgBuf();
+
+
+    public: // New functions
+        
+        /**
+        * @return TPckgBuf<T>* Pointer to TPckgBuf<T> typed member
+        */
+        inline TPckgBuf<T>* PckgBuf();
+
+    private:    // Data
+        // Wrapped TPckgBuf<T>
+        TPckgBuf<T>    iPckgBuf;
+        
+    };
+
+#include "WimCertTClassWrappers.inl"
+
+#endif //WIMICERTCLASSWRAPPERS_H         
+            
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/inc/WimCertTClassWrappers.inl	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  These wrappers are used when we need to fetch/insert 
+*               certificate data asyncronously.
+*
+*/
+
+
+// -----------------------------------------------------------------------------
+// Inline implementation of CWimCertPckgBuf<T> class
+// -----------------------------------------------------------------------------
+
+
+// -----------------------------------------------------------------------------
+// CWimCertPckg<T>::CWimCertPckg()
+// C++ constructor.
+// -----------------------------------------------------------------------------
+template <class T>
+inline CWimCertPckg<T>::CWimCertPckg( const T& aRef ) : iPckg( aRef )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertPckg<T>::~CWimCertPckg()
+// Destructor.
+// -----------------------------------------------------------------------------
+template <class T>
+inline CWimCertPckg<T>::~CWimCertPckg()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertPckgBuf<T>::Pckg()
+// return TPckg<T>* Pointer to TPckg<T> typed member
+// -----------------------------------------------------------------------------
+template <class T>
+inline TPckg<T>* CWimCertPckg<T>::Pckg()
+    {
+    return &iPckg; 
+    }
+
+
+// -----------------------------------------------------------------------------
+// Inline implementation of CWimCertPckgBuf<T> class
+// -----------------------------------------------------------------------------
+
+// -----------------------------------------------------------------------------
+// CWimCertPckgBuf<T>::CWimCertPckgBuf()
+// C++ default constructor.
+// -----------------------------------------------------------------------------
+template <class T>
+inline CWimCertPckgBuf<T>::CWimCertPckgBuf() : iPckgBuf()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertPckgBuf<T>::CWimCertPckgBuf( const T& aRef ) 
+// C++ constructor.
+// -----------------------------------------------------------------------------
+template <class T>
+inline CWimCertPckgBuf<T>::CWimCertPckgBuf( const T& aRef ) : iPckgBuf( aRef )
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimCertPckgBuf<T>::~CWimCertPckgBuf() 
+// Destructor.
+// -----------------------------------------------------------------------------
+template <class T>
+inline CWimCertPckgBuf<T>::~CWimCertPckgBuf()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertPckgBuf<T>::PckgBuf()
+// -----------------------------------------------------------------------------
+template <class T>
+inline TPckgBuf<T>* CWimCertPckgBuf<T>::PckgBuf()
+    {
+    return &iPckgBuf; 
+    }
+
+
+
+
+//  End of File  
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/inc/WimClient.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,164 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Startup place for client & server, message handling.
+*
+*/
+
+
+#ifndef WIMCLIENT_H
+#define WIMCLIENT_H
+
+//  INCLUDES
+#include "WimClsv.h"
+#include <f32file.h>
+#include <e32base.h> 
+
+//FORWARD DECLARATIONS
+class TWIMSrvStartSignal;
+
+//The number of message slots represents the number of operations that
+//can be outstanding at once. If you wish to have more asynchronous operations 
+//outstanding than this, use more message slots. 
+//You should always provide an extra slot for the cancel operation.
+const TInt KMessageSlotsNum = 5;
+
+
+// CLASS DECLARATION
+
+/**
+*  RWimClient, this creates new connection to server and sends 
+*  syncronous & asyncronous messages to server. 
+*  
+*  @lib WimClient
+*  @since Series 60 2.1
+*/
+class RWimClient: public RSessionBase
+    {
+    public:
+
+        /**
+        * Constructor 
+        */
+        RWimClient();
+
+        /**
+        * Destructor 
+        */
+        virtual ~RWimClient();
+
+        /**
+        * Connect to WIMI server
+        * @return TInt
+        */
+        TInt Connect();
+
+        /** 
+        * Starts Server
+        * @return TInt -error code
+        */
+        TInt StartWim();
+
+
+        /** 
+        * Sends initialization command to Server.
+        * @param aStatus -Client status
+        * @return void
+        */
+        void Initialize( TRequestStatus& aStatus );
+        
+        /** 
+        * Cancel initialization command to Server.
+        * @return void
+        */
+        void CancelInitialize();
+
+        /**
+        * Return version
+        * @return TVersion
+        */
+        TVersion Version() const;
+
+        /**
+        * Sends data synchronoysly to server
+        * @param aFn the WIMRequest operation 
+        * @param aIpcArgs IPC parameters
+        * @return TInt
+        */
+        TInt SendReceiveData( TWimServRqst aFn, TIpcArgs& aIpcArcs );
+
+        /**
+        * Sends data asynchronoysly to server
+        * @param aFn the WIMRequest operation 
+        * @param aIpcArgs IPC parameters
+        * @param aStatus -Caller's status
+        * @return void
+        */
+        void SendReceiveData( TWimServRqst aFn, 
+                              TIpcArgs& aIpcArgs,
+                              TRequestStatus& aStatus );
+
+        /**
+        * Free the address list  
+        * @param addrLst -Address of a list to be freed
+        * @return void
+        */
+        void FreeAddrLst( const TUint32 addrLst );
+
+        /**
+        * Free the address list 
+        * @param addrLst    -Reference to WIMI
+        * @param aSize      -Size to be freed
+        * return void
+        */
+        void FreeWIMAddrLst( const TWimAddressList addrLst, const TUint aSize );
+
+        /**
+        * Free the address list  
+        * @param aAddr  -Referece to WIMI
+        * return void
+        */
+        void FreeWIMAddr( const TWimAddress aAddr );
+
+
+    private:
+
+
+        /** 
+        * Return the name of the Wim server file
+        * @param aServer -descriptor for server filename
+        * @return TInt -error code
+        */
+        TInt FindServerFileName( TFileName& aServer );
+    
+    
+    private:
+        
+        /** 
+        * Copy constructor
+        * @param aSource -Reference to class object.
+        */
+        RWimClient( const RWimClient& aSource );
+
+        /** 
+        * Assigment operator
+        * @param aParam -Reference to class object.
+        */
+        RWimClient& operator = ( const RWimClient& aParam );
+
+
+
+
+    };
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/inc/WimMgmt.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,266 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Startup place for client & server, message handling.
+*
+*/
+
+
+#ifndef WIMMGMT_H
+#define WIMMGMT_H
+
+//  INCLUDES
+#include "WimClient.h"
+#include "WimCertTClassWrappers.h"
+#include <secdlg.h>
+
+/**
+*  RWimMgmt 
+*  This class inherits RWimClient and communicates with it.
+*  @lib WimClient
+*  @since Series 60 2.1
+*/
+class RWimMgmt: public RWimClient
+    {
+    public:
+
+        /**
+        * Destructor 
+        */
+        virtual ~RWimMgmt();
+
+        /**
+        * Returns  TUint - the number of WIMs
+        * @return TUint
+        */
+        TUint WIMCount();
+        
+        /**
+        * Gets the array of WIM structures.
+        * @param aWimAddrLst - Pointer to a list of allocated WIM structures
+        * @param aCount  - is the number of WIMs
+        * @return TInt -Error code
+        */
+        TInt WIMRefs( TWimAddressList aWimAddrLst, TUint8 aCount );
+
+
+        /**
+        * Tests whether WIM is open or not.
+        * @param aWimAddr - Address to the WIM.
+        * @return Boolean
+        */
+        TBool IsOpen( const TWimAddress aWimAddr );
+
+        /**
+        * Closes the WIM and returns the status of the WIMI_CloseWIM()
+        * @param aWimAddr - Address to the WIM 
+        * @return TInt the return status of Close   
+        */
+        TInt CloseWIM( const TWimAddress aWimAddr );
+
+        /**
+        * Gets the WIM information in to aTWimSecModuleStruct
+        * @param aWimAddr -Address to the WIM structure (IN)
+        * @param aTWimSecModuleStruct -Reference to the Structure to contain 
+        *                                WIM  information (OUT)
+        * @return TInt -Error code
+        */
+        TInt WIMInfo( const TWimAddress aWimAddr, 
+                      TWimSecModuleStruct& aTWimSecModuleStruct );
+  
+        /**
+        * Returns the time which is set as WIM closing time
+        * @return TUint -closing time
+        */
+        TInt CloseAfter();
+
+        /**
+        * Returns TUint - the timeout in minutes, which tells how long WIM 
+        * Security Module will be open
+        * @return TUint -timeout
+        */
+        TInt TimeRemaining();
+  
+        /*
+        * Sets closing time for WIM.
+        * @param aCloseAfter
+        * @return void
+        */
+        void SetCloseAfter( const TUint aCloseAfter );
+        
+        /**
+        * Returns the count of PINs
+        * @param aWimAddr- Address to the WIM structure (IN)
+        * @return TUint -the count of PINs
+        */  
+        TUint PINCount( const TWimAddress aWimAddr );
+
+        /**
+        * Gets the array of PIN structures.
+        * @param aWimAddr -Address to the WIM structure
+        * @param aPinLstAddr -Reference to PIN list
+        * @param aPinAddrLst    -Address to PIN address list
+        * @param aCount -Count of PINs
+        * @return TInt -Error code
+        */
+        TInt PINRefs( const TWimAddress aWimAddr, 
+                      TUint32& aPinLstAddr, 
+                      TPinAddressList aPinAddrLst, 
+                      TUint8 aCount );
+    
+        /**
+        * Get all of the pins information on a given SecMod asynchronously.
+        * @ param aPinInfoLst array to store the PINs information 
+        * return void 
+        */
+        void PINsInfo( const TWimAddress aWimAddr, 
+                        CArrayFixFlat<TWimPinStruct>& aPinInfoLst,
+                        TUint8 aCount,
+                        TRequestStatus& aStatus );
+        /**
+        * Get all of the pins information on a given SecMod synchronously.
+        * @ param aPinInfoLst array to store the PINs information 
+        * return void 
+        */                
+        TInt PINsInfo( const TWimAddress aWimAddr, 
+               CArrayFixFlat<TWimPinStruct>& aPinInfoLst,
+               TUint8 aCount );                
+        
+        /**
+        * Gets the PIN information in to aPinStruct
+        * @param aPinAddr -Address to the PIN structure (IN)
+        * @param aPinStruct -Reference to the Structure to containing PIN 
+        *                    information (OUT)
+        * @return TInt -Error code
+        */  
+        void PINInfo( const TPinAddress aPinAddr,
+                      TWimPinStruct& aPinStruct,
+                      TRequestStatus& aStatus );
+
+        /**
+        * Used to check is PIN blocked or not.
+        * @param aPinAddr -Address to the PIN struct
+        * @return TInt -Error code
+        */  
+        TInt IsBlocked( const TPinAddress aPinAddr );
+        
+        /**
+        * Used to check is Disabled PIN blocked or not.
+        * @param aPinAddr -Address to the PIN struct
+        * @return TInt -Error code
+        */ 
+        TInt IsDisabledPINBlocked( const TPinAddress aPinAddr );
+
+        /** 
+        * Handles Enable and Disable PIN requests. Server
+        * knows wanted operation by flag which is set in TPINStateRequest.
+        * @param aPinAddr   -Address to the PIN struct.
+        * @param aPinStateRequest   -Enable/Disable flag
+        * @param aPinParams     -General information about PIN.
+        * @param aStatus    -Caller's status
+        * @return void   
+        */
+        void EnableDisablePinQueryL(
+                            const TPinAddress aPinAddr,
+                            const TPINStateRequest& aPinStateRequest,
+                            const TPINParams& aPinParams,
+                            TRequestStatus& aStatus );
+        
+        /** 
+        * Cancel Enable and Disable PIN requests. Server
+        * knows wanted operation by flag which is set in TPINStateRequest.
+        * @param aPinAddr   -Address to the PIN struct.
+        * @return void   
+        */
+        void CancelEnableDisablePin( const TPinAddress aPinAddr );
+        
+        /** 
+        * PinOperationL handles several PIN operations: it can be
+        * verify PIN request, change PIN request or unblock PIN request. The 
+        * type of request is handled via aOpCode.
+        * @param aPinAddr   -Address to the PIN struct
+        * @param aPinParams -General information about PIN
+        * @param aOpCode    -Code that informs the type of operation
+        * @param aStatus    -Caller's status
+        * @return void
+        */
+        void PinOperationL( const TPinAddress aPinAddr,
+                            const TPINParams aPinParams,
+                            const TWimServRqst aOpCode,
+                            TRequestStatus& aStatus );
+        
+        /** 
+        * Cancel PinOperationL handles several PIN operations: it can be
+        * verify PIN request, change PIN request or unblock PIN request. The 
+        * type of request is handled via aOpCode.
+        * @param aPinAddr   -Address to the PIN struct
+        * @param aOpCode    -Code that informs the type of operation
+        * @return void
+        */
+        void CancelPinOperation( const TPinAddress aPinAddr, const TWimServRqst aOpCode );                     
+
+        /**
+        * A static method to get the client session.
+        * @Return RWimMgmt*
+        */  
+        static RWimMgmt* ClientSessionL();
+
+        /** 
+        * Deallocates memory from pckgBuf member variables
+        * @return void
+        */
+        void DeallocMemoryFromEnableDisablePinQuery();
+
+    private:
+
+        /**
+        * Constructor 
+        */
+        RWimMgmt();
+
+        /** 
+        * Copy constructor
+        * @param aSource -Reference to class object.
+        */
+        RWimMgmt( const RWimMgmt& aSource );
+
+        /** 
+        * Assigment operator
+        * @param aParam -Reference to class object.
+        */
+        RWimMgmt& operator = ( const RWimMgmt& aParam );
+
+    private:
+
+        //PckgBuffer to hold PIN state information
+        CWimCertPckgBuf<TPINStateRequest>*  iPinStateRequestBuf;
+
+        //PckgBuffer to hold PIN parameters information
+        CWimCertPckgBuf<TPINParams>*        iPinParamsBuf;
+
+        //Indicates whether iPinStateRequestBuf is allocated or not
+        TBool                               iPinStateRequestBufAllocated;
+
+        //Indicates whether iPinParamsBuf is allocated or not
+        TBool                               iPinParamsBufAllocated;
+        
+        //The pointer descriptor to pin info list
+        TPtr8*                              iPinInfoLstPtr; 
+        
+        TPckg<TWimPinStruct>*               iPinModule;
+
+
+    };
+
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/inc/WimSecModule.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,280 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  API for managing WIM Security Module
+*
+*/
+
+
+
+#ifndef WIMSECMODULE_H
+#define WIMSECMODULE_H
+
+//  INCLUDES
+#include "WimClsv.h"
+#include <e32base.h>
+
+// FORWARD DECLARATIONS
+class CWimPin;
+class RWimMgmt;
+
+
+// CLASS DECLARATION
+
+/**
+*  API for managing WIM Security Module.
+*  Provides methods to manage one WIM Security Module:
+*  check statuses, change settings, use functionality 
+*  provide it and list PINs.
+*
+*  @lib WimClient
+*  @since Series 60 2.1
+*/
+class CWimSecModule: public CActive
+    {
+    public:  // Constructors and destructor
+                    
+        /**
+        * Two-phased constructor.
+        * @param aWimAddr
+        */
+        IMPORT_C static CWimSecModule* NewL( TWimAddress aWimAddr ); 
+        
+        /**
+        * Destructor.
+        */
+        IMPORT_C virtual ~CWimSecModule();
+
+    public: // New functions
+            
+        /**
+        * Checks is WIM already open.
+        * @return ETrue if WIM's is open (=PIN-G verified)
+        *         else EFalse  
+        */
+        IMPORT_C TBool IsOpen(); 
+
+        /**
+        * Returns the time which is set as WIM closeout time
+        * @return Timeout in minutes
+        */
+        IMPORT_C TInt CloseAfter();
+
+        /**
+        * Returns the timeout which tells how 
+        * long WIM Security Module will be open 
+        * after it is opened.
+        * @return Timeout in minutes
+        */
+        IMPORT_C TInt TimeRemaining();
+
+        
+        /**
+        * Returns WIM Security Module's keys' PIN-NR objects in array.
+        * @param aPinNRs -Array of pointers to CWimPin objects which
+        *                are initialized as PIN-NR. (IN/OUT)
+        * @return TInt  -Error code
+        */
+        IMPORT_C TInt PinNrEntriesL( const CArrayPtrFlat<CWimPin>*& aPinNRs, TRequestStatus& aStatus  );
+     
+        /**
+        * Returns WIM Security Module's keys' PIN-NR objects in array.
+        * @param aPinNRs -Array of pointers to CWimPin objects which
+        *                are initialized as PIN-NR. (IN/OUT)
+        * @return TInt  -Error code
+        */
+        IMPORT_C TInt PinNrEntriesL( const CArrayPtrFlat<CWimPin>*& aPinNRs );
+        
+        /**
+        * Returns WIM's version. This will return KErrNone according to PKC15. 
+        * @return Pointer descriptor containing version.
+        */
+        IMPORT_C const TDesC& Version();
+
+        /**
+        * Returns WIM's label.
+        * @return Pointer descriptor containing label.
+        */
+        IMPORT_C TPtrC Label();
+
+        /**
+        * Returns WIM's manufacturer.
+        * @return Pointer descriptor containing manufacturer.
+        */
+        IMPORT_C const TDesC& Manufacturer();
+
+        /**
+        * Returns WIM's serial number which identifies it.
+        * @return Pointer descriptor containing serial number
+        */
+        IMPORT_C const TDesC& SerialNumber();
+
+        /**
+        * Closes the parts of WIM which is opened with PIN-G.
+        * @return TInt Error code
+        */
+        IMPORT_C TInt Close();
+
+        /**
+        * Sets the timeout which defines the time after WIM 
+        * is automatically closed.
+        * @param aTimeout, timeout in minutes.
+        * @return void
+        */
+        IMPORT_C void SetCloseAfter( const TUint aTimeout );
+
+
+        /**
+        * Notifies the client when the token has been removed.
+        * @param aStatus -TRequestStatus
+        * @return void
+        */
+        IMPORT_C void NotifyOnRemoval( TRequestStatus& aStatus );
+
+        /**
+        * Cancels the notifyOnRemoval request.
+        * @return void
+        */
+        IMPORT_C void CancelNotifyOnRemoval();
+
+        /**
+        * Returns the number of the slot, where current token is connected
+        * @return TUint8
+        */
+        IMPORT_C TUint8 TokenNumber();
+
+        /**
+        * Sets pointer RWimMgmt object to modifier iClientSession
+        * @param aClientSession Client session
+        * @return void
+        */
+        void SetClientSession( RWimMgmt* aClientSession );
+
+
+    private:
+
+        /**
+        * C++ constructor.
+        * @param aWimAddr
+        */
+        CWimSecModule( TWimAddress aWimAddr );
+
+        /**
+        * By default EPOC constructor is private.
+        */
+        void ConstructL();
+
+
+        /**
+        * Gets label,manufacturer,serialnumber and the number of 
+        * the slot where card is.
+        * @return TInt
+        */
+        TInt GetWIMInfoL(); 
+
+        /** 
+        * Handles cleanup for an object which is not derived from CBase
+        * @param aObject -object to be cleaned up
+        */
+        static void Cleanup( TAny* aObject );
+
+        /** 
+        * Converts serialnumber to 8-bit form. Conversion reads
+        * memory area from orginal serialnumber and captures its significant
+        * bits to a new 8-bit -modifier. 
+        * @param aSerialNumber -number to be converted
+        * @return void
+        */
+        void ConvertSerialNumberL( HBufC*& aSerialNumber );
+        
+    private:  
+        
+        /**
+        * Gets PIN references and creates new CWimPin objects
+        * @return TInt  -Error code
+        */
+        TInt GetPINModulesL( TRequestStatus& aStatus );
+        
+        /**
+        * Gets PIN references and creates new CWimPin objects
+        * @return TInt  -Error code
+        */
+        TInt GetPINModulesL();
+        
+    private: //from CActive
+        
+        /**
+        * Different phases are handled here.
+        * @return void
+        */
+        void RunL();
+        
+        /**
+        * Cancellation function
+        * Deallocates member variables and completes client status with
+        * KErrCancel error code.
+        * @return void
+        */
+        void DoCancel();
+
+        /**
+        * The active scheduler calls this function if this active 
+        * object's RunL() function leaves. 
+        * Handles neccessary cleanup and completes request with
+        * received error code.
+        * @param aError -Error code which caused this event
+        * @return TInt  -Error code to active scheduler, is always KErrNone.
+        */ 
+        TInt RunError( TInt aError );    
+  
+    private: 
+
+        // Reference to WIM. 
+        TWimAddress             iReference;  
+        // Array of pointers to PIN-NRs.This class owns this and
+        // this is valid as long as CWimSecModule is valid.
+        CArrayPtrFlat<CWimPin>* iPinNRs; 
+        //Contains tokens label.Owned
+        HBufC*                  iLabel;
+        //Contains tokens manufacturer.Owned
+        HBufC*                  iManufacturer;
+        //Contains tokens SerialNumber.Owned
+        HBufC*                  iSerialNumber;
+        //Contains tokens version. Owned
+        HBufC*                  iVersion;
+        //The "slot" where WIM-card is inserted
+        TUint8                  iReader;        
+        //pointer to RWIMMgmt. Owned by CWimSecModuleMgr.
+        RWimMgmt*               iClientSession;
+        //Boolean value 
+        TBool                   iWimInfoConstructed;
+        //TUint32, reference to pinlist.
+        TUint32                 iPinLstAddr;
+        //TUint32, reference to ping.
+        TPinAddress             iRefPing;
+        
+        TWimPinStruct*          iPinStructLst; //Owned
+        
+        TRequestStatus*         iClientStatus;
+        
+        TUint                   iPinCount;
+        
+        CArrayFixFlat<TWimPinStruct>* iPinInfoLst; //Owned
+        //ETrue if iPinNRs is initialized
+        TBool                   iPinNRsInit;
+
+    };
+
+#endif      // WIMSECMODULE_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/inc/WimSecModuleMgr.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,244 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  API for listing all WIM Security Modules
+*
+*/
+
+
+#ifndef WIMSECMODULEMGR_H
+#define WIMSECMODULEMGR_H
+
+//  INCLUDES
+#include "WimClsv.h"
+#include "WimSig.h"
+#include <e32base.h>
+#include <ct.h> 
+
+// FORWARD DECLARATIONS
+class CWimSecModule;
+class RWimMgmt;
+
+
+// CLASS DECLARATION
+/**
+*  API for list all WIM Security Modules
+*  This API provides function to list all WIM Security Modules
+*  which your device finds. Listed CWimSecModule objects provides 
+*  methods to manage key stores. 
+*
+*  @lib WimClient
+*  @since Series 60 2.1
+*/
+class CWimSecModuleMgr: public CActive
+    {
+    public:  
+        
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CWimSecModuleMgr* NewL(); 
+         
+        /**
+        * Destructor.
+        */
+        IMPORT_C virtual ~CWimSecModuleMgr();
+
+    public: // New functions
+        
+        /**
+        * Returns all WIM Security Modules in array. 
+        * @param  aTokens     Array containing all WIMs.(OUT)
+        * @param  aStatus   Status from caller.         
+        * @return void
+        */
+        IMPORT_C void GetEntries( RCPointerArray<HBufC>& aTokens, 
+            TRequestStatus& aStatus );
+        
+
+        /**
+        * Cancels listing operation. 
+        * @return void
+        */        
+        IMPORT_C void CancelList();
+
+        /**
+        * Returns the number of WIM cards
+        * If WIM is not initialized and listing operation completed
+        * before calling WimCount(), this will return KErrNotFound.
+        * @return TInt     aNumber of wims.
+        */        
+        IMPORT_C TInt WimCount();
+
+        /**
+        * Returns CWimSecModule according to received index.
+        * If WIM is not initialized and listing operation completed
+        * before calling this function, User::Leave( KErrNotFound )
+        * is called.        
+        * @param aIndex -needed element from array.
+        * @return CWimSecModule*  -the element from array.
+        */
+        IMPORT_C CWimSecModule* GetWimSecModuleByIndexL( 
+            const TInt aIndex );
+
+        /** 
+        * Returns WIM label according to received index.
+        * If WIM is not initialized and listing operation completed
+        * before calling this function, User::Leave( KErrNotFound )
+        * is called.                
+        * @param aIndex -wanted index from array.
+        * @return TPtrC -pointer to label.
+        */
+        IMPORT_C TPtrC WimLabelByIndexL( const TInt aIndex );
+
+        /** 
+        * Returns the number of "slot" where current token is attached.
+        * If WIM is not initialized and listing operation completed
+        * before calling this function, User::Leave( KErrNotFound )
+        * is called.                
+        * @param aIndex -needed index from array.
+        * @return TInt -the place where token is attached.
+        */
+        IMPORT_C TInt WimTokenNumberByIndexL( const TInt aIndex );
+
+        
+    private:
+        
+        /**
+        * C++ default constructor.
+        */
+        CWimSecModuleMgr();
+
+    
+        /**
+        * By default Symbian 2nd phase constructor is private
+        */
+        void ConstructL();
+
+        /**
+        * Frees memory & preferences that have been allocated.
+        * @return void
+        */
+        void DeAllocateWimReferences();
+
+    private: 
+        
+
+        /**
+        * Sets own iStatus to KRequestPending, and signals it 
+        * with User::RequestComplete() request. This gives chance 
+        * to active scheduler to run other active objects. After a quick
+        * visit in active scheduler, signal returns to RunL() and starts next
+        * phase of listing operation. This makes possible the cancelling 
+        * function to get through.
+        * @return void
+        */
+        void SignalOwnStatusAndComplete();
+        
+        /**
+        * Appends labels of available Tokens (wims) to an array.
+        * @return void
+        */
+        void AppendTokenLabelsToArrayL();
+        
+        /**
+        * Reads the count of the WIM.
+        * @return void
+        */  
+        void ReadWimCount();
+        
+        /**
+        * Five different phases, which are used to initialize
+        * WIM and list security modules.
+        */
+        enum TPhase
+            {
+            EConnectClientSession,
+            ECreateNewSession,
+            EInitializeWim,
+            EGetWimRefs
+            };
+    private: //From CActive
+
+        /**
+        * Different phases are handled here.
+        * @return void
+        */
+        void RunL();
+        
+        /**
+        * Cancellation function
+        * Deallocates member variables and completes client status with
+        * KErrCancel error code.
+        * @return void
+        */
+        void DoCancel();
+
+        /**
+        * The active scheduler calls this function if this active 
+        * object's RunL() function leaves. 
+        * Handles neccessary cleanup and completes request with
+        * received error code.
+        * @param aError -Error code which caused this event
+        * @return TInt  -Error code to active scheduler, is always KErrNone.
+        */ 
+        TInt RunError( TInt aError );
+
+    private: 
+
+        /**
+        * Allocate pointer to WIM and create CWimSecModules
+        * @return TInt -Error code
+        */
+        TInt WIMModulesL();
+
+
+    private:
+
+        //Used to handle initialization of WIM and listing tokentypes
+        TPhase                          iPhase;
+                
+        //Client status is stored here while WIM is started and
+        //listing operation is made. After that User::RequestComplete()
+        //is signalled with iClientStatus.
+        TRequestStatus*                 iClientStatus;
+        
+        //Array containing WIM labels. Not owned, caller is 
+        //responsible to destroy received array.
+        RCPointerArray<HBufC>*          iTokenLabels;
+        
+        //Flag to indicate errors during WIM initialization.
+        TInt                            iWimStartErr;
+        
+        // Array of pointers to WIM Security Modules. Owned. 
+        // Valid as long as CWimSecModuleMgr is valid.
+        CArrayPtrFlat<CWimSecModule>*   iWims; 
+        
+        // Pointer to Client Session. Owned. 
+        // Valid as long as CWimSecModuleMgr is valid.
+        RWimMgmt*                       iClientSession;
+        
+        // WIM reference list. Owned. Valid as long as iClientSession
+        // is valid.
+        TWimAddressList                 iWimAddrLst;
+        
+        // WIM count, defines the amount of WIM cards.
+        TUint                           iWimCount;
+        
+        TPhase                          iCurrentPhase;
+
+    };
+
+#endif      // WIMSECMODULEMGR_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/inc/WimTrustSettingsMgmt.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,198 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Trust Settings management class.
+*
+*/
+
+
+#ifndef WIMTRUSTSETTINGSMGMT_H
+#define WIMTRUSTSETTINGSMGMT_H
+
+//  INCLUDES
+#include "WimClient.h"
+#include "WimCertInfo.h"
+#include "WimCertTClassWrappers.h"
+
+// FORWARD DECLARATIONS
+class CWimCertInfo;
+
+// CLASS DECLARATION
+
+/**
+*  RWimTrustSettingsMgmt 
+*  This class handles Trust Settings Store
+*  related traffic between client and server.
+*  @lib WimClient.lib
+*  @since Series 60 3.0
+*/
+class RWimTrustSettingsMgmt : public RWimClient
+    {
+    public:
+
+        /**
+        * A Static method to get the client Session
+        * @return Pointer to newly created instance of RWimTrustSettingsMgmt
+        */  
+        static RWimTrustSettingsMgmt* ClientSessionL();
+
+        /**
+        * Destructor.
+        * Allocated memory is released.
+        */  
+        virtual ~RWimTrustSettingsMgmt();
+
+        /**
+        * Fetches trust settings for given certificate. 
+        * @param  aCert (IN) Certificate
+        * @param  aStatus (IN/OUT) Request Status of asynchronous call
+        * @return void
+        */
+        void GetTrustSettingsL( const CWimCertInfo& aCert,
+                                TRequestStatus& aStatus );
+
+        /**
+        * Set applicability for given certificate. 
+        * @param aCert (IN) Certificate
+        * @param aApplications (IN) Array of applications supported by 
+        *        certificate
+        * @param aStatus Request (IN/OUT) Status of asynchronous call.
+        * @return void
+        */
+        void SetApplicabilityL( const CWimCertInfo& aCert,
+                                const RArray<TUid>& aApplications,
+                                TRequestStatus& aStatus );
+
+        /**
+        * Set trust flag for given certificate.
+        * @param aCert (IN) Certificate
+        * @param aTrusted (IN) Is certificate trusted
+        * @param aStatus (IN/OUT) Request Status of asynchronous call.
+        * @return void
+        */
+        void SetTrustL( const CWimCertInfo& aCert,
+                        TBool aTrusted,
+                        TRequestStatus& aStatus );
+
+        /**
+        * Set default trust settings for given certificate.
+        * @param aCert (IN) Certificate
+        * @param aAddApps (IN) Are default applications inserted 
+        *        (ETrue means yes)
+        * @param aStatus (IN/OUT) Request Status of asynchronous call
+        * @return void
+        */
+        void SetDefaultTrustSettingsL( const CWimCertInfo& aCert,
+                                       TBool aAddApps,
+                                       TRequestStatus& aStatus );
+
+        /**
+        * Remove trust settings of given certificate. If certificate
+        * is not found, return with status.Int() = KErrNotFound
+        * @param aCert (IN) Certificate
+        * @param aStatus (IN/OUT) Request Status of asynchronous call
+        * @return void
+        */
+        void RemoveTrustSettingsL( const CWimCertInfo& aCert,
+                                   TRequestStatus& aStatus );
+
+        /**
+        * Cancel any issued asynchronous call
+        * @return void
+        */
+        void CancelDoing();
+
+        /**
+        * Returns pointer to package of trust settings.
+        * @return Pointer to package of trust settings
+        */
+        CWimCertPckgBuf<TTrustSettings>* TrustSettingsPckg();
+
+        /**
+        * Delete buffer pointers
+        * @return void
+        */
+        void DeleteBuffers();
+     
+    private:
+        
+        /**
+        * Constructor 
+        */
+        RWimTrustSettingsMgmt();
+
+        /** 
+        * Copy constructor
+        * @param aSource -Reference to class object.
+        */
+        RWimTrustSettingsMgmt( const RWimTrustSettingsMgmt& aSource );
+
+        /** 
+        * Assignment operator
+        * @param aParam -Reference to class object.
+        */
+        RWimTrustSettingsMgmt& operator=( const RWimTrustSettingsMgmt& aParam );
+
+    private:
+
+        // Package for trust settings. Owned.
+        CWimCertPckgBuf<TTrustSettings>* iPckgBufTrustSettings;
+
+        // Package for cert info. Owned.
+        CWimCertPckgBuf<TWimCertInfoPckg>* iCertPkcg;
+    };
+
+#endif // WIMTRUSTSETTINGSMGMT_H
+
+// End of File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/src/JavaUtils.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,825 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+//INCLUDE FILES
+#include "WimCertMgmt.h"
+#include "WimMgmt.h" // To initialize WimServer
+#include "JavaUtils.h"
+#include "WimTrace.h"
+
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::CWimJavaUtils()
+// Default constructor
+// -----------------------------------------------------------------------------
+//
+CWimJavaUtils::CWimJavaUtils(): CActive( EPriorityStandard )
+    {
+    CActiveScheduler::Add( this );
+    iAuthObjsInfoList = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils* CWimJavaUtils::NewL()
+// Symbian 2 phase construction
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CWimJavaUtils* CWimJavaUtils::NewL()
+    {
+    CWimJavaUtils* self = new( ELeave ) CWimJavaUtils();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::ConstructL()
+// Second phase
+// -----------------------------------------------------------------------------
+//
+void CWimJavaUtils::ConstructL()
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::ConstructL" ) );    
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::~CWimJavaUtils()
+// Destructor. All allocated memory is released.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CWimJavaUtils::~CWimJavaUtils()
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::~CWimJavaUtils" ) );
+    Cancel();
+    DeallocMemoryFromJavaProvStruct();
+    DeallocMemoryFromPathAndLabel();
+    if( iConnectionHandle )
+        {
+        iConnectionHandle->Close();
+        delete iConnectionHandle;
+        }
+    
+    if ( iClientSession )
+        {
+        iClientSession->Close();
+        delete iClientSession;
+        }
+	if( iAuthObjsInfoList )
+		{
+		iAuthObjsInfoList->Close();
+		delete iAuthObjsInfoList;
+		}
+		
+	if( iAuthIdList )
+	    {
+		iAuthIdList->Close();
+		delete iAuthIdList;
+	    }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::Initialize()
+// Initializes the WIM server cache.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimJavaUtils::Initialize( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::Initialize" ) );
+    aStatus = KRequestPending;
+    iClientStatus = &aStatus;
+    iPhase = EInitialize;
+    SignalOwnStatusAndComplete();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::CancelInitialize()
+// Cancels outgoing Initialize operation.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimJavaUtils::CancelInitialize()
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::CancelInitialize" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::GetACIFSize()
+// Fetches the size of provisioning information string. This information can
+// be used as a notification, does provisioning information exist.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimJavaUtils::GetACIFSize( TInt& aSize, 
+                                        TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::GetACIFSize" ) );
+    aStatus = KRequestPending;
+    iClientStatus = &aStatus;
+
+    if ( !iClientSession || !iConnectionHandle )
+        {
+        User::RequestComplete( iClientStatus, KErrGeneral );
+        }
+    else
+        {
+        iSize = &aSize;
+        iPhase = EGetACIFSize;
+        SignalOwnStatusAndComplete();
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::GetACFSize()
+// aSize ( OUT )
+// aACFPath ( IN )
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimJavaUtils::GetACFSize( TInt& aSize, 
+                                        const TDesC8& aACFPath,
+                                        TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::GetACFSize" ) );
+    aStatus = KRequestPending;
+    iClientStatus = &aStatus;
+
+    if ( !iClientSession || !iConnectionHandle )
+        {
+        User::RequestComplete( iClientStatus, KErrGeneral );
+        }
+    else
+        {
+        iSize = &aSize;
+        iACFPath.Copy( aACFPath );
+        iPhase = EGetACFSize;
+        SignalOwnStatusAndComplete();
+        }
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::CancelGetACIFSize()
+// Cancels ongoing GetSize operation
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimJavaUtils::CancelGetACIFSize()
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::CancelGetACIFSize" ) );
+    Cancel();
+    }
+    
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::CancelGetACFSize()
+// Cancels ongoing GetSize operation
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimJavaUtils::CancelGetACFSize()
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::CancelGetACFSize" ) );
+    Cancel();
+    }    
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::RetrieveACIFContent()
+// Fetches the whole data of provisioning information string.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimJavaUtils::RetrieveACIFContent( TDes8& aACIFData, 
+                                     TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::RetrieveACIFContent" ) );    
+    aStatus = KRequestPending;
+    iClientStatus = &aStatus;
+
+    if ( !iClientSession || !iConnectionHandle )
+        {
+        User::RequestComplete( iClientStatus, KErrGeneral );
+        return;
+        }
+
+    if ( aACIFData.MaxLength() )
+        {
+        iData = &aACIFData;
+        iPhase = ERetrieveACIFContent;
+        SignalOwnStatusAndComplete();
+        }
+    else
+        {
+        User::RequestComplete( iClientStatus, KErrGeneral );
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::RetrieveACFContent()
+// Fetches the whole data of provisioning information string.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimJavaUtils::RetrieveACFContent( TDes8& aACFData, 
+                                                const TDesC8& aACFPath,
+                                                TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::RetrieveACFContent" ) );    
+    aStatus = KRequestPending;
+    iClientStatus = &aStatus;
+
+    if ( !iClientSession || !iConnectionHandle )
+        {
+        User::RequestComplete( iClientStatus, KErrGeneral );
+        return;
+        }
+
+    if ( aACFData.MaxLength() && aACFPath.Length() )
+        {
+        iData = &aACFData;
+        iACFPath.Copy(aACFPath);
+        iPhase = ERetrieveACFContent;
+        SignalOwnStatusAndComplete();
+        }
+    else
+        {
+        User::RequestComplete( iClientStatus, KErrGeneral );
+        }
+    }
+    
+    
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::RetrieveWimLabelAndPath()
+// Fetches wim label and path.
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C void CWimJavaUtils::RetrieveWimLabelAndPath( TDes8& aWimLabel,
+                                                     TDes8& aPath,
+                                                     TRequestStatus& aStatus )
+    {
+	_WIMTRACE ( _L( "CWimJavaUtils::RetrieveWimLabelAndPath" ) );    
+    aStatus = KRequestPending;
+    iClientStatus = &aStatus;
+
+    if ( !iClientSession || !iConnectionHandle )
+        {
+        User::RequestComplete( iClientStatus, KErrGeneral );
+        return;
+        }
+
+    if( aWimLabel.MaxLength() && aPath.MaxLength() )
+	    {
+	    iLabel = &aWimLabel;
+	    iPath = &aPath;
+	    iPhase = ERetrieveWimLabelAndPath;
+	    SignalOwnStatusAndComplete();	
+	    }
+    else
+	    {
+	    User::RequestComplete( iClientStatus, KErrGeneral );	
+	    }
+     
+    }
+                                                     
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::GetAuthObjsInfo()
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C void CWimJavaUtils::GetAuthObjsInfo( const RArray<TInt>& aAuthIdList, 
+                                       RArray<TJavaPINParams>& aAuthObjsInfoList,
+                                       TRequestStatus& aStatus )
+    {
+	_WIMTRACE ( _L( "CWimOMAProv::GetAuthObjsInfo" ) );
+	aStatus = KRequestPending;
+	iClientStatus = &aStatus;
+	
+	if ( !iClientSession || !iConnectionHandle )
+        {
+        User::RequestComplete( iClientStatus, KErrGeneral );
+        return;
+        }
+
+    if ( aAuthIdList.Count() )
+        {
+        if( iAuthObjsInfoList )
+            {
+        	delete iAuthObjsInfoList;
+        	iAuthObjsInfoList = NULL;
+            }
+            
+        TRAPD( err, iAuthObjsInfoList = new (ELeave) RArray<TJavaPINParams>( aAuthIdList.Count() ) );    
+        
+        if ( err != KErrNone )
+            {
+            User::RequestComplete( iClientStatus, err );	
+            return;
+        	  }
+        
+        if( iAuthIdList )
+            {
+        	delete iAuthIdList;
+        	iAuthIdList = NULL;
+            }
+        
+        TRAP( err, iAuthIdList = new (ELeave ) RArray<TInt>( aAuthIdList.Count() ) );
+        
+        if ( err != KErrNone )
+            {
+            User::RequestComplete( iClientStatus, err );	
+            return;	
+        	  }
+        
+        for( TInt i = 0; i < aAuthIdList.Count() ; i ++ )
+            {
+        	iAuthIdList->Append( aAuthIdList[i]);
+            }
+            
+        iClientsAuthObjsInfoList = &aAuthObjsInfoList;
+		
+		TJavaPINParams pinp;
+		for( TInt i = 0; i < aAuthIdList.Count(); i++ )
+			{
+			iAuthObjsInfoList->Append( pinp );
+			}
+			
+        iPhase = EGetAuthObjsInfo;
+        SignalOwnStatusAndComplete();
+        }
+    else
+        {
+        User::RequestComplete( iClientStatus, KErrGeneral );
+        }
+    
+    
+    }
+      
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::CancelACIFRetrieveContent()
+// Cancels ongoing retrieve operation
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimJavaUtils::CancelRetrieveACIFContent()
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::CancelRetrieveACIFContent" ) );
+    Cancel();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::CancelACFRetrieveContent()
+// Cancels ongoing retrieve operation
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimJavaUtils::CancelRetrieveACFContent()
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::CancelRetrieveACFContent" ) );
+    Cancel();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::CancelACFRetrieveWimLabelAndPath()
+// Cancels ongoing retrieve operation
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimJavaUtils::CancelRetrieveWimLabelAndPath()
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::CancelACFRetrieveWimLabelAndPath" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::CancelGetAuthObjsInfo()
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C void CWimJavaUtils::CancelGetAuthObjsInfo()
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::CancelGetAuthObjsInfo" ) );
+	Cancel();
+    }
+    
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::RunL()
+// Different phases are handled here
+// iPhase = EInitialize: Gets ClientSession handle. Tries to connect
+//          to existing session. If there is no existing session, a new session 
+//          is created.
+// iPhase = EConnectClientSession: If new session was needed to be created, 
+//          new connecting request is needed.
+// iPhase = EInitializeWim: Sends initialize request to server and waits
+//          asyncronously.
+// iPhase = EInitializeDone: Initialization is ready.
+// iPhase = EGetACIFSize: Gets data type and data size from WIM Server
+// iPhase = EGetACIFSizeDone: WIM server has sent data to client and client copies
+//                        data forward to caller.
+// iPhase = ERetrieveACIFContent: Retrieves binary data from WIM Server according to
+//                     type
+// iPhase = ERetrieveACIFContentDone: WIM Server has sent data and client copies data 
+//                         forward to caller.
+// -----------------------------------------------------------------------------
+//
+void CWimJavaUtils::RunL()
+    {
+    switch ( iPhase ) 
+        {
+        case EInitialize:
+            {    
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: EInitialize" ) );
+             //get ClientSession handle
+            iClientSession = RWimMgmt::ClientSessionL();
+
+            iPhase = EConnectClientSession;
+            TInt retval = 0;
+            iWimStartErr = iClientSession->Connect();
+            if ( iWimStartErr == KErrNotFound ) 
+                {
+                retval = iClientSession->StartWim();
+                if( retval != KErrNone )
+                    {
+                    User::RequestComplete( iClientStatus, retval ); 
+                    }
+                else
+                    {
+                    SignalOwnStatusAndComplete();
+                    }
+                }
+            else
+                {
+                 SignalOwnStatusAndComplete(); 
+                }
+            break;
+            }
+        case EConnectClientSession:
+            {
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: EConnectClientSession" ) );
+            //Raise iPhase
+            iPhase = EInitializeWim; 
+            if ( iWimStartErr )
+                {
+                //New session was needed to be created. Try to reconnect.
+                iWimStartErr = iClientSession->Connect();
+                if ( iWimStartErr )
+                    {
+                    //Failed to connect. No reason to continue.
+                    User::RequestComplete( iClientStatus, iWimStartErr );
+                    }
+                else
+                    {
+                    SignalOwnStatusAndComplete();
+                    }
+                }
+            else
+                {
+                SignalOwnStatusAndComplete();
+                }
+            break;
+            }
+        case EInitializeWim:
+            {
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: EInitializeWim" ) );
+            //Initialize WIM
+            SetActive();
+            iClientSession->Initialize( iStatus );
+            iPhase = EInitializeDone;
+            break;   
+            }
+        case EInitializeDone:
+            {
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: EInitializeDone" ) );
+            if ( iStatus.Int() == KErrNone )
+                {
+                 //Get connection handle to WIM Server.
+                iConnectionHandle = RWimCertMgmt::ClientSessionL(); 
+                }
+            User::RequestComplete( iClientStatus, iStatus.Int() );
+            break;
+            }
+        case EGetACIFSize:
+            {
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: EGetACIFSize" ) );
+            TJavaProv javaProv;
+              
+            iConnectionHandle->RetrieveACIFDataL( javaProv, 
+                                                 iStatus, 
+                                                 EGetACIFFileSize );
+            iPhase = EGetACIFSizeDone;
+            SetActive();
+            break;
+            }
+       
+        case EGetACFSize:
+            {
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: EGetACFSize" ) );
+            TJavaProv javaProv;
+            javaProv.iPath = &iACFPath;
+            iConnectionHandle->RetrieveACFDataL( javaProv, 
+                                                 iStatus, 
+                                                 EGetACFFileSize );
+            iPhase = EGetACFSizeDone;
+            SetActive();
+            break;	
+            }
+         case EGetAuthObjsInfo:
+            {
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: EGetAuthObjsInfo" ) );
+            
+            iConnectionHandle->RetrieveAuthObjsInfoL( *iAuthIdList,
+                                                *iAuthObjsInfoList,
+                                                iStatus, 
+                                                ERetrieveAuthObjsInfo );                        
+            iPhase  = EGetAuthObjsInfoDone;
+            SetActive();
+        	break;
+        	
+            }
+        case EGetACIFSizeDone:
+            {
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: EGetACIFSizeDone" ) );
+            if ( iStatus.Int() == KErrNone )
+                {
+                TPckgBuf<TJavaProv> javaProvPckgBuf;
+    
+                javaProvPckgBuf.operator = 
+                    ( *iConnectionHandle->TJavaProvPckgBuf()->PckgBuf() );
+
+                *iSize = javaProvPckgBuf().iSize;
+                }
+            iConnectionHandle->DeallocJavaDataPckgBuf();
+            User::RequestComplete( iClientStatus, iStatus.Int() );
+            break;
+            }
+            
+         case EGetACFSizeDone:
+            {
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: EGetACFSizeDone" ) );
+            if ( iStatus.Int() == KErrNone )
+                {
+                TPckgBuf<TJavaProv> javaProvPckgBuf;
+    
+                javaProvPckgBuf.operator = 
+                    ( *iConnectionHandle->TJavaProvPckgBuf()->PckgBuf() );
+
+                *iSize = javaProvPckgBuf().iSize;
+                }
+            iConnectionHandle->DeallocJavaDataPckgBuf();
+            User::RequestComplete( iClientStatus, iStatus.Int() );
+            break;
+            }   
+            
+        case ERetrieveACIFContent:
+            {
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: EACIFRetrieve" ) );
+            AllocMemoryForJavaProvStructL( iData->MaxLength() );
+            TJavaProv javaProv;
+            javaProv.iJavaData = iJavaProvBufPtr;
+            iConnectionHandle->RetrieveACIFDataL( javaProv, 
+                                                 iStatus,
+                                                 EGetACIFFile );
+            iPhase = ERetrieveACIFContentDone;
+            SetActive();
+            break;
+            }
+            
+        case ERetrieveACFContent:
+            {
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: EACFRetrieve" ) );
+            AllocMemoryForJavaProvStructL( iData->MaxLength() );
+            TJavaProv javaProv;
+            javaProv.iPath = &iACFPath;
+            javaProv.iJavaData = iJavaProvBufPtr;
+            
+            iConnectionHandle->RetrieveACFDataL( javaProv, 
+                                                 iStatus,
+                                                 EGetACFFile );
+            iPhase = ERetrieveACFContentDone;
+            SetActive();
+            break;
+            }   
+            
+        case ERetrieveACIFContentDone:
+            {
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: ERetrieveACIFContentDone" ) );
+            if ( iStatus.Int() == KErrNone )
+                {
+                TPtr8 ptr = iJavaProvBuf->Des();
+                iData->Copy( ptr );
+                }
+            DeallocMemoryFromJavaProvStruct();
+            iConnectionHandle->DeallocJavaDataPckgBuf();
+            User::RequestComplete( iClientStatus, iStatus.Int() );
+            break;
+            }
+            
+        case ERetrieveACFContentDone:
+            {
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: ERetrieveACFContentDone" ) );
+            if ( iStatus.Int() == KErrNone )
+                {
+                TPtr8 ptr = iJavaProvBuf->Des();
+                iData->Copy( ptr );
+                }
+            DeallocMemoryFromJavaProvStruct();
+            iConnectionHandle->DeallocJavaDataPckgBuf();
+            User::RequestComplete( iClientStatus, iStatus.Int() );
+            break;
+            } 
+        case EGetAuthObjsInfoDone:
+            {
+            TInt count = iAuthObjsInfoList->Count();
+            for( TInt i =0; i < count ; i++ )
+	            {
+	            if((*iAuthObjsInfoList)[i].iMinLength > 0 )
+		            {
+		            iClientsAuthObjsInfoList->Append( (*iAuthObjsInfoList)[i] );	
+		            }
+	            }
+            User::RequestComplete( iClientStatus, iStatus.Int() );
+            break;	
+            }
+            
+        case ERetrieveWimLabelAndPath:
+            {
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: EACFRetrieveWimLabelAndPath" ) );
+            AllocMemoryForPathAndLabelL();
+            
+        	iConnectionHandle->RetrieveLabelAndPathL( *iLabelBufPtr,
+        	                                          *iPathBufPtr, 
+                                                      iStatus,
+                                                      EGetLabelAndPath );
+            iPhase = ERetrieveWimLabelAndPathDone;
+            SetActive();
+            break;
+            }
+        
+        case ERetrieveWimLabelAndPathDone:  
+            {
+            _WIMTRACE ( _L( "CWimJavaUtils::RunL case: ERetrieveWimLabelAndPathDone" ) );
+            if( iStatus.Int() == KErrNone )
+	            {
+	            iLabel->Copy( iLabelBuf->Des() );
+	            iPath->Copy( iPathBuf->Des() );
+	            }
+            DeallocMemoryFromPathAndLabel();     
+          
+        	User::RequestComplete( iClientStatus, iStatus.Int() );
+            break;
+            }
+                 
+        default:
+            {
+            break;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::AllocMemoryForJavaProvStructL()
+// Allocates memory for Java binary data
+// -----------------------------------------------------------------------------
+void CWimJavaUtils::AllocMemoryForJavaProvStructL( const TInt aDataLength )
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::AllocMemoryForJavaProvStructL" ) );
+    if ( aDataLength )
+        {
+        iJavaProvBuf = HBufC8::NewL( aDataLength );
+        iJavaProvBufPtr = new( ELeave ) TPtr8( iJavaProvBuf->Des() );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::DeallocMemoryFromJavaProvStruct()
+// Deallocates memory from member variables
+// -----------------------------------------------------------------------------
+void CWimJavaUtils::DeallocMemoryFromJavaProvStruct()
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::DeallocMemoryFromJavaProvStruct" ) );
+    delete iJavaProvBuf;
+    delete iJavaProvBufPtr;
+    iJavaProvBuf = NULL;
+    iJavaProvBufPtr = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::AllocMemoryForPathAndLabelBufferL()
+// Allocates memory for path and label buffer
+// -----------------------------------------------------------------------------
+void CWimJavaUtils::AllocMemoryForPathAndLabelL()
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::AllocMemoryForPathAndLabelL" ) );
+ 
+    iLabelBuf = HBufC8::NewL( KLabelMaxLength );
+    iLabelBufPtr = new( ELeave ) TPtr8( iLabelBuf->Des() );
+    
+    iPathBuf = HBufC8::NewL( KPathMaxLength );
+    iPathBufPtr = new( ELeave ) TPtr8( iPathBuf->Des() );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::DeallocMemoryFromPathAndLabel()
+// Deallocates memory from path and label
+// -----------------------------------------------------------------------------
+void CWimJavaUtils::DeallocMemoryFromPathAndLabel()
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::DeallocMemoryFromPathAndLabel" ) );
+    delete iLabelBuf;
+    delete iPathBuf;
+    delete iLabelBufPtr;
+    delete iPathBufPtr;
+    
+    iLabelBuf = NULL;
+    iLabelBufPtr = NULL;
+    iPathBuf = NULL;
+    iPathBufPtr = NULL;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::DoCancel()
+// Deallocates member variables and completes client status with
+// KErrCancel error code.
+// -----------------------------------------------------------------------------
+//
+void CWimJavaUtils::DoCancel()
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::DoCancel" ) );
+    if ( iConnectionHandle && 
+         ( iPhase == EGetACIFSizeDone || iPhase == ERetrieveACIFContentDone ) )
+        {
+        iConnectionHandle->DeallocJavaDataPckgBuf();
+        }
+    DeallocMemoryFromJavaProvStruct();
+    User::RequestComplete( iClientStatus, KErrCancel );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::RunError()
+// The active scheduler calls this function if this active object's RunL() 
+// function leaves. This gives this active object the opportunity to perform 
+// any necessary cleanup.
+// After cleanup, complete request with received error code.
+// -----------------------------------------------------------------------------
+//
+TInt CWimJavaUtils::RunError( TInt aError )
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::RunError Error = %d" ) );
+    if ( iConnectionHandle && 
+         ( iPhase == EGetACIFSizeDone || iPhase == ERetrieveACIFContentDone ) )
+        {
+        iConnectionHandle->DeallocJavaDataPckgBuf();
+        }
+    DeallocMemoryFromJavaProvStruct();
+    User::RequestComplete( iClientStatus, aError );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaUtils::SignalOwnStatusAndComplete()       
+// Sets own iStatus to KRequestPending, and signals it 
+// with User::RequestComplete() -request. This gives chance 
+// active scheduler to run other active objects. After a quick
+// visit in actives cheduler, signal returns to RunL() and starts next
+// phase of operation. 
+// -----------------------------------------------------------------------------
+//
+void CWimJavaUtils::SignalOwnStatusAndComplete()
+    {
+    _WIMTRACE ( _L( "CWimJavaUtils::SignalOwnStatusAndComplete" ) );
+    iStatus = KRequestPending;
+    SetActive();
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    }
+
+// End of File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/src/ProvSC.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,453 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  API which handles OMA Provisioning related operations
+*
+*/
+
+
+
+
+//INCLUDE FILES
+#include "WimCertMgmt.h"
+#include "WimMgmt.h"
+#include "ProvSC.h"
+#include "WimTrace.h"
+
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::CWimOMAProv()
+// Default constructor
+// -----------------------------------------------------------------------------
+//
+CWimOMAProv::CWimOMAProv(): CActive( EPriorityStandard )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv* CWimOMAProv::NewL()
+// Symbian 2 phase construction
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CWimOMAProv* CWimOMAProv::NewL()
+    {
+    CWimOMAProv* self = new( ELeave ) CWimOMAProv();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::ConstructL()
+// Second phase
+// -----------------------------------------------------------------------------
+//
+void CWimOMAProv::ConstructL()
+    {
+    _WIMTRACE ( _L( "CWimOMAProv::ConstructL" ) );
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::~CWimOMAProv()
+// Destructor. All allocated memory is released.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CWimOMAProv::~CWimOMAProv()
+    {
+    _WIMTRACE ( _L( "CWimOMAProv::~CWimOMAProv" ) );
+    Cancel();
+    DeallocMemoryFromOmaProvStruct();
+    
+    if( iConnectionHandle )
+        {
+        iConnectionHandle->Close();
+        delete iConnectionHandle;
+        }
+    
+    if ( iClientSession )
+        {
+        iClientSession->Close();
+        delete iClientSession;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::Initialize()
+// Initializes the WIM server cache.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimOMAProv::Initialize( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimOMAProv::Initialize" ) );
+    aStatus = KRequestPending;
+    iClientStatus = &aStatus;
+    iPhase = EInitialize;
+    SignalOwnStatusAndComplete();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::CancelInitialize()
+// Cancels outgoing Initialize operation.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimOMAProv::CancelInitialize()
+    {
+    _WIMTRACE ( _L( "CWimOMAProv::CancelInitialize" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::GetSize()
+// Fetches the size of provisioning information string. This information can
+// be used as a notification, does provisioning information exist.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimOMAProv::GetSize( TInt& aSize, 
+                                    const TOMAType& aOMAType, 
+                                    TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimOMAProv::GetSize" ) );
+    aStatus = KRequestPending;
+    iClientStatus = &aStatus;
+
+    if ( !iClientSession || !iConnectionHandle )
+        {
+        User::RequestComplete( iClientStatus, KErrGeneral );
+        }
+    else
+        {
+        iSize = &aSize;
+        iOMAType = aOMAType;
+        iPhase = EGetSize;
+        SignalOwnStatusAndComplete();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::CancelGetSize()
+// Cancels ongoing GetSize operation
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimOMAProv::CancelGetSize()
+    {
+    _WIMTRACE ( _L( "CWimOMAProv::CancelGetSize" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::Retrieve()
+// Fetches the whole data of provisioning information string.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimOMAProv::Retrieve( const TOMAType& aOMAType, 
+                                     TDes8& aOMAData, 
+                                     TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimOMAProv::Retrieve" ) );    
+    aStatus = KRequestPending;
+    iClientStatus = &aStatus;
+
+    if ( !iClientSession || !iConnectionHandle )
+        {
+        User::RequestComplete( iClientStatus, KErrGeneral );
+        return;
+        }
+
+    if ( aOMAData.MaxLength() )
+        {
+        iOMAType = aOMAType;
+        iData = &aOMAData;
+        iPhase = ERetrieve;
+        SignalOwnStatusAndComplete();
+        }
+    else
+        {
+        User::RequestComplete( iClientStatus, KErrGeneral );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::CancelRetrieve()
+// Cancels ongoing retrieve operation
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimOMAProv::CancelRetrieve()
+    {
+    _WIMTRACE ( _L( "CWimOMAProv::CancelRetrieve" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::RunL()
+// Different phases are handled here
+// iPhase = EInitialize: Gets ClientSession handle. Tries to connect
+//          to existing session. If there is no existing session, a new session 
+//          is created.
+// iPhase = EConnectClientSession: If new session was needed to be created, 
+//          new connecting request is needed.
+// iPhase = EInitializeWim: Sends initialize request to server and waits
+//          asyncronously.
+// iPhase = EInitializeDone: Initialization is ready.
+// iPhase = EGetSize: Gets OMA data type and data size from WIM Server
+// iPhase = EGetSizeDone: WIM server has sent data to client and client copies
+//                        data forward to caller.
+// iPhase = ERetrieve: Retrieves OMA binary data from WIM Server according to
+//                     type
+// iPhase = ERetrieveDone: WIM Server has sent data and client copies data 
+//                         forward to caller.
+// -----------------------------------------------------------------------------
+//
+void CWimOMAProv::RunL()
+    {
+    switch ( iPhase ) 
+        {
+        case EInitialize:
+            {    
+            _WIMTRACE ( _L( "CWimOMAProv::RunL case: EInitialize" ) );
+             //get ClientSession handle
+            iClientSession = RWimMgmt::ClientSessionL();
+
+            iPhase = EConnectClientSession;
+            TInt retval = 0;
+            iWimStartErr = iClientSession->Connect();
+            if ( iWimStartErr == KErrNotFound ) 
+                {
+                retval = iClientSession->StartWim();
+                if( retval != KErrNone )
+                    {
+                    User::RequestComplete( iClientStatus, retval ); 
+                    }
+                else
+                    {
+                    SignalOwnStatusAndComplete();
+                    }
+                }
+            else
+                {
+                 SignalOwnStatusAndComplete(); 
+                }
+            break;
+            }
+        case EConnectClientSession:
+            {
+            _WIMTRACE ( _L( "CWimOMAProv::RunL case: EConnectClientSession" ) );
+            //Raise iPhase
+            iPhase = EInitializeWim; 
+            if ( iWimStartErr )
+                {
+                //New session was needed to be created. Try to reconnect.
+                iWimStartErr = iClientSession->Connect();
+                if ( iWimStartErr )
+                    {
+                    //Failed to connect. No reason to continue.
+                    User::RequestComplete( iClientStatus, iWimStartErr );
+                    }
+                else
+                    {
+                    SignalOwnStatusAndComplete();
+                    }
+                }
+            else
+                {
+                SignalOwnStatusAndComplete();
+                }
+            break;
+            }
+        case EInitializeWim:
+            {
+            _WIMTRACE ( _L( "CWimOMAProv::RunL case: EInitializeWim" ) );
+            //Initialize WIM
+            SetActive();
+            iClientSession->Initialize( iStatus );
+            iPhase = EInitializeDone;
+            break;   
+            }
+        case EInitializeDone:
+            {
+            _WIMTRACE ( _L( "CWimOMAProv::RunL case: EInitializeDone" ) );
+            if ( iStatus.Int() == KErrNone )
+                {
+                 //Get connection handle to WIM Server.
+                iConnectionHandle = RWimCertMgmt::ClientSessionL(); 
+                }
+            User::RequestComplete( iClientStatus, iStatus.Int() );
+            break;
+            }
+        case EGetSize:
+            {
+            _WIMTRACE ( _L( "CWimOMAProv::RunL case: EGetSize" ) );
+            TOmaProv omaProv;
+            omaProv.iOmaType = iOMAType;
+            iConnectionHandle->RetrieveOmaDataL( omaProv, 
+                                                 iStatus, 
+                                                 EGetOMAFileSize );
+            iPhase = EGetSizeDone;
+            SetActive();
+            break;
+            }
+        case EGetSizeDone:
+            {
+            _WIMTRACE ( _L( "CWimOMAProv::RunL case: EGetSizeDone" ) );
+            if ( iStatus.Int() == KErrNone )
+                {
+                TPckgBuf<TOmaProv> omaProvPckgBuf;
+    
+                omaProvPckgBuf.operator = 
+                    ( *iConnectionHandle->TOmaProvPckgBuf()->PckgBuf() );
+
+                *iSize = omaProvPckgBuf().iSize;
+                }
+            iConnectionHandle->DeallocOmaDataPckgBuf();
+            User::RequestComplete( iClientStatus, iStatus.Int() );
+            break;
+            }
+        case ERetrieve:
+            {
+            _WIMTRACE ( _L( "CWimOMAProv::RunL case: ERetrieve" ) );
+            AllocMemoryForOmaProvStructL( iData->MaxLength() );
+            TOmaProv omaProv;
+            omaProv.iOmaData = iOmaProvBufPtr;
+            omaProv.iOmaType = iOMAType;
+            iConnectionHandle->RetrieveOmaDataL( omaProv, 
+                                                 iStatus,
+                                                 EGetOMAFile );
+            iPhase = ERetrieveDone;
+            SetActive();
+            break;
+            }
+        case ERetrieveDone:
+            {
+            _WIMTRACE ( _L( "CWimOMAProv::RunL case: ERetrieveDone" ) );
+            if ( iStatus.Int() == KErrNone )
+                {
+                TPtr8 ptr = iOmaProvBuf->Des();
+                iData->Copy( ptr );
+                }
+            DeallocMemoryFromOmaProvStruct();
+            iConnectionHandle->DeallocOmaDataPckgBuf();
+            User::RequestComplete( iClientStatus, iStatus.Int() );
+            break;
+            }
+        default:
+            {
+            break;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::AllocMemoryForOmaProvStructL()
+// Allocates memory for OMA binary data
+// -----------------------------------------------------------------------------
+void CWimOMAProv::AllocMemoryForOmaProvStructL( const TInt aDataLength )
+    {
+    _WIMTRACE ( _L( "CWimOMAProv::AllocMemoryForOmaProvStructL" ) );
+    if ( aDataLength )
+        {
+        iOmaProvBuf = HBufC8::NewL( aDataLength );
+        iOmaProvBufPtr = new( ELeave ) TPtr8( iOmaProvBuf->Des() );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::DeallocMemoryFromOmaProvStruct()
+// Deallocates memory from member variables
+// -----------------------------------------------------------------------------
+void CWimOMAProv::DeallocMemoryFromOmaProvStruct()
+    {
+    _WIMTRACE ( _L( "CWimOMAProv::DeallocMemoryFromOmaProvStruct" ) );
+    delete iOmaProvBuf;
+    delete iOmaProvBufPtr;
+    iOmaProvBuf = NULL;
+    iOmaProvBufPtr = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::DoCancel()
+// Deallocates member variables and completes client status with
+// KErrCancel error code.
+// -----------------------------------------------------------------------------
+//
+void CWimOMAProv::DoCancel()
+    {
+    _WIMTRACE ( _L( "CWimOMAProv::DoCancel" ) );
+    if ( iConnectionHandle && 
+         ( iPhase == EGetSizeDone || iPhase == ERetrieveDone ) )
+        {
+        iConnectionHandle->DeallocOmaDataPckgBuf();
+        }
+    DeallocMemoryFromOmaProvStruct();
+    User::RequestComplete( iClientStatus, KErrCancel );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::RunError()
+// The active scheduler calls this function if this active object's RunL() 
+// function leaves. This gives this active object the opportunity to perform 
+// any necessary cleanup.
+// After cleanup, complete request with received error code.
+// -----------------------------------------------------------------------------
+//
+TInt CWimOMAProv::RunError( TInt aError )
+    {
+    _WIMTRACE ( _L( "CWimOMAProv::RunError Error = %d" ) );
+    if ( iConnectionHandle && 
+         ( iPhase == EGetSizeDone || iPhase == ERetrieveDone ) )
+        {
+        iConnectionHandle->DeallocOmaDataPckgBuf();
+        }
+    DeallocMemoryFromOmaProvStruct();
+    User::RequestComplete( iClientStatus, aError );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOMAProv::SignalOwnStatusAndComplete()       
+// Sets own iStatus to KRequestPending, and signals it 
+// with User::RequestComplete() -request. This gives chance 
+// active scheduler to run other active objects. After a quick
+// visit in actives cheduler, signal returns to RunL() and starts next
+// phase of operation. 
+// -----------------------------------------------------------------------------
+//
+void CWimOMAProv::SignalOwnStatusAndComplete()
+    {
+    _WIMTRACE ( _L( "CWimOMAProv::SignalOwnStatusAndComplete" ) );
+    iStatus = KRequestPending;
+    SetActive();
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    }
+
+// End of File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/src/WimCert.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,775 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  API which handles certificate extra data related operations.
+*
+*/
+
+
+#include "WimCertMgmt.h"
+#include "WimMgmt.h"
+#include "WimCert.h"
+#include "WimTrace.h"
+#include "Wimi.h"
+
+
+// -----------------------------------------------------------------------------
+// CWimCert::CWimCert()
+// Default constructor
+// -----------------------------------------------------------------------------
+CWimCert::CWimCert() : CActive( EPriorityStandard )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::NewL()
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+EXPORT_C CWimCert* CWimCert::NewL()
+    {
+    _WIMTRACE ( _L( "CWimCert::NewL()" ) );
+    CWimCert* self = new( ELeave ) CWimCert();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::ConstructL()
+// Second phase
+// -----------------------------------------------------------------------------
+//
+void CWimCert::ConstructL()
+    {
+    CActiveScheduler::Add( this );
+    _WIMTRACE ( _L( "CWimCert::ConstructL() completed" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::Initialize()
+// Initializes the WIM server cache and restores certificates to
+// WimClient memory area. This is the most time consuming call. 
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimCert::Initialize( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCert::Initialize()" ) );
+    aStatus = KRequestPending;
+    iClientStatus = &aStatus;
+    if ( iClientSession )
+        {
+        iClientSession->Close();
+        delete iClientSession;
+        iClientSession = NULL;
+        }
+    if ( iConnectionHandle )
+        {
+        iConnectionHandle->Close();
+        delete iConnectionHandle;
+        iConnectionHandle = NULL;
+        }
+    iPhase = ECreateNewSession;
+    SignalOwnStatusAndComplete();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::CancelInitialize()
+// Cancels the initialization process.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimCert::CancelInitialize()
+    {
+    _WIMTRACE ( _L( "CWimCert::CancelInitialize" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::SignalOwnStatusAndComplete()       
+// Sets own iStatus to KRequestPending, and signals it 
+// with User::RequestComplete() -request. This gives chance 
+// active scheduler to run other active objects. After a quick
+// visit in active scheduler, signal returns to RunL() and starts next
+// phase of operation. 
+// -----------------------------------------------------------------------------
+//
+void CWimCert::SignalOwnStatusAndComplete()
+    {
+    _WIMTRACE ( _L( "CWimCert::SignalOwnStatusAndComplete()" ) );
+    iStatus = KRequestPending;
+    SetActive();
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::GetExtras()
+// Returns the extra data from certificate that is 
+// not possible yet to fetch from crypto token framework
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimCert::GetExtras( const TDesC8& aKeyId, 
+                                   RCPointerArray<HBufC>& aTrustedUsages,
+                                   TCertLocation& aLocation,
+                                   TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCert::GetExtras()" ) );
+    aStatus = KRequestPending;
+    iClientStatus = &aStatus;
+
+    if ( !iClientSession || !iConnectionHandle )
+        {
+        User::RequestComplete( iClientStatus, KErrNotReady );
+        return;
+        }
+    if ( !iCertCount || aKeyId.Length() != KKeyIdLen )
+        {
+        User::RequestComplete( iClientStatus, KErrNotFound );
+        }
+    else
+        {                
+        if ( iKeyIdToBeMatched )
+            {
+            delete iKeyIdToBeMatched;
+            iKeyIdToBeMatched = NULL;
+            }
+
+        TRAPD ( err, iKeyIdToBeMatched = aKeyId.AllocL() );
+        if ( err )
+            {
+            User::RequestComplete( iClientStatus, KErrNoMemory );
+            }
+        else
+            {
+            iTrustedUsages = &aTrustedUsages;
+            iLocation = &aLocation;
+            iPhase = ELocateCertificate;
+            SignalOwnStatusAndComplete();
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::CancelGetExtras()
+// Cancels GetExtras -request.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimCert::CancelGetExtras()
+    {
+    _WIMTRACE ( _L( "CWimCert::CancelGetExtras" ) );
+    Cancel();
+    }
+    
+// -----------------------------------------------------------------------------
+// CWimCert::~CWimCert()
+// Allocated memory is released.
+// -----------------------------------------------------------------------------
+EXPORT_C CWimCert::~CWimCert()
+    {
+    _WIMTRACE ( _L( "CWimCert::~CWimCert()" ) );
+    Cancel();
+    if ( iConnectionHandle )
+        {
+        iConnectionHandle->Close();
+        delete iConnectionHandle;
+        }
+    if ( iClientSession )
+        {
+        iClientSession->Close();
+        delete iClientSession;
+        }
+    DeallocWimCertInfo();
+    DeAllocMemoryForExtraDataRetrieve();
+    DeallocRArrays();
+    
+    delete iKeyIdToBeMatched;
+    delete iKeyIdPointer;
+
+    iCertTypes.Close();
+    iTrustedUsageLengths.Close();
+    iKeyIds.Close();
+    iUsages.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::RunL()
+// Different phases are handled here. This might be considered as state machine. 
+// iPhase = ECreateNewSession: Gets ClientSession handle. Tries to connect
+//          to existing session. If there is no existing session, a new session 
+//          is created.
+// iPhase = EConnectClientSession: If new session was needed to be created, 
+//          new connecting request is needed.
+// iPhase = EInitializeWim: Sends initialize request to server and waits
+//          asyncronously.
+// iPhase = EGetCertClientSession:Create certificate clientsession and connect
+//          it to WIM server.
+// iPhase = EListCertsFromWim: List certificates from WimServer.
+// iPhase = ELocateCertificate: Try to find matching certificate hash from array
+//          (Application has sent a Key ID, which is used to indentify a 
+//          certificate. If matching certificate has found, retrieve possible 
+//          extra data from WimServer.
+// iPhase = EGiveExtraData: Extra data is retrieved from WimServer. Chop it to 
+//          correct pieces.
+// -----------------------------------------------------------------------------
+//
+void CWimCert::RunL()
+    {
+    //Check for error
+    if ( iStatus.Int() != KErrNone )
+        {
+        if ( iPhase == EGiveExtraData )
+            {
+            iConnectionHandle->DeallocGetExtrasPckgBuf();
+            DeAllocMemoryForExtraDataRetrieve();
+            }
+        User::RequestComplete( iClientStatus, iStatus.Int() );
+        _WIMTRACE2 ( _L( "CWimCert::RunL() error = %d" ), iStatus.Int() );
+        _WIMTRACE2 ( _L( "CWimCert::RunL() phase = %d" ), iPhase );
+        return;
+        }
+
+    switch ( iPhase )
+        {
+        case ECreateNewSession:
+            { 
+            //get ClientSession handle
+            iClientSession = RWimMgmt::ClientSessionL();
+            
+            iPhase = EConnectClientSession;
+            TInt retVal = 0;
+            iWimStartErr = iClientSession->Connect();
+            if ( iWimStartErr == KErrNotFound ) 
+                {
+                retVal = iClientSession->StartWim();
+                if( retVal != KErrNone )
+                    {
+                    User::RequestComplete( iClientStatus, retVal ); 
+                    }
+                else
+                    {
+                    SignalOwnStatusAndComplete();
+                    }
+                }
+            else
+                {
+                 SignalOwnStatusAndComplete(); 
+                }
+            break;
+            }
+        case EConnectClientSession:
+            {
+            //Raise iPhase
+            iPhase = EInitializeWim; 
+            if ( iWimStartErr )
+                {
+                //New session was needed to be created. Try to reconnect.
+                iWimStartErr = iClientSession->Connect();
+                if ( iWimStartErr )
+                    {
+                    //Failed to connect. No reason to continue
+                    User::RequestComplete( iClientStatus, iWimStartErr );
+                    }
+                else
+                    {
+                    SignalOwnStatusAndComplete();
+                    }
+                }
+            else
+                {
+                SignalOwnStatusAndComplete();
+                }
+            break;
+            }
+        case EInitializeWim:
+            {
+            //Initialize WIM
+            SetActive();
+            iClientSession->Initialize( iStatus );
+            iPhase = EGetCertClientSession;
+            break;   
+            }
+        case EGetCertClientSession:
+            {
+                // Create certificate clientsession and connect
+                // it to WIM server.
+            _WIMTRACE ( _L( "CWimCert::RunL(), \
+                             case:EGetCertClientSession") );
+            iConnectionHandle = RWimCertMgmt::ClientSessionL();
+            iPhase = EListCertsFromWim;
+            SignalOwnStatusAndComplete();
+            break;   
+            }
+        case EListCertsFromWim: //get certificates from WIM.
+            {
+            _WIMTRACE ( _L( "CWimCert::RunL(), \
+                             case:EListCertsFromWim") );
+         
+            if ( iCertCount ) //Delete previous preferences. 
+                {
+                DeallocWimCertInfo();
+                DeallocRArrays();
+                }
+            //Ok ready to begin. First get Cert count
+            iCertCount = iConnectionHandle->CertCount( EWimEntryTypeAll );
+            _WIMTRACE2 ( _L( "CWimCert::RunL() certCount =%d" ), 
+                             iCertCount );
+            if ( !iCertCount )  
+                {
+                User::RequestComplete( iClientStatus, KErrNotFound );
+                }
+            else
+                {
+                TCertificateAddressList  certRefLst = 
+                     new( ELeave ) TCertificateAddress[iCertCount]; 
+
+                CleanupStack::PushL( TCleanupItem( CleanupRefLst,
+                                                   certRefLst ) );
+
+                TWimCertInfo* certInfoArr = new( ELeave ) 
+                                        TWimCertInfo[iCertCount];
+
+                CleanupStack::PushL( TCleanupItem( Cleanup, certInfoArr ) );
+
+                _WIMTRACE ( _L( "CWimCert::RunL(), Allocated certRefLst") );
+               
+                //Create arrays
+                TUint8 index = 0;
+                iLabel = new( ELeave ) PHBufC8[iCertCount];
+                iKeyId = new( ELeave ) PHBufC8[iCertCount];
+                iCAId  = new( ELeave ) PHBufC8[iCertCount];
+                iIssuerHash = new( ELeave ) PHBufC8[iCertCount];
+
+                iLabelPtr = new( ELeave ) PTPtr8[iCertCount];
+                iKeyIdPtr = new( ELeave ) PTPtr8[iCertCount];
+                iCAIdPtr  = new( ELeave ) PTPtr8[iCertCount];
+                iIssuerHashPtr = new( ELeave ) PTPtr8[iCertCount];
+
+                 _WIMTRACE ( _L( "CWimCert::RunL(), \
+                 Allocated Member variable arrays") );
+
+
+                for ( index = 0; index < iCertCount; index++ )
+                    {
+                    iLabel[index] = HBufC8::NewL( KLabelLen );
+                    iKeyId[index] = HBufC8::NewL( KKeyIdLen );
+                    iCAId[index]  = HBufC8::NewL( KPkcs15IdLen );
+                    iIssuerHash[index] = HBufC8::NewL( KIssuerHash );
+        
+                    iLabelPtr[index] = new( ELeave ) 
+                                            TPtr8( iLabel[index]->Des() );
+                    iKeyIdPtr[index] = new( ELeave ) 
+                                            TPtr8( iKeyId[index]->Des() );
+                    iCAIdPtr[index]  = new( ELeave ) 
+                                            TPtr8( iCAId[index]->Des() );
+                    iIssuerHashPtr[index] = new( ELeave ) 
+                                            TPtr8( iIssuerHash[index]->Des() );
+
+                    certInfoArr[index].iLabel.Copy( iLabelPtr[index]->Ptr(),
+                                                   iLabelPtr[index]->Length() );
+                    certInfoArr[index].iKeyId.Copy( iKeyIdPtr[index]->Ptr(),
+                                                   iKeyIdPtr[index]->Length() );
+                    certInfoArr[index].iCAId.Copy( iCAIdPtr[index]->Ptr(),
+                                                   iCAIdPtr[index]->Length() );
+                    certInfoArr[index].iIssuerHash.Copy(
+                        iIssuerHashPtr[index]->Ptr(),
+                        iIssuerHashPtr[index]->Length() );
+                    
+                    _WIMTRACE2 ( _L( "CWimCert::RunL(), \
+                    Assigned data to array, loopCount =%d"),index );
+
+                    }
+                _WIMTRACE ( _L( "CWimCert::RunL(), \
+                Array ready for retrieving") );
+
+                //Quick synchronous visit in server.
+                TInt ret = iConnectionHandle->CertRefLst( certRefLst, 
+                                               certInfoArr, 
+                                               iCertCount, 
+                                               EWimEntryTypeAll ); 
+                 _WIMTRACE ( _L( "CWimCert::RunL(), \
+                 Retrieve call issued") );
+
+                if ( ret == KErrNone )
+                    {
+                    //Add necessary certificate information to API arrays
+                    for ( TInt i = 0; i < iCertCount; i++ )
+                        {
+                        iCertTypes.Append( certInfoArr[i].iType );
+                        iTrustedUsageLengths.Append( 
+                                          certInfoArr[i].iTrustedUsageLength );
+                        _WIMTRACE ( _L( "CWimCert::RunL(), \
+                        Trusted usage appended") );
+
+                        iKeyIds.Append( certInfoArr[i].iKeyId.AllocL() );
+
+                        _WIMTRACE ( _L( "CWimCert::RunL(), KeyId appended") );
+
+                        iUsages.Append( certInfoArr[i].iUsage );
+                    
+                        _WIMTRACE2 ( _L( "CWimCert::RunL(), \
+                        Allocating data to RArrays, loopCount =%d"),i );
+                        }
+
+                    }
+                //Clean up unwanted member variable arrays
+                DeallocWimCertInfo(); 
+
+                //Delete local arrays.
+                CleanupStack::PopAndDestroy( 2 ); //certRefLst, certInfoArr
+
+                 _WIMTRACE ( _L( "CWimCert::RunL(), All done") );
+                User::RequestComplete( iClientStatus, iStatus.Int() );
+                }
+            break;
+            }
+        case ELocateCertificate:
+            {
+            _WIMTRACE ( _L( "CWimCert::RunL(), \
+                        case:ELocateCertificate") );
+             TInt retVal = CertificateLocated();
+           
+             delete iKeyIdToBeMatched;
+             iKeyIdToBeMatched = NULL;
+             
+             if ( retVal == KErrNone )
+                {
+                //Allocate memory for Trusted usage string
+                AllocMemoryForExtraDataRetrieveL();
+                TCertExtrasInfo certExtrasInfo;
+                certExtrasInfo.iTrustedUsage = 
+                            iCertHBufTrustedUsageFromServerPtr;
+                
+                //Get reference to right keyId from Array, create pointer and 
+                //get extra information
+                HBufC8* keyId = iKeyIds.operator[]( iCertIndex );
+                iKeyIdPointer = new( ELeave ) TPtr8( keyId->Des() );
+                iConnectionHandle->GetCertExtrasL( 
+                                            iKeyIdPointer,
+                                            certExtrasInfo,
+                                            iUsages.operator[]( iCertIndex ),
+                                            iStatus );
+                iPhase = EGiveExtraData;
+                SetActive();
+                }
+             else
+                {
+                User::RequestComplete( iClientStatus, retVal );
+                }
+            break;
+            }
+        case EGiveExtraData:
+            {
+            _WIMTRACE ( _L( "CWimCert::RunL(), case:EGiveExtraData") );
+            ExtraDataFoundL();
+            delete iKeyIdPointer;
+            iKeyIdPointer = NULL;
+            User::RequestComplete( iClientStatus, iStatus.Int() );
+            break;
+            }
+        default:
+            {
+            _WIMTRACE2 ( _L( "CWimCert::RunL(), \
+                            case:default, iPhase=%d" ), iPhase );
+            User::RequestComplete( iClientStatus, KErrCorrupt );
+            break;
+            }
+        }
+    }
+    
+// -----------------------------------------------------------------------------
+// CWimCert::CertificateLocated()
+// Compares received KeyId to our KeyIds and if match is found,
+// check does that certificate have any extra data. If certificate is not found,
+// return KErrNotFound. If TrustedUsage(Location) is not valid, return 
+// KErrPathNotFound.
+// -----------------------------------------------------------------------------
+//
+TInt CWimCert::CertificateLocated()
+    {
+    _WIMTRACE ( _L( "CWimCert::CertificateLocated" ) );
+    TInt found = 0;
+    TBool certificateMatch = EFalse;
+    //Check, do we have that kind of certificate what user asks.
+    TUint8 i;
+    for ( i = 0; i < iCertCount && !certificateMatch; i++ )
+        {
+        //KeyId must match and certificate type must be X509
+        if ( !iKeyIds.operator []( i )->Compare( *iKeyIdToBeMatched ) &&
+             iCertTypes.operator[]( i ) == WIMI_CT_X509 )
+            {
+            iCertIndex = i;
+            certificateMatch = ETrue;
+            }
+        }
+
+    if ( certificateMatch ) //Certificate was found, check location validity
+        {
+        //Ok, we have found certificate, check does it have any 
+        //extra data.
+        if ( !iTrustedUsageLengths.operator []( iCertIndex ) )
+            {
+            found = KErrPathNotFound;
+            }
+        }
+    else //Certificate was not found, return KErrNotFound
+        {
+        found = KErrNotFound;
+        }
+    return found;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::AllocMemoryForExtraDataRetrieveL()
+// Allocates memory for TrustedUsage String, which is fetched from server.
+// -----------------------------------------------------------------------------
+//
+void CWimCert::AllocMemoryForExtraDataRetrieveL()
+    {
+    _WIMTRACE ( _L( "CWimCert::AllocMemoryForExtraDataRetrieveL" ) );
+    //Trusted usage
+    iCertHBufTrustedUsageFromServer = 
+        HBufC::NewL( iTrustedUsageLengths.operator[]( iCertIndex ) );
+    iCertHBufTrustedUsageFromServerPtr = new( ELeave ) TPtr( 
+                                       iCertHBufTrustedUsageFromServer->Des() );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::DeAllocMemoryForExtraDataRetrieve()
+// DeAllocates memory from TrustedUsage String, which was fetched from server.
+// -----------------------------------------------------------------------------
+//
+void CWimCert::DeAllocMemoryForExtraDataRetrieve()
+    {
+    _WIMTRACE ( _L( "CWimCert::DeAllocMemoryForExtraDataRetrieve" ) );
+    delete iCertHBufTrustedUsageFromServer;
+    iCertHBufTrustedUsageFromServer = NULL;
+
+    delete iCertHBufTrustedUsageFromServerPtr;
+    iCertHBufTrustedUsageFromServerPtr = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::ExtraDataFoundL()
+// Now we have got whole Trusted usage information in one buffer. We need 
+// to chop it to corrects pieces and append it to iTrustedUsage array.
+// Location is added to a member variable .
+// -----------------------------------------------------------------------------
+//
+void CWimCert::ExtraDataFoundL()
+    {
+    _WIMTRACE ( _L( "CWimCert::ExtraDataFoundL" ) );
+    TLex16 lex( *iCertHBufTrustedUsageFromServer );
+    TPtrC16 lexToken;
+    for ( TBool extrasDone = EFalse; extrasDone == EFalse; )
+        {
+        lexToken.Set( lex.NextToken() );
+        if ( lexToken.Length() )
+            {
+            HBufC* oid = lexToken.AllocLC();
+            User::LeaveIfError( iTrustedUsages->Append( oid ) );
+            CleanupStack::Pop( oid ); //oid
+            }
+        else
+            {
+            extrasDone = ETrue;
+            }
+        }
+
+    TPckgBuf<TCertExtrasInfo> certInfoPckg;
+    
+    certInfoPckg.operator = 
+        ( *iConnectionHandle->CertExtrasPckgBuf()->PckgBuf() );
+
+    switch ( certInfoPckg().iCDFRefs )
+        {
+        case EWimTrustedCertsCDF:
+            {
+            *iLocation = ETrustedCerts_CDF;
+            break;
+            }
+        case EWimCertificatesCDF:
+            {
+            *iLocation = ECertificates_CDF;
+            break;
+            }
+        case EWimUsefulCertsCDF:
+            {
+            *iLocation = EUsefulCerts_CDF;
+            break;
+            }
+        default:
+            {
+            *iLocation = EUnknown_CDF;
+            break;
+            }
+        }
+
+    iConnectionHandle->DeallocGetExtrasPckgBuf();
+    DeAllocMemoryForExtraDataRetrieve();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::DoCancel()
+// Deallocates member variables and completes client status with
+// KErrCancel error code.
+// -----------------------------------------------------------------------------
+//
+void CWimCert::DoCancel()
+    {
+    if ( iConnectionHandle && 
+        ( iPhase == EGiveExtraData || iPhase == ELocateCertificate ) )
+        {
+        iConnectionHandle->DeallocGetExtrasPckgBuf();
+        DeAllocMemoryForExtraDataRetrieve();
+        delete iKeyIdPointer;
+        iKeyIdPointer = NULL;
+        delete iKeyIdToBeMatched;
+        iKeyIdToBeMatched = NULL;
+        }
+    else 
+        {//Cancelled initialization
+        DeallocWimCertInfo();
+        DeAllocMemoryForExtraDataRetrieve();
+        DeallocRArrays();
+        }
+    User::RequestComplete( iClientStatus, KErrCancel );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::RunError() 
+// The active scheduler calls this function if this active object's RunL() 
+// function leaves. This gives this active object the opportunity to perform 
+// any necessary cleanup.
+// After array's cleanup, complete request with received error code.
+// -----------------------------------------------------------------------------
+TInt CWimCert::RunError( TInt aError )
+    {
+    _WIMTRACE2 ( _L( "CWimCert::RunError, aError = %d" ), aError );
+    _WIMTRACE2 ( _L( "CWimCert::RunError, iPhase = %d" ), iPhase );
+    DeallocWimCertInfo();
+    DeAllocMemoryForExtraDataRetrieve();
+    DeallocRArrays();
+
+    delete iKeyIdPointer;
+    iKeyIdPointer = NULL;
+
+    User::RequestComplete( iClientStatus, aError );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::Cleanup()
+// Handles cleanup for an object which is not derived from CBase
+// -----------------------------------------------------------------------------
+//
+void CWimCert::Cleanup( TAny* aObject )
+    {
+    _WIMTRACE ( _L( "CWimCert::Cleanup()" ) );
+    delete[] static_cast<TWimCertInfo*>(aObject);
+    aObject = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::CleanupRefLst()
+// Handles cleanup for an object which is not derived from CBase
+// -----------------------------------------------------------------------------
+//
+void CWimCert::CleanupRefLst( TAny* aObject )
+    {
+    _WIMTRACE ( _L( "CWimCert::CleanupRefLst()" ) );
+    delete[] aObject;  
+    aObject = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::DeallocRArrays()
+// Deallocates member variable RArrays
+// -----------------------------------------------------------------------------
+//
+void CWimCert::DeallocRArrays()
+    {
+    for ( TInt i = 0; i< iKeyIds.Count(); i++ )
+        {
+        delete iKeyIds[i];
+        iKeyIds[i] = NULL;
+        }
+    iKeyIds.Close();
+    iCertTypes.Close();
+    iTrustedUsageLengths.Close();
+    iKeyIds.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCert::DeallocWimCertInfo()
+// Deallocates memory. If something has leaved during asynchronous request, we 
+// will deallocate all member data. 
+// -----------------------------------------------------------------------------
+void CWimCert::DeallocWimCertInfo()
+    {
+    _WIMTRACE ( _L( "CWimCert::DeallocWimCertInfo()" ) ); 
+    TUint8 index;
+    for ( index = 0; index < iCertCount; index++ )
+        {
+        if ( iLabel )
+            {
+            delete iLabel[index];
+            }
+        if ( iKeyId )
+            {
+            delete iKeyId[index];
+            }
+        if ( iCAId )
+            {
+            delete iCAId[index];
+            }
+        if ( iIssuerHash )
+            {
+            delete iIssuerHash[index];
+            }
+        if ( iLabelPtr )
+            {
+            delete iLabelPtr[index];
+            }
+        if ( iKeyIdPtr )
+            {
+            delete iKeyIdPtr[index];
+            }
+        if ( iCAIdPtr )
+            {
+            delete iCAIdPtr[index];
+            }
+        if ( iIssuerHashPtr )
+            {
+            delete iIssuerHashPtr[index];
+            }
+        }
+    
+    delete[] iLabel;   
+    delete[] iKeyId;                
+    delete[] iCAId;
+    delete[] iIssuerHash; 
+    delete[] iLabelPtr;        
+    delete[] iKeyIdPtr;        
+    delete[] iCAIdPtr;        
+    delete[] iIssuerHashPtr;  
+    iLabel = NULL;
+    iKeyId  = NULL;
+    iCAId = NULL;
+    iIssuerHash = NULL;
+    iLabelPtr = NULL;
+    iKeyIdPtr = NULL;
+    iCAIdPtr = NULL;
+    iIssuerHashPtr = NULL;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/src/WimCertConverter.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1047 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  API which handles certificate related operatons
+*
+*/
+
+
+
+#include "WimCertMgmt.h"
+#include "WimCertConverter.h"
+#include "WimTrace.h"
+#include "WimCertInfo.h"
+#include "Wimi.h"   
+#include <cctcertinfo.h>
+
+
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::CWimCertConverter()
+// Default constructor
+// -----------------------------------------------------------------------------
+CWimCertConverter::CWimCertConverter( MCTToken& aToken ): 
+CActive( EPriorityStandard ), iToken( aToken )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::NewL()
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+EXPORT_C CWimCertConverter* CWimCertConverter::NewL( MCTToken& aToken )
+    {
+    CWimCertConverter* self = new( ELeave ) CWimCertConverter( aToken );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self ); //self
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::ConstructL()
+// Second phase
+// -----------------------------------------------------------------------------
+void CWimCertConverter::ConstructL()
+    {
+    CActiveScheduler::Add( this );
+    iConnectionHandle = RWimCertMgmt::ClientSessionL();           
+    _WIMTRACE ( _L( "CWimCertConverter::ConstructL() completed" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::Restore()
+// Returns CCTCertInfo objects in array
+// -----------------------------------------------------------------------------
+EXPORT_C void CWimCertConverter::Restore( RPointerArray<CWimCertInfo>& aArray, 
+                                          TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::Restore" ) );
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+    iArray = &aArray;
+    iPhase = EListCertsFromWim;
+    SignalOwnStatusAndComplete();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::CancelRestore()
+// Cancels outgoing Restore operation. Sets an internal flag to true. 
+// After necessary cleanup, caller is signalled with KErrCancel 
+// -error code.
+// -----------------------------------------------------------------------------
+EXPORT_C void CWimCertConverter::CancelRestore()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::CancelRestore" ) );
+    Cancel(); 
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::RetrieveCertByIndexL()
+// Retrieves the actual certificate.
+// -----------------------------------------------------------------------------
+
+EXPORT_C void CWimCertConverter::RetrieveCertByIndexL( const TInt aIndex,
+                                                    TDes8& aEncodedCert, 
+                                                    TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::RetrieveCertByIndexL" ) );
+    //Check that index is valid
+    __ASSERT_ALWAYS( aIndex <= iArraySize && iCertRefLst,
+        User::Leave( KErrArgument )  );
+    iClientStatus = &aStatus;
+    iCertRetrieveIndex = aIndex;
+    iEncodedCert = &aEncodedCert;
+    aStatus = KRequestPending;
+    iPhase = ERetrieveCertificate;
+    SignalOwnStatusAndComplete();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::CancelRetrieve()
+// Cancels an ongoing Retrieve operation.
+// If retrieve is cancelled, then operation is completed with 
+// KErrCancel -error code.
+// -----------------------------------------------------------------------------
+EXPORT_C void CWimCertConverter::CancelRetrieve()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::CancelRetrieve" ) );
+    Cancel();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::AddCertificate()
+// Adds a certificate to the store.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimCertConverter::AddCertificate( const TDesC& aLabel, 
+                              const TCertificateFormat aFormat, 
+                              const TCertificateOwnerType aCertificateOwnerType,
+                              const TKeyIdentifier& aSubjectKeyId,
+                              const TKeyIdentifier& aIssuerKeyId,
+                              const TDesC8& aCert,
+                              TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::AddCertificate()" ) );        
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+    TBool paramErr = EFalse;
+    //First convert format 
+    switch ( aFormat )
+        {
+        case EX509Certificate:
+            {
+            iParam.iFormat = EWimX509Certificate; 
+            break;
+            }
+        case EWTLSCertificate:
+            {
+            iParam.iFormat = EWimWTLSCertificate;
+            break;
+            }
+        case EX968Certificate:
+            {
+            paramErr = ETrue; 
+            break;
+            }
+        case EUnknownCertificate:
+            {
+            paramErr = ETrue;
+            break;
+            }
+        case EX509CertificateUrl:
+            {
+            iParam.iFormat = EWimCertificateURL;
+            break;
+            }
+        case EWTLSCertificateUrl:
+            {
+            iParam.iFormat = EWimCertificateURL; 
+            break;
+            }
+        case EX968CertificateUrl:
+            {
+            paramErr = ETrue; 
+            break;
+            }
+        default:
+            {
+            paramErr = ETrue;
+            break;
+            }
+            
+        }
+    
+    //Then convert owner type    
+    switch ( aCertificateOwnerType )
+        {
+        case ECACertificate:
+            {
+            iParam.iUsage = EWimCertTypeCA;
+            break;
+            }
+        case EUserCertificate:
+            {
+            iParam.iUsage = EWimCertTypePersonal; 
+            break;
+            }
+        case EPeerCertificate:
+            {
+            paramErr = ETrue;
+            break;
+            }   
+        default:
+            {
+            paramErr = ETrue;
+            break;
+            }
+            
+        }
+    if ( paramErr )
+        {
+        User::RequestComplete( iClientStatus, KErrNotSupported );
+        return;
+        }
+
+    TRAPD( err, AllocMemoryForAddCertL( aLabel, 
+                                        aIssuerKeyId, 
+                                        aSubjectKeyId, 
+                                        aCert ) );
+    
+    if ( err != KErrNone ) // is everything ok?
+        {
+        DeallocCertHBufs();         //No.
+        _WIMTRACE ( _L( "CWimCertConverter::AddCertificate error = %d" ) );
+        User::RequestComplete( iClientStatus, err );    
+        }
+    else
+        {
+        iPhase = EAddCertificate;
+        SignalOwnStatusAndComplete(); //Yes.
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::CancelAddCertificate()
+// Cancels an ongoing certificate add operation.
+// If add operation is cancelled, then operation is completed with 
+// KErrCancel -error code.
+// -----------------------------------------------------------------------------
+EXPORT_C void CWimCertConverter::CancelAddCertificate()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::CancelAddCertificate()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::RemoveL()
+// Removes a certificate from WIM
+// -----------------------------------------------------------------------------
+EXPORT_C void CWimCertConverter::RemoveL( const TInt aIndex, 
+                                         TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::RemoveL()" ) );
+    //Check that index is valid
+    __ASSERT_ALWAYS( aIndex <= iArraySize && iCertRefLst, 
+        User::Leave( KErrArgument )  );    
+    iClientStatus = &aStatus;
+    iCertRetrieveIndex = aIndex;
+    aStatus = KRequestPending;
+    iPhase = ERemove;
+    SignalOwnStatusAndComplete();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::CancelRemove()
+// Cancels outgoing certificate remove operation. 
+// -----------------------------------------------------------------------------
+EXPORT_C void CWimCertConverter::CancelRemove()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::CancelRemove()" ) );
+    Cancel();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::AllocMemoryForAddCertL()
+// Allocates memory for member variables, which are needed when adding
+// a certificate asynchronously to WIM.
+// -----------------------------------------------------------------------------
+void CWimCertConverter::AllocMemoryForAddCertL( const TDesC& aLabel, 
+                                      const TKeyIdentifier& aIssuerKeyId, 
+                                      const TKeyIdentifier& aSubjectKeyId, 
+                                      const TDesC8& aCert )
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::AllocMemoryForAddCertL()" ) );
+    iCertHBufOne = aCert.AllocL(); //certificate
+    iCertHBufOnePtr = new( ELeave ) TPtr8( iCertHBufOne->Des() );
+
+    iCertHBufTwo = aIssuerKeyId.AllocL(); //IssuerKeyId
+    iCertHBufTwoPtr = new( ELeave ) TPtr8( iCertHBufTwo->Des() );
+    iParam.iCaId.Copy( iCertHBufTwoPtr->Ptr(), iCertHBufTwoPtr->Length() );
+
+    iCertHBufThree = aSubjectKeyId.AllocL(); //SubjectKeyId
+    iCertHBufThreePtr = new( ELeave ) TPtr8( iCertHBufThree->Des() );
+    iParam.iKeyId.Copy( iCertHBufThreePtr->Ptr(), iCertHBufThreePtr->Length() );
+
+    TBuf8<KLabelLen>buf;
+    buf.Copy( aLabel );
+    buf.ZeroTerminate();
+    iCertHBufFour = buf.AllocL();           //label
+    iCertHBufFourPtr = new( ELeave ) TPtr8( iCertHBufFour->Des() );
+    iParam.iLabel.Copy( iCertHBufFourPtr->Ptr(), iCertHBufFourPtr->Length() );
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::SignalOwnStatusAndComplete()       
+// Sets own iStatus to KRequestPending, and signals it 
+// with User::RequestComplete() -request. This gives chance 
+// active scheduler to run other active objects. After a quick
+// visit in active scheduler, signal returns to RunL() and starts next
+// phase of operation. 
+// @return void
+// -----------------------------------------------------------------------------
+void CWimCertConverter::SignalOwnStatusAndComplete()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::SignalOwnStatusAndComplete()" ) );
+    iStatus = KRequestPending;
+    SetActive();
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    }
+    
+// -----------------------------------------------------------------------------
+// CWimCertConverter::~CWimCertConverter()
+// Allocated memory is released.
+// -----------------------------------------------------------------------------
+EXPORT_C CWimCertConverter::~CWimCertConverter()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::~CWimCertConverter()" ) );
+    Cancel();
+    if( iConnectionHandle )
+        {
+        iConnectionHandle->DeallocWimCertPckgBuf();
+        iConnectionHandle->DeallocCertAddParametersPckgBuf();
+        iConnectionHandle->DeallocRemoveCertPckgBuf();
+        iConnectionHandle->DeallocGetExtrasPckgBuf();
+        iConnectionHandle->Close();
+        delete iConnectionHandle;
+        }
+    
+    DeallocWimCertInfo();
+    DeallocCertHBufs();
+    DeallocReferences();
+    delete iTrustedUsages;
+    delete iTrustedUsagesPtr;
+    delete iKeyIdBuf;
+    delete iKeyIdPointer;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::RunL()
+// This has eight different phases which are explained here:
+// 1. EListCertsFromWim:Allocate member variables for arrays usage. 
+//    Array is passed as an argument to server and it is filled with 
+//    certificate information found from WIM.
+// 2. ECreateNewCertObjects: New certificate objects are created based on 
+//    received information on step one. A little bit of conversion is 
+//    required. Objects are inserted to an array.
+// 3. ERetrieveCertificate:Allocate member variables for struct, 
+//    which is used to fetch certificate details
+// 4. ERetrievingCompleted: Check cancellation. If not cancelled,
+//    copy information to caller's buffer. 
+// 5. EAddCertificate: Adds certificate to WIM.
+// 6. EAddCertificateCompleted: Certificate is added successfully. Deallocate
+//                              variables and complete request.
+// 7. ERemove: Before removing, we will check for cancellation. After that
+//    cancellation is too late.
+// 8. ERemoveCompleted: Removal operation completed ok. Deallocte variables and
+//    complete request
+// 9. EGetCertExtras: Extra data is fetched and async. waiter needs to be 
+//    stopped
+// -----------------------------------------------------------------------------
+void CWimCertConverter::RunL()
+    {
+    _WIMTRACE3( _L( "CWimCertConverter::RunL()|iPhase=%d, iStatus = %d" ), iPhase, iStatus.Int() );
+    //Check for error
+    if( iStatus.Int() != KErrNone )
+        {
+        //failed to retrieve certificate
+        if ( iPhase == ERetrievingCompleted )
+            {
+             iConnectionHandle->DeallocWimCertPckgBuf();
+             DeallocCertHBufs();
+             _WIMTRACE2 ( _L( "CWimCertConverter::RunL() failed to retrieve \
+                 certificate, ERROR = %d" ),iStatus.Int() );
+            }
+        //failed to add certificate
+        else if ( iPhase == EAddCertificateCompleted )
+            {
+            //If user has tried to cancel at this stage, ignore flag.
+            iConnectionHandle->DeallocCertAddParametersPckgBuf();
+            DeallocCertHBufs();
+             _WIMTRACE2 ( _L( "CWimCertConverter::RunL() failed to add \
+                 certificate, ERROR = %d" ),iStatus.Int() );
+            }
+        //failed to remove certificate
+        else if ( iPhase == ERemoveCompleted )
+            {
+            //If user has tried to cancel at this stage, ignore flag.
+            iConnectionHandle->DeallocRemoveCertPckgBuf();
+             _WIMTRACE2 ( _L( "CWimCertConverter::RunL() failed to remove \
+                 certificate, ERROR = %d" ), iStatus.Int() );
+            }
+        User::RequestComplete( iClientStatus, iStatus.Int() );
+        }
+    else
+        {
+        switch( iPhase )
+            {
+            case EListCertsFromWim: //get certificates from WIM.
+                {                  
+                if ( iArraySize ) //Delete previous preferences. 
+                    {           //User might added or removed a certificate. 
+                    DeallocWimCertInfo();
+                    DeallocReferences();
+                    }
+            
+                //Ok ready to begin. First get Cert count
+                iCertCount = iConnectionHandle->CertCount( EWimEntryTypeAll ); 
+                _WIMTRACE2 ( _L( "CWimCertConverter::RunL() \
+                    certCount =%d" ),iCertCount );
+                if ( !iCertCount )  
+                    {
+                    User::RequestComplete( iClientStatus, KErrNotFound );
+                    }
+                else
+                    {
+                    iCertRefLst = new( ELeave ) TCertificateAddress[iCertCount];
+
+                    //Creates new array according to certificate count
+                    iCertInfoArr  = new( ELeave ) TWimCertInfo[iCertCount];
+            
+                    AllocWimCertInfoL( iCertInfoArr, iCertCount );
+                    iStatus = KRequestPending;
+                    iConnectionHandle->CertRefLst( iCertRefLst, 
+                                          iCertInfoArr, 
+                                          iCertCount, 
+                                          EWimEntryTypeAll, 
+                                          iStatus );
+                    iPhase = ECreateNewCertObjects;
+                    iIndex = 0;
+                    SetActive();    
+                    _WIMTRACE ( _L( "CWimCertConverter::RunL() \
+                        GetCertRefLst" ) );
+                    }
+                break;
+                }
+            case ECreateNewCertObjects: //Certificates fetched, 
+                { 
+                CreateNewCertObjectsL();//create new cert-objects
+                break;
+                }
+            case EGetTrustedUsages:
+                {
+                GetTrustedUsagesL();
+                break;
+                }
+            case ETrustedUsagesDone:
+                {
+                TrustedUsagesDoneL();
+                break;
+                }
+            case ECertObjectsDone: 
+                {
+                User::RequestComplete( iClientStatus, KErrNone );    
+                _WIMTRACE ( _L( "CWimCertConverter::RunL() \
+                    ECertObjectsDone" ) );
+                break;
+                }
+            case ERetrieveCertificate: //Get Cert details from WIM
+                {
+                AllocMemoryForCertDetailsL();
+                iConnectionHandle->CertDetailsL( 
+                            iCertRefLst[iCertRetrieveIndex], 
+                            iWimCertDetails, 
+                            iStatus );
+                iPhase = ERetrievingCompleted;
+                SetActive();
+                _WIMTRACE ( _L( "CWimCertConverter::RunL() \
+                    ERetrieveCertificate" ) );
+                break;
+                }
+            case ERetrievingCompleted: //Cert details fetched, check errors &                         
+                {                      //cancellations & complete request                   
+                //copy cert details to iEncodedCert -buffer,
+                //which points to received aEncoded -cert buffer.
+                CopyRetrievedCertData();
+                iConnectionHandle->DeallocWimCertPckgBuf();                
+                DeallocCertHBufs();
+                User::RequestComplete( iClientStatus, KErrNone );
+                _WIMTRACE ( _L( "CWimCertConverter::RunL() \
+                    ERetrievingCompleted" ) );
+                break;
+                }
+            case EAddCertificate: //Add a certificate
+                {
+                iConnectionHandle->StoreCertificateL( *iCertHBufOnePtr, 
+                                                iParam, 
+                                                EWimCertLocationWIMCard, 
+                                                iStatus );  
+                iPhase = EAddCertificateCompleted;
+                SetActive();   
+                _WIMTRACE ( _L( "CWimCertConverter::RunL() \
+                    EAddCertificate" ) );                    
+                break;
+                }
+            case EAddCertificateCompleted: //certificate added 
+                {
+                iConnectionHandle->DeallocCertAddParametersPckgBuf();
+                DeallocCertHBufs();
+                User::RequestComplete( iClientStatus, KErrNone );
+                _WIMTRACE ( _L( "CWimCertConverter::RunL() \
+                        EAddCertificateCompleted" ) );                    
+                break;
+                }
+            case ERemove:                //remove certificate
+                {
+                iWimCertRemoveAddr.iCertAddr = 
+                                iCertRefLst[iCertRetrieveIndex];
+                iWimCertRemoveAddr.iLocation = EWimCertLocationWIMCard;
+                iConnectionHandle->RemoveL( iWimCertRemoveAddr, iStatus );
+                iPhase = ERemoveCompleted;
+                SetActive();
+                _WIMTRACE ( _L( "CWimCertConverter::RunL() \
+                    ERemove" ) );                    
+
+                break;
+                }  
+            case ERemoveCompleted:      //certificate removed. 
+                {
+                iConnectionHandle->DeallocRemoveCertPckgBuf();
+                User::RequestComplete( iClientStatus, KErrNone );
+                _WIMTRACE ( _L( "CWimCertConverter::RunL() \
+                        ERemoveCompleted" ) ); 
+                break;
+                }
+            default:
+                {
+                User::RequestComplete( iClientStatus, KErrNotSupported );
+                break;
+                }
+                
+            }
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::CreateNewCertObjectsL()
+// Creates new certificate objects which can be returned to the caller.
+// -----------------------------------------------------------------------------
+void CWimCertConverter::CreateNewCertObjectsL()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::CreateNewCertObjectsL()" ) );
+
+    HBufC16* label16 = NULL;
+    HBufC8* hash8 = NULL;
+
+    if ( iIndex < iCertCount )
+        {
+        TCertificateOwnerType certificateType;
+        if ( iCertInfoArr[iIndex].iUsage == 0 )
+            {
+            certificateType = EUserCertificate; // 0 == User
+            }
+        else
+            {
+            certificateType = ECACertificate;   // 1 == CA
+            }
+                        
+        label16 = HBufC16::NewLC( iCertInfoArr[iIndex].iLabel.Length() );
+        label16->Des().Copy( iCertInfoArr[iIndex].iLabel );
+            
+        hash8 = HBufC8::NewLC( iCertInfoArr[iIndex].iIssuerHash.Length() );
+        hash8->Des().Copy( iCertInfoArr[iIndex].iIssuerHash );
+        // Convert type 
+        TCertificateFormat format;
+        format = GetCertFormatByIndex( iIndex );
+        //Create key indentifiers
+        TKeyIdentifier subjectKeyId;
+        TKeyIdentifier issuerKeyId;
+        //needs these for CCTCertInfo object -creation
+        subjectKeyId = iCertInfoArr[iIndex].iKeyId;
+        issuerKeyId  = iCertInfoArr[iIndex].iCAId;
+        //Create CCTCertInfo object. 
+        if ( iCertInfoArr[iIndex].iIssuerHash.Length() > 0 )
+            {
+            /**
+            * Certificate modification is not supported in 3.0, 
+            * the iCertInfoArr[iIndex].iModifiable will be replaced 
+            * by EFalse. 
+            * In the future, when modification is supported, it will be 
+            * change back.
+            */
+            iCertInfoArr[iIndex].iModifiable = EFalse;
+            iCert = CCTCertInfo::NewL( label16->Des(), 
+                                      format, 
+                                      certificateType,
+                                      iCertInfoArr[iIndex].iCertlen, 
+                                      &subjectKeyId, 
+                                      &issuerKeyId, 
+                                      iToken, 
+                                      iIndex,
+                                      iCertInfoArr[iIndex].iModifiable,
+                                      hash8 );
+            }
+        else
+            {
+            /**
+            * Same reason as mentioned above
+            */
+            iCertInfoArr[iIndex].iModifiable = EFalse;
+            iCert = CCTCertInfo::NewL( label16->Des(), 
+                                      format, 
+                                      certificateType,
+                                      iCertInfoArr[iIndex].iCertlen, 
+                                      &subjectKeyId, 
+                                      &issuerKeyId, 
+                                      iToken, 
+                                      iIndex,
+                                      iCertInfoArr[iIndex].iModifiable );
+            }
+
+        CleanupStack::PopAndDestroy( hash8 ); 
+        CleanupStack::PopAndDestroy( label16 );
+
+        iOids = new( ELeave ) RArray<HBufC*>();
+        //Check whether certificate has extra data. Certificate type must be
+        // X509
+        if ( iCertInfoArr[iIndex].iCDFRefs &&
+             iCertInfoArr[iIndex].iType == WIMI_CT_X509 )
+            {  
+            iPhase = EGetTrustedUsages;
+            }
+        else
+            {
+            CreateNewWimCertObjectL();
+            }
+        }
+    else
+        {
+        DeallocWimCertInfo(); 
+        iPhase = ECertObjectsDone;
+        }
+    SignalOwnStatusAndComplete();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::CreateNewWimCertObjectL()
+// 
+// -----------------------------------------------------------------------------
+void CWimCertConverter::CreateNewWimCertObjectL()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::CreateNewWimCertObjectL()" ) );
+
+    iCertInfo = CWimCertInfo::NewL( iCert, //CCTCertInfo object
+                                    iCert->SubjectKeyId(), //key hash
+                                    *iOids, 
+                                    iCertInfoArr[iIndex].iCDFRefs );
+    
+    delete iOids;
+    iOids = NULL;
+
+    //Append WimCertInfo -object to array. Ownership to iArray here.
+    User::LeaveIfError( iArray->Append( iCertInfo ) );
+
+    iPhase = ECreateNewCertObjects;
+    iIndex++;
+    }
+        
+// -----------------------------------------------------------------------------
+// CWimCertConverter::GetTrustedUsagesL
+// Get trusted usages (OIDs) of a current certificate, which is pointed out 
+// by a index
+// -----------------------------------------------------------------------------
+void CWimCertConverter::GetTrustedUsagesL()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::GetTrustedUsagesL() | Begin" ) );
+
+    delete iTrustedUsages;
+    iTrustedUsages = NULL;
+    delete iTrustedUsagesPtr;
+    iTrustedUsagesPtr = NULL;
+    //Allocate variables for trusted usage fetching
+    iTrustedUsages = HBufC::NewL( iCertInfoArr[iIndex].iTrustedUsageLength );
+    iTrustedUsagesPtr = new( ELeave ) TPtr( iTrustedUsages->Des() );
+
+    iCertExtrasInfo.iTrustedUsage = iTrustedUsagesPtr;
+    iPhase = ETrustedUsagesDone;
+
+    delete iKeyIdBuf;
+    iKeyIdBuf = NULL;
+    delete iKeyIdPointer;
+    iKeyIdPointer = NULL;
+    // Take a copy of key identifier
+    iKeyIdBuf = iCertInfoArr[iIndex].iKeyId.AllocL();
+    iKeyIdPointer = new( ELeave ) TPtr8( iKeyIdBuf->Des() );
+
+    iConnectionHandle->GetCertExtrasL( iKeyIdPointer,
+                                       iCertExtrasInfo,
+                                       iCertInfoArr[iIndex].iUsage,
+                                       iStatus );
+    SetActive();
+    _WIMTRACE ( _L( "CWimCertConverter::GetTrustedUsagesL() | End" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::TrustedUsagesDoneL()
+// -----------------------------------------------------------------------------
+void CWimCertConverter::TrustedUsagesDoneL()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::TrustedUsagesDoneL()" ) );
+    if ( iStatus.Int() == KErrNone )
+        {
+        //Parse oids and put them to an array
+        TLex16 lex( *iTrustedUsages );
+        TPtrC16 lexToken;
+        for ( TBool extrasDone = EFalse; extrasDone == EFalse; )
+            {
+            lexToken.Set( lex.NextToken() );
+            if ( lexToken.Length() )
+                {
+                HBufC* oid = lexToken.AllocLC();
+                User::LeaveIfError( iOids->Append( oid ) );
+                CleanupStack::Pop( oid ); //oid
+                }
+            else
+                {
+                extrasDone = ETrue;
+                }
+            }
+        CreateNewWimCertObjectL();
+        SignalOwnStatusAndComplete();
+        }
+    else
+        {
+        User::RequestComplete( iClientStatus, iStatus.Int() );
+        }
+
+    iConnectionHandle->DeallocGetExtrasPckgBuf();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::GetCertFormatByIndex()
+// Returns certificate format according to received index
+// -----------------------------------------------------------------------------
+TCertificateFormat CWimCertConverter::GetCertFormatByIndex( TInt aIndex )
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::GetCertFormatByIndex()" ) );
+
+    // Convert type 
+    TCertificateFormat format;
+    switch ( iCertInfoArr[aIndex].iType )
+        {
+        case WIMI_CT_WTLS: 
+            {
+            format = EWTLSCertificate;
+            break;
+            }
+        case WIMI_CT_X509: 
+            {
+            format = EX509Certificate;
+            break;
+            }
+        case WIMI_CT_X968: 
+            {
+            format = EX968Certificate;
+            break;
+            }
+        case WIMI_CT_URL: 
+            {
+            format = EX509CertificateUrl;
+            break;
+            }
+        default:
+            {
+            format = EUnknownCertificate;
+            break;
+            }         
+        }
+    return format;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::DoCancel()
+// Deallocates member variables and completes client status with
+// KErrCancel error code.
+// -----------------------------------------------------------------------------
+void CWimCertConverter::DoCancel()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::DoCancel()" ) );
+    if ( iConnectionHandle && iPhase == ERetrievingCompleted )
+        {
+        iConnectionHandle->DeallocWimCertPckgBuf();
+        }
+    else if ( iConnectionHandle && iPhase == EAddCertificateCompleted ) 
+        {
+        iConnectionHandle->DeallocCertAddParametersPckgBuf();
+        }
+    else if ( iConnectionHandle && iPhase == ERemoveCompleted ) 
+        {
+        iConnectionHandle->DeallocRemoveCertPckgBuf();
+        }
+    else if ( iConnectionHandle && iPhase == ETrustedUsagesDone ) 
+        {
+        iConnectionHandle->DeallocGetExtrasPckgBuf();
+        }
+
+    if ( iPhase == EGetTrustedUsages || iPhase == ETrustedUsagesDone )
+        {
+        iCert->Release();
+        }
+
+    DeallocWimCertInfo();
+    DeallocCertHBufs();
+    DeallocReferences();
+    User::RequestComplete( iClientStatus, KErrCancel );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::RunError() 
+//                                       
+// The active scheduler calls this function if this active object's RunL() 
+// function leaves. This gives this active object the opportunity to perform 
+// any necessary cleanup.
+// After array's cleanup, complete request with received error code.
+// -----------------------------------------------------------------------------
+TInt CWimCertConverter::RunError( TInt aError )
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::RunError \
+            Error = %d" ) );
+    DeallocWimCertInfo();
+    DeallocCertHBufs();
+    delete iTrustedUsages;
+    iTrustedUsages = NULL;
+    delete iTrustedUsagesPtr;
+    iTrustedUsagesPtr = NULL;
+    delete iKeyIdBuf;
+    iKeyIdBuf = NULL;
+    delete iKeyIdPointer;
+    iKeyIdPointer = NULL;
+
+    User::RequestComplete( iClientStatus, aError );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::AllocWimCertInfoL()
+// Allocates memory for the array which is filled by server.
+// -----------------------------------------------------------------------------
+void CWimCertConverter::AllocWimCertInfoL( TWimCertInfo* aWimCertInfoArr, 
+                                           TInt aCount )
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::AllocWimCertInfoL()" ) );
+
+    TUint8 index;    
+    //These are arrays
+    iLabel = new( ELeave ) PHBufC8[aCount];
+    iKeyId = new( ELeave ) PHBufC8[aCount];
+    iCAId  = new( ELeave ) PHBufC8[aCount];
+    iIssuerHash = new( ELeave ) PHBufC8[aCount];
+
+    iLabelPtr = new( ELeave ) PTPtr8[aCount];
+    iKeyIdPtr = new( ELeave ) PTPtr8[aCount];
+    iCAIdPtr  = new( ELeave ) PTPtr8[aCount];
+    iIssuerHashPtr = new( ELeave ) PTPtr8[aCount];
+
+    for ( index = 0; index < aCount ; index++ )
+        {
+        iLabel[index] = HBufC8::NewL( KLabelLen );
+        iKeyId[index] = HBufC8::NewL( KKeyIdLen );
+        iCAId[index]  = HBufC8::NewL( KPkcs15IdLen );
+        iIssuerHash[index] = HBufC8::NewL( KIssuerHash );
+        
+        iLabelPtr[index]  = new( ELeave ) TPtr8( iLabel[index]->Des() );
+        iKeyIdPtr[index]  = new( ELeave ) TPtr8( iKeyId[index]->Des() );
+        iCAIdPtr[index]   = new( ELeave ) TPtr8( iCAId[index]->Des() );
+        iIssuerHashPtr[index] = new( ELeave ) 
+                                TPtr8( iIssuerHash[index]->Des() );
+
+        aWimCertInfoArr[index].iLabel.Copy( iLabelPtr[index]->Ptr(),
+                                            iLabelPtr[index]->Length() );
+        aWimCertInfoArr[index].iKeyId.Copy( iKeyIdPtr[index]->Ptr(),
+                                            iKeyIdPtr[index]->Length() );
+        aWimCertInfoArr[index].iCAId.Copy( iCAIdPtr[index]->Ptr(),
+                                           iCAIdPtr[index]->Length() );
+        aWimCertInfoArr[index].iIssuerHash.Copy(
+            iIssuerHashPtr[index]->Ptr(), iIssuerHashPtr[index]->Length() );
+        }
+    iArraySize = aCount;   
+    }
+
+ 
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::AllocMemoryForCertDetailsL()
+// Allocates memory for a struct which is filled by server.
+// -----------------------------------------------------------------------------     
+void CWimCertConverter::AllocMemoryForCertDetailsL()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::AllocMemoryForCertDetailsL()" ) );
+    iCertHBufOne = HBufC8::NewL( iEncodedCert->MaxLength() ); //whole cert
+    iCertHBufOnePtr = new( ELeave ) TPtr8( iCertHBufOne->Des() ); 
+    iWimCertDetails.iCert = iCertHBufOnePtr;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::CopyRetrievedCertData()
+// Writes data to caller's buffer by using pointer.
+// -----------------------------------------------------------------------------
+void CWimCertConverter::CopyRetrievedCertData()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::CopyRetrievedCertData()" ) );
+    TPtr8 ptr = iCertHBufOne->Des();
+    iEncodedCert->Copy( ptr );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::DeallocCertHBufs()
+// DeAllocates memory from member variables, which are used
+// when communicating with WIM.
+// -----------------------------------------------------------------------------
+void CWimCertConverter::DeallocCertHBufs()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::DeallocCertHBufs()" ) ); 
+    if ( iCertHBufOne )
+        {
+        delete iCertHBufOne;
+        delete iCertHBufOnePtr;
+        iCertHBufOne = NULL;
+        iCertHBufOnePtr = NULL;
+        }
+    if ( iCertHBufTwo )
+        {
+        delete iCertHBufTwo;
+        delete iCertHBufTwoPtr;
+        iCertHBufTwo = NULL;
+        iCertHBufTwoPtr = NULL;
+        }
+    if ( iCertHBufThree )
+        {
+        delete iCertHBufThree;
+        delete iCertHBufThreePtr;
+        iCertHBufThree = NULL;
+        iCertHBufThreePtr = NULL;
+        }
+    if ( iCertHBufFour )
+        {
+        delete iCertHBufFour;
+        delete iCertHBufFourPtr;
+        iCertHBufFour = NULL;
+        iCertHBufFourPtr = NULL;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::DeallocReferences()
+// Deallocates memory. If user has cancelled initialization process, we need
+// to dealloc our references to loaded certs. 
+// -----------------------------------------------------------------------------
+void CWimCertConverter::DeallocReferences()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::DeallocReferences()" ) ); 
+    if ( iCertRefLst )
+        {
+        delete[] iCertRefLst;  
+        iCertRefLst = NULL;
+        }
+    if ( iCertInfoArr )
+        {
+        delete[] iCertInfoArr;
+        iCertInfoArr = NULL;
+        }  
+    iArraySize = 0;
+    iArray = NULL;
+    iCertCount = 0;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertConverter::DeallocWimCertInfo()
+// Deallocates memory. If something has leaved during asynchronous request, we 
+// will deallocate all member data. 
+// -----------------------------------------------------------------------------
+void CWimCertConverter::DeallocWimCertInfo()
+    {
+    _WIMTRACE ( _L( "CWimCertConverter::DeallocWimCertInfo()" ) ); 
+    TUint8 index;
+    for ( index = 0; index < iArraySize; index ++ )
+        {
+        if ( iLabel )
+            {
+            delete iLabel[index];
+            }
+        if ( iKeyId )
+            {
+            delete iKeyId[index];
+            }
+        if ( iCAId )
+            {
+            delete iCAId[index];
+            }
+        if ( iIssuerHash )
+            {
+            delete iIssuerHash[index];
+            }
+        if ( iLabelPtr )
+            {
+            delete iLabelPtr[index];
+            }
+        if ( iKeyIdPtr )
+            {
+            delete iKeyIdPtr[index];
+            }
+        if ( iCAIdPtr )
+            {
+            delete iCAIdPtr[index];
+            }
+        if ( iIssuerHashPtr )
+            {
+            delete iIssuerHashPtr[index];
+            }
+        }
+
+    delete[] iLabel;
+    delete[] iKeyId;
+    delete[] iCAId;
+    delete[] iIssuerHash;
+    delete[] iLabelPtr;
+    delete[] iKeyIdPtr;
+    delete[] iCAIdPtr;
+    delete[] iIssuerHashPtr;
+    iLabel = NULL;
+    iKeyId  = NULL;
+    iCAId = NULL;
+    iIssuerHash = NULL;
+    iLabelPtr = NULL;
+    iKeyIdPtr = NULL;
+    iCAIdPtr = NULL;
+    iIssuerHashPtr = NULL;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/src/WimCertMgmt.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,631 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Certificate & key -management class
+*
+*/
+
+
+//INCLUDES
+#include "WimCertMgmt.h"
+#include "WimTrace.h"
+
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::RWimCertMgmt()
+// Default constructor
+// -----------------------------------------------------------------------------
+//
+RWimCertMgmt::RWimCertMgmt(): iCertLst( NULL, 0, 0 ), iCertInfoLst( NULL, 0, 0 )
+    {
+    iPckgBufAddCertsAllocated = EFalse;
+    iPckgBufCertDetailsAllocated = EFalse;
+    iPckgBufRemoveCertAllocated = EFalse;
+    iPckgBufGetExtrasAllocated = EFalse;
+    iPckgBufKeySignAllocated = EFalse;
+    iPckgBufExportPublicKeyAllocated = EFalse;
+    iPckgBufOmaProvAllocated = EFalse;
+    iPckgBufJavaProvAllocated = EFalse;
+    iAuthObjsInfoLstPtr = NULL;
+    iAuthIdLstPtr = NULL;
+	  iPckgBufOmaProv = NULL;
+    iPckgBufJavaProv = NULL;
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::ClientSessionL()
+// Return new RWimCertMgmt object 
+// -----------------------------------------------------------------------------
+//
+RWimCertMgmt* RWimCertMgmt::ClientSessionL()
+    {
+    RWimCertMgmt* self = new( ELeave ) RWimCertMgmt;
+    CleanupStack::PushL( self );
+    User::LeaveIfError( self->Connect() );
+    CleanupStack::Pop( self ); //self
+    _WIMTRACE ( _L( "RWimCertMgmt::ClientSessionL()" ) );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::~RWimCertMgmt() 
+// Destructor, all allocated memory is released.
+// -----------------------------------------------------------------------------
+//
+RWimCertMgmt::~RWimCertMgmt()
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::~RWimCertMgmt()" ) );
+    iCertLst.Set( NULL, 0, 0 );
+    iCertInfoLst.Set( NULL, 0, 0 );
+    delete  iAuthObjsInfoLstPtr;
+	  delete  iAuthIdLstPtr;
+	  delete  iPckgBufOmaProv;
+    delete  iPckgBufJavaProv;
+    }
+
+
+
+/* Certificate management */
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::CertCount()
+// Returns count of certificates
+// -----------------------------------------------------------------------------
+//
+TUint8 RWimCertMgmt::CertCount( TWimEntryType aType )
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::CertCount()" ) );
+
+    TPckgBuf<TUint8> pckg( 0 );
+    
+    TIpcArgs args;
+    args.Set( 0, &pckg );
+    args.Set( 1, aType );
+    
+    SendReceiveData( EGetCertCount, args );
+    return pckg();
+    }
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::CertRefLst()
+// Returns certificate list on the WIM
+// -----------------------------------------------------------------------------
+//
+void  RWimCertMgmt::CertRefLst( TCertificateAddressList aCertAddrLst, 
+                                TWimCertInfo* aCertInfoArr, 
+                                TUint8 aCount, 
+                                TWimEntryType aCertEntryType,
+                                TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::CertRefLst()" ) );
+    aStatus = KRequestPending;
+    TInt16 size = ( TInt16 ) ( sizeof ( TCertificateAddress ) * aCount );
+    iCertLst.Set( ( TUint8* ) aCertAddrLst, size, size );   
+
+    size = ( TInt16 )( sizeof ( TWimCertInfo ) * aCount );
+    iCertInfoLst.Set( ( TUint8* ) aCertInfoArr, size, size ); 
+    
+    TIpcArgs args;
+    args.Set( 0, &iCertLst );
+    args.Set( 1, &iCertInfoLst );
+    args.Set( 2, aCertEntryType );
+    
+    SendReceiveData( EGetWIMCertLst, args, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::CertRefLst()
+// Returns certificate list on the WIM
+// -----------------------------------------------------------------------------
+//
+TInt RWimCertMgmt::CertRefLst( TCertificateAddressList aCertAddrLst, 
+                               TWimCertInfo* aCertInfoArr, 
+                               TUint8 aCount, 
+                               TWimEntryType aCertEntryType )
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::CertRefLst()" ) );
+    TInt16 size = ( TInt16 ) ( sizeof ( TCertificateAddress ) * aCount );
+    iCertLst.Set( ( TUint8* ) aCertAddrLst, size, size );   
+
+    size = ( TInt16 )( sizeof ( TWimCertInfo ) * aCount );
+    iCertInfoLst.Set( ( TUint8* ) aCertInfoArr, size, size ); 
+    
+    TIpcArgs args;
+    args.Set( 0, &iCertLst );
+    args.Set( 1, &iCertInfoLst );
+    args.Set( 2, aCertEntryType );
+    
+    
+    return SendReceiveData( EGetWIMCertLst, args );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::CertDetailsL() 
+// Returns certificate details.
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::CertDetailsL( const TCertificateAddress aCertAddr, 
+                                 TWimCertDetails& aWimCertDetails,
+                                 TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::CertDetailsL()" ) );
+    aStatus = KRequestPending;
+
+    iPckgBufCertDetails  = new( ELeave ) 
+        CWimCertPckgBuf<TWimCertDetails>( aWimCertDetails );
+    iPckgBufCertDetailsAllocated = ETrue;
+    
+    TIpcArgs args;
+    args.Set( 0, aCertAddr );
+    args.Set( 1, iPckgBufCertDetails->PckgBuf() );
+    args.Set( 2, aWimCertDetails.iCert );
+    
+    SendReceiveData( EGetWIMCertDetails, args, aStatus );
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::StoreCertificateL() 
+// Stores the certificate to WIM
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::StoreCertificateL( const TDes8& aCertificate,
+                                     TWimCertAddParameters& aParams,
+                                     TWimCertLocation aLocation,
+                                     TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::StoreCertificateL()" ) );
+    aStatus = KRequestPending;
+
+    iPckgBufAddCerts = new( ELeave )  
+        CWimCertPckgBuf<TWimCertAddParameters>( aParams ); 
+    iPckgBufAddCertsAllocated = ETrue;
+    
+    TIpcArgs args;
+    args.Set( 0, &aCertificate );
+    args.Set( 1, iPckgBufAddCerts->PckgBuf() );
+    args.Set( 2, aLocation );
+    
+    
+    SendReceiveData( EStoreCertificate, args, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::GetCertExtrasL()
+// Gets certificate extra data from one certificate
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::GetCertExtrasL( const TPtr8* aKeyId, 
+                                 TCertExtrasInfo& aCertExtrasInfo,
+                                 TUint aUsage,
+                                 TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::GetCertExtrasL()" ) );
+    aStatus = KRequestPending;
+    iPckgBufGetExtras  = new( ELeave ) 
+              CWimCertPckgBuf<TCertExtrasInfo>( aCertExtrasInfo );
+    iPckgBufGetExtrasAllocated = ETrue;
+    
+    TIpcArgs args;
+    args.Set( 0, aKeyId );
+    args.Set( 1, iPckgBufGetExtras->PckgBuf() );
+    args.Set( 2, aUsage );
+    args.Set( 3, aCertExtrasInfo.iTrustedUsage );
+    
+    SendReceiveData( EGetCertExtras, args, aStatus );
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::CertExtrasPckgBuf()
+// Returns CWimCertPckgBuf<TCertExtrasInfo>* member variable.
+// -----------------------------------------------------------------------------
+//
+CWimCertPckgBuf<TCertExtrasInfo>* RWimCertMgmt::CertExtrasPckgBuf()
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::CertExtrasPckgBuf()" ) );
+    return iPckgBufGetExtras;
+    }
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::RemoveL() 
+// Removes a certificate from WIM
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::RemoveL( TWimCertRemoveAddr aWimCertRemoveAddr,
+                            TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::RemoveL()" ) );
+    aStatus = KRequestPending;
+    iPckgBufRemoveCert = new( ELeave ) 
+        CWimCertPckgBuf<TWimCertRemoveAddr>( aWimCertRemoveAddr );
+    iPckgBufRemoveCertAllocated = ETrue;
+    
+    TIpcArgs args;
+    args.Set( 0, iPckgBufRemoveCert->PckgBuf() );
+    
+    SendReceiveData( ERemoveCertificate, args, aStatus );
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::DeallocWimCertPckgBuf()
+// DeAllocates memory from iPckgBufCertDetails.
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::DeallocWimCertPckgBuf()
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::DeallocWimCertPckgBuf()" ) );
+    if ( iPckgBufCertDetailsAllocated )
+        {
+        delete iPckgBufCertDetails; 
+        iPckgBufCertDetails = NULL;
+        iPckgBufCertDetailsAllocated = EFalse;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::DeallocCertAddParametersPckgBuf()
+// DeAllocates memory from iPckgBufAddCerts.
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::DeallocCertAddParametersPckgBuf()
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::DeallocCertAddParametersPckgBuf()" ) );
+    if ( iPckgBufAddCertsAllocated )
+        {
+        delete iPckgBufAddCerts;
+        iPckgBufAddCerts = NULL;
+        iPckgBufAddCertsAllocated = EFalse;
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::DeallocRemoveCertPckgBuf()
+// DeAllocates memory from iPckgBufRemoveCert.
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::DeallocRemoveCertPckgBuf()
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::DeallocRemoveCertPckgBuf()" ) );
+    if ( iPckgBufRemoveCertAllocated )
+        {
+        delete iPckgBufRemoveCert;
+        iPckgBufRemoveCert = NULL;
+        iPckgBufRemoveCertAllocated = EFalse;
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::DeallocGetExtrasPckgBuf()
+// DeAllocates memory from iPckgBufGetExtras.
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::DeallocGetExtrasPckgBuf()
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::DeallocGetExtrasPckgBuf()" ) );
+    if ( iPckgBufGetExtrasAllocated )
+        {
+        delete iPckgBufGetExtras;
+        iPckgBufGetExtras = NULL;
+        iPckgBufGetExtrasAllocated = EFalse;
+        }
+    }
+
+
+
+
+/*  Key Management */
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::KeyList()
+//                              
+// Gets the KeyList from the WIM
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::KeyList( TDes8& aKeyList,
+                            TDes8& aKeyCountPkg, 
+                            TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::KeyList()" ) );
+    aStatus = KRequestPending;
+    
+    TIpcArgs args;
+    args.Set( 0, &aKeyList );
+    args.Set( 1, &aKeyCountPkg );
+    
+    
+    SendReceiveData( EGetKeyList, args, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::GetKeyInfo()
+//
+// Gets Info for single key
+// -----------------------------------------------------------------------------
+//
+TInt RWimCertMgmt::GetKeyInfo( const TInt32 aKeyReference,                                
+                               TKeyInfo& aKeyInfo )
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::GetKeyInfo()" ) );
+    TPckg<TKeyInfo> keyinfo ( aKeyInfo );
+    
+    TIpcArgs args;
+    args.Set( 0, aKeyReference );
+    args.Set( 1, &keyinfo );
+    
+    return SendReceiveData( EGetKeyDetails, args );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::SignL()
+// Sign some data
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::SignL( TKeySignParameters& aSignParameters, 
+                         TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::SignL" ) );
+    aStatus = KRequestPending;
+    iPckgBufKeySignParameters = new( ELeave ) 
+              CWimCertPckgBuf<TKeySignParameters>( aSignParameters );
+    iPckgBufKeySignAllocated = ETrue;
+    
+    TIpcArgs args;
+    args.Set( 1, iPckgBufKeySignParameters->PckgBuf() );
+    args.Set( 2, aSignParameters.iSigningData );
+    args.Set( 3, aSignParameters.iSignature );
+    
+    SendReceiveData( ESignTextReq, args, aStatus );
+    }
+    
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::DeallocKeySignPckgBuf()
+// Deallocates member variable
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::DeallocKeySignPckgBuf()
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::DeallocKeySignPckgBuf" ) );
+    if ( iPckgBufKeySignAllocated )
+        {
+        delete iPckgBufKeySignParameters;
+        iPckgBufKeySignParameters = NULL;
+        iPckgBufKeySignAllocated = EFalse;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::ExportPublicKeyL()
+// Export public key
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::ExportPublicKeyL( TExportPublicKey& aPublicKeyParams, 
+                               TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::ExportPublicKeyL" ) );
+    aStatus = KRequestPending;
+    iPckgBufExportPublicKey = new( ELeave ) 
+        CWimCertPckgBuf<TExportPublicKey>( aPublicKeyParams );
+    iPckgBufExportPublicKeyAllocated = ETrue;
+    
+    TIpcArgs args;
+    args.Set( 0, iPckgBufExportPublicKey->PckgBuf() );
+    args.Set( 1, aPublicKeyParams.iPublicKey );
+    
+    SendReceiveData( EExportPublicKey, args, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::DeallocExportPublicKeyPckgBuf()
+// Deallocates member variable.
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::DeallocExportPublicKeyPckgBuf()
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::DeallocExportPublicKeyPckgBuf" ) );
+    if ( iPckgBufExportPublicKey )
+        {
+        delete iPckgBufExportPublicKey;
+        iPckgBufExportPublicKey = NULL;
+        iPckgBufExportPublicKeyAllocated = EFalse;
+        }
+    }
+
+
+
+/*  OMA Provisioning */
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::RetrieveOmaDataL()
+// Retrieves OMA provisioning data.
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::RetrieveOmaDataL( TOmaProv& aOmaProvStruct, 
+                                     TRequestStatus& aStatus,
+                                     const TWimServRqst aOpCode )
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::RetrieveOmaDataL" ) );
+    aStatus = KRequestPending;
+    iPckgBufOmaProv = new( ELeave ) 
+                CWimCertPckgBuf<TOmaProv>( aOmaProvStruct );
+    iPckgBufOmaProvAllocated = ETrue;
+    
+    TIpcArgs args;
+    args.Set( 0, iPckgBufOmaProv->PckgBuf() );
+    args.Set( 1, aOmaProvStruct.iOmaData );
+    
+    SendReceiveData( aOpCode, args, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::RetrieveACIFDataL()
+// Retrieves ACIF data.
+// -----------------------------------------------------------------------------
+//    
+void RWimCertMgmt::RetrieveACIFDataL( TJavaProv& aJavaProvStruct,
+                               TRequestStatus& aStatus,
+                               const TWimServRqst aOpCode )
+    {
+	_WIMTRACE ( _L( "RWimCertMgmt::RetrieveACIFDataL" ) );
+    aStatus = KRequestPending;
+    iPckgBufJavaProv = new( ELeave ) 
+                CWimCertPckgBuf<TJavaProv>( aJavaProvStruct );
+    iPckgBufJavaProvAllocated = ETrue;
+    
+    TIpcArgs args;
+    args.Set( 0, iPckgBufJavaProv->PckgBuf() );
+    args.Set( 1, aJavaProvStruct.iJavaData );
+    
+    SendReceiveData( aOpCode, args, aStatus );
+    }
+    
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::RetrieveACFDataL()
+// Retrieves ACF data.
+// -----------------------------------------------------------------------------
+//    
+void RWimCertMgmt::RetrieveACFDataL( TJavaProv& aJavaProvStruct,
+                               TRequestStatus& aStatus,
+                               const TWimServRqst aOpCode )
+    {
+	_WIMTRACE ( _L( "RWimCertMgmt::RetrieveACFDataL" ) );
+    aStatus = KRequestPending;
+    iPckgBufJavaProv = new( ELeave ) 
+                CWimCertPckgBuf<TJavaProv>( aJavaProvStruct );
+    iPckgBufJavaProvAllocated = ETrue;
+    
+    TIpcArgs args;
+    args.Set( 0, iPckgBufJavaProv->PckgBuf() );
+    args.Set( 1, aJavaProvStruct.iJavaData );
+    args.Set( 2, aJavaProvStruct.iPath );
+    
+    SendReceiveData( aOpCode, args, aStatus );
+    }    
+       
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::GetAuthObjsInfo()
+// Get Authentication Object information
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::RetrieveAuthObjsInfoL( const RArray<TInt>& aAuthIdList,
+                      RArray<TJavaPINParams>& aAuthObjsInfoList,
+                      TRequestStatus& aStatus,
+                      const TWimServRqst aOpCode )             
+    {
+    _WIMTRACE ( _L( "RWimCertMgmt::RetrieveAuthObjsInfo" ) );
+      
+    TInt count = aAuthIdList.Count();
+    TInt authIdLength = count * sizeof( TInt );
+    TInt authobjLength = count * sizeof( TJavaPINParams ); 
+    
+    if ( iAuthIdLstPtr == NULL )
+	    {
+	    iAuthIdLstPtr = new( ELeave )TPtrC8( (TText8*)&aAuthIdList[0], authIdLength );
+	    }
+    else
+        {
+        iAuthIdLstPtr->Set( (TText8*)&aAuthIdList[0], authIdLength );
+        } 
+    
+    if ( iAuthObjsInfoLstPtr == NULL )
+        {
+        iAuthObjsInfoLstPtr = new( ELeave )TPtr8( (TText8*)&aAuthObjsInfoList[0], authobjLength, authobjLength );	
+        }
+    else
+        {
+        iAuthObjsInfoLstPtr->Set( (TText8*)&aAuthObjsInfoList[0], authobjLength, authobjLength );	
+        }
+    
+    aStatus = KRequestPending;
+    TIpcArgs args;
+    
+    args.Set( 0, iAuthIdLstPtr );
+    args.Set( 1, iAuthObjsInfoLstPtr );
+    args.Set( 2, count );
+    
+    
+    SendReceiveData( aOpCode, args, aStatus );
+    }
+                              
+                              
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::RetrieveLabelAndPathL()
+// Get Authentication Object information
+// -----------------------------------------------------------------------------
+//                                                      
+void RWimCertMgmt::RetrieveLabelAndPathL( TDes8& aLabel,
+        	                              TDes8& aPath, 
+                                          TRequestStatus& aStatus,
+                                          const TWimServRqst aOpCode )
+    {
+	aStatus = KRequestPending;
+	TIpcArgs args;
+	
+	args.Set( 0, &aLabel );
+	args.Set( 1, &aPath );
+	
+	SendReceiveData( aOpCode, args, aStatus );
+    }
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::TOmaProvPckgBuf()
+// Returns member variable.
+// -----------------------------------------------------------------------------
+//
+CWimCertPckgBuf<TOmaProv>* RWimCertMgmt::TOmaProvPckgBuf()
+    {
+    return iPckgBufOmaProv;
+    }
+    
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::TJavaProvPckgBuf()
+// Returns member variable.
+// -----------------------------------------------------------------------------
+//
+CWimCertPckgBuf<TJavaProv>* RWimCertMgmt::TJavaProvPckgBuf()
+    {
+    return iPckgBufJavaProv;
+    }    
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::DeallocOmaDataPckgBuf()
+// Deallocates member variable.
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::DeallocOmaDataPckgBuf()
+    {
+    if ( iPckgBufOmaProvAllocated )
+        {
+        delete iPckgBufOmaProv;
+        iPckgBufOmaProv = NULL;
+        iPckgBufOmaProvAllocated = EFalse;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// RWimCertMgmt::DeallocJavaDataPckgBuf()
+// Deallocates member variable.
+// -----------------------------------------------------------------------------
+//
+void RWimCertMgmt::DeallocJavaDataPckgBuf()
+    {
+    if ( iPckgBufJavaProvAllocated )
+        {
+        delete iPckgBufJavaProv;
+        iPckgBufJavaProv = NULL;
+        iPckgBufJavaProvAllocated = EFalse;
+        }
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/src/WimClient.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,272 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Startup place for client & server, message handling.
+*
+*/
+
+
+//INCLUDES
+#include "WimClient.h"
+#include "WimSig.h"
+#include "WimTrace.h"
+
+#ifdef __WINS__
+#include <c32comm.h>
+
+#endif // WINS
+
+
+// -----------------------------------------------------------------------------
+// FindServerFileName()
+// Return the name of the WIM server file
+// -----------------------------------------------------------------------------
+//
+TInt RWimClient::FindServerFileName( TFileName& aServer )
+    {
+    // just return .EXE name, it's loaded from /sys/bin
+    aServer = KWimServerFile;
+    return ( KErrNone );
+    }
+
+
+// -----------------------------------------------------------------------------
+// StartWim()
+// Start the WIM server
+// -----------------------------------------------------------------------------
+//
+TInt RWimClient::StartWim()
+    {
+    _WIMTRACE( _L( "StartWim() ") );
+    // just get .EXE name, it's loaded from /sys/bin
+    TFileName serverFileName( KWimServerFile ); 
+    TRequestStatus stat;
+
+    RProcess server;
+    _WIMTRACE( _L( "StartWim Process() start" ) );
+    TInt r = server.Create( serverFileName, 
+                            KNullDesC,
+                            TUidType( KNullUid, 
+                                      KNullUid, 
+                                      KWimServerUid ) );
+    if ( r != KErrNone )
+        {
+        return r;
+        }
+
+    _WIMTRACE( _L( "StartWim Process() started" ) );
+
+
+    _WIMTRACE( _L( "wait util server release mutex..." ) );
+
+    server.Rendezvous( stat );
+    
+    _WIMTRACE( _L( "mutex is released" ) );
+  
+
+    
+    if ( stat != KRequestPending )
+        {
+        // logon failed - server is not yet running, so cannot have terminated
+        server.Kill(0);       // Abort startup
+        }
+    else
+        {
+        // logon OK - start the server
+        server.Resume();
+        }
+
+    _WIMTRACE( _L( "RWimClient::StartWim() | Wait status to complete" ) );
+
+    User::WaitForRequest( stat ); // Wait server to signal is has started
+    
+    _WIMTRACE2( _L( "RWimClient::StartWim() | complete with error %d" ), stat.Int() );
+ 
+    if ( stat.Int() == KErrAlreadyExists )
+        {
+        r = KErrNone;
+        }
+    else
+        {
+        r = stat.Int();
+        }
+
+    server.Close();
+    _WIMTRACE( _L( "RWimClient::StartWim() | End" ) );
+    
+    
+    return r;
+    }
+
+// -----------------------------------------------------------------------------
+// RWimClient::RWimClient()
+// Default constructor
+// -----------------------------------------------------------------------------
+//
+RWimClient::RWimClient()
+    {
+    _WIMTRACE ( _L( "RWimClient::RWimClient()" ) );
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimClient::~RWimClient()
+// Destructor
+// -----------------------------------------------------------------------------
+//
+RWimClient::~RWimClient()
+    {
+    _WIMTRACE ( _L( "RWimClient::~RWimClient()" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimClient::Connect()
+// Connect to WIMI server
+// -----------------------------------------------------------------------------
+//
+TInt RWimClient::Connect()
+    {
+    _WIMTRACE ( _L( "RWimClient::Connect()" ) );
+#ifdef __WINS__
+    StartC32();
+#endif
+    TInt retryCount = 0;
+    TInt retval = 0;
+    retval = CreateSession( KWIMServerName, 
+        Version(), 
+        KMessageSlotsNum );
+    if ( retval == KErrServerTerminated )
+        {
+        while ( (retval == KErrServerTerminated ) 
+            && ( retryCount++ < KWimServerTerminatingMaxRetryCount) )
+            {   
+            /* Server can take some time to shutdown, retry in a moment */
+            User::After( KWimServerTerminatingRetryTimeout );
+            retval = CreateSession( KWIMServerName, 
+                Version(), 
+                KMessageSlotsNum );
+            }
+        }
+    return retval; 
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimClient::Version() const
+// Return version
+// -----------------------------------------------------------------------------
+//
+TVersion RWimClient::Version( void ) const
+    {
+    _WIMTRACE ( _L( "RWimClient::Version()" ) );
+    return( TVersion( KWIMServMajorVersionNumber, 
+                      KWIMServMinorVersionNumber, 
+                      KWIMServBuildVersionNumber ) );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimClient::SendReceiveData()
+// Send message synchronously to server
+// -----------------------------------------------------------------------------
+//
+TInt  RWimClient::SendReceiveData( TWimServRqst aFn, TIpcArgs& aIpcArgs )
+    {
+    _WIMTRACE ( _L( "RWimClient::SendReceiveData()" ) );
+    return SendReceive( aFn, aIpcArgs ); 
+    }
+
+// -----------------------------------------------------------------------------
+// RWimClient::SendReceiveData()
+// Send message asyncronously to server
+// -----------------------------------------------------------------------------
+//
+void RWimClient::SendReceiveData( TWimServRqst aFn, 
+                                  TIpcArgs& aIpcArgs, 
+                                  TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimClient::SendReceiveData()" ) );
+    SendReceive( aFn, aIpcArgs, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimClient::FreeAddrLst()
+// Free the address list
+// -----------------------------------------------------------------------------
+//
+void RWimClient::FreeAddrLst( const TUint32 addrLst )
+    {
+    _WIMTRACE ( _L( "RWimClient::FreeAddrLst()" ) );
+
+    TIpcArgs args;
+    args.Set( 0, addrLst );
+    SendReceiveData( EFreeMemoryLst, args );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimClient::FreeWIMAddrLst()
+// Free the address list
+// -----------------------------------------------------------------------------
+//
+void RWimClient::FreeWIMAddrLst( const TWimAddressList addrLst, 
+                                 const TUint aSize )
+    {
+    _WIMTRACE ( _L( "RWimClient::FreeWIMAddrLst()" ) );
+
+    TIpcArgs args;
+    args.Set( 0, addrLst[0] );
+    args.Set( 1, aSize );
+    
+    SendReceiveData( EFreeWIMMemoryLst, args );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimClient::FreeWIMAddr()
+// Free the address
+// -----------------------------------------------------------------------------
+//
+void RWimClient::FreeWIMAddr( const TWimAddress aAddr )
+    {
+    _WIMTRACE ( _L( "RWimClient::FreeWIMAddr()" ) );
+    TIpcArgs args;
+    args.Set( 0, aAddr );
+    SendReceiveData( EFreeMemory, args );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimClient::Initialize()
+// Sends initialization command to Server.
+// -----------------------------------------------------------------------------
+//
+void RWimClient::Initialize( TRequestStatus& aStatus )
+    {
+    aStatus = KRequestPending;
+    _WIMTRACE ( _L( "RWimClient::Initialize( TRequestStatus& aStatus )" ) );
+    TIpcArgs args;
+    SendReceiveData( EWimInitialize, args, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimClient::CancelInitialize()
+// Cancel initialization command to Server.
+// -----------------------------------------------------------------------------
+//
+void RWimClient::CancelInitialize()
+    {
+    _WIMTRACE ( _L( "RWimClient::CancelInitialize()" ) );
+	TIpcArgs args;
+    SendReceiveData( ECancelWimInitialize, args );
+    }
+// End of File
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/src/WimKeyDetails.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,648 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Gets keydetails from WIM -card
+*
+*/
+
+
+
+#include "WimCertMgmt.h"
+#include "WimKeyDetails.h"
+#include "WimTrace.h"
+
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::CWimKeyDetails()
+// Default constructor
+// -----------------------------------------------------------------------------
+CWimKeyDetails::CWimKeyDetails( MCTToken& aToken ):
+CActive( EPriorityStandard ), iToken( aToken ), iPckg( iKeyNumber )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::NewL()
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+EXPORT_C CWimKeyDetails* CWimKeyDetails::NewL( MCTToken& aToken )
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::NewL()" ) );
+    CWimKeyDetails* self = new( ELeave ) CWimKeyDetails( aToken );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self ); //self
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::ConstructL()
+// Second phase
+// -----------------------------------------------------------------------------
+void CWimKeyDetails::ConstructL()
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::ConstructL()" ) );
+    CActiveScheduler::Add( this );
+    iConnectionHandle = RWimCertMgmt::ClientSessionL();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::~CWimKeyDetails()
+// Allocated memory is released.
+// -----------------------------------------------------------------------------
+EXPORT_C CWimKeyDetails::~CWimKeyDetails()
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::~CWimKeyDetails()" ) );
+    Cancel();
+    iConnectionHandle->Close();
+    delete iConnectionHandle;
+    iKeyReferences.Close();
+    DeallocMemoryFromSign();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::GetKeyList()
+// Starts to list all keys found from WIM -card
+// -----------------------------------------------------------------------------
+EXPORT_C void CWimKeyDetails::GetKeyList( RPointerArray<CCTKeyInfo>& aKeys,
+                                          CArrayFixFlat<TUint8>& aKeyNumbers,
+                                          TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::GetKeyList()" ) );
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+    iKeys = &aKeys;
+    iKeyNumberArray = &aKeyNumbers;
+    iPhase = EGetKeyList;
+    SignalOwnStatusAndComplete();
+    iFetchedKeyInfos = 0;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::CancelList()
+// Cancels listing operation.
+// -----------------------------------------------------------------------------
+EXPORT_C void CWimKeyDetails::CancelList()
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::CancelList()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::Sign()
+// Sign some data. Authentication is handled by server.
+// -----------------------------------------------------------------------------
+
+EXPORT_C void CWimKeyDetails::Sign( const TDesC8& aData, 
+                                   TDesC8& aKeyId, 
+                                   HBufC8*& aSignature, 
+                                   TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::Sign()" ) );
+
+    aStatus = KRequestPending;
+    iClientStatus = &aStatus;
+    
+    if ( aKeyId.Length() )
+        {
+        //Check that the data is not too long
+        if ( aData.Length() > KMaxRSADigestSize )
+            {
+            User::RequestComplete( iClientStatus, KErrOverflow );
+            }
+        else
+            {     
+            iSignature = aSignature; 
+            TRAPD( err, AllocMemoryForSignL( aData, aKeyId ) );
+            if ( err )
+                {
+                User::RequestComplete( iClientStatus, err );
+                }
+            else
+                {
+                iPhase = ESign;
+                SignalOwnStatusAndComplete();
+                }
+            }
+        }
+    else
+        {
+        User::RequestComplete( iClientStatus, KErrArgument );
+        }
+    }
+  
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::CancelSign()
+// Cancels outgoing signing operation 
+// -----------------------------------------------------------------------------
+EXPORT_C void CWimKeyDetails::CancelSign()
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::CancelSign()" ) );
+    Cancel();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::ExportPublicKeyL()
+// Export public key
+// -----------------------------------------------------------------------------
+EXPORT_C void CWimKeyDetails::ExportPublicKeyL( TDesC8& aKeyId, 
+                                                HBufC8*& aPublicKey, 
+                                                TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::ExportPublicKeyL()" ) );
+
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+    
+    if ( aKeyId.Length() )
+        {   
+        //KeyId from Plugin 
+        iKeyId = aKeyId.AllocL();
+        iKeyIdPtr = new( ELeave ) TPtr8( iKeyId->Des() );
+        iExportPublicKey.iKeyId.Copy( iKeyIdPtr->Ptr(), iKeyIdPtr->Length() );
+    
+        //Exported key from Server
+        iPublicKey = aPublicKey;
+        iPublicKeyPtr = new( ELeave ) TPtr8( iPublicKey->Des() );
+        iExportPublicKey.iPublicKey = iPublicKeyPtr;
+    
+        //Request to Server
+        iConnectionHandle->ExportPublicKeyL( iExportPublicKey, 
+                                             iStatus );
+        iPhase = EExportPublicKey;
+        SetActive();
+        }
+    else 
+        {
+        User::RequestComplete( iClientStatus, KErrArgument );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::CancelExport()
+// Cancel public key export
+// -----------------------------------------------------------------------------
+EXPORT_C void CWimKeyDetails::CancelExport()
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::CancelExport()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::AllocMemoryForSignL()
+// Allocates memory for signing operation
+// -----------------------------------------------------------------------------
+void CWimKeyDetails::AllocMemoryForSignL( const TDesC8& aData,
+                                          const TDesC8& aKeyId )
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::AllocMemoryForSignL()" ) );
+
+    iSigningData = aData.AllocL(); //Data to be signed
+    iSigningDataPtr = new( ELeave ) TPtr8( iSigningData->Des() );
+
+    iKeyId = aKeyId.AllocL(); //KeyId used to match correct signing key
+    iKeyIdPtr = new( ELeave ) TPtr8( iKeyId->Des() );
+
+    //Alloc pointer for signature buffer, which is owned by keystore
+    iSignaturePtr = new( ELeave ) TPtr8( iSignature->Des() );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::DeallocMemoryFromSign()
+// Deallocates memory after signing  operation
+// -----------------------------------------------------------------------------
+void CWimKeyDetails::DeallocMemoryFromSign()
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::DeallocMemoryFromSign()" ) );
+
+    delete iSigningData;
+    delete iSigningDataPtr;
+    delete iSignaturePtr;
+    delete iKeyId;
+    delete iKeyIdPtr;
+    iSigningData = NULL;
+    iSigningDataPtr = NULL;
+    iSignaturePtr = NULL;
+    iKeyId = NULL;
+    iKeyIdPtr = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::SignalOwnStatusAndComplete()       
+// Sets own iStatus to KRequestPending, and signals it 
+// with User::RequestComplete() -request. This gives chance 
+// active scheduler to run other active objects. After a quick
+// visit in active scheduler, signal returns to RunL() and starts next
+// phase of operation. 
+// @return void
+// -----------------------------------------------------------------------------
+void CWimKeyDetails::SignalOwnStatusAndComplete()
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::SignalOwnStatusAndComplete()" ) );
+    iStatus = KRequestPending;
+    SetActive();
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::RunL()
+// EGetKeyList: Get the number of keys key and references to each key.
+// EConvertParams: Gets key references from string and puts them to RArray
+// EGetKeyInfo: Fetches a single keyinfo. According to received values, a new
+//              CCTKeyInfo -object is created and inserted to an Array. Received
+//              parameters requires a little bit conversion. 
+// ESign:       Sends signing request with data to be signed to server.
+// ESignCompleted: Sign is done 
+// EExportPublicKey: Sends Export public key request to server. Receives 
+//              exported public key.
+// -----------------------------------------------------------------------------
+void CWimKeyDetails::RunL()
+    {
+	//Check for error
+    if ( iStatus.Int() != KErrNone )
+        {
+        if ( iPhase == EConvertParams )
+            {
+            DeallocMemoryFromKeyList();
+            }
+        else if ( iPhase == ESignCompleted )
+            {
+            iConnectionHandle->DeallocKeySignPckgBuf();
+            DeallocMemoryFromSign();
+            }
+        else if ( iPhase == EExportPublicKey )
+            {
+            iConnectionHandle->DeallocExportPublicKeyPckgBuf();
+            DeallocMemoryFromKeyInfo();
+            delete iPublicKeyPtr;
+            iPublicKey = NULL;      // no delete, ownership moved to caller
+            iPublicKeyPtr = NULL;
+            }
+        User::RequestComplete( iClientStatus, iStatus.Int() );
+        }
+    else
+        {
+        switch ( iPhase )
+            {
+            case EGetKeyList:
+                {
+                AllocMemoryForKeyListL();
+                iConnectionHandle->KeyList( *iKeyListPtr, 
+                                            iPckg,
+                                            iStatus );  
+                iPhase = EConvertParams;
+                SetActive();
+                _WIMTRACE ( _L( "CWimKeyDetails::RunL(),\
+                        case:EGetKeyList" ) );
+                break;
+                }
+            case EConvertParams: //Convert previously fetched parameters
+                {                //and put them to an RArray.
+                ConvertKeyListL();
+                DeallocMemoryFromKeyList(); //We don't need keylist anymore
+                iPhase = EGetKeyInfo;
+                SignalOwnStatusAndComplete();
+                _WIMTRACE ( _L( "CWimKeyDetails::RunL(),EConvertParams" ) );
+                break;
+                }
+            case EGetKeyInfo: //Now we can fetch details for every key.
+                {
+                //Are all keyinfo -objects fetched?
+                if ( iFetchedKeyInfos < iKeyReferences.Count() )
+                    { //No, get next keyinfo..
+                    TKeyInfo keyInfo;
+                    AllocMemoryForKeyInfoL( keyInfo );
+                    TInt ret = iConnectionHandle->GetKeyInfo(
+                              iKeyReferences.operator[]( iFetchedKeyInfos ),
+                              keyInfo );
+
+                    if ( ret != KErrNone )//Something went wrong
+                        {
+                        DeallocMemoryFromKeyInfo();
+                        User::RequestComplete( iClientStatus, ret );
+                        }
+                    else
+                        {
+                        TKeyUsagePKCS15 keyUsage;
+                        keyUsage = ConvertKeyUsage( keyInfo.iUsage );
+
+                        //Convert key type to support only RSA signing or
+                        //invalidAlgorithm
+                        if ( keyInfo.iType != CKeyInfoBase::ERSA )
+                            {
+                            keyInfo.iType = 
+                                  ( TUint8 )CKeyInfoBase::EInvalidAlgorithm;
+                            }
+                        //Create new KeyInfo -object and put it into array.
+                        CCTKeyInfo* cctKeyInfo = NULL;
+
+                        // Create a 16 bit heap-based buffer descriptor and a
+                        // pointer to it
+                        HBufC16* label16 = HBufC16::NewLC( KLabelLen );
+                        // 16 bit modifiable pointer descriptor to object 
+                        // above in order to manipulate data
+                        TPtr16 labelPtr16 = label16->Des();
+                        
+                        labelPtr16.Copy( keyInfo.iLabel.Left(
+                                                    keyInfo.iLabel.Length() ) );
+                       
+						TTime nullTime( _L( "00000000:" ) );
+#ifdef __SECURITY_PLATSEC_ARCH__
+						TSecurityPolicy usePolicy; 
+                        TSecurityPolicy managementPolicy;
+
+                        cctKeyInfo = CCTKeyInfo::NewL( 
+                                   keyInfo.iKeyId,      //Key ID
+                                   keyUsage,            //Key usage
+                                   keyInfo.iLength,     //Key length
+                                   NULL,                //protector
+                                   label16,             //Key label
+                                   iToken,              //token
+                                   keyInfo.iKeyNumber,  //Key number
+                                   usePolicy,			//
+								   managementPolicy,	//
+                                   ( CKeyInfoBase::EKeyAlgorithm )keyInfo.iType,
+                                   CKeyInfoBase::EInvalidAccess, //bitf. access
+                                   ETrue,               //Always Native
+                                   nullTime,            //NULL time
+                                   nullTime );          //NULL time
+#else
+                        RArray<TUid> array;
+
+                        cctKeyInfo = CCTKeyInfo::NewL( 
+                                   keyInfo.iKeyId,      //Key ID
+                                   keyUsage,            //Key usage
+                                   keyInfo.iLength,     //Key length
+                                   NULL,                //protector
+                                   label16,             //Key label
+                                   iToken,              //token
+                                   keyInfo.iKeyNumber,  //Key number
+								   KWimServerUid, //WimServer owns all keys
+                                   array,               //Null array
+                                   ( CKeyInfoBase::EKeyAlgorithm )keyInfo.iType,
+                                   CKeyInfoBase::EInvalidAccess, //bitf. access
+                                   ETrue,               //Always Native
+                                   nullTime,            //NULL time
+                                   nullTime );          //NULL time
+#endif
+
+                         _WIMTRACE ( _L( "CWimKeyDetails::RunL(),EGetKeyInfo | CCTKeyInfo is initialized " ) );
+
+                        ret =  iKeys->Append( cctKeyInfo );
+
+                        if ( ret != KErrNone )
+                            {
+                            CleanupStack::Pop( label16 );
+                            cctKeyInfo->Release();
+                            User::Leave( ret );
+                            }
+                       
+                         //Append corresponding pinnumber to array.
+                        iKeyNumberArray->AppendL( keyInfo.iPinNumber );  
+                         
+                        //We must not destroy label16, because CCTKeyInfo 
+                        //-object takes ownership.
+                        CleanupStack::Pop( label16 );
+                        //Increase counter, we have successfully fetched 
+                        //infos for single key and corresponding CCTKeyInfo 
+                        //is created
+                        iFetchedKeyInfos++;
+                        //Cleanup label and keyid modifiers.
+                        DeallocMemoryFromKeyInfo();
+                        iPhase = EGetKeyInfo;
+                        SignalOwnStatusAndComplete();
+                        _WIMTRACE ( _L( "CWimKeyDetails::RunL(),\
+                            case:EGetKeyInfo" ) );
+                            }
+                        }
+                    else//Yep, All done.
+                        {
+                        iFetchedKeyInfos = 0;
+                        //Don't need key references anymore
+                        iKeyReferences.Close(); 
+                        User::RequestComplete( iClientStatus, iStatus.Int() );
+                        }
+                break;
+                }
+            case ESign:
+                {
+                iPhase = ESignCompleted;
+                iKeySignParameters.iSigningData = iSigningDataPtr;
+                iKeySignParameters.iSignature = iSignaturePtr;
+                iKeySignParameters.iKeyId.Copy( iKeyIdPtr->Ptr(), iKeyIdPtr->Length() );
+                iConnectionHandle->SignL( iKeySignParameters, iStatus );
+                SetActive();
+                break;
+                }
+            case ESignCompleted:
+                {
+                //signature data is copied by now to plugins memory.   
+                iConnectionHandle->DeallocKeySignPckgBuf();
+                DeallocMemoryFromSign();
+                User::RequestComplete( iClientStatus, iStatus.Int() );
+                break;
+                }
+            case EExportPublicKey:
+                {
+                iConnectionHandle->DeallocExportPublicKeyPckgBuf();
+                DeallocMemoryFromKeyInfo();
+                delete iPublicKeyPtr;
+                iPublicKeyPtr = NULL;
+                User::RequestComplete( iClientStatus, iStatus.Int() );
+                break;
+                }
+            default:
+                {
+                break;
+                }    
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::ConvertKeyUsage()
+// Converts keyUsage to new form. All keyUsages loaded from WIM are treated
+// as private keys.
+// -----------------------------------------------------------------------------
+TKeyUsagePKCS15 CWimKeyDetails::ConvertKeyUsage( TUint16 aKeyUsage )
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::ConvertKeyUsage()" ) );
+
+    TKeyUsagePKCS15 usage = EPKCS15UsageNone;
+    switch ( aKeyUsage ) 
+        {
+        case KPkcs15KeyUsageFlagsDecrypt:
+            {
+            usage = EPKCS15UsageDecrypt;
+            break;
+            }
+        case KPkcs15KeyUsageFlagsSign:
+            {
+            usage = EPKCS15UsageSign;
+            break;
+            }
+        case KPkcs15KeyUsageFlagsSignRecover:
+            {
+            usage = EPKCS15UsageSignRecover;
+            break;
+            }
+        case KPkcs15KeyUsageFlagsUnwrap:
+            {
+            usage = EPKCS15UsageUnwrap;
+            break;
+            }
+        case KPkcs15KeyUsageFlagsDerive:
+            {
+            usage = EPKCS15UsageDerive;
+            break;
+            }
+        case KPkcs15KeyUsageFlagsNonRepudiation:
+            {
+            usage = EPKCS15UsageNonRepudiation;
+            break;
+            }
+        default:
+            {
+            break;
+            }
+        }
+    return usage;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::AllocMemoryForKeyListL()
+// Allocates memory for Array which is filled by server.
+// -----------------------------------------------------------------------------
+void CWimKeyDetails::AllocMemoryForKeyListL()
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::AllocMemoryForKeyListL()" ) );
+
+    iKeyList = HBufC8::NewL( KLabelLen );
+    iKeyListPtr = new( ELeave ) TPtr8( iKeyList->Des() );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::DeallocMemoryFromKeyList()
+// Deallocates memory from Array which was filled by server.
+// -----------------------------------------------------------------------------
+void CWimKeyDetails::DeallocMemoryFromKeyList()
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::DeallocMemoryFromKeyList()" ) );
+
+    delete iKeyList;
+    delete iKeyListPtr;
+    iKeyList = NULL;
+    iKeyListPtr = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::ConvertKeyListL()
+// Converts keylist parameters. Extracts data out from keylist & keynumber.
+// Extracted data is inserted to RArray.
+// -----------------------------------------------------------------------------
+void CWimKeyDetails::ConvertKeyListL()
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::ConvertKeyListL()" ) );
+
+    TInt32 output = 0;
+    
+    TLex8 lex8( iKeyListPtr->Ptr() );
+    for ( TInt i = 0; i < iKeyNumber; i++ ) //Put keyreferences to array.
+        {
+        lex8.SkipSpaceAndMark();
+        lex8.Val( output );
+        User::LeaveIfError( iKeyReferences.Append( output ) );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::AllocMemoryForKeyInfoL()
+// Allocates memory for label and keyid.
+// -----------------------------------------------------------------------------
+void CWimKeyDetails::AllocMemoryForKeyInfoL( TKeyInfo& aKeyInfo )
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::AllocMemoryForKeyInfoL()" ) );
+
+    iLabel = HBufC8::NewL( KLabelLen ); //Label
+    iLabelPtr = new( ELeave ) TPtr8( iLabel->Des() );
+    aKeyInfo.iLabel.Copy( iLabelPtr->Ptr(), iLabelPtr->Length() );
+   
+    iKeyId = HBufC8::NewL( KKeyIdLen ); //KeyId
+    iKeyIdPtr = new( ELeave ) TPtr8( iKeyId->Des() );
+    aKeyInfo.iKeyId.Copy( iKeyIdPtr->Ptr(), iKeyIdPtr->Length() ); 
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::DeallocMemoryFromKeyInfo()
+// Deallocates memory from label and keyid.
+// -----------------------------------------------------------------------------
+void CWimKeyDetails::DeallocMemoryFromKeyInfo()
+    {
+    _WIMTRACE ( _L( "CWimKeyDetails::DeallocMemoryFromKeyInfo()" ) );
+
+    delete iLabel;
+    delete iLabelPtr;
+    delete iKeyId;
+    delete iKeyIdPtr;
+    iLabel = NULL;
+    iLabelPtr = NULL;
+    iKeyId = NULL;
+    iKeyIdPtr = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::RunError()                                        
+// The active scheduler calls this function if this active object's RunL() 
+// function leaves. This gives this active object the opportunity to perform 
+// any necessary cleanup.
+// After array's cleanup, complete request with received error code.
+// -----------------------------------------------------------------------------
+TInt CWimKeyDetails::RunError( TInt aError )
+    {  
+    _WIMTRACE ( _L( "CWimKeyDetails::RunError()" ) );
+    DeallocMemoryFromKeyInfo();
+    DeallocMemoryFromKeyList();
+    User::RequestComplete( iClientStatus, aError );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyDetails::DoCancel()
+// Deallocates member variables and completes client status with
+// KErrCancel error code.
+// -----------------------------------------------------------------------------
+void CWimKeyDetails::DoCancel()
+    {    
+    _WIMTRACE ( _L( "CWimKeyDetails::DoCancel()" ) );
+
+    if ( iConnectionHandle && iPhase == ESignCompleted )
+        {
+        iConnectionHandle->DeallocKeySignPckgBuf();
+        }
+    else if ( iConnectionHandle && iPhase == EExportPublicKey )
+        {
+        delete iPublicKeyPtr;
+        iPublicKey = NULL;
+        iPublicKeyPtr = NULL;
+        iConnectionHandle->DeallocExportPublicKeyPckgBuf();
+        }
+    DeallocMemoryFromKeyList();
+    DeallocMemoryFromKeyInfo();
+    DeallocMemoryFromSign();
+    iKeyReferences.Close();
+    User::RequestComplete( iClientStatus, KErrCancel );
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/src/WimMgmt.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,514 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Startup place for client & server, message handling.
+*
+*/
+
+
+//INCLUDES
+#include "WimMgmt.h"
+#include "WimTrace.h"
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::RWimMgmt()
+// Default constructor
+// -----------------------------------------------------------------------------
+//
+RWimMgmt::RWimMgmt()
+    {
+    _WIMTRACE ( _L( "RWimMgmt::RWimMgmt()" ) );
+    iPinStateRequestBufAllocated = EFalse;
+    iPinParamsBufAllocated = EFalse;
+    iPinInfoLstPtr = NULL;
+    iPinModule = NULL;
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::~RWimMgmt()
+// Destructor
+// -----------------------------------------------------------------------------
+//
+RWimMgmt::~RWimMgmt()
+    {
+    _WIMTRACE ( _L( "RWimMgmt::~RWimMgmt()" ) );
+    delete iPinInfoLstPtr;
+    delete iPinModule;
+    }
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::WIMCount()
+// Returns  TUint - the number of WIMs
+// -----------------------------------------------------------------------------
+//
+TUint RWimMgmt::WIMCount()
+    {
+    _WIMTRACE ( _L( "RWimMgmt::WIMCount()" ) );
+
+    TPckgBuf<TUint> pckg;
+
+    TIpcArgs args;
+    args.Set( 0, &pckg );
+    
+    if ( SendReceiveData( EGetWIMCount, args ) == KErrNone )
+        {
+        return pckg();
+        }
+    else
+        {
+        return 0;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::IsOpen()
+// Tests whether WIM is open or not.
+// -----------------------------------------------------------------------------
+//
+TBool RWimMgmt::IsOpen( const TWimAddress aWimAddr )
+    {
+    _WIMTRACE ( _L( "RWimMgmt::IsOpen()" ) );
+
+    TPckgBuf<TBool> pckg;
+    
+    TIpcArgs args;
+    args.Set( 0, aWimAddr );
+    args.Set( 1, &pckg );
+    
+    SendReceiveData( EIsWIMOpen, args );
+    
+    return pckg();
+    }
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::CloseWIM()
+// Closes the WIM and returns the status of the WIMI_CloseWIM()
+// -----------------------------------------------------------------------------
+//
+TInt RWimMgmt::CloseWIM( const TWimAddress aWimAddr )
+    {
+    _WIMTRACE ( _L( "RWimMgmt::CloseWIM()" ) );
+
+    TIpcArgs args;
+    args.Set( 0, aWimAddr );
+    
+    return SendReceiveData( EWIMClose, args );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::CloseAfter()
+// Returns the time which is set as WIM closeout time
+// -----------------------------------------------------------------------------
+//
+TInt RWimMgmt::CloseAfter()
+    {
+    _WIMTRACE ( _L( "RWimMgmt::CloseAfter()" ) );
+
+    TPckgBuf<TInt> pckg;
+    
+    TIpcArgs args;
+    args.Set( 0, &pckg );
+    
+    if ( SendReceiveData( EGetCloseWIMAfter, args ) == KErrNone )
+        {
+        return pckg();
+        }
+    else
+        {
+        return 0;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::CloseAfter()
+// Returns TUint - the timeout in minutes, which tells how long 
+// WIM Security Module will be open
+// -----------------------------------------------------------------------------
+//
+TInt RWimMgmt::TimeRemaining()
+    {
+    _WIMTRACE ( _L( "RWimMgmt::TimeRemaining()" ) );
+
+    TPckgBuf<TInt> pckg;
+    
+    TIpcArgs args;
+    args.Set( 0, &pckg );
+      
+    if ( SendReceiveData( EWimTimeRemaining, args ) == KErrNone )
+        {
+        return pckg();
+        }
+    else
+        {
+        return 0;
+        }
+    }
+// -----------------------------------------------------------------------------
+// RWimMgmt::SetCloseAfter()
+// Sets closing time for WIM.
+// -----------------------------------------------------------------------------
+//
+void RWimMgmt::SetCloseAfter( const TUint aCloseAfter )
+    {
+    _WIMTRACE ( _L( "RWimMgmt::SetCloseAfter()" ) );
+    
+    TIpcArgs args;
+    args.Set( 0, aCloseAfter );
+    
+    SendReceiveData( ECloseWIMAfter, args );
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::WIMRefs()
+// Gets the array of WIM structures. aCount is the number of WIMs
+// -----------------------------------------------------------------------------
+//
+TInt RWimMgmt::WIMRefs( TWimAddressList aWimAddrLst, TUint8 aCount )
+    {
+    _WIMTRACE ( _L( "RWimMgmt::WIMRefs()" ) );
+
+    TInt length = ( TInt )( aCount * sizeof( TWimAddress ) );
+    TPtr8 pt( ( TUint8* )aWimAddrLst, length, length );
+    
+    TIpcArgs args;
+    args.Set( 0, &pt );
+    
+    return SendReceiveData( EGetWIMRefs, args );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::WIMInfo()
+// Gets the WIM information in to aTWimSecModuleStruct
+// -----------------------------------------------------------------------------
+//
+TInt RWimMgmt::WIMInfo( const TWimAddress aWimAddr, 
+                        TWimSecModuleStruct& aTWimSecModuleStruct )
+    {
+    _WIMTRACE ( _L( "RWimMgmt::WIMInfo()" ) );
+
+    TPckg<TWimSecModuleStruct> wimModule( aTWimSecModuleStruct );
+    
+    TIpcArgs args;
+    args.Set( 0, aWimAddr );
+    args.Set( 1, &wimModule );
+    
+    return SendReceiveData( EGetWIMInfo, args );
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::PINCount()
+// Returns  TUint - the number of PINs
+// -----------------------------------------------------------------------------
+//
+TUint RWimMgmt::PINCount( const TWimAddress aWimAddr )
+    {
+    _WIMTRACE ( _L( "RWimMgmt::PINCount()" ) );
+
+    TPckgBuf<TUint> pckg;
+ 
+    TIpcArgs args;
+    args.Set( 0, aWimAddr );
+    args.Set( 1, &pckg );
+
+    if ( SendReceiveData( EGetPINCount, args ) == KErrNone )
+        {
+        return pckg();
+        }
+    else
+        {
+        return 0;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::IsBlocked()
+// Checks is PIN blocked or not.
+// -----------------------------------------------------------------------------
+//
+TInt RWimMgmt::IsBlocked( const TPinAddress aPinAddr )
+    {
+    _WIMTRACE ( _L( "RWimMgmt::IsBlocked()" ) );
+    
+    TIpcArgs args;
+    args.Set( 0, aPinAddr );
+
+    return SendReceiveData( EIsPinBlocked, args );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::IsDisabledPINBlocked()
+// Checks is PIN blocked or not.
+// -----------------------------------------------------------------------------
+//
+TInt RWimMgmt::IsDisabledPINBlocked( const TPinAddress aPinAddr )
+    {
+    _WIMTRACE ( _L( "RWimMgmt::IsDisabledPINBlocked()" ) );
+    
+    TIpcArgs args;
+    args.Set( 0, aPinAddr );
+    
+    return SendReceiveData( EIsDisabledPinBlocked, args );
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::PINInfo()
+// Gets the PIN information in to rPinStruct
+// -----------------------------------------------------------------------------
+//
+void RWimMgmt::PINInfo( const TPinAddress aPinAddr, 
+                        TWimPinStruct& aPinStruct,
+                        TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimMgmt::PINInfo()" ) );
+    
+    if( iPinModule != NULL )
+    {
+    delete iPinModule;
+    iPinModule = NULL; 	
+    }
+    
+    iPinModule = new TPckg<TWimPinStruct>( aPinStruct );
+    
+    TIpcArgs args;
+    args.Set( 0, aPinAddr );
+    args.Set( 1, iPinModule );
+  
+    SendReceiveData( EGetPINInfo, args, aStatus );
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::PINRefs()
+// Gets the array of PIN structures.
+// -----------------------------------------------------------------------------
+//
+TInt RWimMgmt::PINRefs( const TWimAddress aWimAddr, 
+                        TUint32& aPinLstAddr, 
+                        TPinAddressList aPinAddrLst, 
+                        TUint8 aCount )
+    {
+    _WIMTRACE ( _L( "RWimMgmt::PINRefs()" ) );
+    TInt status = 0;
+
+    TInt16 length = ( TInt16 ) ( aCount * sizeof( TWimAddress ) );
+    TPtr8 pt( ( TUint8* ) aPinAddrLst, length, length );
+    TPckgBuf<TUint32> lstAddr;
+    
+    TIpcArgs args;
+    args.Set( 0, aWimAddr );
+    args.Set( 1, &lstAddr );
+    args.Set( 2, &pt );
+    
+    status = SendReceiveData( EGetPINRefs, args );
+    
+    if ( status == KErrNone )
+        {
+        aPinLstAddr = lstAddr();
+        }
+    else
+        {
+        aPinLstAddr = NULL;
+        }
+        
+    return status;
+    }
+    
+    
+// -----------------------------------------------------------------------------
+// RWimMgmt::PINsInfo() Asynchronous
+// Initialize elements in PinNR array
+// -----------------------------------------------------------------------------
+//    
+void RWimMgmt::PINsInfo( const TWimAddress aWimAddr, 
+               CArrayFixFlat<TWimPinStruct>& aPinInfoLst,
+               TUint8 aCount,
+               TRequestStatus& aStatus )
+  {
+   _WIMTRACE ( _L( "RWimMgmt::PINsInfo()" ) );
+   TInt16 length = ( TInt16 ) ( aCount * sizeof( TWimPinStruct ) );
+    
+   if( iPinInfoLstPtr == NULL )
+	  {
+	  iPinInfoLstPtr = new TPtr8( (TText8*)&aPinInfoLst[0],length, length ); 
+	  }
+   else
+      {
+      iPinInfoLstPtr->Set( (TText8*)&aPinInfoLst[0], length, length );
+      } 
+  
+   TIpcArgs args;
+   args.Set( 0, aWimAddr );
+   args.Set( 1, iPinInfoLstPtr );
+   args.Set( 2, aCount );
+    
+   aStatus = KRequestPending;
+   SendReceiveData( EGetPINsInfo, args, aStatus );         	
+   }
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::PINsInfo() Synchronous
+// Initialize elements in PinNR array
+// -----------------------------------------------------------------------------
+// 
+TInt RWimMgmt::PINsInfo( const TWimAddress aWimAddr, 
+               CArrayFixFlat<TWimPinStruct>& aPinInfoLst,
+               TUint8 aCount )
+  {
+  _WIMTRACE ( _L( "RWimMgmt::PINsInfo() synchronous" ) );
+    
+  TInt16 length = ( TInt16 ) ( aCount * sizeof( TWimPinStruct ) );
+    
+  if( iPinInfoLstPtr == NULL )
+	  {
+	  iPinInfoLstPtr = new TPtr8( (TText8*)&aPinInfoLst[0],length,length );	
+	  }
+  else
+      {
+      iPinInfoLstPtr->Set( (TText8*)&aPinInfoLst[0], length, length );	
+      }  
+   
+   TIpcArgs args;
+   args.Set( 0, aWimAddr );
+   args.Set( 1, iPinInfoLstPtr );
+   args.Set( 2, aCount );
+    
+   return SendReceiveData( EGetPINsInfo, args );
+        	
+   }
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::EnableDisablePinQueryL()
+// Handles Enable and Disable PIN requests. Server
+// knows wanted operation by flag which is set in TPINStateRequest.
+// -----------------------------------------------------------------------------
+//
+void RWimMgmt::EnableDisablePinQueryL( const TPinAddress aPinAddr, 
+                                       const TPINStateRequest& aPinStateRequest,
+                                       const TPINParams& aPinParams,
+                                       TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimMgmt::EnableDisablePinQuery()" ) );
+
+    iPinStateRequestBuf = new( ELeave )  
+        CWimCertPckgBuf<TPINStateRequest>( aPinStateRequest );
+    iPinStateRequestBufAllocated = ETrue;
+        
+    iPinParamsBuf = new( ELeave )  
+        CWimCertPckgBuf<TPINParams>( aPinParams );
+    iPinParamsBufAllocated = ETrue;
+
+    TIpcArgs args;
+    args.Set( 0, aPinAddr );
+    args.Set( 1, iPinStateRequestBuf->PckgBuf() );
+    args.Set( 2, iPinParamsBuf->PckgBuf() );
+
+    aStatus = KRequestPending;
+    SendReceiveData( EEnablePINReq, args, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::CancelEnableDisablePinQueryL()
+// Cancel Enable and Disable PIN requests. Server
+// knows wanted operation by flag which is set in TPINStateRequest.
+// -----------------------------------------------------------------------------
+//
+void RWimMgmt::CancelEnableDisablePin( const TPinAddress aPinAddr )
+    {
+    _WIMTRACE ( _L( "RWimMgmt::CancelEnableDisablePinQuery()" ) );
+    TIpcArgs args;
+    args.Set( 0, aPinAddr );
+    SendReceiveData( ECancelEnablePin, args );
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::DeallocMemoryFromEnableDisablePinQuery()
+// Deallocates memory from pckgBuf member variables
+// -----------------------------------------------------------------------------
+//
+void RWimMgmt::DeallocMemoryFromEnableDisablePinQuery()
+    {
+    _WIMTRACE ( _L( "RWimMgmt::DeallocMemoryFromEnableDisablePinQuery()" ) );
+
+    if ( iPinStateRequestBufAllocated )
+        {
+        delete iPinStateRequestBuf;
+        iPinStateRequestBuf = NULL;
+        iPinStateRequestBufAllocated = EFalse;
+        }
+    if ( iPinParamsBufAllocated )
+        {
+        delete iPinParamsBuf;
+        iPinParamsBuf = NULL;
+        iPinParamsBufAllocated = EFalse;
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::PinOperationL()
+// PinOperationL handles several PIN operations: it can be
+// verify PIN request, change PIN request or unblock PIN request. The 
+// type of request is handled via aOpCode.
+// -----------------------------------------------------------------------------
+//
+void RWimMgmt::PinOperationL( const TPinAddress aPinAddr,
+                              const TPINParams aPinParams,
+                              const TWimServRqst aOpCode,
+                              TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimMgmt::PinOperationL" ) );
+
+    iPinParamsBuf = new( ELeave ) CWimCertPckgBuf<TPINParams>( aPinParams );
+    iPinParamsBufAllocated = ETrue;
+
+    TIpcArgs args;
+    args.Set( 0, aPinAddr );
+    args.Set( 1, iPinParamsBuf->PckgBuf() );
+    
+    aStatus = KRequestPending;
+    SendReceiveData( aOpCode, args, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::CancelPinOperationL()
+// PinOperationL handles several PIN operations: it can be
+// verify PIN request, change PIN request or unblock PIN request. The 
+// type of request is handled via aOpCode.
+// -----------------------------------------------------------------------------
+//
+void RWimMgmt::CancelPinOperation( const TPinAddress aPinAddr,
+                                   const TWimServRqst aOpCode )
+    {
+    _WIMTRACE ( _L( "RWimMgmt::CancelPinOperation" ) );
+    TIpcArgs args;
+    args.Set( 0, aPinAddr );
+    SendReceiveData( aOpCode, args );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimMgmt::ClientSessionL()
+// Returns new RWimMgmt object
+// -----------------------------------------------------------------------------
+//
+RWimMgmt* RWimMgmt::ClientSessionL()
+    {
+    _WIMTRACE ( _L( "RWimMgmt::ClientSessionL()" ) );
+    return new( ELeave ) RWimMgmt();
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/src/WimPin.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,635 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  API for managing PIN
+*
+*/
+
+
+//INCLUDES
+#include "WimPin.h"
+#include "WimMgmt.h"
+#include "WimTrace.h"
+#include <mctauthobject.h>
+
+
+
+
+
+// ================= MEMBER FUNCTIONS  for CWimPin=======================
+//
+// C++ default constructor. Initialize the member variables
+//
+//
+CWimPin::CWimPin( TWimPin aPin, TPinAddress aPinAddr )
+:CActive( EPriorityStandard ), iReference( aPinAddr ), iPinType( aPin )
+    {
+    }
+      
+      
+// -----------------------------------------------------------------------------
+//CWimPin::NewL()
+//Two phased construction
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CWimPin* CWimPin::NewL( TWimPin aPin, 
+                                 const TPinAddress aPinAddr,
+                                 TDesC& aTokenLabel )
+    {
+    _WIMTRACE ( _L( "CWimPin::NewL()" ) );
+    __ASSERT_ALWAYS( aPinAddr, User::Leave( KErrArgument ) );
+    CWimPin* self = new( ELeave ) CWimPin( aPin, aPinAddr );
+    CleanupStack::PushL( self );
+    self->ConstructL( aTokenLabel );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimPin::ConstructL()
+// ConstructL -this method can leave
+// -----------------------------------------------------------------------------
+//
+void CWimPin::ConstructL( const TDesC& aTokenLabel )  
+    {
+    _WIMTRACE ( _L( "CWimPin::ConstructL()" ) );
+    CActiveScheduler::Add( this );
+    iTokenLabel = aTokenLabel.AllocL();
+    iLabel = HBufC::NewL( KLabelLen ); 
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::~CWimPin()
+// Destructor, allocated memory is released.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CWimPin::~CWimPin()
+    {
+    _WIMTRACE ( _L( "CWimPin::~CWimPin()" ) );
+    Cancel();
+    delete iLabel;
+    delete iTokenLabel;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::EnablePinQuery()
+// Enables PIN query of the PIN
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimPin::EnablePinQuery( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimPin::EnablePinQuery()" ) );
+    
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+    
+    iPhase = EEnablePinQueryStart;
+    SignalOwnStatusAndComplete();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::CancelEnablePinQuery()
+// Cancel Enables PIN query of the PIN
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimPin::CancelEnablePinQuery()
+    {
+    _WIMTRACE ( _L( "CWimPin::CancelEnablePinQuery()" ) );
+    
+    if( IsActive() )
+        {
+    	Cancel();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::DisablePinQuery()
+// Disables PIN query of the PIN
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimPin::DisablePinQuery( TRequestStatus& aStatus )
+    {  
+    _WIMTRACE ( _L( "CWimPin::DisablePinQuery()" ) );
+    
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+    
+    iPhase = EDisablePinQueryStart;
+    SignalOwnStatusAndComplete();
+    
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::CancelDisablePinQuery()
+// Cancel Disables PIN query of the PIN
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimPin::CancelDisablePinQuery()
+    {  
+    _WIMTRACE ( _L( "CWimPin::CancelDisablePinQuery()" ) );
+    
+    if( IsActive() )
+        {
+    	Cancel();
+        }
+    }    
+
+// -----------------------------------------------------------------------------
+// CWimPin::ChangePin()
+// Changes PIN
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimPin::ChangePin( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimPin::ChangePin()" ) );
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+    
+    iPhase = EChangePinStart;
+    SignalOwnStatusAndComplete();  
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::CancelChangePin()
+// Cancel Changes PIN
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimPin::CancelChangePin()
+    {
+    _WIMTRACE ( _L( "CWimPin::CancelChangePin()" ) );
+    if( IsActive() )
+        {
+    	Cancel();
+        }
+    }
+// -----------------------------------------------------------------------------
+// CWimPin::UnblockPin()
+// Unblocks PIN 
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimPin::UnblockPin( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimPin::UnblockPin()" ) );
+
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+    
+    iPhase = EUnblockPinStart;
+    SignalOwnStatusAndComplete();
+        
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::CancelUnblockPin()
+// Cancel Unblocks PIN 
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimPin:: CancelUnblockPin()
+    {
+    _WIMTRACE ( _L( "CWimPin::CancelUnblockPin()" ) );
+
+    if( IsActive() )
+        {
+    	Cancel();
+        }
+        
+    }    
+
+// -----------------------------------------------------------------------------
+// CWimPin::VerifyPin()
+// Verifies the entered PIN request.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimPin::VerifyPin( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimPin::VerifyPin()" ) );
+
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+    iPhase = EVerifyPinStart;
+    SignalOwnStatusAndComplete();
+   
+    }
+    
+// -----------------------------------------------------------------------------
+// CWimPin::CancelVerifyPin()
+// Cancel Verifies the entered PIN request.
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C void CWimPin::CancelVerifyPin()
+    {
+    _WIMTRACE ( _L( "CWimPin::CancelVerifyPin()" ) );
+
+    if( IsActive() )
+        {
+    	Cancel();
+        }
+   
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::Label
+// Returns PIN's label.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TPtrC CWimPin::Label() 
+    {
+    _WIMTRACE ( _L( "CWimPin::Label()" ) );
+    return iLabel->Des();    
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimPin::PinStatus()
+// returns the status of PIN.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TWimPinStatus CWimPin::PinStatus() 
+    {
+    _WIMTRACE ( _L( "CWimPin::PinStatus()" ) );
+    return iPinStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::PinNumber()
+// returns the number of the PIN. It can be 0,1,2....
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TUint8 CWimPin::PinNumber()
+    {
+    _WIMTRACE ( _L( "CWimPin::PinNumber()" ) );
+    return iPinNumber;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::RunL()
+// Different phases are handled here
+// iPhase = EEnablePinQueryStart: Sends enable PIN query message to server.
+// iPhase = EEnablePinQueryEnd: Deallocates pckgbuffer used for message sending
+//                              and completes request with received error code.
+// iPhase = EDisablePinQueryStart: Sends disable PIN query message to server.
+// iPhase = EDisablePinQueryEnd: Deallocates pckgbuffer used for message sending
+//                               and completes request with received error code.
+// iPhase = EChangePinStart: Sends change PIN message to server. 
+// iPhase = EChangePinEnd: Dealloactes pckgbuffer used for message sending and 
+//                         completes request with received error code.
+// iPhase = EUnblockPinStart: Sends unblock PIN message to server
+// iPhase = EUnblockPinEnd: Deallocates pckgbuffer used for message sending
+//                               and completes request with received error code.
+// iPhase = EVerifyPinStart: Sends verify PIN message to server.
+// iPhase = EVerifyPinEnd:Deallocates pckgbuffer used for message sending
+//                               and completes request with received error code.
+// -----------------------------------------------------------------------------
+//
+void CWimPin::RunL()
+    {
+    _WIMTRACE ( _L( "CWimPin::RunL Start()" ) );
+    if( iStatus.Int() == KErrCancel )
+        {
+        User::RequestComplete( iClientStatus, KErrCancel );
+    	return;
+        }
+        
+    switch( iPhase ) 
+        {
+        case EEnablePinQueryStart:
+            {
+            _WIMTRACE ( _L( "CWimPin::RunL EEnablePinQueryStart" ) );
+            iCurrentPhase = EEnablePinQueryStart;
+            
+            PinParams( iPinParams );
+            iPinStateRequest.iEnable = ETrue; //Enable PIN query
+            iClientSession->EnableDisablePinQueryL( iReference,
+                                                    iPinStateRequest,
+                                                    iPinParams,
+                                                    iStatus );
+            iPhase = EEnablePinQueryEnd;
+            SetActive();
+            break;
+            }
+        case EEnablePinQueryEnd:
+            {
+            iCurrentPhase = EEnablePinQueryEnd;
+            
+            iClientSession->DeallocMemoryFromEnableDisablePinQuery();
+            
+            iReceivedStatus = iStatus.Int();
+            iPhase = EUpdatePinStatus;
+            SignalOwnStatusAndComplete();
+            break;
+            }
+        case EDisablePinQueryStart:
+            {
+            _WIMTRACE ( _L( "CWimPin::RunL EDisablePinQueryStart" ) );
+            iCurrentPhase = EDisablePinQueryStart;
+            
+            PinParams( iPinParams );
+            iPinStateRequest.iEnable = EFalse; //Disable PIN query
+            iClientSession->EnableDisablePinQueryL( iReference,
+                                                        iPinStateRequest,
+                                                        iPinParams,
+                                                        iStatus );
+            iPhase = EDisablePinQueryEnd;
+            SetActive();
+            break;
+            }
+        case EDisablePinQueryEnd:
+            {
+            
+            iCurrentPhase = EDisablePinQueryEnd;
+            
+            iClientSession->DeallocMemoryFromEnableDisablePinQuery();
+            
+            iReceivedStatus = iStatus.Int();
+            iPhase = EUpdatePinStatus;
+            SignalOwnStatusAndComplete();
+            break;
+            }
+        case EChangePinStart:
+            {
+            _WIMTRACE ( _L( "CWimPin::RunL EChangePinStart" ) );
+            iCurrentPhase = EChangePinStart;
+
+            
+            PinParams( iPinParams );            
+            iClientSession->PinOperationL( iReference,
+                                           iPinParams, 
+                                           EChangePINReq, 
+                                           iStatus );
+            iPhase = EChangePinEnd;
+            SetActive();
+            break;
+            }
+        case EChangePinEnd:
+            {
+            
+            iCurrentPhase = EChangePinEnd;
+            
+            iClientSession->DeallocMemoryFromEnableDisablePinQuery();
+            
+            iReceivedStatus = iStatus.Int();
+            iPhase = EUpdatePinStatus;
+            SignalOwnStatusAndComplete();
+            break;
+            }
+        case EUnblockPinStart:
+            {
+            _WIMTRACE ( _L( "CWimPin::RunL EUnblockPinStart" ) );
+            iCurrentPhase = EUnblockPinStart;
+            
+            PinParams( iPinParams );
+            iClientSession->PinOperationL( iReference, 
+                                           iPinParams,
+                                           EUnblockPinReq,
+                                           iStatus );
+            iPhase = EUnblockPinEnd;
+            SetActive();
+            break;
+            }
+        case EUnblockPinEnd:
+            {
+            
+            iCurrentPhase = EUnblockPinEnd;
+            
+            iClientSession->DeallocMemoryFromEnableDisablePinQuery();
+            
+            iReceivedStatus = iStatus.Int();
+            iPhase = EUpdatePinStatus;
+            SignalOwnStatusAndComplete();
+            break;
+            }
+        case EVerifyPinStart:
+            {
+            _WIMTRACE ( _L( "CWimPin::RunL EVerfiyPinStart" ) );
+            iCurrentPhase = EVerifyPinStart;
+            
+            PinParams( iPinParams );
+            iClientSession->PinOperationL( iReference, 
+                                           iPinParams,
+                                           EVerifyPinReq,
+                                           iStatus );
+            iPhase = EVerifyPinEnd;
+            SetActive();
+            break;
+            }
+        case EVerifyPinEnd:
+            {
+            
+            iCurrentPhase = EVerifyPinEnd;
+            
+            iClientSession->DeallocMemoryFromEnableDisablePinQuery();
+            
+            iReceivedStatus = iStatus.Int();
+            iPhase = EUpdatePinStatus;
+            SignalOwnStatusAndComplete();
+            break;
+            }
+        case EUpdatePinStatus:
+            {
+            _WIMTRACE ( _L( "CWimPin::RunL EUpdatePinStatus" ) );
+            iCurrentPhase = EUpdatePinStatus;
+            
+            PinInfo( iStatus );
+            iPhase = EUpdatePinStatusDone;
+            SetActive();
+            break;	
+            }
+        case EUpdatePinStatusDone:
+            {
+            
+            iCurrentPhase = EUpdatePinStatusDone;
+            
+             if ( iStatus.Int() == KErrNone )
+		        {
+		        TPtr label = iLabel->Des();
+		        label.Copy( iPinStruct.iLabel.Ptr(), iPinStruct.iLabel.Length() );
+		        label.ZeroTerminate();
+		        iPinStatus = iPinStruct.iStatus;
+		        iPinNumber = iPinStruct.iPinNumber;
+		        
+		        User::RequestComplete( iClientStatus, iReceivedStatus );
+		        }
+		     else
+		        {
+		        User::RequestComplete( iClientStatus, iStatus.Int() );	
+		        }   
+        	break;
+            }
+        default:
+            {
+            break;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::DoCancel()
+// Not supported
+// -----------------------------------------------------------------------------
+void CWimPin::DoCancel()
+    {
+    switch( iCurrentPhase )
+	    {
+	    case EVerifyPinStart:
+	        {
+	    	iClientSession->CancelPinOperation( iReference, 
+                                                ECancelVerifyPin );
+	    	break;
+	        }
+	    case EEnablePinQueryStart:
+	    case EDisablePinQueryStart:
+	        {
+	        iClientSession->CancelEnableDisablePin( iReference );
+	    	break;
+	        }
+	       
+	    case EChangePinStart:
+	        {
+	        iClientSession->CancelPinOperation( iReference, 
+                                                ECancelChangePin );
+	    	break;
+	        }
+	     case EUnblockPinStart:
+	        {
+	        iClientSession->CancelPinOperation( iReference, 
+                                                ECancelUnblockPin );
+	        break;	
+	        }
+	        
+	     default: break;   
+	    }
+	    
+    User::RequestComplete( iClientStatus, KErrCancel );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::RunError()
+//
+// The active scheduler calls this function if this active object's RunL() 
+// function leaves. This gives this active object the opportunity to perform 
+// any necessary cleanup.
+// After array's cleanup, complete request with received error code.
+// -----------------------------------------------------------------------------
+TInt CWimPin::RunError( TInt aError )
+    {
+    iClientSession->DeallocMemoryFromEnableDisablePinQuery();
+    User::RequestComplete( iClientStatus, aError );
+    return KErrNone;    
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::PinParams()
+// Constructs PIN -params and returns it
+// -----------------------------------------------------------------------------
+void CWimPin::PinParams( TPINParams& aPinParams)
+    {
+    _WIMTRACE ( _L( "CWimPin::PinParams()" ) );
+    aPinParams.iMaxLength = KMaxPinLen;
+    aPinParams.iMinLength = KMinPinLen;
+    aPinParams.iPINLabel.Copy( *iLabel );
+    aPinParams.iTokenLabel.Copy( *iTokenLabel );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimPin::SignalOwnStatusAndComplete()       
+// Sets own iStatus to KRequestPending, and signals it 
+// with User::RequestComplete() -request. This gives change 
+// active scheduler to run other active objects. After a quick
+// visit in active scheduler, signal returns to RunL() and starts next
+// phase of operation. 
+// @return void
+// -----------------------------------------------------------------------------
+void CWimPin::SignalOwnStatusAndComplete()
+    {
+    _WIMTRACE ( _L( "CWimPin::SignalOwnStatusAndComplete()" ) );
+    iStatus = KRequestPending;
+    SetActive();
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::PINChangeable 
+// Checks can you change the PIN number.
+// -----------------------------------------------------------------------------
+//
+TBool CWimPin::PinChangeable()
+    {
+    _WIMTRACE ( _L( "CWimPin::PinChangeable()" ) );
+    return !( iPinStatus & EChangeDisabled );    
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimPin:::PinInfo()
+// Get PIN info. Gets always latest information from WIM.
+// -----------------------------------------------------------------------------
+//
+void CWimPin::PinInfo( TRequestStatus& aStatus ) 
+    {   
+    _WIMTRACE ( _L( "CWimPin::GetPinInfo()" ) );
+
+    iPinStruct.iLabel.Delete( 0, KLabelLen );
+    iPinStruct.iStatus = 0;
+    
+    iClientSession->PINInfo( iReference, iPinStruct, aStatus );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::SetClientSession()
+// Sets client session
+// -----------------------------------------------------------------------------
+//
+void CWimPin::SetClientSession( RWimMgmt* aClientSession )
+    {    
+     _WIMTRACE ( _L( "CWimPin::SetClientSession()" ) );
+    iClientSession = aClientSession;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::SetLabel()
+// Sets label
+// -----------------------------------------------------------------------------
+//
+void CWimPin::SetLabel( TBuf<KLabelLen>& aLabel )
+    {
+    _WIMTRACE ( _L( "CWimPin::SetLabel()" ) );	
+ 	  TPtr label = iLabel->Des();
+    label.Copy( aLabel.Ptr(), aLabel.Length() );
+    label.ZeroTerminate(); 
+    }
+    
+// -----------------------------------------------------------------------------
+// CWimPin::SetPinStatus()
+// Sets Pin Status
+// -----------------------------------------------------------------------------
+//   
+void CWimPin::SetPinStatus( TWimPinStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimPin::SetPinStatus()" ) );	
+	  iPinStatus = aStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimPin::SetPinNumber()
+// Sets pin number
+// -----------------------------------------------------------------------------
+//
+void CWimPin::SetPinNumber( TUint8& aPinNumber )
+    {
+    _WIMTRACE ( _L( "CWimPin::SetPinNumber()" ) );	
+    iPinNumber = aPinNumber;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/src/WimSecModule.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,683 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  API for managing WIM Security Module.
+*
+*/
+
+
+//INCLUDES
+#include "WimSecModule.h"
+#include "WimConsts.h"
+#include "WimPin.h"
+#include "WimMgmt.h"
+#include "WimTrace.h"
+
+//CONSTANTS
+_LIT( KZeroHex,"0%x" );
+_LIT( KHex, "%x" );
+//Must be const, else this won't compile to Thumb & arm4
+const TUint KSerialNumberMask = 0x0F; 
+const TUint KPinNum = 0x02;	
+
+//================= MEMBER FUNCTIONS  for CWimSecModule=======================
+//
+//  C++ default constructor. Initialize the member variables
+//
+//
+CWimSecModule::CWimSecModule( TWimAddress aWimAddr ): CActive( EPriorityHigh ),
+                                                      iReference( aWimAddr ),
+                                                      iPinNRsInit( EFalse )
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::NewL()
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CWimSecModule* CWimSecModule::NewL( TWimAddress aWimAddr )
+    {
+    _WIMTRACE ( _L( "CWimSecModule::NewL()" ) );
+    __ASSERT_DEBUG( aWimAddr, User::Leave( KErrArgument ) );    
+    CWimSecModule* self = new( ELeave ) CWimSecModule( aWimAddr );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self ); //self
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::ConstructL()
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimSecModule::ConstructL()
+    {
+    CActiveScheduler::Add( this );
+    _WIMTRACE ( _L( "CWimSecModule::ConstructL()" ) );
+    iLabel = HBufC::NewL( KLabelLen );
+    iManufacturer = HBufC::NewL( KManufacturerLen );
+    iSerialNumber = HBufC::NewL( KSerialNumberLen );
+    iPinInfoLst = new( ELeave )CArrayFixFlat<TWimPinStruct>(KPinNum);
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::IsOpen()
+// Checks is WIM already open.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TBool CWimSecModule::IsOpen()
+    {
+    _WIMTRACE ( _L( "CWimSecModule::IsOpen()" ) );
+    return iClientSession->IsOpen( iReference ); 
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::CloseAfter()
+// Returns the time which is set as WIM closeout time
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CWimSecModule::CloseAfter()
+    {
+    _WIMTRACE ( _L( "CWimSecModule::CloseAfter()" ) );
+    return iClientSession->CloseAfter();  
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::TimeRemaining()
+// Returns the timeout which tells how long WIM Security Module will be open 
+// after it is opened.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CWimSecModule::TimeRemaining()
+    {
+    _WIMTRACE ( _L( "CWimSecModule::TimeRemaining()" ) );
+    return iClientSession->TimeRemaining( );      
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::PinNrEntriesL()
+// Returns WIM Security Module's keys' PIN-NR objects in array.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CWimSecModule::PinNrEntriesL( 
+                                      const CArrayPtrFlat<CWimPin>*& aPinNRs,
+                                      TRequestStatus& aStatus ) 
+    {
+    _WIMTRACE ( _L( "CWimSecModule::PinNrEntriesL()" ) );
+    TInt status = KErrNone;
+    
+    if( !iPinNRsInit )
+	    {
+	    status = GetPINModulesL( aStatus );	
+	    }
+    else
+        {
+    	aPinNRs = iPinNRs;
+    	iClientStatus = &aStatus;
+    	User::RequestComplete( iClientStatus, KErrNone );
+    	return status;
+        }
+    
+    if ( status == KErrNone )
+        {
+        aPinNRs = iPinNRs;
+        }
+    else
+        {
+        aPinNRs = NULL;
+        }
+    return status;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::PinNrEntriesL()
+// Returns WIM Security Module's keys' PIN-NR objects in array.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CWimSecModule::PinNrEntriesL( 
+                                      const CArrayPtrFlat<CWimPin>*& aPinNRs ) 
+    {
+    _WIMTRACE ( _L( "CWimSecModule::PinNrEntriesL()" ) );
+    TInt status = KErrNone;
+   
+   if( !iPinNRsInit )
+       {
+   	   status = GetPINModulesL();
+       }
+    
+    if ( status == KErrNone )
+        {
+        aPinNRs = iPinNRs;
+        }
+    else
+        {
+        aPinNRs = NULL;
+        }
+    return status;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::Label()
+// Returns WIM's label.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TPtrC CWimSecModule::Label()
+    {
+    _WIMTRACE ( _L( "CWimSecModule::Label()" ) );
+    TInt status = KErrNone;
+    TRAPD( err, status = GetWIMInfoL() );
+    if ( status == KErrNone && !err )
+        {
+        return iLabel->Des();
+        }
+    else
+        {
+        return TPtrC( NULL, 0 );
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::Manufacturer()
+// Returns WIM's manufacturer.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C const TDesC& CWimSecModule::Manufacturer()
+    {
+    _WIMTRACE ( _L( "CWimSecModule::Manufacturer()" ) );
+    TInt status = KErrNone;
+    TRAPD( err, status = GetWIMInfoL() );
+    if ( status == KErrNone && !err )
+        {
+        return *iManufacturer;
+        }
+    else
+        {
+        return KNullDesC;
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::Version()
+// Returns WIM's version.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C const TDesC& CWimSecModule::Version()
+    { 
+    _WIMTRACE ( _L( "CWimSecModule::Version()" ) );
+    TInt status = KErrNone;
+    TRAPD( err, status = GetWIMInfoL() );
+    if ( status == KErrNone && !err )
+        {
+        return *iVersion;
+        }
+    else
+        {
+        return KNullDesC;   
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::SerialNumber()
+// Returns WIM's serial number which identifies it.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C const TDesC& CWimSecModule::SerialNumber()
+    {
+    _WIMTRACE ( _L( "CWimSecModule::SerialNumber()" ) );
+    TInt status = KErrNone;
+    TRAPD( err, status = GetWIMInfoL() );
+    if ( status == KErrNone && !err )
+        {
+        return *iSerialNumber; 
+        }
+    else
+        {
+        return KNullDesC;
+        }
+    }
+ 
+
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::Close()
+// Closes the parts of WIM which is opened with PIN-G.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CWimSecModule::Close()
+    {
+    _WIMTRACE ( _L( "CWimSecModule::Close()" ) );
+    
+    iWimInfoConstructed = EFalse;
+    iPinNRsInit = EFalse;
+    
+    if ( iReference )
+        {
+        return iClientSession->CloseWIM( iReference );
+        }
+    else
+        {
+        return KWimSMInfoError;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::SetCloseAfter()
+// Sets the timeout which defines the time after WIM is automatically closed.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimSecModule::SetCloseAfter( const TUint aTimeout )
+    {
+    _WIMTRACE ( _L( "CWimSecModule::SetCloseAfter()" ) );
+    iClientSession->SetCloseAfter( aTimeout );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::~CWimSecModule()
+// Destructor, all allocated memory is released.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CWimSecModule::~CWimSecModule()
+    {
+    _WIMTRACE ( _L( "CWimSecModule::~CWimSecModule()()" ) );
+    Cancel();
+    
+    if( iPinInfoLst )
+        {
+    	iPinInfoLst->Reset();
+    	delete iPinInfoLst;
+        }
+    if ( iPinLstAddr )
+        {
+        iClientSession->FreeAddrLst( iPinLstAddr );
+        }
+    if ( iPinNRs )
+        {
+        iPinNRs->ResetAndDestroy();/* Destroy  */
+        delete iPinNRs;    /* Array of pointers to PIN-NRs. */
+        }
+    if ( iRefPing )
+        {
+        iClientSession->FreeWIMAddr( iRefPing );
+        }
+    delete iLabel;
+    delete iManufacturer;
+    delete iSerialNumber;
+    if ( iVersion )
+        {
+        delete iVersion;
+        iVersion = NULL;
+        }
+   
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::TokenNumber()
+// Returns TUint8 iReader which identifies the slot 
+// where the WIM card is actually.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TUint8 CWimSecModule::TokenNumber()
+    {
+    _WIMTRACE ( _L( "CWimSecModule::TokenNumber()" ) );
+    return iReader;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::NotifyOnRemoval()
+// Notifies the client when the token has been removed.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimSecModule::NotifyOnRemoval( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimSecModule::NotifyOnRemoval()" ) );
+
+    TIpcArgs args;
+    iClientSession->SendReceiveData( ENotifyOnRemoval, args, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::CancelNotifyOnRemoval()
+// Cancels the NotifyOnRemoval request.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimSecModule::CancelNotifyOnRemoval()
+    {
+    _WIMTRACE ( _L( "CWimSecModule::CancelNotifyOnRemoval()" ) );
+
+    TIpcArgs args;
+    iClientSession->SendReceiveData( ECancelNotifyOnRemoval, args );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::GetWIMInfoL()
+// Gets label,manufacturer,serialnumber and the number of the slot 
+// where card is.
+// -----------------------------------------------------------------------------
+//
+TInt CWimSecModule::GetWIMInfoL()
+    {
+    _WIMTRACE ( _L( "CWimSecModule::GetWIMInfoL()" ) );
+
+    TBuf<KVersionNumberLen> temporalVersionNum;   
+
+    TInt status = KErrNone;
+    if ( !iWimInfoConstructed )
+        {
+        HBufC* temporalSerialNumber = HBufC::NewLC( KSerialNumberLen );                
+        TWimSecModuleStruct wimSecModuleStruct;
+        TPtr label = iLabel->Des();
+        TPtr manufacturer = iManufacturer->Des();
+        TPtr serialnumber = temporalSerialNumber->Des();
+        wimSecModuleStruct.iLabel = label;
+        wimSecModuleStruct.iManufacturer = manufacturer;
+        wimSecModuleStruct.iSerialNumber = serialnumber;
+        status = iClientSession->WIMInfo( iReference, wimSecModuleStruct );
+        if ( status == KErrNone ) 
+            {
+            temporalVersionNum.Num( ( TInt )wimSecModuleStruct.iVersion );
+            iVersion = temporalVersionNum.AllocL();
+            iReader = wimSecModuleStruct.iReader;
+            label.Copy( wimSecModuleStruct.iLabel );
+            manufacturer.Copy( wimSecModuleStruct.iManufacturer );
+            serialnumber.Copy( wimSecModuleStruct.iSerialNumber );
+            label.ZeroTerminate();
+            manufacturer.ZeroTerminate();
+            serialnumber.ZeroTerminate();
+            iRefPing = wimSecModuleStruct.iRefPinG;
+            
+            //status = GetPINModulesL( aStatus );
+            
+            if ( status == KErrNone )
+                {
+                if ( iReader != KSoftId )
+                    {
+                    ConvertSerialNumberL( temporalSerialNumber );                    
+                    }
+                else
+                    {
+                    TBuf<KVersionNumberLen> newSerialNumber;
+                    TPtr ptr = temporalSerialNumber->Des();
+                    newSerialNumber.Copy( ptr ); 
+                    delete iSerialNumber;
+                    iSerialNumber = NULL;
+                    iSerialNumber = newSerialNumber.AllocL();
+                    }
+                iWimInfoConstructed = ETrue;                
+                }
+            }                       //temporalSerialNumber
+        CleanupStack::PopAndDestroy( temporalSerialNumber );               
+        }
+    return status;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::ConvertSerialNumberL()
+// Converts serialnumber. 
+// -----------------------------------------------------------------------------
+//
+void CWimSecModule::ConvertSerialNumberL( HBufC*& aSerialNumber )
+    {
+    _WIMTRACE ( _L( "CWimSecModule::ConvertSerialNumberL()" ) );
+
+    TBuf<KVersionNumberLen> orginalVersionNumber;
+    TBuf<KVersionNumberLen> newSerialNumber;
+    TPtr ptr = aSerialNumber->Des();
+    orginalVersionNumber.Copy( ptr );
+    TInt len = orginalVersionNumber.Length(); 
+    TInt i;
+    TUint item;
+    for ( i = 0; i<len; i++ )
+        {
+        item = orginalVersionNumber.operator[]( i ); 
+        if ( item <= KSerialNumberMask )
+            {
+            //In this case we need to add an extra zero before actual value.
+            newSerialNumber.AppendFormat( KZeroHex, 
+                TUint( orginalVersionNumber.operator[]( i ) ) );
+            }
+        else
+            {
+            //No need for further processing, simply append. 
+            newSerialNumber.AppendFormat( KHex, 
+                TUint( orginalVersionNumber.operator[]( i ) ) );            
+            }
+        }
+    delete iSerialNumber;
+    iSerialNumber = NULL;
+    iSerialNumber = newSerialNumber.AllocL();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::GetPINModulesL( ) Asynchronous
+// Gets PIN references and creates new CWimPin objects.
+// -----------------------------------------------------------------------------
+//
+TInt CWimSecModule::GetPINModulesL( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimSecModule::GetPINModulesL()" ) );
+
+    TInt status = KErrNone;
+    TUint pinCount= iClientSession->PINCount( iReference );
+    iPinCount = pinCount;
+    iPinInfoLst->Reset();
+    
+    if ( pinCount )
+        {
+        TPinAddress* pinLst = new( ELeave ) TPinAddress[pinCount];  
+        CleanupStack::PushL( TCleanupItem( Cleanup, pinLst ) );
+        
+        status = iClientSession->PINRefs( iReference, iPinLstAddr, pinLst,
+                                        ( TText8 )pinCount );
+        if ( status == KErrNone ) 
+            {
+            if( iPinNRs == NULL )
+	            {
+	            iPinNRs = new( ELeave ) CArrayPtrFlat<CWimPin>( pinCount );	
+	            }
+            else
+	            {
+	            iPinNRs->Reset();
+	            iPinNRs->ResizeL( pinCount );	
+	            }
+            /* Construct PIN  modules */
+            TUint8 index;
+            for ( index = 0; index < pinCount; index++ )
+                {
+                CWimPin* pinModule = CWimPin::NewL( EWimPinNR, 
+                                                    pinLst[index],
+                                                    *iLabel );
+                CleanupStack::PushL( pinModule );
+                pinModule->SetClientSession( iClientSession );
+                iPinNRs->AppendL( pinModule );
+                CleanupStack::Pop( pinModule );/* Pop pinModule  */
+                }
+              
+            if(iPinInfoLst->Count() != pinCount )
+                {
+            	iPinInfoLst->ResizeL( pinCount );
+                }
+            
+            iClientStatus = &aStatus;
+            
+            iStatus = KRequestPending;
+            
+            SetActive();
+ 
+            iClientSession->PINsInfo( iReference, *iPinInfoLst,(TText8)pinCount, iStatus);
+             
+            }
+        
+        CleanupStack::PopAndDestroy( pinLst );/* pinLst */   
+        
+        }
+    return status;
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::GetPINModulesL( ) Synchronous
+// Gets PIN references and creates new CWimPin objects.
+// -----------------------------------------------------------------------------
+//
+TInt CWimSecModule::GetPINModulesL()
+    {
+    _WIMTRACE ( _L( "CWimSecModule::GetPINModulesL()" ) );
+
+    TInt status = KErrNone;
+    TUint pinCount= iClientSession->PINCount( iReference );
+    iPinCount = pinCount;
+    iPinInfoLst->Reset();
+    
+    if ( pinCount )
+        {
+        TPinAddress* pinLst = new( ELeave ) TPinAddress[pinCount];  
+        
+        CleanupStack::PushL( TCleanupItem( Cleanup, pinLst ) );
+        
+        status = iClientSession->PINRefs( iReference, iPinLstAddr, pinLst,
+                                        ( TText8 )pinCount );
+        if ( status == KErrNone ) 
+            {
+            if( iPinNRs == NULL )
+	            {
+	            iPinNRs = new( ELeave ) CArrayPtrFlat<CWimPin>( pinCount );	
+	            }
+            else
+	            {
+	            iPinNRs->Reset();
+	            iPinNRs->ResizeL( pinCount );	
+	            }
+            /* Construct PIN  modules */
+            TUint8 index;
+            for ( index = 0; index < pinCount; index++ )
+                {
+                CWimPin* pinModule = CWimPin::NewL( EWimPinNR, 
+                                                    pinLst[index],
+                                                    *iLabel );
+                CleanupStack::PushL( pinModule );
+                pinModule->SetClientSession( iClientSession );
+                iPinNRs->AppendL( pinModule );
+                CleanupStack::Pop( pinModule );/* Pop pinModule  */
+                }
+            
+            if(iPinInfoLst->Count() != pinCount )
+                {
+            	iPinInfoLst->ResizeL( pinCount );
+                }
+          
+          TInt err = iClientSession->PINsInfo( iReference, *iPinInfoLst,(TText8)pinCount );
+           
+          if( err != KErrNone )
+             {
+             User::LeaveIfError( KErrGeneral );	
+             }
+          
+          for(TInt i=0; i<iPinCount; i++ )
+	          {
+	          ( *iPinNRs )[ i]->SetLabel( (*iPinInfoLst)[ i].iLabel );
+	    	  ( *iPinNRs )[ i]->SetPinStatus( (*iPinInfoLst)[ i].iStatus );
+	          ( *iPinNRs )[ i]->SetPinNumber( (*iPinInfoLst)[ i].iPinNumber );	
+	          }
+            
+            iPinNRsInit = ETrue;
+            iPinInfoLst->Reset();    
+            }
+            
+        CleanupStack::PopAndDestroy( pinLst );/* pinLst */
+        }
+    return status;
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::Cleanup()
+// Handles cleanup for an object which is not derived from CBase
+// -----------------------------------------------------------------------------
+//
+void CWimSecModule::Cleanup( TAny* aObject )
+    {
+    _WIMTRACE ( _L( "CWimSecModule::Cleanup()" ) );
+    delete aObject;
+    aObject = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::SetClientSession()
+// Sets pointer RWimMgmt object to modifier iClientSession
+// -----------------------------------------------------------------------------
+//
+void CWimSecModule::SetClientSession( RWimMgmt* aClientSession )
+    {
+    _WIMTRACE ( _L( "CWimSecModule::SetClientSession()" ) );
+    iClientSession = aClientSession;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::RunL()
+// -----------------------------------------------------------------------------
+//
+void CWimSecModule::RunL()
+    {
+    _WIMTRACE ( _L( "CWimSecModule::RunL()" ) );
+    
+    if( iStatus.Int() != KErrNone )
+        {
+    	return;
+        } 
+        
+    for(TInt i=0; i<iPinCount; i++ )
+        {
+    	( *iPinNRs )[ i]->SetLabel( (*iPinInfoLst)[ i].iLabel );
+    	( *iPinNRs )[ i]->SetPinStatus( (*iPinInfoLst)[ i].iStatus );
+        ( *iPinNRs )[ i]->SetPinNumber( (*iPinInfoLst)[ i].iPinNumber );
+        }
+    
+    iPinNRsInit = ETrue;
+     
+    iPinInfoLst->Reset();    
+    User::RequestComplete( iClientStatus, KErrNone );
+    }
+        
+// -----------------------------------------------------------------------------
+// CWimSecModule::DoCancel()
+// -----------------------------------------------------------------------------
+//
+void CWimSecModule::DoCancel()
+    {
+	_WIMTRACE ( _L( "CWimSecModule::DoCancel() " ) );
+	User::RequestComplete( iClientStatus, KErrCancel );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModule::RunError()
+// -----------------------------------------------------------------------------
+//
+TInt CWimSecModule::RunError( TInt aError )
+    {
+	_WIMTRACE ( _L( "CWimSecModule::RunError() " ) );
+	User::RequestComplete( iClientStatus, aError );
+	return KErrNone;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/src/WimSecModuleMgr.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,446 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  API for list all WIM Security Modules
+*
+*/
+
+
+
+//INCLUDES
+#include "WimSecModuleMgr.h"
+#include "WimSecModule.h"
+#include "WimMgmt.h"
+#include "WimTrace.h"
+ 
+
+
+// ================= MEMBER FUNCTIONS  for CWimSecModuleMgr=======================
+//
+//  C++ default constructor. 
+//
+//
+CWimSecModuleMgr::CWimSecModuleMgr():CActive( EPriorityHigh )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::NewL()
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CWimSecModuleMgr* CWimSecModuleMgr::NewL()
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::NewL()" ) );
+    CWimSecModuleMgr* self = new( ELeave ) CWimSecModuleMgr();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::ConstructL()
+// Second phase
+// -----------------------------------------------------------------------------
+//
+void CWimSecModuleMgr::ConstructL()
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::ConstructL()" ) );
+    CActiveScheduler::Add( this );  
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::~CWimSecModuleMgr()
+// Frees memory & preferences that have been allocated.
+// -----------------------------------------------------------------------------
+//     
+EXPORT_C CWimSecModuleMgr::~CWimSecModuleMgr()
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::~CWimSecModuleMgr()" ) );
+    Cancel();
+    DeAllocateWimReferences();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::GetEntries()
+// Returns all WIM Security Modules in array.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimSecModuleMgr::GetEntries( RCPointerArray<HBufC>& aTokens, 
+                                           TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::GetEntries()" ) );
+    aStatus = KRequestPending;
+    iTokenLabels = &aTokens;  
+    iPhase = ECreateNewSession;
+    iClientStatus = &aStatus;   
+    SignalOwnStatusAndComplete();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::WimCount()
+// Returns the number of WIM-cards
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CWimSecModuleMgr::WimCount()
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::WimCount()" ) );
+    if( !iWims )
+        {
+        return KErrNotFound;
+        }
+    return iWims->Count(); 
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::GetWimSecModuleByIndexL()
+// Returns CWimSecModule according to received index.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CWimSecModule* CWimSecModuleMgr::GetWimSecModuleByIndexL(
+                                                   const TInt aIndex )
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::GetWimSecModuleByIndexL()" ) );
+    if ( !iWims || aIndex > iWims->Count() || aIndex < 0 )
+        {
+        User::Leave( KErrNotFound );
+        }
+    return iWims->At( aIndex );        
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::WimLabelByIndexL()
+// Returns WIM label according to received index
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TPtrC CWimSecModuleMgr::WimLabelByIndexL( const TInt aIndex )
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::WimLabelByIndexL()" ) );
+    if ( !iWims || aIndex > iWims->Count() || aIndex < 0 )
+        {
+        User::Leave( KErrNotFound );
+        }
+    return iWims->At( aIndex )->Label();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::WimTokenNumberByIndexL()
+// Returns the number of "slot" -where current token is attached.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CWimSecModuleMgr::WimTokenNumberByIndexL( const TInt aIndex )
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::WimTokenNumberByIndexL()" ) );
+    if ( !iWims || aIndex > iWims->Count() || aIndex < 0 )
+        {
+        User::Leave( KErrNotFound );
+        }
+    return iWims->At( aIndex )->TokenNumber();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::CancelList()
+// Cancels listing operation.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimSecModuleMgr::CancelList()
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::CancelList()" ) );
+    Cancel();                          
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::SignalOwnStatusAndComplete()
+// Sets own iStatus to KRequestPending, and signals it 
+// with User::RequestComplete() -request. This gives chance 
+// to active scheduler to run other active objects. After a quick
+// visit in active scheduler, signal returns to RunL() and starts next
+// phase of listing operation. This makes possible the cancelling 
+// -function to get through.
+// -----------------------------------------------------------------------------
+//
+void CWimSecModuleMgr::SignalOwnStatusAndComplete()
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::SignalOwnStatusAndComplete()" ) );
+    iStatus = KRequestPending;
+    SetActive();
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    }
+
+
+// -----------------------------------------------------------------------------
+//  CWimSecModuleMgr::WIMModulesL() 
+//  Allocate pointer to WIM and create CWimSecModules.
+//  This function calls server one time. It gets WIM references.
+// -----------------------------------------------------------------------------
+//
+TInt CWimSecModuleMgr::WIMModulesL() 
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::WIMModulesL()" ) );
+    ReadWimCount();
+    TInt status = KErrNone;
+    if ( iWimCount > 0 )
+        {
+        iWimAddrLst = new ( ELeave ) TWimAddress[iWimCount];
+        status = iClientSession->WIMRefs( iWimAddrLst, ( TText8 )iWimCount );
+        
+        if ( status == KErrNone )
+            {
+            if( iWims )
+                {
+                iWims->ResetAndDestroy();
+                delete iWims;
+                iWims = NULL;
+                }
+            
+            iWims = new( ELeave ) CArrayPtrFlat<CWimSecModule> ( iWimCount );
+            /* Construct WIM security modules */ 
+            TUint8 index;
+            for( index = 0; index < iWimCount; index++ )
+                {
+                CWimSecModule* wimSecModule = CWimSecModule::NewL( 
+                                                    iWimAddrLst[index] );
+                CleanupStack::PushL( wimSecModule );
+                wimSecModule->SetClientSession( iClientSession );
+                iWims->AppendL( wimSecModule );
+                CleanupStack::Pop( wimSecModule );
+                }
+            AppendTokenLabelsToArrayL();
+            }
+        }
+    else
+        {
+        status = KErrHardwareNotAvailable;
+        }
+    return status;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::AppendTokenLabelsToArrayL()
+// Appends labels of available Tokens (wims) to an array.
+// -----------------------------------------------------------------------------
+//
+void CWimSecModuleMgr::AppendTokenLabelsToArrayL()
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::AppendTokenLabelsToArrayL()" ) );
+    TInt count = iWims->Count();
+    TInt i;
+    for ( i = 0; i < count; i++ )
+        {
+        HBufC* Tokenlabel = iWims->At( i )->Label().AllocLC();
+        User::LeaveIfError( iTokenLabels->Append( Tokenlabel ) );
+        CleanupStack::Pop( Tokenlabel ); //Tokenlabel
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::ReadWimCount()
+// Reads the count of the WIM.
+// -----------------------------------------------------------------------------
+//
+void CWimSecModuleMgr::ReadWimCount()
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::ReadWimCount()" ) );
+    iWimCount = iClientSession->WIMCount();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::DoCancel()
+// Deallocates member variables and completes client status with
+// KErrCancel error code..
+// -----------------------------------------------------------------------------
+//
+void CWimSecModuleMgr::DoCancel()
+    {
+    if( iCurrentPhase == EInitializeWim )
+	    {
+	    iClientSession->CancelInitialize();	
+	    }
+    User::RequestComplete( iClientStatus, KErrCancel );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::RunL()
+// Different phases are handled here. This might be considered as state machine. 
+// iPhase = ECreateNewSession: Gets ClientSession handle. Tries to connect
+//          to existing session. If there is no existing session, a new session 
+//          is created.
+// iPhase = EConnectClientSession: If new session was needed to be created, 
+//          new connecting request is needed.
+// iPhase = EInitializeWim: Sends initialize request to server and waits
+//          asyncronously.
+// iPhase = EGetWimRefs: Reads information about WIM-cards and
+//          constructs CWimSecmodules. (one WIM-card  == one CWimSecModule )
+// -----------------------------------------------------------------------------
+//
+void CWimSecModuleMgr::RunL()
+    {
+    
+    if ( iStatus.Int() != KErrNone )
+        {
+        //This is possible only when initializing WIM.
+        _WIMTRACE2( _L("CWimSecModuleMgr::RunL unable to initialize =%d"),iStatus.Int() );
+        DeAllocateWimReferences();
+        User::RequestComplete( iClientStatus, KErrHardwareNotAvailable );
+        return;
+        }
+
+    switch ( iPhase )
+        {
+        case ECreateNewSession:
+            { 
+            iCurrentPhase = ECreateNewSession;
+            
+            if ( !iClientSession )
+                {
+                 _WIMTRACE ( _L( "CWimSecModuleMgr::RunL() brand new session" ) );
+                //get ClientSession handle
+                iClientSession = RWimMgmt::ClientSessionL();
+                }
+            
+            iPhase = EConnectClientSession;
+            TInt retval = 0;
+            iWimStartErr = iClientSession->Connect();
+            if ( iWimStartErr == KErrNotFound ) //is there existing session?
+                {
+                retval = iClientSession->StartWim();
+                if ( retval != KErrNone )
+                    {
+                    User::RequestComplete( iClientStatus, 
+                                           KErrHardwareNotAvailable ); 
+                    }
+                else
+                    {
+                    SignalOwnStatusAndComplete();
+                    }
+                } 
+            else
+                {
+                 // Yes there is, continue
+                 SignalOwnStatusAndComplete(); 
+                }
+            break;
+            }
+        case EConnectClientSession:
+            {
+            //Raise iPhase
+            iCurrentPhase  = EConnectClientSession;
+            iPhase = EInitializeWim; 
+            if ( iWimStartErr )
+                {
+                //New session was needed to be created. Try to reconnect.
+                iWimStartErr = iClientSession->Connect();
+                if ( iWimStartErr != KErrNone )
+                    {
+                    //Failed to connect. No reason to continue
+                    User::RequestComplete( iClientStatus, 
+                                           KErrHardwareNotAvailable );
+                    }
+                else
+                    {
+                    SignalOwnStatusAndComplete();
+                    }
+                }
+            else
+                {
+                SignalOwnStatusAndComplete();
+                }
+            break;
+            }
+        case EInitializeWim:
+            {
+            iCurrentPhase = EInitializeWim;
+            //Initialize WIM
+            SetActive();
+            iClientSession->Initialize( iStatus );
+            iPhase = EGetWimRefs;
+            break;   
+            }
+        case EGetWimRefs:
+            {
+            iCurrentPhase = EGetWimRefs;
+            TInt retval = TInt( WIMModulesL() );
+            _WIMTRACE2 ( _L( "CWimSecModuleMgr::RunL(),\
+                case:EGetWimRefs error =%d" ), retval );
+      
+            User::RequestComplete( iClientStatus, retval );
+            break;
+            }
+
+        default:
+            {
+            break;
+            }
+        } 
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::RunError() 
+//                                       
+// The active scheduler calls this function if this active object's RunL() 
+// function leaves. This gives this active object the opportunity to perform 
+// any necessary cleanup.
+// After array's cleanup, complete request with received error code.
+// -----------------------------------------------------------------------------
+TInt CWimSecModuleMgr::RunError( TInt aError )
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::RunError()" ) );
+    DeAllocateWimReferences();
+    User::RequestComplete( iClientStatus, aError );
+    return KErrNone;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimSecModuleMgr::DeAllocateWimReferences()
+// Frees memory & preferences that have been allocated.
+// -----------------------------------------------------------------------------
+//     
+
+void CWimSecModuleMgr::DeAllocateWimReferences()
+    {
+    _WIMTRACE ( _L( "CWimSecModuleMgr::DeAllocateWimReferences()" ) );
+    if ( iTokenLabels )
+        {
+        iTokenLabels = NULL;
+        }
+    if ( iWims )
+        {
+        iWims->ResetAndDestroy();
+        delete iWims;
+        iWims = NULL;
+        }
+    if ( iClientSession )
+        {
+        if (( iWimCount > 0 ) && iWimAddrLst )
+            {
+            iClientSession->FreeWIMAddrLst( iWimAddrLst, iWimCount );
+            delete[] iWimAddrLst;
+            }
+        }
+    if ( iClientSession )
+        {
+        iClientSession->Close();
+        delete iClientSession;
+        iClientSession = NULL;
+        }
+    }
+
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/src/WimTrustSettingsAPI.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,282 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface for WIM Trust Settings Store
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "WimTrustSettingsAPI.h"
+#include "WimCertInfo.h"
+#include "WimTrustSettingsMgmt.h"
+#include "WimTrace.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsAPI::CWimTrustSettingsAPI()
+// Default constructor.
+// -----------------------------------------------------------------------------
+//
+CWimTrustSettingsAPI::CWimTrustSettingsAPI() : CActive( EPriorityNormal )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsAPI::ConstructL()
+// Second phase constructor.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsAPI::ConstructL()
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsAPI::ConstructL()" ) );
+    iConnectionHandle = RWimTrustSettingsMgmt::ClientSessionL();  
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsAPI::NewL()
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CWimTrustSettingsAPI* CWimTrustSettingsAPI::NewL()
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsAPI::NewL()" ) );
+    CWimTrustSettingsAPI* self = new( ELeave ) CWimTrustSettingsAPI;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsAPI::~CWimTrustSettingsAPI()
+// Destructor. If updates has been done, compact databse.
+// -----------------------------------------------------------------------------
+
+EXPORT_C CWimTrustSettingsAPI::~CWimTrustSettingsAPI()
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsAPI::~CWimTrustSettingsAPI()" ) );
+    iConnectionHandle->Close();
+    delete iConnectionHandle;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsAPI::Close()
+// Closes all open resources and deletes this instance of the TrustSettingsStore
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimTrustSettingsAPI::Close()
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsAPI::Close()" ) );
+    delete ( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsAPI::GetTrustSettings()
+// Return trust settings for given certificate.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimTrustSettingsAPI::GetTrustSettings( 
+    const CWimCertInfo& aCert,
+    TBool& aTrusted,
+    RArray<TUid>& aApplications, 
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsAPI::GetTrustSettings()" ) );
+    
+    iApplications = &aApplications;
+    iTrusted = &aTrusted;
+
+    iClientStatus = &aStatus;
+    iStatus = KRequestPending;
+    iPhase = EGetTrustSettings;
+
+    TRAPD( error, iConnectionHandle->GetTrustSettingsL( aCert,
+                                                        iStatus ) );
+    SetActive();
+
+    HandleLeaveError( error );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsAPI::SetApplicability()
+// Set applicability for certificate.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimTrustSettingsAPI::SetApplicability(
+    const CWimCertInfo& aCert,
+    const RArray<TUid>& aApplications,
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsAPI::SetApplicability()" ) );
+    iClientStatus = &aStatus;
+    iStatus = KRequestPending;
+    iPhase = ESetApplicability;
+
+    SetActive();
+    
+    TRAPD( error,
+        iConnectionHandle->SetApplicabilityL( aCert, aApplications, iStatus ) );
+
+    HandleLeaveError( error );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsAPI::SetTrust()
+// Set trust flag for certificate.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimTrustSettingsAPI::SetTrust(
+    const CWimCertInfo& aCert,
+    TBool aTrusted,
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsAPI::SetTrust()" ) );
+    iClientStatus = &aStatus;
+    iStatus = KRequestPending;
+    iPhase = ESetTrust;
+
+    TRAPD( error, iConnectionHandle->SetTrustL( aCert, aTrusted, iStatus ) );
+    SetActive();
+    HandleLeaveError( error );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsAPI::SetDefaultTrustSettings()
+// Set default trust settings for certificate.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimTrustSettingsAPI::SetDefaultTrustSettings(
+    const CWimCertInfo& aCert,
+    TBool aAddApps,
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsAPI::SetDefaultTrustSettings()" ) );
+
+    iClientStatus = &aStatus;
+    iStatus = KRequestPending;
+    iPhase = ESetDefaultTrustSettings;
+
+    TRAPD( error, iConnectionHandle->SetDefaultTrustSettingsL( aCert,
+                                                               aAddApps,
+                                                               iStatus ) );
+    SetActive();   
+    HandleLeaveError( error );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsAPI::RemoveTrustSettings()
+// Remove trust settings of given certificate
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimTrustSettingsAPI::RemoveTrustSettings(
+    const CWimCertInfo& aCert,
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE( _L( "CWimTrustSettingsAPI::RemoveTrustSettings()" ) );
+    
+    iClientStatus = &aStatus;
+    iStatus = KRequestPending;
+    iPhase = ERemoveTrustSettings;
+
+    TRAPD( error,
+        iConnectionHandle->RemoveTrustSettingsL( aCert, iStatus ) );
+    SetActive();
+    HandleLeaveError( error );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsAPI::CancelDoing()
+// Cancel ongoing operation
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimTrustSettingsAPI::CancelDoing()
+    {
+    _WIMTRACE( _L( "CWimTrustSettingsAPI::CancelDoing()" ) );
+    iConnectionHandle->CancelDoing();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsAPI::RunL()
+// Handle result of asynchronous Trust Settings Store operation.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsAPI::RunL()
+    {
+    _WIMTRACE2( _L( "CWimTrustSettingsAPI::RunL(), iStatus=%d" ),
+               iStatus.Int() );
+
+    switch ( iPhase )
+        {
+        case EGetTrustSettings:
+            {
+            if ( iStatus.Int() == KErrNone )
+                {
+                TPckgBuf<TTrustSettings> trustSettingsPckgBuf;
+    
+                trustSettingsPckgBuf = 
+                    ( *iConnectionHandle->TrustSettingsPckg()->PckgBuf() );
+
+                TUid uid;
+
+                for ( TInt i = 0;
+                    i < trustSettingsPckgBuf().iApplicationCount; i++ )
+                    {
+                    uid.iUid = trustSettingsPckgBuf().iUids[i];
+
+                    iApplications->Append( uid );
+                    }
+                *iTrusted = trustSettingsPckgBuf().iTrusted;
+                }
+
+            break;
+            }
+
+        default:
+            {
+            break;
+            }
+        }
+    User::RequestComplete( iClientStatus, iStatus.Int() );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsAPI::DoCancel()
+// 
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsAPI::DoCancel()
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsAPI::HandleLeaveError()
+// Handle trapped leave. Complete client request with error code.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsAPI::HandleLeaveError( TInt aError )
+    {
+    _WIMTRACE2( _L( "CWimTrustSettingsAPI::HandleLeaveError(), aError=%d" ),
+                aError );
+    if ( aError != KErrNone )
+        {
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, aError );
+        }
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimClient/src/WimTrustSettingsMgmt.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,271 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Trust Settings management class
+*
+*/
+
+
+//INCLUDES
+#include "WimTrustSettingsMgmt.h"
+#include "WimCertInfo.h"
+#include "WimTrace.h"
+
+
+// -----------------------------------------------------------------------------
+// RWimTrustSettingsMgmt::RWimTrustSettingsMgmt()
+// Default constructor
+// -----------------------------------------------------------------------------
+//
+RWimTrustSettingsMgmt::RWimTrustSettingsMgmt() : iPckgBufTrustSettings( NULL ),
+																								 iCertPkcg( NULL )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// RWimTrustSettingsMgmt::ClientSessionL()
+// Return new RWimTrustSettingsMgmt object 
+// -----------------------------------------------------------------------------
+//
+RWimTrustSettingsMgmt* RWimTrustSettingsMgmt::ClientSessionL()
+    {
+    RWimTrustSettingsMgmt* self = new( ELeave ) RWimTrustSettingsMgmt;
+    CleanupStack::PushL( self );
+    User::LeaveIfError( self->Connect() );
+    CleanupStack::Pop( self );
+    _WIMTRACE ( _L( "RWimTrustSettingsMgmt::ClientSessionL()" ) );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// RWimTrustSettingsMgmt::~RWimTrustSettingsMgmt() 
+// Destructor, all allocated memory is released.
+// -----------------------------------------------------------------------------
+//
+RWimTrustSettingsMgmt::~RWimTrustSettingsMgmt()
+    {
+    _WIMTRACE ( _L( "RWimTrustSettingsMgmt::~RWimTrustSettingsMgmt()" ) );
+    DeleteBuffers();
+    }
+
+// -----------------------------------------------------------------------------
+// RWimTrustSettingsMgmt::GetTrustSettings()
+// Return trust settings for given certificate.
+// -----------------------------------------------------------------------------
+//
+void RWimTrustSettingsMgmt::GetTrustSettingsL( 
+    const CWimCertInfo& aCert,
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimTrustSettingsMgmt::GetTrustSettings()" ) );
+
+    TTrustSettings trustSettings;
+    trustSettings.iTrusted = EFalse; // Initialised to remove warning
+
+    if ( iPckgBufTrustSettings || iCertPkcg )
+        {
+        DeleteBuffers();
+        }
+    iPckgBufTrustSettings = new( ELeave ) CWimCertPckgBuf<TTrustSettings>( 
+                                                                trustSettings );
+    TWimCertInfoPckg* certInfo = aCert.ExternalizeL();
+
+    iCertPkcg = new( ELeave ) CWimCertPckgBuf<TWimCertInfoPckg>( *certInfo );
+
+    TIpcArgs args;
+    args.Set( 0, iCertPkcg->PckgBuf() );
+    args.Set( 1, iPckgBufTrustSettings->PckgBuf() );
+    
+    SendReceiveData( EGetTrustSettings, args, aStatus );
+    
+    delete certInfo;
+    }
+
+// -----------------------------------------------------------------------------
+// RWimTrustSettingsMgmt::SetApplicabilityL()
+// Set applicability for certificate.
+// -----------------------------------------------------------------------------
+//
+void RWimTrustSettingsMgmt::SetApplicabilityL(
+    const CWimCertInfo& aCert,
+    const RArray<TUid>& aApplications,
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimTrustSettingsMgmt::SetApplicabilityL()" ) );
+    
+    TInt applicationCount = aApplications.Count();
+
+    // Check that there is no more applications than allocated in array for
+    if ( applicationCount > KMaxApplicationCount )
+        {
+        User::Leave( KErrOverflow );
+        }
+
+    TTrustSettings trustSettings;
+    for ( TInt i = 0; i < applicationCount; i++ )
+        {
+        trustSettings.iUids[i] = aApplications[i].iUid;
+        }
+    trustSettings.iApplicationCount = aApplications.Count();
+
+    if ( iPckgBufTrustSettings || iCertPkcg )
+        {
+        DeleteBuffers();
+        }
+    iPckgBufTrustSettings = new( ELeave ) CWimCertPckgBuf<TTrustSettings>(
+                                                                trustSettings );
+
+    TWimCertInfoPckg* certInfo = aCert.ExternalizeL();
+
+    iCertPkcg = new( ELeave ) CWimCertPckgBuf<TWimCertInfoPckg>( *certInfo );
+
+    TIpcArgs args;
+    args.Set( 0, iCertPkcg->PckgBuf() );
+    args.Set( 1, iPckgBufTrustSettings->PckgBuf() );
+
+    SendReceiveData( ESetApplicability, args, aStatus );
+    
+    delete certInfo;
+    }
+
+// -----------------------------------------------------------------------------
+// RWimTrustSettingsMgmt::SetTrustL()
+// Set trust flag for certificate.
+// -----------------------------------------------------------------------------
+//
+void RWimTrustSettingsMgmt::SetTrustL(
+    const CWimCertInfo& aCert,
+    TBool aTrusted,
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimTrustSettingsMgmt::SetTrustL()" ) );
+
+    TTrustSettings trustSettings;
+    trustSettings.iTrusted = aTrusted;
+
+    if ( iPckgBufTrustSettings || iCertPkcg )
+        {
+        DeleteBuffers();
+        }
+    iPckgBufTrustSettings = new( ELeave ) CWimCertPckgBuf<TTrustSettings>(
+                                                                trustSettings );
+
+    TWimCertInfoPckg* certInfo = aCert.ExternalizeL();
+
+    iCertPkcg = new( ELeave ) CWimCertPckgBuf<TWimCertInfoPckg>( *certInfo );
+
+    TIpcArgs args;
+    args.Set( 0, iCertPkcg->PckgBuf() );
+    args.Set( 1, iPckgBufTrustSettings->PckgBuf() );
+
+    SendReceiveData( ESetTrust, args, aStatus );
+    
+    delete certInfo;
+    }
+
+// -----------------------------------------------------------------------------
+// RWimTrustSettingsMgmt::SetDefaultTrustSettingsL()
+// Set default trust settings for certificate.
+// -----------------------------------------------------------------------------
+//
+void RWimTrustSettingsMgmt::SetDefaultTrustSettingsL(
+    const CWimCertInfo& aCert,
+    TBool aAddApps,
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "RWimTrustSettingsMgmt::SetDefaultTrustSettingsL()" ) );
+
+    if ( iPckgBufTrustSettings || iCertPkcg )
+        {
+        DeleteBuffers();
+        }
+    TWimCertInfoPckg* certInfo = aCert.ExternalizeL();
+
+    iCertPkcg = new( ELeave ) CWimCertPckgBuf<TWimCertInfoPckg>( *certInfo );
+
+    TIpcArgs args;
+    args.Set( 0, iCertPkcg->PckgBuf() );
+    args.Set( 1, aAddApps );
+
+    SendReceiveData( ESetDefaultTrustSettings, args, aStatus );
+
+    delete certInfo;
+    }
+
+// -----------------------------------------------------------------------------
+// RWimTrustSettingsMgmt::RemoveTrustSettingsL()
+// Remove trust settings of given certificate
+// -----------------------------------------------------------------------------
+//
+void RWimTrustSettingsMgmt::RemoveTrustSettingsL(
+    const CWimCertInfo& aCert,
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE( _L( "RWimTrustSettingsMgmt::RemoveTrustSettingsL()" ) );
+
+    if ( iPckgBufTrustSettings || iCertPkcg )
+        {
+        DeleteBuffers();
+        }
+    TWimCertInfoPckg* certInfo = aCert.ExternalizeL();
+
+    iCertPkcg = new( ELeave ) CWimCertPckgBuf<TWimCertInfoPckg>( *certInfo );
+
+    TIpcArgs args;
+    args.Set( 0, iCertPkcg->PckgBuf() );
+
+    SendReceiveData( ERemoveTrustSettings, args, aStatus );
+    
+    delete certInfo;
+    }
+
+// -----------------------------------------------------------------------------
+// RWimTrustSettingsMgmt::CancelDoing
+// Cancel any asynchronous operation ongoing
+// -----------------------------------------------------------------------------
+//
+void RWimTrustSettingsMgmt::CancelDoing()
+    {
+    _WIMTRACE( _L( "RWimTrustSettingsMgmt::CancelDoing()" ) );
+
+    TIpcArgs args;
+
+    SendReceiveData( ECancelTrustSettings, args );
+    }
+
+// -----------------------------------------------------------------------------
+// RWimTrustSettingsMgmt::TrustSettingsPckg
+// Return pointer to trust settings package.
+// -----------------------------------------------------------------------------
+//
+CWimCertPckgBuf<TTrustSettings>* RWimTrustSettingsMgmt::TrustSettingsPckg()
+    {
+    return iPckgBufTrustSettings;
+    }
+
+// -----------------------------------------------------------------------------
+// RWimTrustSettingsMgmt::DeleteBuffers
+// Deletes packet buffers
+// -----------------------------------------------------------------------------
+//
+void RWimTrustSettingsMgmt::DeleteBuffers()
+    {
+    _WIMTRACE( _L( "RWimTrustSettingsMgmt::DeleteBuffers()" ) );
+
+    delete iCertPkcg;
+    delete iPckgBufTrustSettings;
+    iCertPkcg = NULL;
+    iPckgBufTrustSettings = NULL;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/data/101FB674.rss	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Contains information about Wim implementations and their
+*               supported interfaces
+*
+*/
+
+
+//INCLUDES
+
+#include "WimImplementationUID.hrh"
+#include <ecom/registryinfov2.rh>	
+#include "ct/interfaceuid.hrh" 
+
+RESOURCE REGISTRY_INFO theInfo
+    {
+	resource_format_version = RESOURCE_FORMAT_VERSION_2;
+    dll_uid = 0x101FB674;
+    interfaces = 
+        {
+        INTERFACE_INFO
+            {
+            interface_uid = CT_INTERFACE_UID;
+            implementations = 
+                {
+                BINARY_IMPLEMENTATION_INFO
+                    {
+                    implementation_uid = WIM_IMPLEMENTATION_UID;
+                    version_no = 1;
+                    display_name = "Wim Card Token Type";       // Wim card
+                    default_data = {CT_CERT_STORE
+#ifdef __WIM
+                                    ,CT_WRITEABLE_CERT_STORE,            
+                                    CT_AUTHENTICATION_OBJECT,   
+                                    CT_KEY_STORE
+#endif
+									};              
+                    opaque_data  = {CT_MIN_TOKEN_COUNT,   CT_NUM8(0),
+                                    CT_MAX_TOKEN_COUNT,   CT_NUM8(8),
+                                    CT_ACCESS_CONTROLLED, CT_TRUE,
+                                    CT_REMOVABLE,         CT_TRUE,
+                                    CT_SOFTWARE,          CT_FALSE};
+					rom_only = 1;	// This plugin can be loaded only from ROM
+                    }
+
+                };
+            }
+        };
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/group/WimPlugin.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,66 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Contains information for building WimPlugin dll
+*
+*/
+
+#include <platform_paths.hrh>
+TARGET        WimPlugin.dll
+TARGETTYPE    PLUGIN
+
+UID           0x10009D8D 0x101FB674
+
+CAPABILITY    CAP_ECOM_PLUGIN
+VENDORID      VID_DEFAULT
+
+//MACRO __WIM_ENABLE_TRACES
+//#define __WIM_ENABLE_TRACES
+
+// WimPlugin core files
+SOURCE        ../src/WimToken.cpp
+SOURCE        ../src/WimTokenType.cpp
+SOURCE        ../src/WimCertStore.cpp
+SOURCE        ../src/WimCertStoreMapping.cpp
+SOURCE        ../src/WimCertStoreMappings.cpp
+SOURCE        ../src/WimTokenListener.cpp
+SOURCE        ../src/WimAuthenticationObject.cpp
+SOURCE        ../src/WimAuthenticationObjectList.cpp
+SOURCE        ../src/WimKeyStore.cpp
+SOURCE        ../src/WimRSASigner.cpp
+
+
+USERINCLUDE     ../inc
+USERINCLUDE     ../../inc
+USERINCLUDE     ../../WimClient/inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+START RESOURCE ../data/101FB674.rss
+TARGET WimPlugin.rsc
+END
+
+LIBRARY     euser.lib
+LIBRARY     ECom.lib
+LIBRARY     wimclient.lib
+LIBRARY     ctframework.lib
+LIBRARY     wimutil.lib
+LIBRARY     certstore.lib
+LIBRARY     x509.lib
+LIBRARY     wtlscert.lib
+LIBRARY     cryptography.lib
+LIBRARY     hash.lib
+LIBRARY     ctfinder.lib // CCTTokenTypeInfo
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/inc/WimAuthenticationObject.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,503 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  An implementation of single authentication object
+*
+*/
+
+
+#ifndef CWIMAUTHENTICATIONOBJECT_H
+#define CWIMAUTHENTICATIONOBJECT_H
+
+// INCLUDES
+
+#include <mctauthobject.h>
+#include <mctkeystore.h>
+#include <unifiedcertstore.h>
+#include <mctwritablecertstore.h>
+#include <unifiedkeystore.h>
+#include "WimToken.h"
+
+// FORWARD DECLARATIONS
+
+class CCTKeyInfo;
+class CWimPin;
+
+// CLASS DECLARATION
+
+/**
+*  Represents one authentication object (for example a pin code)
+*
+*  @lib   WimPlugin
+*  @since Series 60 2.1
+*/
+
+class CWimAuthenticationObject : public CActive, public MCTAuthenticationObject
+    {
+
+    public: // Two-phased constructor
+
+        /**
+        * @param  aToken   A reference to current token
+        * @param  aWimPin  A reference to current pin manager
+        * @param  aLabel   A reference to label for this object
+        * @param  aType    Type of this object
+        * @param  aHandle  Handle of this object
+        * @param  aObjectStatus  Status of this object
+        * @return An instance of this class
+        */
+        static CWimAuthenticationObject* NewLC( CWimToken& aToken, 
+                                                CWimPin& aWimPin,
+                                                const TDesC& aLabel,
+                                                const TUid aType,
+                                                const TInt aHandle,
+                                                TUint32 aObjectStatus );
+
+    public: // Functions from base class MCTTokenObject
+
+        /**
+        * Returns a reference to this authentication object's 
+        * human-readable label.
+        * @return A reference to object's label.
+        */
+        const TDesC& Label() const;
+
+        /**
+        * Returns a reference to current token.
+        * @return A reference to current token.
+        */
+        MCTToken& Token() const;
+
+        /**
+        * Returns type (UID) of current authentication object. 
+        * Must be unique within a token. WIM_PIN_G_UID or WIM_PIN_NR_UID
+        * @return UID of the current object.
+        */
+        TUid Type() const;      
+
+        /**
+        * Returns a handle of the authentication object.
+        * @return A handle
+        *         Must be unique within a token.
+        */
+        TCTTokenObjectHandle Handle() const;    
+
+    public: // Functions from base class MCTAuthenticationObject
+
+        /**
+        * Returns a list of all the objects which this authentication object 
+        * protects; for example keys and certificates.
+        * The caller of this functions owns all its parameters.
+        * @param  aObjects (OUT) The returned objects will be appended 
+        *         to this array.
+        * @param  aStatus (IN/OUT) Completed with the return code when 
+        *         the operation completes.
+        *         KErrNone, if no errors detected. Note: if protected
+        *         objects are not found, it is also KErrNone
+        *         KErrCancel, if call is canceled
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void ListProtectedObjects( RMPointerArray<MCTTokenObject>& aObjects,
+                                   TRequestStatus& aStatus );
+
+        /**
+        * Cancels an ongoing ListProtectedObjects operation.
+        * @return void
+        */
+        void CancelListProtectedObjects();
+
+        /**
+        * Changes the reference data (e.g. PIN value). The security
+        * dialog component will prompt for the old and new reference data.
+        * @param  aStatus (IN/OUT) Completed with the return code when the 
+        *         operation completes.
+        *         KErrNone, if no errors detected.
+        *         KErrLocked, if this authentication object is blocked
+        *         KErrNotSupported, if authentication object reference data 
+        *         cannot be changed
+        *         KErrBadData, if user entered wrong authentication data
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void ChangeReferenceData( TRequestStatus &aStatus );
+
+        /**
+        * Cancels an ongoing ChangeReferenceData operation. 
+        * @return void
+        */
+        void CancelChangeReferenceData();
+
+        /**
+        * Unblocks the authentication object. The security dialog component will
+        * prompt for the unblocking authentication object.
+        * @param  aStatus (IN/OUT) Completed with the return code when the 
+        *         operation completes. 
+        *         KErrNone, if no errors detected, or authentication object was
+        *         not blocked
+        *         KErrNotSupported, if authentication object cannot be unblocked
+        *         KErrBadData, if user entered wrong authentication data
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void Unblock( TRequestStatus &aStatus );
+    
+        /**
+        * Cancels an ongoing Unblock operation.
+        * @return void
+        */
+        void CancelUnblock();
+
+        /**
+        * Gets the status of the authentication object. 
+        * @return  See TCTAuthenticationStatus for the format of the 
+        *          return value.
+        *          When status cannot be fetched for some reasons, this value 
+        *          is zero.
+        */
+        TUint32 Status() const;
+
+        /**
+        * Disables the authentication object.
+        * @param  aStatus (IN/OUT) Completed with the return code when the 
+        *         operation completes.
+        *         KErrNone, if no errors detected
+        *         KErrLocked, if authentication object is blocked
+        *         KErrNotFound, if authentication object cannot be found
+        *         KErrBadData, if user entered wrong authentication data
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void Disable( TRequestStatus &aStatus );
+
+        /**
+        * Cancels an ongoing Disable operation.
+        * @return void
+        */
+        void CancelDisable();
+
+        /**
+        * Enables the authentication object.
+        * @param  aStatus (IN/OUT) Completed with the return code when 
+        *         the operation completes.
+        *         KErrNone, if no errors detected
+        *         KErrLocked, if authentication object is blocked
+        *         KErrNotFound, if authentication object cannot be found
+        *         KErrBadData, if user entered wrong authentication data
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void Enable( TRequestStatus &aStatus );
+
+        /**
+        * Cancels an ongoing Enable operation.
+        * @return void
+        */
+        void CancelEnable();
+
+        /** 
+        * Opens the authentication object, meaning that the protected objects 
+        * can be accessed without provoking the authentication mechanism for 
+        * the duration of the timeout period. Note. It is not strictly 
+        * necessary to call this function, as the authentication object will 
+        * be opened when any operation that needs it to be opened is called, 
+        * but it is sometimes useful to control the timing of authentication 
+        * dialogs. Note also that this function will do nothing if the 
+        * authentication object is open, or if it authentication object requires
+        * the authentication.
+        * @param aStatus  TRequestStatus from the caller.(IN/OUT)
+        *         KErrNone, if no errors detected,  or authentication object
+        *         is open
+        *         KErrLocked, if authentication object is blocked
+        *         KErrNotFound, if authentication object cannot be found
+        *         KErrNotSupported, if authentication object is not openable 
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void Open( TRequestStatus& aStatus );
+
+        /** 
+        * Closes an authentication object.
+        * @param aStatus  TRequestStatus from the caller.(IN/OUT)
+        *         KErrNone, if no errors detected or authentication object
+        *         is closed.
+        *         KErrLocked, if authentication object is blocked
+        *         KErrNotSupported, if authentication object is not closeable
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void Close( TRequestStatus& aStatus );
+
+        /** 
+        * Returns the amount of time in seconds that the authentication object
+        * will remain open for, or 0 if it is closed. Thís call is valid
+        * only for authentication object, that can be opened (e.g. PIN-G)
+        * @param aStime   Time (in seconds) to be returned. (OUT)
+        * @param aStatus  TRequestStatus from the caller. (IN/OUT)
+        *         KErrNone, if no errors detected, or authentication object
+        *         is closed.
+        *         KErrLocked, if authentication object is blocked
+        *         KErrNotSupported, if authentication object is not allowed to
+        *         be asked for timing information
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void TimeRemaining( TInt& aStime, TRequestStatus& aStatus ); 
+
+        /** 
+        * Sets the time in seconds for this authentication
+        * object. Permitted values include 0, meaning always ask, and -1,
+        * meaning until it's explicitly closed. Particular authentication
+        * objects might restrict the range of values permitted. Thís call 
+        * is valid only for authentication object, that can be opened 
+        * (e.g. PIN-G)
+        * @param aTime    (IN) Timeout (in seconds) to be set.
+        * @param aStatus  TRequestStatus from the caller. (IN/OUT)
+        *         KErrNone, if no errors detected, or authentication object
+        *         is closed.
+        *         KErrLocked, if authentication object is blocked
+        *         KErrArgument, if aTime is not allowed. Permitted values 
+        *         include 0, meaning always ask, and -1, meaning until it's 
+        *         explicitly closed.
+        *         KErrNotSupported, if authentication object is not allowed to
+        *         be set time
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void SetTimeout( TInt aTime, TRequestStatus& aStatus ); 
+
+        /** 
+        * Gets the current timeout value, in seconds. See SetTimeout for
+        * an explanation of the values. Thís call is valid only for 
+        * authentication object, that can be opened (e.g. PIN-G)
+        * @param aTime  Current timeout (in seconds) to be returned. (OUT)
+        * @param aStatus  TRequestStatus from the caller. (IN/OUT)
+        *         KErrNone, if no errors detected, or authentication object
+        *         is closed.
+        *         KErrNotSupported, if authentication object is not allowed to
+        *         be queried about timing information
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void Timeout( TInt& aTime, TRequestStatus& aStatus ); 
+
+        /** 
+        * Returns more token information than framework's MCTToken.
+        * Needed in MCTAuthenticationObjectList interface when creating
+        * authentication objects.
+        * @return  A reference to CWimToken.
+        */
+        CWimToken& TokenWider() const;
+
+        /** 
+        * Returns a reference to pin module.
+        * Needed in MCTAuthenticationObjectList interface when creating
+        * authentication objects.
+        * @return  A reference to CWimPin.
+        */
+        CWimPin& PinModule() const;
+
+    protected:  // From base class MCTTokenObject
+        
+        virtual void DoRelease();
+
+    protected:  // From base class CActive
+
+        void RunL();
+
+        /** 
+        * Leaves in RunL are handled here.
+        * @param  aError  Leaving code
+        * @return An integer that should be KErrNone if leave was handled.
+        */
+        TInt RunError( TInt aError );
+        
+        void DoCancel();
+
+    private: // Constructors
+
+        /**
+        * Default constructor
+        * @param  aToken   A reference to current token
+        * @param  aWimPin  A reference to current pin manager
+        * @param  aType    Type of this object
+        * @param  aHandle  Handle of this object
+        * @param  aObjectStatus  Status of this object
+        */
+        CWimAuthenticationObject( CWimToken& aToken,
+                                  CWimPin& aWimPin,
+                                  const TUid aType,
+                                  const TInt aHandle,
+                                  TUint32 aObjectStatus );
+
+        /**
+        * Second phase constructor
+        * @param  aLabel  A reference to this object's label
+        */
+        void ConstructL( const TDesC& aLabel );
+
+        // Destructor
+        virtual ~CWimAuthenticationObject();
+
+    private: // Own functions
+
+        /** 
+        * Frees unified key store resources.
+        * @return void
+        */
+        void FreeUnifiedKeyStore();
+
+        /** 
+        * Frees unified cert store resources.
+        * @return void
+        */
+        void FreeUnifiedCertStore();
+
+        /** 
+        * Selects keys according to given filter.
+        * @return void
+        */
+        void DoFilterKeys();
+
+        /** 
+        * Validates protected certificates
+        * @return void
+        */
+        void DoListCertEntries();
+
+        /** 
+        * Constructs final protected objects
+        * @return void
+        */
+        void DoMakeObjectsL();
+
+        /** 
+        * General function for creating authentication objects.
+        * @param  aHandle  Handle of authentication object
+        * @return  A pointer to created object
+        */
+        MCTAuthenticationObject* MakeAuthObjectL();
+
+        /** 
+        * Returns true or false indicating if token is removed or not
+        * @return  Boolean true or false
+        */
+        TBool TokenRemoved();
+
+        // Checks if token is removed or is this object active
+        TBool EnteringAllowed( TRequestStatus& aStatus );
+
+    private: // Data
+
+        // State flag for RunL
+
+        enum TPhase
+            {
+            EGetKeyInfos = 0,
+            EFilterKeys,
+            EGetCerts,
+            EInitCertStore,
+            EListCertEntries,
+            EMakeObjects,
+            EIdle,
+            EEnablePinQuery,
+            EDisablePinQuery,
+            EChangePin,
+            EUnblockPin,
+            EVerifyPin
+            };
+
+        // Flag for internal state machine
+        TPhase iPhase;
+
+        // Used for saving caller status 
+        // This class don't own the pointed object
+        TRequestStatus* iOriginalRequestStatus;
+
+        // A reference to current token. Will be asssigned in construction.
+        // This class don't own that referenced object.
+        CWimToken& iToken;
+
+        // Pointer to pin manager, this class don't own pointed object.
+        CWimPin& iWimPin;
+
+        // A pointer to buffer containing human readable label for 
+        // this authentication object. This class owns this buffer.
+        HBufC* iLabel;
+
+        // Contains the type of this authentication object.
+        // For example WIM_PIN_G_UID or WIM_PIN_NR_UID
+        TUid iType;     
+
+        // The handle of authentication object. An integer value
+        // running from 0 to (number of authentication objects) - 1
+        TInt iObjectId;
+
+        // Holds a status of this authentication object. 
+        // See enum TCTAuthenticationStatus in MCTAuthObject.h 
+        // for status values.
+        TUint32 iObjectStatus;
+
+        // Used with unified key store to save keys for a while
+        RMPointerArray<CCTKeyInfo> iKeyInfos;
+
+        // Used with unified key store to filter keys
+        TCTKeyAttributeFilter iKeyFilter;   
+
+        // Temporal array for object pointers
+        // This array is used to append objects in List operation
+        // This class don't own the pointed objects
+        RMPointerArray<MCTTokenObject>* iObjects;
+
+        // A pointer to unified key store
+        // This class owns the pointed object
+        CUnifiedKeyStore* iUnifiedKeyStore;
+
+        // A pointer to unified cert store
+        // This class owns the pointed object
+        CUnifiedCertStore* iUnifiedCertStore;
+
+        // A pointer to certificate filter object
+        // This class owns the pointed object.
+        CCertAttributeFilter* iCertFilter;
+
+        // Temporal array for certificates this authentication 
+        // object protects.
+        RMPointerArray<CCTCertInfo> iCertStoreEntries;
+
+        // A Reference to wider implementation specific token
+        // for internal functions.
+        CWimToken& iTokenWider;
+
+        // For call to Unified KeyStore, which might have file key store
+        RFs iFs;
+
+        // Array of pointers to PIN modules.This class don't own pointed
+        // objects.
+        const CArrayPtrFlat<CWimPin>* iPinNRs; 
+    };
+
+
+#endif      // CWIMAUTHENTICATIONOBJECT_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/inc/WimAuthenticationObjectList.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,204 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Authentication objects can be listed through this interface
+*
+*/
+
+
+#ifndef CWIMAUTHENTICATIONOBJECTLIST_H
+#define CWIMAUTHENTICATIONOBJECTLIST_H
+
+//  INCLUDES
+
+#include <mctauthobject.h>
+
+// FORWARD DECLARATIONS
+
+class CWimToken;
+class CWimPin;
+class CWimAuthenticationObject;
+
+// CLASS DECLARATION
+
+/**
+*  Represents an interface to authentication objects
+*
+*
+*  @lib   WimPlugin
+*  @since Series 60 2.1
+*/
+
+class CWimAuthenticationObjectList : public CActive, 
+                                     public MCTAuthenticationObjectList
+    {
+    public:
+
+        /**
+        * Default constructor
+        * @param  aToken  A reference to current token
+        * @return A pointer to this class
+        */
+        static CWimAuthenticationObjectList* NewL( CWimToken& aToken );
+
+        /**
+        * Destructor
+        */
+        virtual ~CWimAuthenticationObjectList();
+
+    public: // From base class MCTTokenInterface
+        
+        /**
+        * Returns a reference to current token.
+        * @return A reference to current token.
+        */
+        MCTToken& Token();
+
+    public: // From base class MCTAuthenticationObjectList
+
+        /**
+        * Lists authentication objects.
+        * The caller of this function owns all parameters.
+        * Altought asynchronous look and behaviour this call is 
+        * synchronous.
+        * @param  aAuthObjects (OUT) The returned authentication objects 
+        *         will be appended to this array.
+        * @param  aStatus (IN/OUT) This will be completed with the final 
+        *         status code.
+        *         KErrNone, if no errors detected. Note: thought none 
+        *         authentication objects are found, it is also KErrNone
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void List( RMPointerArray<MCTAuthenticationObject>& aAuthObjects,
+                   TRequestStatus& aStatus );
+
+        /**
+        * Cancels an ongoing List operation. Because List is synchronous, 
+        * there is nothing to do here.
+        * @return void
+        */
+        void CancelList();
+
+    protected:  // From base class MCTTokenInterface
+        
+        virtual void DoRelease();
+
+    private: // Constructors
+
+        /**
+        * Default constructor
+        * @param  aToken  (IN) A reference to current token
+        */
+        CWimAuthenticationObjectList( CWimToken& aToken );
+
+        // Second phase constructor
+        void ConstructL();
+    
+    private: //from CActive 
+       
+       /**
+        * Different phases are handled here.
+        * @return void
+        */
+        void RunL();
+        
+        /**
+        * Cancellation function
+        * @return void
+        */
+        void DoCancel();
+
+        /**
+        * The active scheduler calls this function if this active 
+        * object's RunL() function leaves. 
+        * @param aError -Error code which caused this event
+        * @return TInt  -Error code to active scheduler, is always KErrNone.
+        */ 
+        TInt RunError( TInt aError );    
+
+    private:
+    
+        /**
+        * Leavable authentication objects list function.
+        * @return void
+        */
+        void CreateListL( TRequestStatus& aStatus );
+
+        /**
+        * Leavable authentication objects creation function.
+        * @param  aToken (IN) Current token
+        * @param  aPinModule (IN) Pin manager module
+        * @param  aLabel (IN) A label for authentication object.
+        * @param  aType (IN) Type of this authenticaion object.
+        * @param  aHandle (IN) A handle of this authentication object.
+        * @param  aStatus (IN) The status of this authentication object.
+        * @return Pointer to CWimAuthenticationObject
+        */
+        CWimAuthenticationObject* MakeAuthObjectL( CWimToken& aToken,
+                                                   CWimPin& aPinModule,
+                                                   const TDesC& aLabel,
+                                                   TUid aType,
+                                                   TUint32 aHandle,
+                                                   TUint32 aStatus );
+        /**
+        * Leavable authentication objects list function.
+        * The caller of this function owns all parameters.
+        * @param  aAuthObjects (OUT) The returned authentication objects 
+        *         will be appended to this array.
+        * @return void
+        */
+        void DoListL( RMPointerArray<MCTAuthenticationObject>& aAuthObjects );
+
+        /**
+        * Returns true or false indicating if token is removed or not
+        * @return Boolean true or false
+        */
+        TBool TokenRemoved();
+        
+    
+    private:
+    
+    enum TAuthObjPhase
+            {
+            ECreateList,
+            ECreateListDone,
+            EDoList
+            };   
+            
+
+    private: // Data
+
+        // A reference to current token.
+        CWimToken& iToken;
+
+        // Array of pointers to PIN modules. Not owned.
+        const CArrayPtrFlat<CWimPin>* iPinNRs; 
+        
+        // An internal array of listed authentication objects.
+        RPointerArray<CWimAuthenticationObject> iAuthObjects;
+        
+        //Used to handle Authobj interface making
+        TAuthObjPhase                   iPhase;
+        //Client status is stored here 
+        TRequestStatus*                 iClientStatus;
+        
+        //Not Owned
+        RMPointerArray<MCTAuthenticationObject>* iClientAuthObjects;
+    };
+
+
+#endif      // CWIMAUTHENTICATIONOBJECTLIST_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/inc/WimCertStore.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,675 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  An implementation of certificate store interface
+*
+*/
+
+
+#ifndef CWIMCERTSTORE_H
+#define CWIMCERTSTORE_H
+
+//  INCLUDES
+
+#include "WimCertStoreMappings.h"
+#include <mctkeystore.h>
+#include <mctwritablecertstore.h>
+#include <unifiedkeystore.h>
+
+// FORWARD DECLARATION
+
+class CWimCertConverter;
+class CWimCertInfo;
+class CWimTrustSettingsAPI;
+class CWimToken;
+
+
+// CLASS DECLARATION
+
+/**
+*  Represents read only and writable certificate store.
+*
+*  @lib   WimPlugin
+*  @since Series60 2.1
+*/
+
+class CWimCertStore : public CActive, public MCTWritableCertStore   
+    {
+    public: 
+
+        /**
+        * Two-phased constructor
+        * @param  aToken (IN) A refernece to curren token
+        * @return An instance of this class
+        */
+        static CWimCertStore* NewL( CWimToken& aToken );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CWimCertStore();
+
+    public: // A function from base class MCTTokenInterface
+        
+        /**
+        * Returns a reference to current token.
+        * @return A reference to current token.
+        */
+        MCTToken& Token();
+
+    public: // Functions from base class MCertStore
+
+        /**
+        * Lists certificates from the store. 
+        * The caller of this function owns all its parameters.
+        * @param  aCerts (OUT) An array into which the returned certificates 
+        *         are placed.
+        * @param  aFilter (IN) A filter to select which certificates should 
+        *         be included.
+        * @param  aStatus (IN/OUT) A Request status that will be completed when
+        *         the operation completes.
+        *         KErrNone, if no errors detected. Note: if certificates not
+        *         found, it is also KErrNone
+        *         KErrCancel, if call is canceled
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void List( RMPointerArray<CCTCertInfo>& aCerts, 
+                   const CCertAttributeFilter& aFilter,
+                   TRequestStatus& aStatus );
+    
+        /**
+        * Cancels ongoing list operation.
+        * @return void
+        */
+        void CancelList();
+
+        /**
+        * Gets a certificate info according to given handle. 
+        * The caller of this function owns all its parameters.
+        * @param  aCertInfo (OUT) The returned certificate info.
+        * @param  aHandle   (IN) The handle of the certificate info to return.
+        * @param  aStatus   (IN/OUT) A request status that is completed when 
+        *         the operation has finished.
+        *         KErrNone, if no errors detected. 
+        *         KErrNotFound, if certificate with given handle not found
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void GetCert( CCTCertInfo*& aCertInfo, 
+                      const TCTTokenObjectHandle& aHandle, 
+                      TRequestStatus& aStatus );
+
+        /**
+        * Cancels an ongoing GetCert operation. No influence.
+        * @return void
+        */
+        void CancelGetCert();
+
+        /**
+        * Queries the applications that given certificate supports.
+        * The caller of this function owns all its parameters.
+        * @param  aCertInfo (IN) The certificate to return applications for.
+        * @param  aApplications (OUT) An array where applications are added in.
+        * @param  aStatus       A request status that is completed when the 
+        *         operation has finished.
+        *         KErrNone, if no errors detected
+        *         KErrNotFound, if aCertInfo not found
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void Applications( const CCTCertInfo& aCertInfo, 
+                           RArray<TUid>& aApplications,
+                           TRequestStatus& aStatus );
+
+        /**
+        * Cancels an ongoing Applications operation. No influence.
+        * @return void
+        */
+        void CancelApplications();
+
+        /**
+        * Indicates if a particular certificate is applicable to a particular 
+        * application. 
+        * The caller of this function owns all its parameters.
+        * @param  aCertInfo (IN) The certificate in question.
+        * @param  aApplication (IN) The application.
+        * @param  aIsApplicable (OUT) Set to ETrue or EFalse by the function 
+        *         to return the result.
+        * @param  aStatus (IN/OUT) A request status that is completed when the 
+        *         operation has finished.
+        *         KErrNone, if no errors detected.
+        *         KErrNotFound, if aCertInfo not found
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void IsApplicable( const CCTCertInfo& aCertInfo, 
+                           TUid aApplication, 
+                           TBool& aIsApplicable, 
+                           TRequestStatus& aStatus );
+
+        /**
+        * Cancels an IsApplicable operation. No influence.
+        * @return void
+        */
+        void CancelIsApplicable();
+
+        /**
+        * Returns true value if given certificate is trusted. 
+        * The caller of this function owns all its parameters.
+        * @param  aCertInfo (IN) The certificate we're interested in.
+        * @param  aTrusted (OUT) Used to return the trust status.
+        * @param  aStatus (IN/OUT) A request status that is completed when the 
+        *         operation has finished.
+        *         KErrNone, if no errors detected.
+        *         KErrNotFound, if aCertInfo not found
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void Trusted( const CCTCertInfo& aCertInfo, 
+                      TBool& aTrusted, 
+                      TRequestStatus& aStatus );
+
+        /**
+        * Cancels an ongoing Trusted operation. No influence.
+        * @return void
+        */
+        void CancelTrusted();
+
+        /**
+        * Retrieves the actual certificate.
+        * The caller of this function owns all its parameters.
+        * @param  aCertInfo (IN) The certificate to retrieve.
+        * @param  aEncodedCert (OUT) A buffer to put the certificate in. 
+        *         It must be big enough. The size is stored in aCertInfo.
+        * @param  aStatus (IN/OUT) A request status that is completed when the 
+        *         operation has finished.
+        *         KErrNone, if no errors detected.
+        *         KErrNotFound, if aCertInfo not found
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void Retrieve( const CCTCertInfo& aCertInfo, 
+                       TDes8& aEncodedCert, 
+                       TRequestStatus& aStatus );
+
+        /**
+        * Cancels an ongoing Retrieve operation.
+        * @return void
+        */
+        void CancelRetrieve();
+
+    public: // From base class MCTWritableCertStore
+
+        /** 
+        * CURRENTLY NOT SUPPORTED. Adds a certificate to the cert store.
+        * The caller of this function owns all its parameters.
+        * @param  aLabel (IN) The label of the certificate to add
+        * @param  aFormat (IN) the format of the certificate
+        * @param  aCertificateOwnerType (IN) The owner type
+        * @param  aSubjectKeyId (IN) The Subject key ID
+        * @param  aIssuerKeyId (IN) The issuer key ID
+        * @param  aCert (IN) The certificate to add
+        * @param  aStatus (IN/OUT) This is completed with the return result 
+        *         when the add has completed 
+        *         KErrNone, if no errors detected.
+        *         KErrArgument, 
+        *           - if label length is zero, or
+        *           - certificate owner type is unknown, or
+        *           - certificate is X509 or WTLS and computed subject key id 
+        *             is not as given subject key id
+        *           - X509 and Url, and subject key is not given
+        *         KErrNotSupported, if certificate format not supported.
+        *         (Supported formats are: X509, WTLS and URL)
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * return  void
+        */
+        void Add( const TDesC& aLabel, 
+                  TCertificateFormat aFormat,
+                  TCertificateOwnerType aCertificateOwnerType, 
+                  const TKeyIdentifier* aSubjectKeyId,
+                  const TKeyIdentifier* aIssuerKeyId,
+                  const TDesC8& aCert, 
+                  TRequestStatus& aStatus );
+
+        /**
+        * Cancels an ongoing add operation.
+        * @return void
+        */
+        void CancelAdd();
+
+        /** 
+        * CURRENTLY NOT SUPPORTED. Removes a certificate from Wim cert store.
+        * The caller of this function owns all its parameters.
+        * @param  aCertInfo (IN) The certificate to remove.
+        * @param  aStatus (IN/OUT) This is completed with the return result 
+        *         when the remove has completed.
+        *         KErrNone, if no errors detected.
+        *         KErrNotFound, if aCertInfo not found
+        *         KErrNotSupported, if certificate format not supported.
+        *         (Supported formats are: X509, WTLS and URL)
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        */
+        void Remove( const CCTCertInfo& aCertInfo, 
+                     TRequestStatus& aStatus );
+
+        /** 
+        * Cancels an ongoing remove operation.
+        * @return  void
+        */
+        void CancelRemove();
+
+        /** 
+        * Replaces the current applicability settings with the settings
+        * in the supplied array. 
+        * The caller of this function owns all its parameters except aApplications 
+        * which ownership is transferred to this class
+        * @param  aCertInfo (IN) The certificate whose applicability should 
+        *         be updated.
+        * @param  aApplications (IN) The new applications. 
+        * @param  aStatus (IN/OUT) This is completed with the return result 
+        *         when the operation has completed.
+        *         KErrNone, if no errors detected.
+        *         KErrNotFound, if aCertInfo not found
+        *         KErrArgument, if some of the given applications is not 
+        *         found from system file (certclients.dat)
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        */
+        void SetApplicability( const CCTCertInfo& aCertInfo,
+#ifdef __SECURITY_PLATSEC_ARCH__        
+                               const RArray<TUid>& aApplications, 
+#else
+                               RArray<TUid>* aApplications,
+#endif                               
+                               TRequestStatus &aStatus );
+
+        /** 
+        * Cancels an ongoing operation. No influence.
+        * @return void
+        */
+        void CancelSetApplicability();
+    
+        /** 
+        * Changes the trust settings. CA certificate is 
+        * trusted if the user is willing to use it for authenticating servers. 
+        * It has no meaning with other types of certificates. 
+        * The caller of this function owns all its parameters.
+        * @param  aCertInfo (IN) The certificate to update.
+        * @param  aTrusted (IN) Whether or not it is trusted
+        * @param  aStatus (IN/OUT) This is completed with the return result 
+        *         when the operation has completed.
+        *         KErrNone, if no errors detected.
+        *         KErrNotFound, if aCertInfo not found
+        *         KErrArgument, if given aTrusted parameter is not true or false.
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void SetTrust( const CCTCertInfo& aCertInfo, 
+                       TBool aTrusted, 
+                       TRequestStatus& aStatus );
+
+        /** 
+        * Cancels an ongoing operation. No influence.
+        * @return void
+        */
+        void CancelSetTrust();
+
+    private: // New functions
+
+        /** 
+        * Makes some initializations.
+        * @return void
+        */
+        void Initialize();
+
+        /** 
+        * Sets trusted and appliaction info on certificate mapping.
+        * @param  aTrusted   (IN) True or false value
+        * @param  aCertificateApps  (IN) An array of application uids for 
+        *         certificate
+        * @return void
+        */
+        void SetTrustSettingsOnMappingL( TBool aTrusted,
+                                         RArray<TUid>* aCertificateApps );
+
+    protected:  // From base class MCTTokenInterface
+        
+        virtual void DoRelease();
+
+    protected:  // From base class CActive
+
+        void RunL();
+        
+        TInt RunError(TInt aError);
+        
+        void DoCancel();
+
+    private: // New functions
+
+        /** 
+        * Creates iCerts array and loads certificate infos into it.
+        * @return void
+        */
+        void LoadMappingsL();
+
+        // Computes and checks subject key in add operation
+        void ComputeAndCheckSubjectKeyIdL();
+
+        /** 
+        * Checks if given application is known by system
+        * @param  aCertInfo   (IN) The certificate that the update concern
+        * @param  aApplications  (IN) An array of application uids for the
+        *         certificate
+        * @param  aStatus (IN/OUT) This is completed with the return result 
+        *         when the operation has completed.
+        * @return void
+        */
+
+        void CheckApplicabilityL(
+#ifdef __SECURITY_PLATSEC_ARCH__        
+                                  const RArray<TUid>& aTrusters );
+#else
+                                  RArray<TUid>* aTrusters );
+#endif         
+
+        /** 
+        * Starts applicability updates and completes the message
+        * @return void
+        */
+
+        void DoSetApplicability();
+
+        /** 
+        * Contains actual functions to update applicability
+        * @return void
+        */
+
+        void DoSetApplicabilityL();
+
+        /** 
+        * Sets trust information for a certificate
+        * @param  aCertInfo   (IN) The certificate that the update concern
+        * @param  aTrusted  (IN) Trusted info for the certificate, values
+        *         are true (trusted) or false (not trusted)
+        * @param  aStatus (IN/OUT) This is completed with the return result 
+        *         when the operation has completed.
+        * @return void
+        */
+        void DoSetTrustL();
+
+        // General function to free unified key storage objects
+        void FreeUnifiedKeyStore();
+        
+        // RunL phase where LoadMappingsL is called
+        void DoInitializeLoadMappingsL();
+
+        // RunL phase where trust settings are loaded
+        void DoInitializeLoadTrustSettingsStartL();
+
+        // RunL phase where trust settings call are waited
+        void DoInitializeLoadTrustSettingsWaitL();
+
+        // RunL phase where key infos are fetched
+        void DoGetKeyInfos();
+
+        // RunL phase where list operation is actually done
+        void DoListGoL();
+
+        // RunL phase where list operation is actually started
+        void DoInitializeGetCertListL();
+
+        // RunL phase where list operation is started
+        void DoList();
+
+        // RunL phase where private key is checked
+        void DoCheckCorrespondingPrivateKey();
+
+        // RunL phase where delete from wim is checked
+        void DoCheckDeleteFromWim();
+
+        // Returns the status of token
+        TBool TokenRemoved();
+
+        /** 
+        * Checks if token is removed or is this object active
+        * @param  aStatus (IN/OUT) This is completed with the return result 
+        *         when the operation has completed.
+        * @return TBool
+        */
+        TBool EnteringAllowed( TRequestStatus& aStatus );
+
+        // RunL phase for getting a certificate info
+        void DoGetCert();
+
+        // RunL phase for getting a certificate applications
+        void DoApplications();
+
+        // RunL phase for checking application applicability
+        void DoIsApplicable();
+
+        // RunL phase for checking certificate's trust info
+        void DoTrusted();
+
+        // RunL phase for retrieving certificate binary data
+        void DoRetrieve();
+
+        // RunL phase for adding a certificate
+        void DoAdd();
+
+        // RunL phase for certificate removal
+        void DoRemove();
+
+        // RunL phase for certificate trusted info
+        void DoSetTrust();
+
+        /** 
+        * Cleans trusters array if leave occurs
+        * @param  aTrusters (IN) An array of applications (trusters)
+        * @return void
+        */
+        static void CleanTrustersArray( TAny* aTrusters );
+
+    private: // Constructors
+        
+        /** 
+        * The default constructor
+        * @param  aToken   (IN) A reference of current token
+        * @return None
+        */
+        CWimCertStore( CWimToken& aToken );
+
+        // Second phase constructor
+        void ConstructL();
+
+    private: // Data
+
+        // Reference to current token of this cert store interface. 
+
+        CWimToken& iToken;
+
+        // State flag for RunL
+
+        enum TPhase
+            {
+            EInitializeGetCertList = 0,
+            EInitializeLoadMappings,
+            EInitializeLoadTrustSettingsStart,
+            EInitializeLoadTrustSettingsWait,
+            EList,
+            EListGo,
+            EGetKeyInfos,
+            EGetCert,
+            EApplications,
+            EIsApplicable,
+            ETrusted,
+            ERetrieve,
+            ERetrieveFromWim,
+            ERetrieveWait,
+            EGetCorrespondingPrivateKey,
+            ECheckCorrespondingPrivateKey,
+            EAdd,
+            EAddToWim,
+            ECheckAddToWim,
+            ERemove,
+            EWaitRemoveTrustSettings,
+            EDeleteFromWim,
+            ECheckDeleteFromWim,
+            ESetApplicability,
+            EWaitSetApplicability,
+            ESetTrust,
+            EWaitSetTrust,
+            ECompleteMessage,
+            EIdle
+            };
+
+        // Flag for internal state machine
+        TPhase iPhase;
+
+        // Save place for original state
+        TPhase iPhaseOriginal;
+
+        // Used for saving caller status 
+        // This class don't own the pointed object
+        TRequestStatus* iOriginalRequestStatus;
+
+        // The list of certificates (mapping objects) contained in the 
+        // trust store.
+        // This class owns the pointed objects and is responsible
+        // to release them in the end of this class life cycle.
+        CWimCertStoreMappings* iCerts;
+
+        // Temporal array for certificate infos. 
+        // This array is used to fetch certificate infos from WimClient.
+        // At first this class owns the pointed objects. Ownership is 
+        // transferred to iCerts. See iCerts above.
+        RPointerArray<CWimCertInfo> iCertInfos;
+
+        // Temporal array for certificate info pointers
+        // This array is used to append certificate infos in List operation
+        // This class don't own the pointed objects
+        RPointerArray<CCTCertInfo>* iCertsList;
+
+        // Array for adding certificate applications to trust store
+        // This class don't own the pointed objects
+        RArray<TUid>* iCertificateApps;
+
+        // Index for going through all certificates
+        TInt iCertIndex;
+
+        // Used for fetching and updating trust settings
+        TBool iTrusted;
+    
+        // Used in List operation in order to use in RunL
+        // This class don't own the pointed object.
+        const CCertAttributeFilter* iFilter;
+
+        // Used with unified key store to filter keys
+        TCTKeyAttributeFilter iKeyFilter;   
+
+        // Used with unified key store to save keys for a while
+        RMPointerArray<CCTKeyInfo> iKeyInfos;
+
+        // A pointer to unified key store
+        // This class owns also the pointed object
+        CUnifiedKeyStore* iUnifiedKeyStore;
+
+        // Used in Retrieve operation in order to use in RunL
+        // Points to whole certificate data string
+        // This class don't own the pointed data
+        TDes8* iEncodedCert;
+
+        // The pointed object acts as a converter between
+        // CWimCertStore interface and WimClient
+        // This class owns the pointed object
+        CWimCertConverter* iCWimCertConverter;
+
+        // The pointed object acts as a database store for trust settings
+        // This class owns the pointed object
+        CWimTrustSettingsAPI* iCWimTrustSettingsStore;
+
+        // A pointer to label of certificate to be added
+        // This class don't own the pointed object
+        const TDesC* iLabel;
+
+        // A pointer to format of certificate to be added
+        TCertificateFormat iFormat;
+
+        // Owner type  of certificate to be added
+        TCertificateOwnerType iCertificateOwnerType;
+
+        // A pointer to subject key id of certificate to be added
+        // This class don't own the pointed object
+        const TKeyIdentifier* iSubjectKeyId;
+
+        // A pointer to issuer key id of certificate to be added
+        // This class don't own the pointed object
+        const TKeyIdentifier* iIssuerKeyId;
+
+        // A pointer to binary data of certificate to be added
+        // This class don't own the pointed object
+        const TDesC8* iCert;
+
+        // A hash of subject key id of certificate to be added
+        TKeyIdentifier iComputedSubjectKeyId;   
+
+        // For the call of unified keystore.
+        RFs iFs;
+
+        // A pointer to user's certificate data area. Used during 
+        // set active object. Not owned.
+        CCTCertInfo** iCertInfo;
+
+        // A pointer to user given certificate handle. Not owned.
+        const TCTTokenObjectHandle* iHandle;
+
+        // A pointer to user's certificate data area. Used during 
+        // set active object. Not owned.
+        const CCTCertInfo* iCertInfoReadOnly;
+
+        // A pointer array application Uids
+        RArray<TUid>* iApplications;
+
+        // A place holder to application Uid
+        TUid iApplication;
+
+        // A pointer to boolean variable in user area. Not owned.
+        TBool* iIsApplicable;
+
+        // A pointer to boolean variable in user area. Not owned.
+        TBool* iTrustedCert;
+
+        // Place holder for certificate trusted info update
+        TBool iTrustedValue;
+
+        // Save old trust value for back up reason
+        TBool iOldTrusted;
+
+        // Pointer array for old applications. Ownership moved to mapping
+        // if setting new applications fails.
+        RArray<TUid>* iOldTrusters;
+
+};
+
+#endif      // CWIMCERTSTORE_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/inc/WimCertStoreMapping.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,135 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Represents one certificate info with trust settings.
+*                This entity is called here as a "mapping".
+*
+*/
+
+
+#ifndef WIMCERTSTOREMAPPING_H
+#define WIMCERTSTOREMAPPING_H
+
+//  INCLUDES
+
+#include <e32base.h>
+#include <s32std.h>
+#include <ct.h>
+#include <mctcertstore.h>
+
+// CLASS DECLARATION
+
+/**
+* This class is used to associate an entry with the mappings class
+*
+*
+*  @lib   WimPlugin
+*  @since Series60 2.1
+*/
+class CWimCertStoreMapping : public CBase
+    {
+    public: 
+
+        /**
+        * Constructors
+        */
+        static CWimCertStoreMapping* NewL();
+
+        static CWimCertStoreMapping* NewLC();
+
+        /**
+        * Destructor
+        */
+        ~CWimCertStoreMapping();
+
+    public: 
+
+        /**
+        * Sets the mapping class certificate part (iEntry). 
+        * If there is already an entry, it is deleted.
+        * @param  aCertInfo (IN) Certificate info class.
+        * @return void
+        */
+        void SetEntryL( CCTCertInfo* aCertInfo );
+
+        /**
+        * Returns a pointer to the mapping class certificate object (iEntry).
+        * @return  A pointer to object of certificate info class.
+        */
+        CCTCertInfo* Entry() const;
+
+        /**
+        * Returns an array of applications the mapping supports.
+        * @return  A array of of references to integers (application id's)
+        */
+        const RArray<TUid>& CertificateApps() const;
+
+        /**
+        * Sets an array of applications to the mapping.
+        * @param  aCertificateApps (IN) TUids of applications
+        * @return void
+        */
+        void SetCertificateAppsL( RArray<TUid>* aCertificateApps );
+
+        /**
+        * Returns a boolean value indicating whether or not
+        * the certificate part of mapping supports given application.
+        * @param   aApplication (IN) A TUid of application
+        * @return  A boolean value true or false
+        */
+        TBool IsApplicable( const TUid& aApplication ) const;
+
+        /**
+        * Returns a boolean value indicating whether or not
+        * the certificte part of mapping is trusted.
+        * @return  A boolean value true or false
+        */
+        TBool Trusted() const;
+
+        /**
+        * Sets a boolean value to mapping trusted settings
+        * indicating whether or not the certificate part of mapping is trusted.
+        * @param   aTrusted (IN) A boolean value
+        * @return ETrue, when trusted, EFalse when not trusted
+        */
+        void SetTrusted( TBool aTrusted );
+
+    private:
+
+        /**
+        * Second phase constructor
+        */
+        void ConstructL();
+
+        /**
+        * Default constructor
+        */
+        CWimCertStoreMapping();
+
+    private:
+
+        // A pointer to the certificate part of one mapping entry. 
+        // This class don't own the pointed object.
+        CCTCertInfo* iEntry;
+
+        // An array of applications the certificate part of mapping supports.
+        // This class owns the pointer objects.
+        RArray<TUid>* iCertificateApps;
+
+        // Is the certificate part of this mapping trusted or not
+        TBool iTrusted;
+    };
+
+#endif // WIMCERTSTOREMAPPING_H
+
+//end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/inc/WimCertStoreMappings.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,138 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implements a class managing mapping entries which contain
+*                information of certificates with trusted settings
+*
+*/
+
+
+#ifndef WIMCERTSTOREMAPPINGS_H
+#define WIMCERTSTOREMAPPINGS_H
+
+// INCLUDES 
+
+#include "WimCertStoreMapping.h"
+#include <s32file.h>
+
+// CLASS DECLARATION
+
+/**
+* This class manages the entries in an internal array
+* where the data of the certificate is stored.
+*
+*
+*  @lib   WimPlugin
+*  @since Series60 2.1
+*/
+class CWimCertStoreMappings : public CBase
+    {
+    public: 
+
+        /**
+        * Constructor
+        */
+        static CWimCertStoreMappings* NewL();
+
+        /**
+        * Destructor
+        */
+        ~CWimCertStoreMappings();
+
+    public: 
+
+        /**
+        * Returns the count of mapping entries in the array
+        * @return A integer value
+        */
+        TInt Count() const;
+
+        /**
+        * Adds a new mapping entry in the array
+        * @param  aEntry (IN) One mapping entry
+        * @return void
+        */
+        void AddL( const CWimCertStoreMapping* aEntry );
+
+        /**
+        * Removes an mapping entry from the array
+        * @param   aEntry The entry to delete
+        * @return  KErrNotFound if aEntry is not found in the array 
+        *          KErrNone is the entry was successfully deleted.
+        */
+        //TInt Remove( const CCTCertInfo& aEntry );
+
+        /**
+        * Updates a new entry in the array
+        * @param  aEntry (IN) One certificate info
+        * @return void
+        */
+        void UpdateL( const CCTCertInfo& aEntry );
+
+        /**
+        * Returns the index in the array. The function goes through
+        * the array entries and returns the index of the first entry whose 
+        * label matches the label of aEntry.
+        * @param   aEntry The certificate info in the mapping entry
+        *          we want the index of.
+        * @return  The index of mapping entry in the array.
+        */
+        TInt Index( const CCTCertInfo& aEntry );
+
+        /**
+        * Returns one mapping entry from the array. 
+        * @param   aIndex The index of the mapping
+        * @return  The mapping from the array.
+        */
+        CWimCertStoreMapping* Mapping( TInt aIndex );
+    
+        /**
+        * Returns certificate info from the array in the given index. 
+        * @param   aIndex The index of the certificate info
+        * @return  The certificate from the array.
+        */
+        const CCTCertInfo& Entry( TInt aIndex );
+
+        /**
+        * Returns certificate info from the array using given handle. 
+        * @param   aHandle The handle of the mapping
+        * @return  The certificate from the array.
+        */
+        const CCTCertInfo& EntryByHandleL( TInt aHandle ) const;
+
+        /**
+        * Returns next available handle that can be used for 
+        * adding a new mapping in to the array
+        * @return  A integer value of new handle.
+        */
+        //TInt NextHandle() const;
+
+    private:
+
+        /**
+        *   Second phase constructor
+        */
+        void ConstructL();
+
+        /**
+        *   Default constructor
+        */
+        CWimCertStoreMappings();
+
+        // An internal array of mapping entries
+        RPointerArray<CWimCertStoreMapping> iMappings;
+    };
+
+#endif // WIMCERTSTOREMAPPINGS_H
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/inc/WimImplementationUID.hrh	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This file contains UID constants for Wim implementations
+*
+*/
+
+
+#ifndef WIMIMPLEMENTATIONUID_HRH
+#define WIMIMPLEMENTATIONUID_HRH
+
+#define WIM_IMPLEMENTATION_UID  0x101F79D9		// Wim card
+#define WIM_PIN_G_UID			0x101F79DA		// PIN-G
+#define WIM_PIN_NR_UID			0x101F79DB		// PIN-NR
+
+// Some defines of useful values for attributes to simplify
+// writing resource files
+
+// True
+#define CT_TRUE 1,0,0,0
+// False
+#define CT_FALSE 0,0,0,0
+// A number between 0 and 255
+#define CT_NUM8(x) x,0,0,0
+
+// Attribute UIDs.
+#define CT_SOFTWARE 0x7b, 0x52, 0x1f, 0x10
+#define CT_REMOVABLE 0x7c, 0x52, 0x1f, 0x10
+#define CT_ACCESS_CONTROLLED 0x7d, 0x52, 0x1f, 0x10
+#define CT_MAX_TOKEN_COUNT 0x7e, 0x52, 0x1f, 0x10
+#define CT_MIN_TOKEN_COUNT 0x7f, 0x52, 0x1f, 0x10
+
+// Interface UIDs
+#define CT_CERT_STORE 0x1B, 0x50, 0x1F, 0x10
+#define CT_WRITEABLE_CERT_STORE 0xFB, 0x20, 0x20, 0x10
+//#define CT_KEY_STORE 0x1d, 0x50, 0x1f, 0x10 depricated
+#define CT_KEY_STORE 0x34, 0x73, 0x1f, 0x10
+#define CT_AUTHENTICATION_OBJECT 0xAE, 0x51, 0x1F, 0x10
+
+#endif // WIMIMPLEMENTATIONUID_HRH
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/inc/WimKeyStore.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,383 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  An implementation of single key store interface
+*
+*/
+
+
+#ifndef CWIMKEYSTORE_H
+#define CWIMKEYSTORE_H
+
+//  INCLUDES
+
+#include <mctkeystore.h>
+#include <e32base.h>
+
+// FORWARD DECLARATION
+
+class CWimKeyDetails;
+class MCTAuthenticationObjectList;
+class CWimToken;
+class CWimPin;
+class CWimRSASigner;
+
+
+// CLASS DECLARATION
+
+/**
+*  Represents read only key store.
+*
+*  @lib   WimPlugin
+*  @since Series60 2.1
+*/
+
+class CWimKeyStore : public CActive, public MCTKeyStore 
+    {
+    public: // Constructor and destructor
+
+        /**
+        * Constructor
+        * @param  aToken   (IN) A reference to current token
+        * @return An instance of this class
+        */
+        static CWimKeyStore* NewL( CWimToken& aToken );
+    public: // Function from base class MCTTokenInterface
+        
+        /**
+        * Returns a reference to current token
+        * @return A Reference to current token
+        */
+        MCTToken& Token();
+
+    public: // Functions from base class MKeyStore
+        
+        /**
+        * Lists all the keys in the store that match the filter
+        * The caller of this function owns all given parameters
+        * @param  aKeys    (OUT) An array to which the returned keys 
+        *         are appended.
+        * @param  aFilter  (IN) A filter controlling which keys are returned
+        * @param  aStatus  (IN/OUT) This will be completed with the final 
+        *         status code. Caller should set it to value TRequestPending
+        *         KErrNone, if no errors detected. Note: if no keys are found,
+        *         it is also KErrNone
+        *         KErrArgument, if aKeys array is NULL
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void List( RMPointerArray<CCTKeyInfo>& aKeys, 
+                   const TCTKeyAttributeFilter& aFilter, 
+                   TRequestStatus& aStatus );
+
+        /**
+        * Cancels an ongoing List operation
+        * @return void
+        */
+        void CancelList();
+
+        /**
+        * Retrieves a reference to pointer of key depending on given 
+        * handle (aHandle). The caller of this function owns all given 
+        * parameters.
+        * @param  aHandle   The handle of the required key.
+        * @param  aInfo     The returned key info.
+        * @param  aStatus   Async request notification.
+        *         KErrNone, if no errors detected
+        *         KErrArgument, if aHandle is not current token's handle
+        *         KErrNotFound, if aInfo not found
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void GetKeyInfo( TCTTokenObjectHandle aHandle, 
+                         CCTKeyInfo*& aInfo,
+                         TRequestStatus& aStatus );
+
+        /**
+        * Cancels an ongoing GetKeyInfo operation
+        * @return void
+        */
+        void CancelGetKeyInfo();
+
+        /** 
+        * Open an RSA key for signing
+        * @param aHandle The handle of the key to be opened
+        * This must be the handle of a RSA key on this store that is
+        * usable for signing by this process or the operation will fail.
+        * @param aSigner The returned signer object
+        * @param aStatus Asynchronous request notification.
+        * @return void
+        */
+        void Open( const TCTTokenObjectHandle& aHandle, 
+                   MRSASigner*& aSigner,
+                   TRequestStatus& aStatus );
+        
+        /** 
+        * Open a DSA key for signing
+        * @param aHandle -The handle of the key to be opened
+        * This must be the handle of a DSA key on this store that is
+        * usable by this process for signing or the operation will fail.
+        * @param aSigner -The returned signer object
+        * @param aStatus -Asynchronous request notification.
+        * @return void
+        */
+        void Open( const TCTTokenObjectHandle& aHandle, 
+                   MDSASigner*& aSigner, 
+                   TRequestStatus& aStatus );
+
+        /** 
+        * Open a RSA key for private decryption
+        * @param aHandle -The handle of the key to be opened
+        * This must be the handle of a RSA key on this store that is
+        * usable by this process for decryption or the operation will fail.
+        * @param aDecryptor -The returned decryptor object
+        * @param aStatus -Asynchronous request notification.
+        * @return void
+        */
+        void Open( const TCTTokenObjectHandle& aHandle, 
+                   MCTDecryptor*& aDecryptor,
+                   TRequestStatus& aStatus );
+
+        /** 
+        * Open a DH key for key agreement
+        * @param aHandle -The handle of the key to be opened
+        * This must be the handle of a DH key on this store that is
+        * usable by this process for decryption or the operation will fail.
+        * @param aDH    -The returned agreement object
+        * @param aStatus -Asynchronous request notification.
+        * @return void
+        */
+        void Open( const TCTTokenObjectHandle& aHandle, 
+                   MCTDH*& aDH, 
+                   TRequestStatus& aStatus );
+
+        /** 
+        * Cancels an ongoing Open operation
+        * @return void
+        */
+        void CancelOpen();
+
+        /** 
+        * Returns the public key in DER-encoded ASN-1
+        * @param aHandle    -The handle of the key to be opened
+        * @param aPublicKey -returned key
+        * @param aStatus    -Asynchronous request notification.
+        * @return void
+        */
+        void ExportPublic( const TCTTokenObjectHandle& aHandle,
+                           HBufC8*& aPublicKey,
+                           TRequestStatus& aStatus );
+        
+        /**  
+        * Cancels an ongoing Export operation
+        * @return void
+        */
+        void CancelExportPublic();
+
+       
+        /** 
+        * Perform signing operation.
+        * @param  aObject -The handle of signer object. 
+        * @param  aDigest -The data to be signed.   
+        * @param  aSignature -The returned signature. This remains owned
+        *         by the signer, and is valid until the signer is released or
+        *         until the next Sign.
+        * @param aStatus -Async status notification
+        * @return void
+        */ 
+        void NonRepudiableRSASign( const TCTTokenObjectHandle& aObject, 
+                                   const TDesC8& aDigest, 
+                                   CRSASignature*& aSignature, 
+                                   TRequestStatus& aStatus );
+
+    protected:  // From base class MCTTokenInterface
+        
+        virtual void DoRelease();
+
+    private: // Constructors
+
+        /**
+        * Default constructor
+        * @param  aToken   (IN) A reference to current token
+        */
+        CWimKeyStore( CWimToken& aToken );
+
+        // Second phase constructor
+        void ConstructL();
+
+        // Destructor
+        virtual ~CWimKeyStore();
+
+    private:
+
+        /**
+        * Starts initialization on this class.
+        * @return void
+        */
+        void Initialize();
+
+        /**
+        * Creates one key info for list or get key info operation
+        * @param   aIndex (IN) An index value of current key info in
+        *          the internal array
+        * @return  A pointer to created key info
+        */
+
+        CCTKeyInfo* CreateKeyInfoL( TInt aIndex );
+
+        /**
+        * Leavable function to filter keys in list operation.
+        * @return void
+        */
+        void DoFilterKeysL();
+
+        /**
+        * Leavable function for key creation.
+        * @param   aHandle (IN) Handle of desired authentication object.
+        * @return  A pointer to created authentication object
+        */
+        MCTAuthenticationObject* MakeAuthObjectL( TInt aHandle );
+
+        /**
+        * Returns boolean value true or false indicating if token is removed
+        * @return  Boolean value: true, if token removed, false if not
+        */
+        TBool TokenRemoved();
+
+        
+        /**
+        * Checks if token is removed or is this object active
+        * @return  Boolean value: true if allowed, false if not
+        */
+        TBool EnteringAllowed( TRequestStatus& aStatus );
+
+
+    private: // From base class CActive
+
+        void RunL();
+        
+        /** 
+        * Leaves in RunL are handled here.
+        * @param  aError  Leaving code
+        * @return An integer that should be KErrNone if leave was handled.
+        */
+        TInt RunError( TInt aError );
+        
+        void DoCancel();
+
+    private: // Data
+
+        // A reference to current token of this interface
+        CWimToken& iToken;
+
+        // State flag for RunL
+        enum TPhase
+            {
+            EIdle,
+            EOpenAuthObjectsInterface,
+            EListAuthObjects,
+            EGetKeyList,
+            ECheckGetKeyList,
+            EFilterKeys,
+            EGetKey,
+            ECreateRSASignerObject,
+            EStartNonRepudiableRSASign,
+            ESignCompleted,
+            EStartExportPublicKey,
+            EExportPublicKeyDone
+            };
+
+        // Flag for internal state machine
+        TPhase iPhase;
+
+        // Flag for internal state machine
+        TPhase iPhaseOriginal;
+
+        // The pointed object acts as a converter between
+        // CWimCertStore/CWimKeyStore interface and WimClient
+        // This class owns the pointed object
+        CWimKeyDetails* iCWimKeyDetails;
+
+        // Used for saving caller status in asynchronous call
+        // This class don't own the pointed object
+        TRequestStatus* iOriginalRequestStatus;
+
+        // Temporal array for key info pointers
+        // This array is used to append key infos in List operation
+        // This class don't own the pointed objects
+        RPointerArray<CCTKeyInfo>* iKeyList;
+
+        // Temporal array for key infos. 
+        // This array is used to fetch key infos from WimClient.
+        RPointerArray<CCTKeyInfo> iKeyInfos;
+
+        // Used with list operation to filter keys
+        TCTKeyAttributeFilter iKeyFilter;   
+
+        // Index for going through all keys asynchronously 
+        // in list operation.
+        TInt iKeyIndex;
+
+        // Used to fetch one key info from wimclient
+        // This class don't own the pointed object.
+        CCTKeyInfo** iInfo;
+
+        // Key value for key object. Used in asynchronous call of
+        // getting one key info.
+        TInt iHandle;
+        
+        // Array for key info keys fetched from wimclient
+        CArrayFixFlat<TUint8>* iKeyNumbers;
+
+        // Array of pointers to PIN-NRs.This class don't own the pointed
+        // objects
+        const CArrayPtrFlat<CWimPin>* iPinNRs; 
+
+        // Is key list done or not already. Set to true value in the first
+        // key list.
+        TBool iListDone;
+
+        //Signer object, which is returned to caller. Not Owned.
+        CWimRSASigner*              iSigner;
+              
+        //Handle stored during opening new RSA signer object.
+        TCTTokenObjectHandle        iOpenSigninKeyHandle;
+
+        //Buffer, which holds received signature from server. Owned.
+        HBufC8*                     iSignature;
+        
+        //Signature object which is filled with data received from server.
+        //Not owned.
+        CRSASignature**              iRSASignature; 
+        
+        //Buffer used to contain KeyId in Sign and public key export
+        //operations. Owned.
+        HBufC8*                     iKeyId;
+
+        //Buffer to hold public key data during public key export. Not Owned.
+        HBufC8*                     iPublicKey;
+
+        // The index of exported key
+        TInt                        iExportKeyIdIndex;
+        
+        TInt                        iRSAKeyIdIndex;
+        
+        const TDesC8*               iDigest;
+        
+    };
+
+#endif      // CWIMKEYSTORE_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/inc/WimRSASigner.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,184 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface which handles RSA signing operations.
+*
+*/
+  
+
+
+#ifndef WIMRSASIGNER_H
+#define WIMRSASIGNER_H
+
+
+//INCLUDES
+
+#include <e32base.h>
+#include <e32std.h>
+
+
+//FORWARD DECLARATIONS
+
+class CMessageDigest;
+class CWimKeyStore;
+
+
+/**
+*  RSA signer object. Handles RSA signing.
+*
+*  @lib   WimPlugin
+*  @since Series60 2.6
+*/
+class CWimRSASigner: public CBase, public MRSASigner
+    {
+ 
+    public:
+    
+        /** 
+        * Creates new Instance of CWimRSASigner
+        * @param aClient -Reference to keystore
+        * @return An instance of this class
+        */
+        static CWimRSASigner* NewL( CWimKeyStore& aClient );
+    
+        /** 
+        * Destructor
+        */
+        ~CWimRSASigner();
+
+        /** 
+        * Returns the object's human-readable label
+        * @return TDesC&
+        */
+        const TDesC& Label() const;
+    
+        /** 
+        * Returns a reference to the associated token
+        * @return MCTToken&
+        */
+        MCTToken& Token() const;
+    
+        /** 
+        * Returns a UID representing the type of the token object. The
+        * meanings of possible UIDs should be documented in the
+        * documentation for the interface that returns them.
+        * @return TUid
+        */
+        TUid Type() const;
+
+        /** 
+        * Returns a handle for the object. The primary purpose of the
+        * handle is to allow token objects to be 'passed' between
+        * processes. See TCTTokenObjectHandle for more details.
+        * @return   TCTTokenObjectHandle
+        */
+        TCTTokenObjectHandle Handle() const;
+
+        /** 
+        * Sign some data. 
+        * The data is hashed before the signature is created using the SHA-1
+        * algorithm.
+        * @param    aPlaintext The string to be signed.
+        * @param    aSignature The returned signature. This remains owned
+        *           by the signer, and is valid until the signer is released or
+        *           until the next Sign.
+        * @param    aStatus Async status notification
+        * @return void
+        */
+        void SignMessage( const TDesC8& aPlaintext, 
+                          CRSASignature*& aSignature, 
+                          TRequestStatus& aStatus );
+             
+        /** 
+        * Perform a raw signing operation.
+        * @param  aData The data to be signed - this should be some form of hash 
+        *         of the actual message to be signed.  If the data is too long, 
+        *         this method will return KErrOverflow through aStatus. 
+        * @param  aSignature The returned signature. This remains owned
+        *         by the signer, and is valid until the signer is released or
+        *         until the next Sign.
+        * @param aStatus Async status notification
+        * @return void
+        */
+        void Sign( const TDesC8& aData, 
+                   CRSASignature*& aSignature, 
+                   TRequestStatus& aStatus );
+    
+        /** 
+        * Cancel an ongoing sign
+        * @return void
+        */
+        void CancelSign();
+
+        /** 
+        * Release object
+        * @return void
+        */
+        void Release();
+
+        /** 
+        * Sets label for signin key object.
+        * @param aLabel -label to be set.
+        * @return void
+        */
+        void SetLabelL( const TDesC& aLabel );
+
+        /** 
+        * Sets objectId for this object.
+        * @param aObjectID -points to a certain key
+        * @return void
+        */
+        void SetObjectId( const TInt aObjectId );
+
+    protected:
+
+        /** 
+        * Releases the object once the base-class framework work has
+        * been done. The default implementation simply does a 'delete
+        * this', but derived classes can substitute their own behaviour,
+        * for instance to implement reference counting of the token
+        * objects themselves.
+        * @return void
+        */
+        void DoRelease();
+
+    private:
+
+        /**
+        * Default constructor
+        * @param    aClient pointer to caller.
+        */
+        CWimRSASigner( CWimKeyStore& aClient );
+
+    private:
+    
+        //Handles hashing. Owned
+        CMessageDigest*         iDigest;
+
+        //Objects handle
+        TCTTokenObjectHandle    iHandle;
+
+        //Reference to keystore
+        CWimKeyStore&           iClient;
+    
+        //holds key label. Owned.
+        HBufC*                  iLabel;
+        
+        //buffer for hash result
+        HBufC8*                 iDigestBuf;
+
+    };
+
+#endif // WIMRSASIGNER_H
+
+// end of file 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/inc/WimToken.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,263 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A token represents one instance of a particular kind of 
+*                cryptographic module
+*
+*/
+
+
+
+#ifndef CWIMTOKEN_H
+#define CWIMTOKEN_H
+
+//  INCLUDES
+
+#include "WimSecModule.h"
+#include <e32base.h>
+#include <ct.h>
+
+// FORWARD DECLARATION
+
+class CWimTokenListener;
+class MCTCertStore;
+class MCTWritableCertStore;
+class MCTKeyStore;
+class MCTAuthenticationObjectList;
+
+// CLASS DECLARATION
+
+/**
+*  CWimToken is a class which implements one cryptographic interface
+*
+*
+*  @lib   WimPlugin
+*  @since Series60 2.1
+*/
+class CWimToken : public CBase, public MCTToken
+    {
+	public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        * @param aWimSecModule (IN) Current security module
+        * @param aTokenType (IN) Created token's token type
+        * @return  An instance of this class
+        */
+        static CWimToken* NewL( CWimSecModule* aWimSecModule, 
+										 MCTTokenType& aTokenType );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimToken();
+
+    public: // Functions from base class MCTToken
+        
+		/**
+        * Returns a reference to this token's label.
+        * @return  A Reference to this token's label.
+        */
+		const TDesC& Label();
+        
+		/**
+        * Returns the associated token type.
+        * @return A reference to token's token type
+        */
+		MCTTokenType& TokenType();
+        
+		/**
+        * Returns the token's handle which is TCTTokenHandle class.
+        * @return tokens handle
+        */
+		TCTTokenHandle Handle();
+        
+        /** 
+        * Returns the specified information string about the token.
+        * @param aRequiredInformation (IN) Specifies the required information
+        *        needed from the token. See value from TTokenInformation.
+        * @return TDesC&  (OUT) Information string of the token, or KNullDesC,
+        *         if token information cannot be given
+        */
+        const TDesC& Information( 
+                                TTokenInformation aRequiredInformation );
+
+		/**
+		* Notifies the client when the token has been removed. Notify is 
+        * given by changing the status code of given TRequestStatus.
+        * The caller should give listener's TRequestStatus in pending state 
+        * to this function.
+        * Note: this is not an asynchronous call, it only stores the
+        * address of given TRequestStatus for later notifications.
+		* @param  aStatus (IN/OUT) Async. request status.
+        *         KErrPending, token is on it's place
+        *         KErrCancel, caller has cancelled to notify token removal
+        *         KErrHardwareNotAvailable, token is removed
+		*		  Any other system error code
+		* @return void
+		*/
+		void NotifyOnRemoval( TRequestStatus& aStatus );
+
+		/**
+		* Cancels the NotifyOnRemoval request.
+		* @return void
+		*/
+		void CancelNotify();
+
+	protected: // Functions from base class MCTToken
+
+        /**
+        * Returns a reference to pointer of an interface object.
+		* The caller owns all the parameters.
+        * @param  aRequiredInterface (IN) The UID of the interface that 
+		*		  should be returned
+		* @param  aReturnedInterface (OUT). This will be set to a pointer to 
+		*		  the returned interface on success and
+		*		  to NULL if it isn't supported by this token
+        * @param  aStatus (IN/OUT) Async. request status.
+		*		  KErrNone, if all ok and interface returned
+		*		  KErrCancel, if call canceled
+		*		  KErrNotSupported, if interface not supported
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+		* @return void
+        */
+        void DoGetInterface( TUid aRequiredInterface,
+						              MCTTokenInterface*& aReturnedInterface, 
+						              TRequestStatus& aStatus );
+		
+		/**
+        * Cancels DoGetInterface operation.
+        * @return Boolean value: true, if cancel is appropriate, false if
+        *         cancel is not appropriate
+        */
+		TBool DoCancelGetInterface();
+
+	public: // New functions
+
+		/**
+		* Returns a pointer to current security module.
+		* @return A pointer to current security module
+		*/
+		CWimSecModule* WimSecModule();
+
+		/**
+		* Returns a pointer to token listener
+		* @return A pointer to token listener
+		*/
+		CWimTokenListener* TokenListener();
+
+		/**
+		* Returns a boolean indicating if token is removed
+		* @return True, if token removed, false if not
+		*/
+		TBool TokenRemoved();
+
+    protected:  // New functions
+        
+        /**
+        * Returns a reference to a variable to be used as a reference counter
+        * @return  A reference to reference counter
+        */
+        TInt& ReferenceCount();
+
+	private: // Constructors
+    
+        /**
+        * Default constructor.
+        * @param aWimSecModule (IN) Current security module
+        * @param aTokenType (IN) Created token's token type
+        */
+        CWimToken( CWimSecModule* aWimSecModule, 
+				   MCTTokenType& aTokenType );
+
+        void ConstructL();
+
+	private: // Own function
+
+        /**
+        * Returns as a parameter a reference to pointer of an interface object.
+        * @param  aRequiredInterface (IN) The UID of the interface that 
+		*		  should be returned
+		* @param  aReturnedInterface (OUT). This will be set to a pointer to 
+		*		  the returned interface on success and
+		*		  to NULL if it isn't supported by this token
+        * @param  aStatus (IN/OUT) Async. request status.
+		*		  KErrNone, if all ok and interface returned
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+		* @return void
+        */
+        void MakeInterfaceL( TUid aRequiredInterface,
+                             MCTTokenInterface*& aReturnedInterface );
+    private:    
+		
+		// A pointer to current security module.
+		// This class don't own the pointed object.
+		CWimSecModule* iWimSecModule;
+
+		// Reference to the token type of this token. 
+		// This class don't own the referenced object.
+		MCTTokenType& iTokenType;
+
+		// A pointer to label buffer that contains the name of this token.
+		// This class owns the pointed object.
+		HBufC* iLabel;
+
+		// A variable needed for reference counting
+		TInt iCount;
+
+		// Used in token notify on removal
+		CWimTokenListener* iWimTokenListener;
+
+  		// A pointer to certificate store
+		// Ownership of pointed object is transferred to caller
+		MCTCertStore* iCertStoreIf;
+
+		// A pointer to writable certificate
+		// Ownership of pointed object is transferred to caller
+		MCTWritableCertStore* iCertStoreWritableIf;
+
+		// A pointer to Wim key store
+		// Ownership of pointed object is transferred to caller
+		MCTKeyStore* iKeyStoreIf;
+
+		// A pointer to Wim authentication object list
+		// Ownership of pointed object is transferred to caller
+		MCTAuthenticationObjectList* iAuthObjectListIf;
+
+    };
+
+        /**
+        * Helper class to filter token types
+        */
+
+class TCurrentTokenType : public MCTTokenTypeFilter
+    {
+
+    public: // From base class MCTTokenTypeFilter
+    
+        /**
+        * Sets value to given token type info.
+        * @param  aTokenType  (IN) Info class for token type
+        * @return ETrue if current token type is same as given token type
+        *         EFalse, if not
+        */
+        virtual TBool Accept( const CCTTokenTypeInfo& aTokenType ) const;
+
+    };
+
+
+#endif      // CWIMTOKEN_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/inc/WimTokenListener.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,120 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Listener class for Wim token removal event
+*
+*/
+
+
+
+#ifndef CWIMTOKENLISTENER_H
+#define CWIMTOKENLISTENER_H
+
+//  INCLUDES
+
+#include "WimSecModule.h"
+#include <e32base.h>
+
+// FORWARD DECLARATIONS
+
+
+// CLASS DECLARATION
+
+/**
+*  CWimTokenListener listens removal event from WimServer
+*
+*  @lib   WimPlugin
+*  @since Series60 2.1
+*/
+class CWimTokenListener : public CActive
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        * @param aWimSecModule (IN) A pointer to current security module
+        * @return An instance of this class
+        */
+        static CWimTokenListener* NewL( CWimSecModule* aWimSecModule );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimTokenListener();
+
+
+    public: // New functions
+
+        /**
+        * Starts system to listen token removal
+        * @return void
+        */
+        void StartListening();
+
+        /**
+        * Set client status
+        * @param aStatus (IN/OUT) Client status that wants to know if token 
+        *        is removed
+        * @return void
+        */
+        void SetClientStatus( TRequestStatus& aStatus );
+
+        /**
+        * Clear client status. This is done when framework's CancelNotify()
+        * is called. The client won't get any message about token removal.
+        * @return void
+        */
+        void ClearClientStatus();
+
+        /**
+        * Returns token status.
+        * @return KRequestPending meaning that token is not removed, 
+        *         KErrNone meaning that token has been removed, 
+        */
+        TInt TokenStatus();
+
+    private: // From base class CActive
+
+        void RunL();
+        
+        void DoCancel();
+
+    private: // Constructors
+    
+        /**
+        * Default constructor.
+        * @param aWimSecModule (IN) A pointer to current security module
+        */
+        CWimTokenListener( CWimSecModule* aWimSecModule );
+
+        // Second phase constructor
+        void ConstructL();
+
+    private:    
+        
+        // A pointer to current security module.
+        // This class don't own the pointed object.
+        CWimSecModule* iWimSecModule;
+
+        // A pointer to UI's request status
+        // This class don't own the pointed object.
+        TRequestStatus* iClientStatus;
+
+        // Status value of token
+        TInt iTokenStatus;
+
+    };
+
+#endif      // CWIMTOKENLISTENER_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/inc/WimTokenType.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This class is instantiated via ECom for a particular token type
+*
+*/
+
+
+#ifndef CWIMTOKENTYPE_H
+#define CWIMTOKENTYPE_H
+
+//  INCLUDES
+
+#include "WimSecModuleMgr.h"
+#include <e32base.h>
+#include <ct.h>
+
+
+/**
+*  This refers to a software module that supports the instantiation of a tokens
+*
+*  @lib   WimPlugin
+*  @since Series60 2.1
+*/ 
+
+class CWimTokenType :   public CCTTokenType
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimTokenType* NewL();
+
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimTokenType();
+
+    public: // Functions from base class MCTTokenType
+        
+        /**
+        * Lists all the tokens of this type. Caller owns all parameters and
+        * is responsible to destroy all objects in the received RCPointerArray.
+        * @param  aTokens (OUT) The returned tokens are added to this array.
+        * @param  aStatus (IN/OUT). Asyncronous return status: 
+        *         KErrNone, if no errors occurred
+        *         KErrNotFound, if Wim information not found
+        *         KErrCancel, if list operation cancelled
+        *         Any other system wide error code
+        * @return void
+        */
+        void List( RCPointerArray<HBufC>& aTokens, 
+                            TRequestStatus& aStatus );
+
+        /**
+        * Cancel a list operation.
+        * @return void
+        */
+        void CancelList();
+
+        /**
+        * Opens a specified token with token info.
+        * The caller owns all the parameters.
+        * @param  aTokenInfo (IN) The info of the required token (token label)
+        * @param  aToken (OUT) The returned token.
+        * @param  aStatus (IN/OUT) Asynchronous return status.  
+        *         KErrNone, if token opening succeeded
+        *         KErrNotFound, if token not found by aTokenInfo
+        *         Any other system wide error code
+        * @return void
+        */
+        void OpenToken( const TDesC& aTokenInfo, 
+                                 MCTToken*& aToken,
+                                 TRequestStatus& aStatus );
+    
+        /**
+        * Opens a specified token with handle
+        * The caller owns all the parameters.
+        * @param  aHandle (IN) The handle of the required token
+        * @param  aToken (OUT) The returned token.
+        * @param  aStatus (IN/OUT) Asynchronous return status.  
+        *         KErrNone, if token opening succeeded
+        *         KErrNotFound, if token not found by aHandle
+        *         Any other system wide error code
+        * @return void
+        */
+        void OpenToken( TCTTokenHandle aHandle, 
+                                 MCTToken*& aToken,
+                                 TRequestStatus& aStatus );
+    
+         /**
+        * Cancel an OpenToken operation.
+        * @return void
+        */
+        void CancelOpenToken();      
+
+    private: // Constructors
+
+        /**
+        * Second phase constructor
+        */
+        void ConstructL();
+
+        /**
+        * Default constructor
+        */
+        CWimTokenType();
+
+    private: // Data
+        
+        // A pointer to security module handler.
+        // The ownership of this object belongs to this class
+        CWimSecModuleMgr* iWimSecModuleMgr;
+
+    };
+
+#endif      // CWIMTOKENTYPE_H  
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/src/WimAuthenticationObject.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1189 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of single authentication object
+*
+*/
+
+
+// INCLUDE FILES
+
+#include "WimSecModuleMgr.h"
+#include "WimAuthenticationObject.h"
+#include "WimPin.h"
+#include "WimTrace.h"
+//#include "WimDebug.h"
+#include "WimTokenListener.h"
+#include "WimImplementationUID.hrh"
+#include <unifiedkeystore.h>
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::CWimAuthenticationObject()
+// Defalt constructor
+// -----------------------------------------------------------------------------
+//
+CWimAuthenticationObject::CWimAuthenticationObject(
+                                               CWimToken& aToken,
+                                               CWimPin& aWimPin,
+                                               const TUid aType,
+                                               const TInt aHandle,
+                                               TUint32 aObjectStatus ) :
+
+                                               CActive( EPriorityNormal ),
+                                               MCTAuthenticationObject( aToken ),
+                                               iToken( aToken ),
+                                               iWimPin ( aWimPin ),
+                                               iType ( aType ),
+                                               iObjectId ( aHandle ),
+                                               iObjectStatus( aObjectStatus ),
+                                               iTokenWider( aToken )
+
+    {
+    CActiveScheduler::Add( this );
+    iPhase = EIdle;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::NewLC()
+// Two-phased constructor. One object stays in cleanup stack.
+// -----------------------------------------------------------------------------
+//
+CWimAuthenticationObject* CWimAuthenticationObject::NewLC(
+                                                         CWimToken& aToken,
+                                                         CWimPin& aWimPin,
+                                                         const TDesC& aLabel,
+                                                         const TUid aType,
+                                                         const TInt aHandle,
+                                                         TUint32 aObjectStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::NewLC()" ) );
+    __ASSERT_ALWAYS( aLabel.Length() > 0, User::Leave( KErrArgument ) );
+
+    if ( aType.iUid != WIM_PIN_G_UID && aType.iUid != WIM_PIN_NR_UID )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    CWimAuthenticationObject* that =
+        new( ELeave ) CWimAuthenticationObject( aToken,
+                                                 aWimPin,
+                                                 aType,
+                                                 aHandle,
+                                                 aObjectStatus );
+    CleanupStack::PushL( that );
+    that->ConstructL( aLabel );
+    return that;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::ConstructL()
+// Second phase constructor.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::ConstructL( const TDesC& aLabel )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::ConstructL()" ) );
+    iLabel = aLabel.AllocL();
+    iPhase = EIdle;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::~CWimAuthenticationObject()
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CWimAuthenticationObject::~CWimAuthenticationObject()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::~CWimAuthenticationObject()" ) );
+    Cancel();
+    FreeUnifiedKeyStore();
+    FreeUnifiedCertStore();
+    delete iCertFilter;
+    delete iLabel;
+    }
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::Label()
+// Returns a reference to this authentication object's label.
+// -----------------------------------------------------------------------------
+//
+const TDesC& CWimAuthenticationObject::Label() const
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::Label()" ) );
+
+    return *iLabel;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::Token()
+// Returns a reference to token (MCTToken) of this authentication object
+// -----------------------------------------------------------------------------
+//
+MCTToken& CWimAuthenticationObject::Token() const
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::Token()" ) );
+    return iToken;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::TokenWider()
+// Returns a reference to token (CWimToken) of this authentication object
+// -----------------------------------------------------------------------------
+//
+CWimToken& CWimAuthenticationObject::TokenWider() const
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::TokenWider()" ) );
+    return iTokenWider;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::Type()
+// Returns type (TUid) of current authentication object.
+// WIM_PIN_G_UID or WIM_PIN_NR_UID
+// -----------------------------------------------------------------------------
+//
+TUid CWimAuthenticationObject::Type() const
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::Type()" ) );
+    return iType;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::Release()
+// Deletes this instance
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::DoRelease()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::DoRelease()" ) );
+    delete this;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::Handle()
+// Returns a handle (TCTTokenObjectHandle) of this authentication object.
+// iObjectId runs from 0 to N where N is (count of authentication objects) - 1
+// -----------------------------------------------------------------------------
+//
+TCTTokenObjectHandle CWimAuthenticationObject::Handle() const
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::Handle()" ) );
+    return TCTTokenObjectHandle( Token().Handle(), iObjectId );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::PinModule()
+// Returns a reference to pin module manager (CWimPin)
+// -----------------------------------------------------------------------------
+//
+CWimPin& CWimAuthenticationObject::PinModule() const
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::PinModule()" ) );
+    return iWimPin;
+    }
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::ListProtectedObjects()
+// Returns a list of all the objects which this authentication object protects.
+// Procedure: 1. Fetch all keys this authentication object protects
+//            2. Fetch certificates those keys are used for and
+//            3. Make objects from those protected keys and certificates
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::
+     ListProtectedObjects( RMPointerArray<MCTTokenObject>& aObjects,
+                           TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::ListProtectedObjects()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    iObjects = &aObjects;
+
+    iKeyInfos.Close();
+
+    iFs = static_cast<CCTTokenType&>( Token().TokenType() ).Fs();
+
+    TRAPD( err, iUnifiedKeyStore = CUnifiedKeyStore::NewL( iFs ) );
+
+    if ( err != KErrNone )
+        {
+        User::RequestComplete( iOriginalRequestStatus, err );
+        }
+    else
+        {
+        iStatus = KRequestPending;
+        iUnifiedKeyStore->Initialize( iStatus );
+        iPhase = EGetKeyInfos;
+        SetActive();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimAuthenticationObject::RunL()
+// Core operations are done here.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::RunL()
+    {
+    switch ( iPhase )
+        {
+        case EGetKeyInfos:
+            {
+            if ( iStatus.Int() == KErrNone )
+                {
+                iKeyFilter.iKeyId = KNullDesC8;
+                iKeyFilter.iUsage = EPKCS15UsageAll;
+                iStatus = KRequestPending;
+                iPhase = EFilterKeys;
+                iStatus = KRequestPending;
+                iUnifiedKeyStore->List( iKeyInfos, iKeyFilter, iStatus );
+                SetActive();
+                }
+            else // Something went wrong (or call was cancelled) with
+                 // iUnifiedKeyStore->Initialize( iStatus )
+                {
+                FreeUnifiedKeyStore();
+                iPhase = EIdle;
+                User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+                }
+            break;
+            }
+        case EFilterKeys:
+            {
+            DoFilterKeys();
+            break;
+            }
+        case EGetCerts:
+            {
+            // In this phase cert store must allways be NULL
+            if ( !iUnifiedCertStore )
+                {
+                iFs = static_cast<CCTTokenType&>( Token().TokenType() ).Fs();
+                iUnifiedCertStore = CUnifiedCertStore::NewL( iFs, EFalse );
+                iStatus = KRequestPending;
+                iPhase = EInitCertStore;
+                iUnifiedCertStore->Initialize( iStatus );
+                SetActive();
+                }
+            else
+                {
+                FreeUnifiedKeyStore();
+                iPhase = EIdle;
+                User::RequestComplete( iOriginalRequestStatus, KErrCorrupt );
+                }
+            break;
+            }
+        case EInitCertStore:
+            {
+            // Called when cert store init completes
+            if ( iStatus.Int() == KErrNone )
+                {
+                if ( iCertFilter )
+                    {
+                    delete iCertFilter;
+                    iCertFilter = NULL;
+                    }
+                iCertFilter = CCertAttributeFilter::NewL();
+                iStatus = KRequestPending;
+                iPhase = EListCertEntries;
+                iUnifiedCertStore->List( iCertStoreEntries,
+                                        *iCertFilter,
+                                         iStatus );
+                SetActive();
+                }
+            else // Something went wrong (or call was cancelled) with
+                 // iUnifiedCertStore->Initialize( iStatus )
+                {
+                FreeUnifiedKeyStore();
+                FreeUnifiedCertStore();
+                iPhase = EIdle;
+                User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+                }
+            break;
+            }
+        case EListCertEntries:
+            {
+            DoListCertEntries();
+            break;
+            }
+        case EMakeObjects:
+            {
+            DoMakeObjectsL();
+            break;
+            }
+        case EEnablePinQuery:
+            {
+            User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+            break;
+            }
+        case EDisablePinQuery:
+            {
+            User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+            break;
+            }
+        case EChangePin:
+            {
+            User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+            break;
+            }
+        case EUnblockPin:
+            {
+            User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+            break;
+            }
+        case EVerifyPin:
+            {
+            User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+            break;
+            }
+        default:
+            {
+            User::RequestComplete( iOriginalRequestStatus, KErrCorrupt );
+            break;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimAuthenticationObject::DoFilterKeys()
+// Select keys according to given filter
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::DoFilterKeys()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::DoFilterKeys()" ) );
+    if ( iStatus.Int() == KErrNone )
+        {
+        // From all keys get only those that match with
+        // this protector
+        TInt count = iKeyInfos.Count();
+        TInt i = 0;
+        for ( i = 0; i < count ; i++ )
+            {
+            // If protector is not set or protector is not this, delete item
+            if ( !iKeyInfos[i]->Protector() ||
+                ( iKeyInfos[i]->Protector()->Handle().iObjectId !=
+                                       this->Handle().iObjectId ) )
+                {
+                    // If match is not found, delete object
+                    CCTKeyInfo* keyinfo = ( iKeyInfos ) [i];
+                    keyinfo->Release();
+                    ( iKeyInfos ) [i] = NULL;
+                }
+            }
+        i = 0;
+        while ( count )
+            {
+            if ( !iKeyInfos[i] )
+                {
+                // Remove element placeholder from CWimCertStore array
+                iKeyInfos.Remove( i );
+                }
+            else
+                {
+                i++;
+                }
+            count--;
+            }
+        iKeyInfos.Compress();
+        count = iKeyInfos.Count();
+        if ( count ) // Continue handling
+            {
+            iPhase = EGetCerts;
+            TRequestStatus* status = &iStatus;
+            User::RequestComplete( status, KErrNone );
+            SetActive();
+            }
+        else // No keys, no continue
+            {
+            FreeUnifiedKeyStore();
+            iPhase = EIdle;
+            User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+            }
+        }
+    else // Something went wrong (or call was cancelled) with
+         // iUnifiedKeyStore->List(...)
+        {
+        FreeUnifiedKeyStore();
+        iPhase = EIdle;
+        User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimAuthenticationObject::DoListCertEntries()
+// Select certificates according to keys
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::DoListCertEntries()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::DoListCertEntries()" ) );
+    if ( iStatus.Int() == KErrNone )
+        {
+         // All certs are listed
+         // Match every cert to keys. If match not found, delete cert
+         TInt certcount = iCertStoreEntries.Count();
+         TInt i = 0;
+         for ( i = 0; i < certcount; i++ )
+             {
+             TInt keycount = iKeyInfos.Count();
+             TInt j = 0;
+             for ( j = 0; j < keycount; j++ )
+                 {
+                 if ( iKeyInfos[j]->ID() ==
+                                iCertStoreEntries[i]->SubjectKeyId() )
+                    {
+                    j = keycount + 1;
+                    }
+                 }
+             if ( j == keycount )
+                {
+                // If match is not found, delete object and remove item
+                CCTCertInfo* certinfo = ( iCertStoreEntries ) [i];
+                // Delete object self
+                certinfo->Release();
+                ( iCertStoreEntries ) [i] = NULL;
+                }
+            }
+        i = 0;
+        while ( certcount )
+            {
+            if ( !iCertStoreEntries[i] )
+                {
+                // Remove element placeholder from array
+                iCertStoreEntries.Remove( i );
+                }
+            else
+                {
+                i++;
+                }
+            certcount--;
+            }
+        iCertStoreEntries.Compress();
+        iPhase = EMakeObjects;
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        SetActive();
+        }
+    else // Something went wrong (or call was cancelled) with
+         // iUnifiedCertStore->List(...)
+        {
+        FreeUnifiedKeyStore();
+        FreeUnifiedCertStore();
+        iPhase = EIdle;
+        User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimAuthenticationObject::DoMakeObjectsL()
+// Protected objects are validated here
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::DoMakeObjectsL()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::DoMakeObjectsL()" ) );
+    if ( iStatus.Int() == KErrNone ) // Not cancelled
+        {
+        TInt count = iKeyInfos.Count();
+        TInt i = 0;
+        for ( ; i < count; i++ )
+            {
+            // Make a copy of key info
+            HBufC* wlabel = HBufC::NewLC( ( iKeyInfos )[i]->Label().Length() );
+            wlabel->Des().Copy( ( iKeyInfos )[i]->Label() );
+            // Make a copy of protector if there is
+            MCTAuthenticationObject* protector = NULL;
+            if ( iKeyInfos[i]->Protector() )
+                {
+                TUint thishandle = iKeyInfos[i]->Protector()->
+                                                    Handle().iObjectId;
+                
+                //All the key list here is protected by this Authobj
+                if( this->Handle().iObjectId == thishandle )
+	                {
+	                protector = MakeAuthObjectL();
+	                }
+                                                    
+                else
+                    {
+                	return;
+                    }
+                
+                
+                if ( protector )
+                    {
+                    CleanupStack::PushL( protector );
+                    }
+                }
+#ifdef __SECURITY_PLATSEC_ARCH__
+            CCTKeyInfo* copy =
+                CCTKeyInfo::NewL( ( iKeyInfos ) [i]->ID(),
+                                  ( iKeyInfos ) [i]->Usage(),
+                                  ( iKeyInfos ) [i]->Size(),
+                                    protector,
+                                    wlabel,
+                                  ( iKeyInfos ) [i]->Token(),
+                                  ( iKeyInfos ) [i]->Handle().iObjectId,
+                                  ( iKeyInfos ) [i]->UsePolicy(),
+                                  ( iKeyInfos ) [i]->ManagementPolicy(),
+                                  ( iKeyInfos ) [i]->Algorithm(),
+                                  ( iKeyInfos ) [i]->AccessType(),
+                                  ( iKeyInfos ) [i]->Native(),
+                                  ( iKeyInfos ) [i]->StartDate(),
+                                  ( iKeyInfos ) [i]->EndDate() );
+#else
+            CCTKeyInfo* copy =
+                CCTKeyInfo::NewL( ( iKeyInfos ) [i]->ID(),
+                                  ( iKeyInfos ) [i]->Usage(),
+                                  ( iKeyInfos ) [i]->Size(),
+                                    protector,
+                                    wlabel,
+                                  ( iKeyInfos ) [i]->Token(),
+                                  ( iKeyInfos ) [i]->Handle().iObjectId,
+                                  ( iKeyInfos ) [i]->Owner(),
+                                  ( iKeyInfos ) [i]->Users(),
+                                  ( iKeyInfos ) [i]->Algorithm(),
+                                  ( iKeyInfos ) [i]->AccessType(),
+                                  ( iKeyInfos ) [i]->Native(),
+                                  ( iKeyInfos ) [i]->StartDate(),
+                                  ( iKeyInfos ) [i]->EndDate() );
+#endif
+            // Call Release() for copy, if leave occurs
+            CleanupReleasePushL( *copy );
+            // Take MCTokenObject part of it and append it to client
+            MCTTokenObject* obj = copy;
+            User::LeaveIfError( iObjects->Append ( obj ) );
+            CleanupStack::Pop( copy );
+            if ( protector )
+                {
+                CleanupStack::Pop( protector );
+                }
+            CleanupStack::Pop( wlabel );
+            }
+        count = iCertStoreEntries.Count();
+        for ( i = 0; i < count; i++ )
+            {
+            // Make a copy of certificate info
+
+            CCTCertInfo* copy = CCTCertInfo::NewLC( *iCertStoreEntries [i] );
+            MCTTokenObject* obj = copy;
+            User::LeaveIfError( iObjects->Append ( obj ) );
+            CleanupStack::Pop( copy );
+            }
+        }
+    FreeUnifiedKeyStore();
+    FreeUnifiedCertStore();
+    iPhase = EIdle;
+    User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimAuthenticationObject::MakeAuthObjectL()
+// Leavable function for making authenticaton objects
+// -----------------------------------------------------------------------------
+//
+MCTAuthenticationObject*
+                       CWimAuthenticationObject::MakeAuthObjectL()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::MakeAuthObjectL()" ) );
+    
+     CWimAuthenticationObject* me = 
+          CWimAuthenticationObject::NewLC( this->TokenWider(),
+                                           this->PinModule(),
+                                           this->Label(),
+                                           this->Type(),
+                                           this->Handle().iObjectId,
+                                           this->Status() );
+      CleanupStack::Pop( me );
+      return me;                                     
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimAuthenticationObject::FreeUnifiedKeyStore()
+// Frees key storage resources.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::FreeUnifiedKeyStore()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::FreeUnifiedKeyStore()" ) );
+    if ( iUnifiedKeyStore )
+        {
+        iKeyInfos.Close();
+        delete iUnifiedKeyStore;
+        iUnifiedKeyStore = 0;
+        }
+    iPhase = EIdle;
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimAuthenticationObject::FreeUnifiedCertStore()
+// Frees certificate storage resources.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::FreeUnifiedCertStore()
+    {
+    if ( iUnifiedCertStore )
+        {
+        iCertStoreEntries.Close();
+        delete iUnifiedCertStore;
+        iUnifiedCertStore = NULL;
+        }
+    }
+// -----------------------------------------------------------------------------
+// void CWimAuthenticationObject::RunError()
+// Unexpected error in RunL (e.g. Leave) leads us here.
+// -----------------------------------------------------------------------------
+//
+TInt CWimAuthenticationObject::RunError( TInt aError )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::RunError()" ) );
+    FreeUnifiedKeyStore();
+    FreeUnifiedCertStore();
+    iPhase = EIdle;
+    User::RequestComplete( iOriginalRequestStatus, aError );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimAuthenticationObject::DoCancel()
+//
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::DoCancel()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::DoCancel()" ) );
+
+    if ( iUnifiedKeyStore )
+        {
+        switch ( iPhase )
+            {
+            case EGetKeyInfos:
+                {
+                if ( iUnifiedKeyStore->IsActive() )
+                    {
+                    iUnifiedKeyStore->CancelInitialize();
+                    }
+                break;
+                }
+            case EFilterKeys:
+                {
+                if ( iUnifiedKeyStore->IsActive() )
+                    {
+                    iUnifiedKeyStore->CancelList();
+                    }
+                break;
+                }
+            default:
+                {
+                 break;
+                }
+            }
+        }
+
+    if ( iUnifiedCertStore )
+        {
+        switch ( iPhase )
+            {
+            case EInitCertStore:
+                {
+                if ( iUnifiedCertStore->IsActive() )
+                    {
+                    iUnifiedCertStore->CancelInitialize();
+                    }
+                break;
+                }
+            case EListCertEntries:
+                {
+                if ( iUnifiedCertStore->IsActive() )
+                    {
+                    iUnifiedCertStore->CancelList();
+                    }
+                break;
+                }
+            default:
+                {
+                // Other phases won't cause any action
+                break;
+                }
+            }
+        }
+    
+    switch ( iPhase )
+        {
+        case EEnablePinQuery:
+        	{
+        	PinModule().CancelEnablePinQuery();	
+        	break;
+        	}
+        case EDisablePinQuery:
+            {
+            PinModule().CancelDisablePinQuery();
+            break;	
+            }
+        case EChangePin:
+            {
+        	PinModule().CancelChangePin();
+        	break;
+            }
+        case EUnblockPin:
+            {
+         	PinModule().CancelUnblockPin();
+         	break;
+            }
+        case EVerifyPin:
+            {
+            PinModule().CancelVerifyPin();
+            break;
+            }
+        default: break;   
+        }
+    
+    
+    FreeUnifiedKeyStore();
+    FreeUnifiedCertStore();
+    iPhase = EIdle;
+    User::RequestComplete( iOriginalRequestStatus, KErrCancel );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::CancelListProtectedObjects()
+// Cancels an ongoing ListProtectedObjects operation.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::CancelListProtectedObjects()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::CancelListProtectedObjects()" ) );
+
+    if ( TokenRemoved() )
+        {
+        return;
+        }
+
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::ChangeReferenceData()
+// Change the reference data (e.g. PIN value).
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::ChangeReferenceData( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::ChangeReferenceData()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    PinModule().ChangePin( iStatus );
+    iPhase = EChangePin;
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::CancelListProtectedObjects()
+// Cancel an ongoing ChangeReferenceData operation.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::CancelChangeReferenceData()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::CancelChangeReferenceData()" ) );
+
+    if ( TokenRemoved() )
+        {
+        return;
+        }
+
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::Unblock()
+// Unblock the authentication object.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::Unblock( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::Unblock()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    PinModule().UnblockPin( iStatus );
+    iPhase = EUnblockPin;
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::CancelUnblock()
+// Cancel an ongoing Unblock operation.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::CancelUnblock()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::CancelUnblock()" ) );
+
+    if ( TokenRemoved() )
+        {
+        return;
+        }
+
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::Status()
+// Get the status of the authentication object.
+// Values are as in enum TCTAuthenticationStatus. Note: Blocked information
+// is not available before authentication object is verified.
+// -----------------------------------------------------------------------------
+//
+TUint32 CWimAuthenticationObject::Status() const
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::Status()" ) );
+
+    if ( iToken.TokenListener()->TokenStatus() != KRequestPending )
+        {
+        return 0;
+        }
+
+    return PinModule().PinStatus();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::Disable()
+// Disables the authentication object. This means that authentication data is
+// is not asked for any operations. Note: Disabling requires authentication data
+// to be entered.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::Disable( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::Disable()" ) );
+
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    PinModule().DisablePinQuery( iStatus );
+    iPhase = EDisablePinQuery;
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::CancelDisable()
+// Cancel an ongoing Disable operation.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::CancelDisable()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::CancelDisable()" ) );
+
+    if ( TokenRemoved() )
+        {
+        return;
+        }
+    
+    Cancel();	
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::Enable()
+// Enables the authentication object. This means that authentication data is
+// is asked for certain operations. Note: Enabling requires authentication data
+// to be entered.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::Enable( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::Enable()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    PinModule().EnablePinQuery( iStatus );
+    iPhase = EEnablePinQuery;
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::CancelEnable()
+// Cancel an ongoing Enable operation.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::CancelEnable()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::CancelEnable()" ) );
+
+    if ( TokenRemoved() )
+        {
+        return;
+        }
+
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::Open()
+// Opens the authentication object, meaning that the protected objects can be
+// accessed without provoking the authentication mechanism for the duration of
+// the timeout period. Note. It is not strictly necessary to call this function,
+// as the authentication object will be opened when any operation that needs it
+// to be opened is called, but it is sometimes useful to control the timing of
+// authentication dialogs. Note also that this function will do nothing if the
+// authentication object is open, or if it authentication object requires
+// the authentication
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::Open( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::Open()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    if ( this->Type().iUid == WIM_PIN_G_UID ) // If this is a Pin-G
+        {
+        TBool wimopen = iToken.WimSecModule()->IsOpen();
+        if ( !wimopen )
+            {
+            if( iToken.WimSecModule()->CloseAfter() != 0 )
+                {
+                PinModule().VerifyPin( iStatus );
+                iPhase = EVerifyPin;
+                SetActive();
+                }
+            else
+                {
+                User::RequestComplete( iOriginalRequestStatus, KErrNone );
+                }
+            
+            }
+        else
+            {
+            User::RequestComplete( iOriginalRequestStatus, KErrNone );
+            }
+        }
+    else
+        {
+        User::RequestComplete( iOriginalRequestStatus, KErrNotSupported );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::Close()
+// Closes an authentication object. After this call authentication data is
+// needed again for certain operations.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::Close( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::Close()" ) );
+    TInt err = KErrNone;
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    if ( this->Type().iUid == WIM_PIN_G_UID ) // If this is a Pin-G
+        {
+        TBool wimopen = iToken.WimSecModule()->IsOpen();
+        if ( wimopen )
+            {
+            err = iToken.WimSecModule()->Close();
+            }
+        }
+    else
+        {
+        err = KErrNotSupported;
+        }
+    User::RequestComplete( iOriginalRequestStatus, err );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::TimeRemaining()
+// Returns the amount of time in seconds that the authentication object
+// will remain open for, or 0 if it is closed.
+// -----------------------------------------------------------------------------
+void CWimAuthenticationObject::TimeRemaining( TInt& aStime,
+                                              TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::TimeRemaining()" ) );
+    TInt ret = KErrNone;
+    aStime = 0;
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    if ( this->Type().iUid == WIM_PIN_G_UID ) // If this is a Pin-G
+        {
+        TBool wimopen = iToken.WimSecModule()->IsOpen();
+        if ( wimopen )
+            {
+            aStime = iToken.WimSecModule()->CloseAfter();
+            }
+        }
+    else
+        {
+        ret = KErrNotSupported;
+        }
+    User::RequestComplete( iOriginalRequestStatus, ret );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::SetTimeout()
+// Sets the time in seconds for this authentication object. Non-positive
+// special values is 0, meaning always ask, and -1, meaning until it's
+// explicitly closed.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::SetTimeout( TInt aTimeout,
+                                           TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::SetTimeout()" ) );
+    TInt ret = KErrNone;
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    if ( this->Type().iUid == WIM_PIN_G_UID ) // If this is a Pin-G
+        {
+        if ( aTimeout >= -1 && aTimeout <= 2146 )
+            {
+            iToken.WimSecModule()->SetCloseAfter( aTimeout );
+            }
+        else
+            {
+            ret = KErrArgument;
+            }
+        }
+    else
+        {
+        ret = KErrNotSupported;
+        }
+    User::RequestComplete( iOriginalRequestStatus, ret );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::Timeout()
+// Gets the current timeout value, in seconds. See SetTimeout for an explanation
+// of the values.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObject::Timeout( TInt& aTime,
+                                        TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::Timeout()" ) );
+    TInt ret = KErrNone;
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    aTime = 0;
+
+    if ( this->Type().iUid == WIM_PIN_G_UID ) // If this is a Pin-G
+        {
+        aTime = iToken.WimSecModule()->CloseAfter();
+        }
+    else
+        {
+        ret = KErrNotSupported;
+        }
+    User::RequestComplete( iOriginalRequestStatus, ret );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::EnteringAllowed()
+//
+// -----------------------------------------------------------------------------
+//
+TBool CWimAuthenticationObject::EnteringAllowed( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::EnteringAllowed()" ) );
+    if ( TokenRemoved() )
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete( status, KErrHardwareNotAvailable );
+        return EFalse;
+        }
+
+    // If this active object is in running, don't accept entering
+    if ( IsActive() )
+        {
+        // If the caller status is the same as the status, that activated
+        // this object, just return
+        if ( &aStatus == iOriginalRequestStatus )
+            {
+            return EFalse;
+            }
+        else
+            {
+            // Otherwise complete it with error
+            TRequestStatus* status = &aStatus;
+            User::RequestComplete( status, KErrInUse );
+            return EFalse;
+            }
+        }
+    else
+        {
+        iOriginalRequestStatus = &aStatus;
+        aStatus = KRequestPending;
+        return ETrue;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObject::TokenRemoved()
+// Returns true or false indicating if token is removed
+// -----------------------------------------------------------------------------
+//
+TBool CWimAuthenticationObject::TokenRemoved()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObject::TokenRemoved()" ) );
+
+    // If token listener is not alive, then token is removed
+    if ( iToken.TokenListener()->TokenStatus() != KRequestPending )
+        {
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/src/WimAuthenticationObjectList.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,353 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of authentication object list
+*
+*/
+
+
+// INCLUDE FILES
+
+#include "WimAuthenticationObjectList.h"
+#include "WimAuthenticationObject.h"
+#include "WimPin.h"
+#include "WimClsv.h"
+#include "WimTrace.h"
+#include "WimTokenListener.h"
+#include "WimImplementationUID.hrh"
+#include <mctauthobject.h>
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObjectList::CWimAuthenticationObjectList()
+// Default constructor
+// -----------------------------------------------------------------------------
+//
+CWimAuthenticationObjectList::CWimAuthenticationObjectList( CWimToken& aToken ) : 
+                                                            CActive( EPriorityHigh ),
+                                                            iToken( aToken ) 
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObjectList::NewL()
+// Two phased constructor
+// -----------------------------------------------------------------------------
+//
+CWimAuthenticationObjectList* 
+                      CWimAuthenticationObjectList::NewL( CWimToken& aToken ) 
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObjectList::NewL()" ) );
+    CWimAuthenticationObjectList* that = 
+                        new( ELeave ) CWimAuthenticationObjectList( aToken );
+    CleanupStack::PushL( that );
+    that->ConstructL();
+    CleanupStack::Pop( that );
+    return that;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObjectList::ConstructL()
+// Second phase constructor.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObjectList::ConstructL()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObjectList::ConstructL()" ) );
+    CActiveScheduler::Add( this ); 
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::DoRelease()
+// Deletes this interface on demand.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObjectList::DoRelease()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObjectList::DoRelease()" ) );
+    delete this;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObjectList::~CWimAuthenticationObjectList()
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CWimAuthenticationObjectList::~CWimAuthenticationObjectList()
+    {
+    _WIMTRACE ( 
+        _L( "CWimAuthenticationObjectList::~CWimAuthenticationObjectList()" ) );
+    Cancel();
+    TInt count = iAuthObjects.Count();
+
+    while ( count )
+        {
+        CWimAuthenticationObject* entry = iAuthObjects[count - 1];
+        entry->Release();
+        iAuthObjects.Remove( count - 1 );
+        count--;
+        }
+
+    iAuthObjects.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObjectList::Token()
+// Returns a reference to current token (MCTToken) of this authentication 
+// object list interface.
+// -----------------------------------------------------------------------------
+//
+MCTToken& CWimAuthenticationObjectList::Token()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObjectList::Token()" ) );
+    return iToken;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObjectList::List()
+// Lists all authentication objects.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObjectList::List( 
+                        RMPointerArray<MCTAuthenticationObject>& aAuthObjects, 
+                        TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObjectList::List()" ) );
+
+    if ( TokenRemoved() )
+        {
+        return;
+        }
+    
+    _WIMTRACE ( _L( "CWimAuthenticationObjectList::List() after TokenRemoved checking" ) );
+    aStatus = KRequestPending;
+    iPhase = ECreateList;
+        
+    iClientStatus = &aStatus;
+    iClientAuthObjects = &aAuthObjects;
+       
+    iStatus = KRequestPending;
+    SetActive();
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    
+    _WIMTRACE ( _L( "CWimAuthenticationObjectList::List() End" ) );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObjectList::DoListL()
+// Fetches first all authentication objects from Wim. After that makes a copy
+// each of them for the client.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObjectList::DoListL( 
+                        RMPointerArray<MCTAuthenticationObject>& aAuthObjects )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObjectList::DoListL()" ) );
+    
+    TInt count = iAuthObjects.Count();
+
+    for ( TInt i = 0; i < count; i++ )
+        {
+        
+        //SecModUI will call Status() to get the PIN status later.
+        //We donot need to send PIN status in the phase
+        
+        TUint32 status = 0;
+        CWimAuthenticationObject* me = 
+                          MakeAuthObjectL( iAuthObjects[i]->TokenWider(),
+                                           iAuthObjects[i]->PinModule(),
+                                           iAuthObjects[i]->Label(),
+                                           iAuthObjects[i]->Type(),
+                                           iAuthObjects[i]->Handle().iObjectId,
+                                           status );
+        CleanupStack::PushL( me );
+        User::LeaveIfError( aAuthObjects.Append( me ) );
+        CleanupStack::Pop( me );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObjectList::CreateListL()
+// This function creates an internal array for authentication objects.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObjectList::CreateListL( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObjectList::CreateListL()" ) );
+
+    // Delete previous ones
+    TInt count = iAuthObjects.Count();
+
+    while ( count )
+        {
+        CWimAuthenticationObject* entry = iAuthObjects[count - 1];
+        entry->Release();
+        iAuthObjects.Remove( count - 1 );
+        count--;
+        }
+    
+   TInt ret = iToken.WimSecModule()->PinNrEntriesL( iPinNRs, aStatus );
+    
+    if ( ret != KErrNone )
+        {
+        User::Leave( ret );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObjectList::MakeAuthObjectL()
+// This function is called from two different places
+// -----------------------------------------------------------------------------
+//
+CWimAuthenticationObject* 
+     CWimAuthenticationObjectList::MakeAuthObjectL( CWimToken& aToken,
+                                                    CWimPin& aPinModule,
+                                                    const TDesC& aLabel,
+                                                    TUid aType,
+                                                    TUint32 aHandle,
+                                                    TUint32 aStatus )
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObjectList::MakeAuthObjectL()" ) );
+    CWimAuthenticationObject* me = 
+                   CWimAuthenticationObject::NewLC( aToken,
+                                                    aPinModule,
+                                                    aLabel,
+                                                    aType,
+                                                    aHandle,
+                                                    aStatus );
+    CleanupStack::Pop( me );
+    return me;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObjectList::CancelList()
+// Because List is synchronous, there is nothing to do here.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObjectList::CancelList()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObjectList::CancelList()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObjectList::TokenRemoved()
+// Returns true or false indicating if token is removed
+// -----------------------------------------------------------------------------
+//
+TBool CWimAuthenticationObjectList::TokenRemoved()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObjectList::TokenRemoved()" ) );
+    // If token listener is not alive, then token is removed
+    if ( iToken.TokenListener()->TokenStatus() != KRequestPending )
+        {
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObjectList::RunL()
+// -----------------------------------------------------------------------------
+//
+void CWimAuthenticationObjectList::RunL()
+    {
+    _WIMTRACE ( _L( "CWimAuthenticationObjectList::RunL()" ) );
+    switch ( iPhase )
+        {
+        case ECreateList:
+            {
+            iPhase = ECreateListDone;
+            iStatus = KRequestPending;
+            SetActive();
+            //iPinNRs is initialized here
+            CreateListL( iStatus ); 
+            break;	
+            }
+            
+        case ECreateListDone:
+            {
+            //Pin type is set here
+            
+            if ( iPinNRs ) // If PINs were found
+	           {
+	           TUid pintype = {WIM_PIN_G_UID}; // The first one is always PIN-G
+	           TInt count = iPinNRs->Count();
+	           TUint32 status = 0;
+
+	           for ( TInt i = 0; i < count; i++ )
+		           {
+		           CWimAuthenticationObject* me = 
+		                                MakeAuthObjectL( iToken, 
+		                                             *( *iPinNRs )[i],
+		                                              ( *iPinNRs )[i]->Label(),
+		                                                 pintype,
+		                                              ( *iPinNRs )[i]->PinNumber(),
+		                                                 status );
+		           CleanupStack::PushL( me );
+		           User::LeaveIfError ( iAuthObjects.Append( me ) );
+		           CleanupStack::Pop( me );
+		           pintype.iUid = WIM_PIN_NR_UID; // The others are always PIN-NR
+		           }
+	           }    
+            iPhase  = EDoList;  
+            iStatus = KRequestPending;
+            SetActive();
+            TRequestStatus* status = &iStatus;
+            User::RequestComplete( status, KErrNone );
+            break;         	
+            } 
+    	
+    	case EDoList:
+    	    {
+    	    _WIMTRACE ( _L( "CWimAuthenticationObjectList::RunL(): EDoList" ) );
+    	    DoListL( *iClientAuthObjects );
+			    User::RequestComplete( iClientStatus, KErrNone );  	
+			    break;
+    	    }
+    	    
+       default:
+            break;	
+         }
+    
+    }
+        
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObjectList::DoCancel()
+// -----------------------------------------------------------------------------
+//       
+void CWimAuthenticationObjectList::DoCancel()
+   {
+   _WIMTRACE ( _L( "CWimAuthenticationObjectList::DoCancel()" ) );	
+   User::RequestComplete( iClientStatus, KErrCancel );
+   }
+  
+// -----------------------------------------------------------------------------
+// CWimAuthenticationObjectList::RunError()
+// -----------------------------------------------------------------------------
+//  
+TInt CWimAuthenticationObjectList::RunError( TInt aError )    
+   {
+   _WIMTRACE ( _L( "CWimAuthenticationObjectList::RunError()" ) );	
+   User::RequestComplete( iClientStatus, aError );
+   return KErrNone;
+   }
+   
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/src/WimCertStore.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,2138 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of single certificate store interface
+*
+*/
+
+
+// INCLUDE FILES
+
+#include "WimCertStore.h"
+#include "WimCertConverter.h"
+#include "WimCertInfo.h"
+#include "WimTrustSettingsAPI.h"
+#include "WimTrace.h"
+#include "WimToken.h"
+#include "WimTokenListener.h"
+#include <unifiedkeystore.h>
+#include <ct.h>
+#include <x509cert.h>
+#include <x509certext.h>
+#include <wtlscert.h>
+#include <certificateapps.h>
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::CWimCertStore()
+// Default constructor
+// -----------------------------------------------------------------------------
+//
+CWimCertStore::CWimCertStore( CWimToken& aToken )
+                            : CActive( EPriorityNormal ),
+                              iToken( aToken )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::NewL()
+// Two-phased constructor
+// -----------------------------------------------------------------------------
+//
+CWimCertStore* CWimCertStore::NewL( CWimToken& aToken )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::NewL()" ) );
+    CWimCertStore* self = new( ELeave ) CWimCertStore( aToken );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::ConstructL()
+// Instantiates converter, completes message
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::ConstructL()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::ConstructL()" ) );
+    iCWimCertConverter = CWimCertConverter::NewL( Token() );
+    // Open trust settings database
+    iCWimTrustSettingsStore = CWimTrustSettingsAPI::NewL();
+    iPhase = EIdle;
+    iPhaseOriginal = EIdle;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::~CWimCertStore()
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CWimCertStore::~CWimCertStore()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::~CWimCertStore()" ) );
+    Cancel();
+    iKeyInfos.Close();
+    if ( iCerts )
+        {
+        delete iCerts;
+        }
+    iCertInfos.ResetAndDestroy();
+    iCertsList = NULL;
+    delete iUnifiedKeyStore;
+    if ( iCWimTrustSettingsStore )
+        {
+        iCWimTrustSettingsStore->Close();
+        }
+    iOriginalRequestStatus = NULL;
+    iFilter = NULL;
+    iEncodedCert = NULL;
+    if ( iCWimCertConverter )
+        {
+        delete iCWimCertConverter;
+        }
+
+    if ( iOldTrusters )
+        {
+        iOldTrusters->Close();
+        delete iOldTrusters;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::Token()
+// Returns a reference to current token (MCTToken) of this certificate store
+// interface. Reference is created during construction.
+// -----------------------------------------------------------------------------
+//
+MCTToken& CWimCertStore::Token()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::Token()" ) );
+    return iToken;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::DoRelease()
+// Deletes this interface on demand.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoRelease()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoRelease()" ) );
+    delete this;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::List()
+// Lists certificates according to filter parameter.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::List( RMPointerArray<CCTCertInfo>& aCertInfos,
+                          const CCertAttributeFilter& aFilter,
+                          TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::List()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    iCertsList = &aCertInfos;
+    iFilter = &aFilter;
+
+    if ( iFilter->iKeyUsage != EX509UsageAll )
+        {
+        // We must ensure that in this case only user certs are allowed
+        if ( iFilter->iOwnerTypeIsSet &&
+             iFilter->iOwnerType == EUserCertificate )
+            {
+            // We have to initialize the unified key store because
+            // in this phase we don't know if user certificates are found or not.
+            // User certificate private key must be checked for usage reason
+            if ( iUnifiedKeyStore )
+                {
+                User::RequestComplete( iOriginalRequestStatus, KErrCorrupt );
+                }
+            else
+                {
+                iFs = static_cast<CCTTokenType&>( Token().TokenType() ).Fs();
+                TRAPD( err, iUnifiedKeyStore = CUnifiedKeyStore::NewL( iFs ) );
+
+                if ( err != KErrNone )
+                    {
+                    User::RequestComplete( iOriginalRequestStatus, err );
+                    }
+                else
+                    {
+                    iPhase = EGetKeyInfos;
+                    iUnifiedKeyStore->Initialize( iStatus );
+                    SetActive();
+                    }
+                }
+            }
+        else
+            {
+            User::RequestComplete( iOriginalRequestStatus, KErrArgument );
+            }
+        }
+    else
+        {
+        iPhase = EList;
+        iPhaseOriginal = EList;
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        SetActive();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::CancelList()
+// Cancels issued List operation. Main functionality in DoCancel().
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::CancelList()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::CancelList()" ) );
+    if ( TokenRemoved() )
+        {
+        return;
+        }
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::GetCert()
+// Fetches one certificate info according to given handle.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::GetCert( CCTCertInfo*& aCertInfo,
+                             const TCTTokenObjectHandle& aHandle,
+                             TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::GetCert()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    if ( aHandle.iTokenHandle != Token().Handle() )
+        {
+        User::RequestComplete( iOriginalRequestStatus, KErrBadHandle );
+        }
+    else
+        {
+        iCertInfo = &aCertInfo;
+        iHandle = &aHandle;
+        iPhase = EGetCert;
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        SetActive();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::DoGetCert()
+// Fetches one certificate
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoGetCert()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoGetCert()" ) );
+
+    TInt err = KErrNotFound;
+    TRAP( err, *iCertInfo =
+            CCTCertInfo::NewL( iCerts->EntryByHandleL ( iHandle->iObjectId ) ) );
+    User::RequestComplete( iOriginalRequestStatus, err );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::CancelGetCert()
+// Cancels issued GetCert operation. Main functionality in DoCancel().
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::CancelGetCert()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::CancelGetCert()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::Applications()
+// Lists the applications of a certificate. Applications are represented by UIDs
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::Applications( const CCTCertInfo& aCertInfo,
+                                  RArray<TUid>& aApplications,
+                                  TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::Applications()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    iCertInfoReadOnly = &aCertInfo;
+    iApplications = &aApplications;
+    iPhase = EApplications;
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::DoApplications()
+// Fetch all certificate's applications
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoApplications()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoApplications()" ) );
+
+    TInt err = KErrNone;
+    TInt index = iCerts->Index( *iCertInfoReadOnly );
+
+    if ( index != KErrNotFound )
+        {
+        const RArray<TUid>& apps = iCerts->Mapping( index )->CertificateApps();
+        TInt end = apps.Count();
+        for ( TInt i = 0; ( i < end ) && ( err == KErrNone ); i++ )
+            {
+            err = iApplications->Append( apps[i] );
+            }
+        }
+    else
+        {
+        err = index;
+        }
+
+    if ( err != KErrNone )
+        {
+        iApplications->Reset();
+        }
+    User::RequestComplete( iOriginalRequestStatus, err );
+    }
+// -----------------------------------------------------------------------------
+// CWimCertStore::CancelApplications()
+// Cancels issued Applications operation. Main functionality in DoCancel().
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::CancelApplications()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::CancelApplications()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::IsApplicable()
+// Checks if a particular certificate is applicable to a particular application.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::IsApplicable( const CCTCertInfo& aCertInfo,
+                                  TUid aApplication,
+                                  TBool& aIsApplicable,
+                                  TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::IsApplicable()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    iCertInfoReadOnly = &aCertInfo;
+    iApplication = aApplication;
+    iIsApplicable = &aIsApplicable;
+    iPhase = EIsApplicable;
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::DoIsApplicable()
+// Match given application to certificate's application
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoIsApplicable()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoIsApplicable()" ) );
+
+    TInt index = iCerts->Index( *iCertInfoReadOnly );
+    if ( index != KErrNotFound )
+        {
+        const RArray<TUid>& apps = iCerts->Mapping( index )->CertificateApps();
+        TInt end = apps.Count();
+        TInt i = 0;
+        for ( ; i < end; i++ )
+            {
+            if ( apps[i] == iApplication )
+                {
+                i = end + 1; // This completes loop but differentiates from
+                             // normal end condition
+                }
+            }
+        if ( i == end )
+            {
+            *iIsApplicable = EFalse;
+            }
+        else
+            {
+            *iIsApplicable = ETrue;
+            }
+        index = KErrNone;
+        }
+    User::RequestComplete( iOriginalRequestStatus, index );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::CancelIsApplicable()
+// Cancels issued IsApplicable operation. Main functionality in DoCancel().
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::CancelIsApplicable()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::CancelIsApplicable()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::Trusted()
+// Returns a parameter with true or false, if a certificate is trusted.
+// Trust is only meaningful for CA certificates where it means that the
+// certificate can be used as a trust root for the purposes
+// of certificate validation.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::Trusted( const CCTCertInfo& aCertInfo,
+                             TBool& aTrusted,
+                             TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::Trusted()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    iCertInfoReadOnly = &aCertInfo;
+    iTrustedCert = &aTrusted;
+    iPhase = ETrusted;
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::DoTrusted()
+// 
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoTrusted()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoTrusted()" ) );
+
+    TInt index = iCerts->Index( *iCertInfoReadOnly );
+    if ( index != KErrNotFound )
+        {
+        *iTrustedCert = iCerts->Mapping( index )->Trusted();
+        index = KErrNone;
+        }
+
+    User::RequestComplete( iOriginalRequestStatus, index );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::CancelTrusted()
+// Cancels issued Trusted operation. Main functionality in DoCancel().
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::CancelTrusted()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::CancelTrusted()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::Retrieve()
+// Retrieves all the data of the certificate.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::Retrieve( const CCTCertInfo& aCertInfo,
+                              TDes8& aEncodedCert,
+                              TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::Retrieve()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    iCertInfoReadOnly = &aCertInfo;
+    iEncodedCert = &aEncodedCert;
+    iPhase = ERetrieve;
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::DoRetrieve()
+// Retrieves all the data of the certificate.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoRetrieve()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoRetrieve()" ) );
+
+    // Let's get the index of certificate info
+    // Index used as handle in WimClient in order to locate this certificate
+    iCertIndex = iCerts->Index( *iCertInfoReadOnly );
+
+    if ( iCertIndex == KErrNotFound )
+        {
+        User::RequestComplete( iOriginalRequestStatus, KErrNotFound );
+        }
+    else
+        {
+        iPhase = ERetrieveFromWim;
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        SetActive();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::CancelRetrieve()
+// Cancels issued Retrieve operation and informs converter to stop.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::CancelRetrieve()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::CancelRetrieve()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::Add()
+// Adds a certificate to the WIM store.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::Add( const TDesC& aLabel,
+                         TCertificateFormat aFormat,
+                         TCertificateOwnerType aCertificateOwnerType,
+                         const TKeyIdentifier* aSubjectKeyId,
+                         const TKeyIdentifier* aIssuerKeyId,
+                         const TDesC8& aCert,
+                         TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::Add()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    // Label must be
+    if ( aLabel.Length() == 0 )
+        {
+        User::RequestComplete( iOriginalRequestStatus, KErrArgument );
+        return;
+        }
+
+    switch ( aCertificateOwnerType )
+        {
+        case ECACertificate:
+            {
+            break;
+            }
+        case EUserCertificate:
+            {
+            break;
+            }
+        case EPeerCertificate:
+            {
+            break;
+            }
+        default:
+            {
+            User::RequestComplete( iOriginalRequestStatus, KErrArgument );
+            return;
+            }
+        }
+
+    iKeyFilter.iKeyId = KNullDesC8;
+    iKeyFilter.iUsage = ( TKeyUsagePKCS15 )0;
+    iLabel = &aLabel;
+    iFormat = aFormat;
+    iCertificateOwnerType = aCertificateOwnerType;
+
+    if ( aSubjectKeyId && ( *aSubjectKeyId != KNullDesC8 ) )
+        {
+        iSubjectKeyId = aSubjectKeyId;
+        }
+    else
+        {
+        iSubjectKeyId = 0;
+        }
+
+    iIssuerKeyId = aIssuerKeyId;
+    iCert = &aCert;
+
+    TRAPD( err, ComputeAndCheckSubjectKeyIdL() );
+
+    if ( err != KErrNone )
+        {
+        User::RequestComplete( iOriginalRequestStatus, err );
+        return;
+        }
+
+    if ( aCertificateOwnerType == EUserCertificate )
+        {
+        if ( iUnifiedKeyStore ) // Should never happen
+            {
+            User::RequestComplete( iOriginalRequestStatus, KErrCorrupt );
+            }
+        else
+            {
+            iFs = static_cast<CCTTokenType&>( Token().TokenType() ).Fs();
+
+            TRAPD( err2, iUnifiedKeyStore = CUnifiedKeyStore::NewL( iFs ) );
+            if ( err2 != KErrNone )
+                {
+                User::RequestComplete( iOriginalRequestStatus, err2 );
+                }
+            else
+                {
+                iPhase = EGetCorrespondingPrivateKey;
+                iUnifiedKeyStore->Initialize( iStatus );
+                SetActive();
+                }
+            }
+        }
+    else
+        {
+        iPhase = EAdd;
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        SetActive();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoAdd()
+// Adds a certificate to the WIM store.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoAdd()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoAdd()" ) );
+
+    // Check that certificate label don't already exist
+    TInt iend = iCerts->Count();
+    for ( TInt i = 0; i < iend; i++ )
+        {
+        if ( iCerts->Entry( i ).Label() == *iLabel )
+            {
+            User::RequestComplete( iOriginalRequestStatus, KErrBadName );
+            return;
+            }
+        }
+    iPhase = EAddToWim;
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::ComputeAndCheckSubjectKeyIdL()
+// Computes subject key id
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::ComputeAndCheckSubjectKeyIdL()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::ComputeAndCheckSubjectKeyIdL()" ) );
+    switch ( iFormat )
+        {
+        case EX509Certificate:
+            {
+            CX509Certificate* cert = CX509Certificate::NewLC( *iCert );
+            const CX509CertExtension* ext = cert->Extension( KKeyUsage );
+            if ( ext )
+                {
+                CX509KeyUsageExt* keyUsageExt =
+                                  CX509KeyUsageExt::NewLC( ext->Data() );
+                if ( keyUsageExt->IsSet( EX509DigitalSignature ) )
+                    {
+                    iKeyFilter.iUsage =
+                        ( TKeyUsagePKCS15 )
+                        ( iKeyFilter.iUsage | EX509UsageDigitalSignature );
+                    }
+                if ( keyUsageExt->IsSet( EX509NonRepudiation ) )
+                    {
+                    iKeyFilter.iUsage =
+                        ( TKeyUsagePKCS15 )
+                        ( iKeyFilter.iUsage | EX509UsageNonRepudiation );
+                    }
+                if ( keyUsageExt->IsSet( EX509KeyEncipherment ) )
+                    {
+                    iKeyFilter.iUsage =
+                        ( TKeyUsagePKCS15 )
+                        ( iKeyFilter.iUsage | EX509UsageKeyEncipherment );
+                    }
+                if ( keyUsageExt->IsSet( EX509DataEncipherment ) )
+                    {
+                    iKeyFilter.iUsage =
+                        ( TKeyUsagePKCS15 )
+                        ( iKeyFilter.iUsage | EX509UsageDataEncipherment );
+                    }
+                if ( keyUsageExt->IsSet( EX509KeyAgreement ) )
+                    {
+                    iKeyFilter.iUsage =
+                        ( TKeyUsagePKCS15 )
+                        ( iKeyFilter.iUsage | EX509UsageKeyAgreement );
+                    }
+                if ( keyUsageExt->IsSet( EX509KeyCertSign ) )
+                    {
+                    iKeyFilter.iUsage =
+                        ( TKeyUsagePKCS15 )
+                        ( iKeyFilter.iUsage | EX509UsageKeyCertSign );
+                    }
+                if ( keyUsageExt->IsSet( EX509CRLSign ) )
+                    {
+                    iKeyFilter.iUsage =
+                        ( TKeyUsagePKCS15 )
+                        ( iKeyFilter.iUsage | EX509UsageCRLSign );
+                    }
+                if ( keyUsageExt->IsSet( EX509EncipherOnly ) )
+                    {
+                    iKeyFilter.iUsage =
+                        ( TKeyUsagePKCS15 )
+                        ( iKeyFilter.iUsage | EX509UsageEncipherOnly );
+                    }
+                if ( keyUsageExt->IsSet( EX509DecipherOnly ) )
+                    {
+                    iKeyFilter.iUsage =
+                        ( TKeyUsagePKCS15 )
+                        ( iKeyFilter.iUsage | EX509UsageDecipherOnly );
+                    }
+
+                CleanupStack::PopAndDestroy( keyUsageExt );
+                }
+            iComputedSubjectKeyId = cert->KeyIdentifierL();
+            if ( !iSubjectKeyId )
+                {
+                iSubjectKeyId = &iComputedSubjectKeyId;
+                }
+            else if ( iComputedSubjectKeyId.Compare( *iSubjectKeyId ) )
+                {
+                User::Leave( KErrArgument );
+                }
+            CleanupStack::PopAndDestroy( cert );
+            break;
+            }
+        case EWTLSCertificate:
+            {
+            CCertificate* cert = CWTLSCertificate::NewLC( *iCert );
+            iComputedSubjectKeyId = cert->KeyIdentifierL();
+            if ( !iSubjectKeyId )
+                {
+                iSubjectKeyId = &iComputedSubjectKeyId;
+                }
+            else if ( iComputedSubjectKeyId.Compare( *iSubjectKeyId ) )
+                {
+                User::Leave( KErrArgument );
+                }
+            CleanupStack::PopAndDestroy( cert );
+            break;
+            }
+        case EX509CertificateUrl:
+            {
+            iKeyFilter.iUsage = EPKCS15UsageAll;
+            if ( !iSubjectKeyId )
+                {
+                User::Leave( KErrArgument );
+                }
+            break;
+            }
+        default:
+            {
+            User::Leave( KErrNotSupported );
+            break;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::CancelAdd()
+// Cancels issued Add operation and informs converter to stop.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::CancelAdd()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::CancelAdd()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::Remove()
+// Removes a certificate from WIM store
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::Remove( const CCTCertInfo& aCertInfo,
+                                     TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::Remove()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    iCertInfoReadOnly = &aCertInfo;
+    iPhase = ERemove;
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::DoRemove()
+// Removes a certificate from WIM store
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoRemove()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoRemove()" ) );
+
+    TInt index = iCerts->Index( *iCertInfoReadOnly );
+    // Check that given certificate info exists
+    if ( index == KErrNotFound )
+        {
+        User::RequestComplete( iOriginalRequestStatus, KErrNotFound );
+        return;
+        }
+
+    CWimCertStoreMapping* mapping = iCerts->Mapping( index );
+
+    if ( !mapping )
+        {
+        User::RequestComplete( iOriginalRequestStatus, KErrNotFound );
+        return;
+        }
+
+    // Is certificate deletable?
+
+    const CCTCertInfo& certInfo = iCerts->Entry( index );
+
+    if ( !certInfo.IsDeletable() )
+        {
+        User::RequestComplete( iOriginalRequestStatus, KErrAccessDenied );
+        return;
+        }
+
+    // This index is used in the next phase when deleting certificate from Wim
+    iCertIndex = index;
+    iPhase = EDeleteFromWim;
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::CancelRemove()
+// Cancels ongoing certificate removal.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::CancelRemove()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::CancelRemove()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::SetApplicability()
+// Replaces the current applicability settings with the settings
+// in the supplied array.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::SetApplicability( const CCTCertInfo& aCertInfo,
+#ifdef __SECURITY_PLATSEC_ARCH__
+                                      const RArray<TUid>& aTrusters,
+#else
+                                      RArray<TUid>* aTrusters,
+#endif
+                                      TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::SetApplicability()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    TRAPD( err, CheckApplicabilityL( aTrusters ) );
+
+    if ( err == KErrNone )
+        {
+        iCertInfoReadOnly = &aCertInfo;
+
+#ifdef __SECURITY_PLATSEC_ARCH__
+        iApplications = new RArray<TUid>;
+        if ( iApplications )
+            {
+            for ( TInt i = 0; i < aTrusters.Count(); i++ )
+                {
+                iApplications->Append( aTrusters[i] );
+                }
+            }
+        else
+            {
+            User::RequestComplete( iOriginalRequestStatus, KErrNoMemory );
+            }
+#else
+        iApplications = aTrusters;
+#endif
+
+        iPhase = ESetApplicability;
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        SetActive();
+        }
+    else
+        {
+        User::RequestComplete( iOriginalRequestStatus, err );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoSetApplicability()
+// Replaces the current applicability settings with the settings
+// in the supplied array.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoSetApplicability()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoSetApplicability()" ) );
+
+    TRAPD( err, DoSetApplicabilityL() );
+    if ( err != KErrNone )
+        {
+#ifdef __SECURITY_PLATSEC_ARCH__
+        iApplications->Close();
+        delete iApplications;
+        iApplications = NULL;
+#endif
+        User::RequestComplete( iOriginalRequestStatus, err );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::CheckApplicabilityL()
+// Check that given applications exist
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::CheckApplicabilityL(
+#ifdef __SECURITY_PLATSEC_ARCH__
+    const RArray<TUid>& aTrusters
+#else
+    RArray<TUid>* aTrusters
+#endif
+    )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::CheckApplicabilityL()" ) );
+
+#ifndef __SECURITY_PLATSEC_ARCH__
+    TCleanupItem cleanupTrusters( CWimCertStore::CleanTrustersArray, aTrusters );
+    CleanupStack::PushL( cleanupTrusters );
+#endif
+    // Let's fetch application infos from file this device supports
+    iFs = static_cast<CCTTokenType&>( Token().TokenType() ).Fs();
+    CCertificateAppInfoManager* appInfoManager =
+                                CCertificateAppInfoManager::NewLC( iFs, EFalse );
+    // Take references to those application infos
+    const RArray<TCertificateAppInfo>& applications =
+                                       appInfoManager->Applications();
+    // Chcek that given new applications exists in supported applications
+#ifdef __SECURITY_PLATSEC_ARCH__
+    TInt count1 = aTrusters.Count();
+#else
+    TInt count1 = aTrusters->Count();
+#endif
+
+    TInt count2 = applications.Count();
+    TInt i = 0;
+    for ( ; i < count1; i++ )
+        {
+        TInt j = 0;
+        for ( ; j < count2; j++ )
+            {
+#ifdef __SECURITY_PLATSEC_ARCH__
+            if ( aTrusters[i] == applications[j].Id() ) // Match found
+#else
+            if ( ( *aTrusters)[i] == applications[j].Id() ) // Match found
+#endif
+
+                {
+                j = count2 + 1; // This stops loop but differentiates from
+                                // normal end ( j == count2 )
+                }
+            }
+        if ( j == count2 )      // Some of the given application does not exist
+            {
+            User::Leave( KErrArgument );
+            }
+        }
+
+    // Application info not needed anymore
+    CleanupStack::PopAndDestroy( appInfoManager );
+#ifndef __SECURITY_PLATSEC_ARCH__
+    CleanupStack::Pop();
+#endif
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::CleanTrustersArray()
+// Deletes array of trusters.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::CleanTrustersArray( TAny* aTrusters )
+    {
+    RArray<TUid>* array = reinterpret_cast< RArray<TUid>* >( aTrusters );
+    array->Close();
+    delete array;
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoSetApplicabilityL()
+// Replaces the current applicability settings with the settings
+// in the supplied array.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoSetApplicabilityL()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoSetApplicabilityL()" ) );
+
+    TCleanupItem cleanupTrusters( CWimCertStore::CleanTrustersArray, iApplications );
+    CleanupStack::PushL( cleanupTrusters );
+
+    // Check that given certificate info exists
+    TInt index = iCerts->Index( *iCertInfoReadOnly );
+    if ( index == KErrNotFound )
+        {
+        User::Leave( index );
+        }
+
+    // The idea behind next operation is to keep old applications in safe
+    // until they are succesfully replaced with given new applications
+
+    // Take a pointer to mapping
+    CWimCertStoreMapping* mapping = iCerts->Mapping( index );
+    // Check that mapping is found
+    if ( !mapping )
+        {
+        User::Leave( KErrNotFound );
+        }
+    // Take a reference to old applications
+    const RArray<TUid>& trusters = mapping->CertificateApps();
+        
+    // Copy old applications to recently created new pointer array
+    if ( iOldTrusters )
+        {
+        // There can be old trusters if next leaving function has leaved
+        // last time
+        iOldTrusters->Close();
+        delete iOldTrusters;
+        iOldTrusters = NULL;
+        }
+
+    iOldTrusters = new( ELeave ) RArray<TUid>;
+    TInt end = trusters.Count();
+    for ( TInt i = 0; i < end; i++ )
+        {
+        User::LeaveIfError( iOldTrusters->Append( trusters[i] ) );
+        }
+    // Set new applications to mapping. This replaces old ones
+    mapping->SetCertificateAppsL( iApplications );
+
+    // In this phase old applications are in oldTrusted
+    // and new applications are in mapping
+    // Now we must update TrustSettingStore to make applications permanent
+    iStatus = KRequestPending;
+    iPhase = EWaitSetApplicability;
+    iCWimTrustSettingsStore->SetApplicability( *iCertInfos[index],
+                                               *iApplications,
+                                                iStatus );
+    SetActive();
+ 
+    CleanupStack::Pop();
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::CancelSetApplicability()
+// Cancels an ongoing operation. The operation will be
+// completed with KErrCancel if it was cancelled
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::CancelSetApplicability()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::CancelSetApplicability()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::SetTrust()
+// Changes the trust settings. A CA certificate is trusted if the
+// user is willing to use it for authenticating servers. It has no
+// meaning with other types of certificates.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::SetTrust( const CCTCertInfo& aCertInfo,
+                              TBool aTrusted,
+                              TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::SetTrust()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    switch ( aTrusted )
+        {
+        case EFalse:
+            {
+            break;
+            }
+        case ETrue:
+            {
+            break;
+            }
+        default:
+            {
+            User::RequestComplete( iOriginalRequestStatus, KErrArgument );
+            return;
+            }
+        }
+
+    iCertInfoReadOnly = &aCertInfo;
+    iTrustedValue = aTrusted;
+    iPhase = ESetTrust;
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoSetTrust()
+// Changes the trust settings.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoSetTrust()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoSetTrust()" ) );
+    TRAPD( err, DoSetTrustL() );
+    
+    if ( err != KErrNone )
+        {
+        User::RequestComplete( iOriginalRequestStatus, err );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoSetTrustL()
+// Changes the trust settings.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoSetTrustL()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoSetTrustL()" ) );
+    // Check that given certificate info exists
+    TInt index = iCerts->Index( *iCertInfoReadOnly );
+    if ( index == KErrNotFound )
+        {
+        User::Leave( index );
+        }
+
+    CWimCertStoreMapping* mapping = iCerts->Mapping( index );
+    // Check that mapping is found
+    if ( !mapping )
+        {
+        User::Leave( KErrNotFound );
+        }
+    // Save old trust value for back up reason
+    iOldTrusted = mapping->Trusted();
+    // Set new trust value
+    const_cast<CWimCertStoreMapping*>( mapping )->SetTrusted( iTrusted );
+    // In this phase old trust value is in iOldTrusted
+    // and new value is in mapping
+    // Now we must update TrustSettingStore to make trust value permanent
+    iPhase = EWaitSetTrust;
+    iStatus = KRequestPending;
+    iCWimTrustSettingsStore->SetTrust( *iCertInfos[index],
+                                        iTrusted,
+                                        iStatus );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::CancelSetTrust()
+// Cancels an ongoing SetTrust operation.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::CancelSetTrust()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::CancelSetTrust()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::RunL()
+// The first thing is to ensure that certificates are read from WIM
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::RunL()
+    {
+    _WIMTRACE3( _L( "CWimCertStore::RunL()| iStatus=%d, iPhase=%d" ), iStatus.Int(), iPhase );
+    if ( !iCerts &&
+         iPhase != EList &&
+         iPhase != EInitializeGetCertList &&
+         iPhase != EInitializeLoadMappings &&
+         iPhase != EGetKeyInfos )
+        {
+        iPhaseOriginal = iPhase;
+        iPhase = EList;
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        SetActive();
+        }
+    else
+        {
+        switch ( iPhase )
+        {
+            case EInitializeGetCertList:
+                {
+                DoInitializeGetCertListL();
+                break;
+                }
+            case EInitializeLoadMappings:
+                {
+                DoInitializeLoadMappingsL();
+                break;
+                }
+            case EInitializeLoadTrustSettingsStart:
+                {
+                DoInitializeLoadTrustSettingsStartL();
+                break;
+                }
+            case EInitializeLoadTrustSettingsWait:
+                {
+                DoInitializeLoadTrustSettingsWaitL();
+                break;
+                }
+            case EGetKeyInfos:
+                {
+                DoGetKeyInfos();
+                break;
+                }
+            case EList:
+                {
+                DoList();
+                break;
+                }
+            case EListGo:
+                {
+                DoListGoL();
+                break;
+                }
+            case EGetCert:
+                {
+                DoGetCert();
+                break;
+                }
+            case EApplications:
+                {
+                DoApplications();
+                break;
+                }
+            case EIsApplicable:
+                {
+                DoIsApplicable();
+                break;
+                }
+            case ETrusted:
+                {
+                DoTrusted();
+                break;
+                }
+            case ESetApplicability:
+                {
+                DoSetApplicability();
+                break;
+                }
+            case EWaitSetApplicability:
+                {
+                // If there is an error undo the change
+                if ( iStatus.Int() != KErrNone ) 
+                    {
+                    TInt index = iCerts->Index( *iCertInfoReadOnly );
+                    // Take a pointer to mapping
+                    CWimCertStoreMapping* mapping = iCerts->Mapping( index );
+                    // Set backed up trusters to mapping
+                    mapping->SetCertificateAppsL( iOldTrusters );
+                    iOldTrusters = NULL; // Ownership moved to mapping
+                    }
+                else // Delete old trusters array, it is not needed anymore
+                    {
+                    iOldTrusters->Close();
+                    delete iOldTrusters;
+                    iOldTrusters = NULL;
+                    }
+                User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+                break;
+                }
+            case ESetTrust:
+                {
+                DoSetTrust();
+                break;
+                }
+            case EWaitSetTrust:
+                {
+                if ( iStatus.Int() != KErrNone )
+                    {
+                    // Couldn't add changes to file, so restore old settings
+                    TInt index = iCerts->Index( *iCertInfoReadOnly );
+                    CWimCertStoreMapping* mapping = iCerts->Mapping( index );
+                    mapping->SetTrusted( iOldTrusted );
+                    }
+                User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+                break;
+                }
+            case ERetrieve:
+                {
+                DoRetrieve();
+                break;
+                }
+            case ERetrieveFromWim:
+                {
+                iPhase = ERetrieveWait;
+                iCWimCertConverter->RetrieveCertByIndexL( iCertIndex,
+                                                        *iEncodedCert,
+                                                         iStatus );
+                SetActive();
+                break;
+                }
+            case ERetrieveWait:
+                {
+                iPhase = EIdle;
+                User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+                break;
+                }
+            case EGetCorrespondingPrivateKey:
+                {
+                if ( iStatus.Int() == KErrNone )
+                    {
+                    iKeyFilter.iKeyId = *iSubjectKeyId;
+                    iUnifiedKeyStore->List( iKeyInfos, iKeyFilter, iStatus );
+                    iPhase = ECheckCorrespondingPrivateKey;
+                    SetActive();
+                    }
+                else
+                    {
+                    iPhase = EIdle;
+                    User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+                    }
+                break;
+                }
+            case ECheckCorrespondingPrivateKey:
+                {
+                DoCheckCorrespondingPrivateKey();
+                break;
+                }
+            case EAdd:
+                {
+                DoAdd();
+                break;
+                }
+            case EAddToWim:
+                {
+                iPhase = ECheckAddToWim;
+                // Update last Wim cache
+                iCWimCertConverter->AddCertificate ( *iLabel,
+                                                  iFormat,
+                                                  iCertificateOwnerType,
+                                                 *iSubjectKeyId,
+                                                 *iIssuerKeyId,
+                                                 *iCert,
+                                                  iStatus );
+                SetActive();
+                break;
+                }
+            case ECheckAddToWim:
+                {
+                if ( iStatus.Int() == KErrNone )
+                    {
+                    iPhase = EList;
+                    iPhaseOriginal = ECompleteMessage;
+                    TRequestStatus* status = &iStatus;
+                    User::RequestComplete( status, KErrNone );
+                    SetActive();
+                    }
+                else
+                    {
+                    iPhase = EIdle;
+                    User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+                    }
+                break;
+                }
+            case ERemove:
+                {
+                DoRemove();
+                break;
+                }
+            case EDeleteFromWim:
+                {
+                iPhase = ECheckDeleteFromWim;
+                // Update Wim cache
+                iCWimCertConverter->RemoveL( iCertIndex, iStatus );
+                SetActive();
+                break;
+                }
+            case ECheckDeleteFromWim:
+                {
+                DoCheckDeleteFromWim();
+                break;
+                }
+            case EWaitRemoveTrustSettings:
+                {
+                if ( iStatus.Int() == KErrNone )
+                    {
+                    iPhase = EList;
+                    iPhaseOriginal = ECompleteMessage;
+                    TRequestStatus* status = &iStatus;
+                    User::RequestComplete( status, KErrNone );
+                    SetActive();
+                    }
+                else
+                    {
+                    iPhase = EIdle;
+                    User::RequestComplete( iOriginalRequestStatus,
+                                           iStatus.Int() );
+                    }
+                break;
+                }
+            case ECompleteMessage:
+                {
+                iPhase = EIdle;
+                User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+                break;
+                }
+            default:
+                {
+                // Here we should not be
+                User::RequestComplete( iOriginalRequestStatus, KErrCorrupt );
+                break;
+                }
+            } // switch
+        } // if
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoInitializeGetCertListL()
+// Certificates are fetched from Wim
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoInitializeGetCertListL()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoInitializeGetCertListL()" ) );
+    iCertInfos.ResetAndDestroy();
+    if ( iCWimCertConverter )
+        {
+        delete iCWimCertConverter;
+        iCWimCertConverter = NULL;
+        }
+    iCWimCertConverter = CWimCertConverter::NewL( Token() );
+    iStatus = KRequestPending;
+    // Call converter to fetch certificate infos from Wim
+    iPhase = EInitializeLoadMappings;
+    iCWimCertConverter->Restore( iCertInfos, iStatus );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoInitializeLoadMappingsL()
+// Load certificates into mappings
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoInitializeLoadMappingsL()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoInitializeLoadMappingsL()" ) );
+     if ( iStatus.Int() == KErrNone || iStatus.Int() == KErrNotFound )
+        {
+        // Load certificate infos into mappings
+        LoadMappingsL();
+        iCertIndex = 0;
+        if ( iCertInfos.Count() > 0 )
+            {
+            iPhase = EInitializeLoadTrustSettingsStart;
+            }
+        else
+            {
+            iPhase = EListGo;
+            }
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        SetActive();
+        }
+     else // Something went wrong with Restore or Cancel call was issued
+        {
+        FreeUnifiedKeyStore();
+        iPhase = EIdle;
+        User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+        }
+    }
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoInitializeLoadTrustSettingsStartL()
+// Fetch trust settings for a certificate
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoInitializeLoadTrustSettingsStartL()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoInitializeLoadTrustSettingsStartL()" ) );
+    switch ( iStatus.Int() )
+        {
+        case KErrNone:
+            {
+            // Application array is created here
+            // Ownership is transferred to CWimCertStoreMapping class
+            iCertificateApps = new( ELeave ) RArray<TUid>();
+            iStatus = KRequestPending;
+            iCWimTrustSettingsStore->
+               GetTrustSettings( *iCertInfos[iCertIndex],
+                                  iTrusted,
+                                 *iCertificateApps,
+                                  iStatus );
+            iPhase = EInitializeLoadTrustSettingsWait;
+            SetActive();
+            break;
+            }
+        case KErrArgument:
+            {
+            // Certificate data was corrupted. Skip default trustsettings.
+            if ( iCertIndex < iCerts->Count() - 1 )
+                {
+                iCertIndex++;
+                iPhase = EInitializeLoadTrustSettingsStart;
+                }
+            else
+                {
+                iCertIndex = 0;
+                iPhase = EListGo;
+                }
+            TRequestStatus* status = &iStatus;
+            User::RequestComplete( status, KErrNone );
+            SetActive();
+            break;
+            }
+        default:
+            {
+            FreeUnifiedKeyStore();
+            iPhase = EIdle;
+            User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoInitializeLoadTrustSettingsWaitL()
+// Check if trust settings were found, if not, do them and assign to mappings
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoInitializeLoadTrustSettingsWaitL()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoInitializeLoadTrustSettingsWaitL()" ) );
+    switch ( iStatus.Int() )
+        {
+        case KErrNone:
+            {
+            // Parameters are fetched from trust store
+            // and assigned into mapping
+            SetTrustSettingsOnMappingL( iTrusted,
+                                        iCertificateApps );
+            if ( iCertIndex < iCerts->Count() - 1 )
+                {
+                iCertIndex++;
+                iPhase = EInitializeLoadTrustSettingsStart;
+                }
+            else
+                {
+                iCertIndex = 0;
+                iPhase = EListGo;
+                }
+            TRequestStatus* status = &iStatus;
+            User::RequestComplete( status, KErrNone );
+            SetActive();
+            break;
+            }
+        case KErrNotFound: // Trust settings not found; let's do
+            {
+            iStatus = KRequestPending;
+            iCWimTrustSettingsStore->SetDefaultTrustSettings( 
+                                                        *iCertInfos[iCertIndex],
+                                                        ETrue,
+                                                        iStatus );
+            iPhase = EInitializeLoadTrustSettingsStart;
+
+            // Nobody is taking ownership of these so delete them
+            if ( iCertificateApps )
+                {
+                iCertificateApps->Close();
+                delete iCertificateApps;
+                iCertificateApps = NULL;
+                }
+
+            SetActive();
+            break;
+            }
+        default: // Something went wrong with GetTrustSettings
+                // or Cancel call was issued
+            {
+            // Nobody is taking ownership of these so delete them
+            if ( iCertificateApps )
+                {
+                iCertificateApps->Close();
+                delete iCertificateApps;
+                iCertificateApps = NULL;
+                }
+
+            FreeUnifiedKeyStore();
+            iPhase = EIdle;
+            User::RequestComplete( iOriginalRequestStatus,
+                                   iStatus.Int() );
+            break;
+            }
+        } // switch
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoGetKeyInfos()
+// Fetch keys from keystores
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoGetKeyInfos()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoGetKeyInfos()" ) );
+    if ( iStatus.Int() == KErrNone )
+        {
+        // In this phase key info count must allways be zero
+        if ( iKeyInfos.Count() == 0 )
+            {
+            iCertIndex = 0;
+            iKeyFilter.iKeyId = KNullDesC8;
+            iKeyFilter.iUsage =
+                KeyUsageX509ToPKCS15Private( iFilter->iKeyUsage );
+            iPhase = EList;
+            iPhaseOriginal = EList;
+            iUnifiedKeyStore->List( iKeyInfos, iKeyFilter, iStatus );
+            SetActive();
+            }
+        else
+            {
+            FreeUnifiedKeyStore();
+            iPhase = EIdle;
+            User::RequestComplete( iOriginalRequestStatus, KErrCorrupt );
+            }
+        }
+    else // Something went wrong (or call was cancelled) with
+         // iUnifiedKeyStore->Initialize( iStatus )
+        {
+        FreeUnifiedKeyStore();
+        iPhase = EIdle;
+        User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoList()
+// Start listing certificates
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoList()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoList()" ) );
+    if ( iStatus.Int() == KErrNone )
+        {
+        iCertIndex = 0;
+        iPhase = EInitializeGetCertList;
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        SetActive();
+        }
+    else // iUnifiedKeyStore->List call has been cancelled or failed
+        {
+        FreeUnifiedKeyStore();
+        iPhase = EIdle;
+        User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoListGoL()
+// In this phase all certificates are fetched from Wim.
+// Serve the original request.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoListGoL()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoListGoL()" ) );
+    if ( iPhaseOriginal == EList )
+        {
+        if ( iCertIndex < ( iCerts->Count() ) )
+            {
+            const CCTCertInfo& certInfo = iCerts->Entry( iCertIndex );
+            TBool accept = ETrue;
+            if ( iFilter->iUidIsSet )
+                {
+                accept = iCerts->Mapping( iCertIndex )->
+                                 IsApplicable( iFilter->iUid );
+                }
+            if ( iFilter->iFormatIsSet && accept )
+                {
+                accept = ( iFilter->iFormat == certInfo.CertificateFormat() );
+                }
+            if ( iFilter->iOwnerTypeIsSet && accept )
+                {
+                accept = ( iFilter->iOwnerType == certInfo.CertificateOwnerType() );
+                }
+            if ( ( iFilter->iSubjectKeyId != KNullDesC8 ) && accept )
+                {
+                accept = ( iFilter->iSubjectKeyId == certInfo.SubjectKeyId() );
+                }
+            if ( ( iFilter->iIssuerKeyId != KNullDesC8 ) && accept )
+                {
+                accept = ( iFilter->iIssuerKeyId == certInfo.IssuerKeyId() );
+                }
+            if ( ( iFilter->iLabelIsSet ) && accept )
+                {
+                accept = ( iFilter->iLabel == certInfo.Label() );
+                }
+            if ( ( iFilter->iKeyUsage != EX509UsageAll ) && accept &&
+                 ( certInfo.CertificateOwnerType() == EUserCertificate) )
+                {
+                // This test must be done after we checked that
+                // the certificate owner is a user cert
+                // We must get the private key info associated with the
+                // certificate so that we know the usages
+                TInt end = iKeyInfos.Count();
+                TInt i = 0;
+                for ( ; i < end; i++ )
+                    {
+                    if ( iKeyInfos[i]->ID() == certInfo.SubjectKeyId() )
+                        {
+                        i = end + 1; // This completes loop and
+                                     // differentiates from normal
+                                    // ending (i == end)
+                        }
+                    }
+                if ( i == end )
+                    {
+                    accept = EFalse;
+                    }
+                }
+
+            if ( accept )
+                {
+                // Here is done another copy of certificate for
+                // application needs
+                CCTCertInfo* copy = CCTCertInfo::NewLC( certInfo );
+                User::LeaveIfError( iCertsList->Append( copy ) );
+                CleanupStack::Pop( copy );
+                }
+
+            // iCertIndex is initialized in EList/KErrNone
+            iCertIndex++;
+
+            // Poll status in order to give time for other aos
+            TRequestStatus* status = &iStatus;
+            User::RequestComplete( status, KErrNone );
+            SetActive();
+            } // if ( iCertIndex...
+        else
+            {
+            // All certificates are listed or there are not any
+            iKeyInfos.Close();
+            delete iUnifiedKeyStore;
+            iUnifiedKeyStore = NULL;
+            iPhase = EIdle;
+            User::RequestComplete( iOriginalRequestStatus, KErrNone );
+            }
+        }
+    else
+        {
+        iPhase = iPhaseOriginal;
+        iPhaseOriginal = EIdle;
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        SetActive();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoCheckCorrespondingPrivateKey()
+// Check if private key is found for user certificate
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoCheckCorrespondingPrivateKey()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoCheckCorrespondingPrivateKey()" ) );
+    if ( iStatus.Int() == KErrNone )
+        {
+        if ( ( iKeyInfos.Count() == 0 ) ||
+           ( ( iFormat != EX509CertificateUrl ) &&
+             ( iKeyInfos[0]->Usage() != iKeyFilter.iUsage ) ) )
+            {
+            // The private key can't be found in any key store,
+            // so we must return an error
+            iPhase = EIdle;
+            User::RequestComplete( iOriginalRequestStatus, KErrArgument );
+            }
+        else
+            {
+            //
+            iPhase = EAdd;
+            TRequestStatus* status = &iStatus;
+            User::RequestComplete( status, KErrNone );
+            SetActive();
+            }
+        }
+    else
+        {
+        iPhase = EIdle;
+        User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+        }
+    iKeyInfos.Close();
+    delete iUnifiedKeyStore;
+    iUnifiedKeyStore = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoCheckDeleteFromWim()
+// If delete from Wim succeeded, continue deleting from trust setting store
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoCheckDeleteFromWim()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoCheckDeleteFromWim()" ) );
+    if ( iStatus.Int() == KErrNone )
+        {
+        iStatus = KRequestPending;
+        iPhase = EWaitRemoveTrustSettings;
+        iCWimTrustSettingsStore->RemoveTrustSettings(
+                                            *iCertInfos[iCertIndex], iStatus );
+        SetActive();
+        }
+    else
+        {
+        iPhase = EIdle;
+        User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::FreeUnifiedKeyStore()
+// Frees key storage resources.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::FreeUnifiedKeyStore()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::FreeUnifiedKeyStore()" ) );
+    if ( iUnifiedKeyStore )
+        {
+        iKeyInfos.Close();
+        delete iUnifiedKeyStore;
+        iUnifiedKeyStore = NULL;
+        iCertsList->Reset();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::RunError()
+// Unexpected error in RunL (e.g. Leave) leads us here.
+// -----------------------------------------------------------------------------
+//
+TInt CWimCertStore::RunError( TInt aError )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::RunError()" ) );
+
+    FreeUnifiedKeyStore();
+    iPhase = EIdle;
+    User::RequestComplete( iOriginalRequestStatus, aError );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::DoCancel()
+// Cancels current operation.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::DoCancel()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::DoCancel()" ) );
+
+    if ( iUnifiedKeyStore )
+        {
+        switch ( iPhase )
+            {
+            case EGetKeyInfos:
+                {
+                if ( iUnifiedKeyStore->IsActive() )
+                    {
+                    iUnifiedKeyStore->CancelInitialize();
+                    }
+                break;
+                }
+            case EList:
+                {
+                if ( iUnifiedKeyStore->IsActive() )
+                    {
+                    iUnifiedKeyStore->CancelList();
+                    }
+                break;
+                }
+            default:
+                {
+                // Other phases won't cause any action
+                break;
+                }
+            }
+        }
+
+    if ( iCWimCertConverter )
+        {
+        switch ( iPhase )
+            {
+            case EInitializeLoadMappings:
+                {
+                if ( iCWimCertConverter->IsActive() )
+                    {
+                    iCWimCertConverter->CancelRestore();
+                    delete iCWimCertConverter;
+                    iCWimCertConverter = NULL;
+                    }
+                break;
+                }
+            case ERetrieveWait:
+                {
+                if ( iCWimCertConverter->IsActive() )
+                    {
+                    iCWimCertConverter->CancelRetrieve();
+                    delete iCWimCertConverter;
+                    iCWimCertConverter = NULL;
+                    }
+                break;
+                }
+            case ECheckAddToWim:
+                {
+                if ( iCWimCertConverter->IsActive() )
+                    {
+                    iCWimCertConverter->CancelAddCertificate();
+                    delete iCWimCertConverter;
+                    iCWimCertConverter = NULL;
+                    }
+                break;
+                }
+            case ECheckDeleteFromWim:
+                {
+                if ( iCWimCertConverter->IsActive() )
+                    {
+                    iCWimCertConverter->CancelRemove();
+                    delete iCWimCertConverter;
+                    iCWimCertConverter = NULL;
+                    }
+                break;
+                }
+            default:
+                {
+                // Other phases won't cause any action
+                break;
+                }
+            }
+        }
+
+    if ( iCWimTrustSettingsStore )
+        {
+        switch ( iPhase )
+            {
+            case EInitializeLoadTrustSettingsStart:
+                {
+                if ( iCWimTrustSettingsStore->IsActive() )
+                    {
+                    iCWimTrustSettingsStore->CancelDoing();
+                    }
+                break;
+                }
+            default:
+                {
+                // Other phases won't cause any action
+                break;
+                }
+            }
+        }
+
+    if ( iCerts )
+        {
+        delete iCerts;
+        iCerts = NULL;
+        }
+
+    if ( iPhase == EInitializeLoadTrustSettingsWait )
+        {
+        // Nobody is taking ownership of these so delete them
+        iCertificateApps->Close();
+        delete iCertificateApps;
+        }
+
+    FreeUnifiedKeyStore();
+    iPhase = EIdle;
+    User::RequestComplete( iOriginalRequestStatus, KErrCancel );
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::LoadMappingsL()
+// In this phase we have retrieved certificate infos from WimClient and they
+// are in the iCertInfos array. This methdod creates iCerts array
+// and loads those certificates into it. Trust settings are updated in the next
+// phase.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::LoadMappingsL()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::LoadMappingsL()" ) );
+    if ( iCerts )
+        {
+        delete iCerts;
+        iCerts = NULL;
+        }
+    // Create a manager class for mapping entries
+    iCerts = CWimCertStoreMappings::NewL();
+    TInt count = iCertInfos.Count();
+    // Go through all certificates and insert them into a mapping array
+    for ( TInt i = 0; i < count; i++ )
+        {
+        CWimCertStoreMapping* certMapping = CWimCertStoreMapping::NewL();
+        CleanupStack::PushL( certMapping );
+        // Ownership moves to CWimCertStoreMapping
+        CCTCertInfo* certInfo = ( CCTCertInfo* )( iCertInfos )[i]->CctCert();
+        certMapping->SetEntryL( certInfo );
+        // Set default applications. This object must not push to cleanupstack
+        // because on leave at AddL this object is deleted in association with
+        // certMapping
+        RArray<TUid>* certificateApps = new( ELeave ) RArray<TUid>();
+        certMapping->SetCertificateAppsL( certificateApps );
+        // Set default
+        certMapping->SetTrusted( ETrue );
+        // Append mapping pointer to pointer array
+        iCerts->AddL( certMapping );
+        CleanupStack::Pop( certMapping );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimCertStore::SetTrustSettingsOnMappingL()
+// If certificate has no trust settings and there should be,
+// here they are updated. This method sets applications and trusted
+// information into mapping entry.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStore::SetTrustSettingsOnMappingL( TBool aTrusted,
+                                                RArray<TUid>* aApplications )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::SetTrustSettingsOnMappingL()" ) );
+    // Take a pointer to mapping
+    CWimCertStoreMapping* mapping = iCerts->Mapping( iCertIndex );
+    // Check that mapping is found
+    if ( !mapping )
+        {
+        User::Leave( KErrNotFound );
+        }
+    // Ownership is changed here:
+    // iCertificateApps is not any more responsible for this array.
+    mapping->SetCertificateAppsL( aApplications );
+    mapping->SetTrusted( aTrusted );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::EnteringAllowed()
+// Check if token is removed and if this ao is active.
+// -----------------------------------------------------------------------------
+//
+TBool CWimCertStore::EnteringAllowed( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimCertStore::EnteringAllowed()" ) );
+    if ( TokenRemoved() )
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete( status, KErrHardwareNotAvailable );
+        return EFalse;
+        }
+
+    // If this active object is in running, don't accept entering
+    if ( IsActive() )
+        {
+        // If the caller status is the same as the status, that activated
+        // this object, just return
+        if ( &aStatus == iOriginalRequestStatus )
+            {
+            return EFalse;
+            }
+        else
+            {
+            // Otherwise complete it with error
+            TRequestStatus* status = &aStatus;
+            User::RequestComplete( status, KErrInUse );
+            return EFalse;
+            }
+        }
+    else
+        {
+        iOriginalRequestStatus = &aStatus;
+        aStatus = KRequestPending;
+        return ETrue;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStore::TokenRemoved()
+// Returns true or false indicating if token is removed
+// -----------------------------------------------------------------------------
+//
+TBool CWimCertStore::TokenRemoved()
+    {
+    _WIMTRACE ( _L( "CWimCertStore::TokenRemoved()" ) );
+    // If token listener is not alive, then token is removed
+    if ( iToken.TokenListener()->TokenStatus() != KRequestPending )
+        {
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/src/WimCertStoreMapping.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,192 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This implementation represents one entry in an array
+*               where one mapping contains certificate info 
+*               with trusted settings
+*
+*/
+
+
+// INCLUDE FILES
+
+#include "WimCertStoreMapping.h"
+#include "WimTrace.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMapping::NewL()
+// NewL constructor which uses NewLC constructor
+// -----------------------------------------------------------------------------
+//
+CWimCertStoreMapping* CWimCertStoreMapping::NewL()
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMapping::NewL()" ) );
+    CWimCertStoreMapping* self = CWimCertStoreMapping::NewLC();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMapping::NewLC()
+// NewLC constructor pushes pointer to cleanup stack
+// -----------------------------------------------------------------------------
+//
+CWimCertStoreMapping* CWimCertStoreMapping::NewLC()
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMapping::NewLC()" ) );
+    CWimCertStoreMapping* self = new( ELeave ) CWimCertStoreMapping();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMapping::ConstructL()
+// Create an array for certificate applications in this mapping
+// -----------------------------------------------------------------------------
+//
+void CWimCertStoreMapping::ConstructL()
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMapping::ConstructL()" ) );
+    iCertificateApps = new( ELeave ) RArray<TUid>();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMapping::CWimCertStoreMapping()
+// Default constructor.
+// -----------------------------------------------------------------------------
+//
+CWimCertStoreMapping::CWimCertStoreMapping()
+    {   
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMapping::~CWimCertStoreMapping()
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CWimCertStoreMapping::~CWimCertStoreMapping()
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMapping::~CWimCertStoreMapping()" ) );
+    // CCTCertInfo class release is done in CWimCertInfo class
+    iEntry = NULL;
+
+    if ( iCertificateApps )
+        {
+        iCertificateApps->Close();
+        delete iCertificateApps;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMapping::SetEntryL()
+// Sets given certificate info into mapping entry
+// -----------------------------------------------------------------------------
+//
+void CWimCertStoreMapping::SetEntryL( CCTCertInfo* aCertInfo )
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMapping::SetEntryL()" ) );
+    __ASSERT_ALWAYS( aCertInfo, User::Leave( KErrArgument ) );
+    
+    if ( iEntry )
+        {
+        iEntry->Release();
+        }
+    iEntry = aCertInfo;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMapping::SetCertificateAppsL()
+// Sets certificate applications to mapping entry
+// -----------------------------------------------------------------------------
+//
+void CWimCertStoreMapping::SetCertificateAppsL( RArray<TUid>* aCertificateApps )
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMapping::SetCertificateAppsL()" ) );
+    TInt count = aCertificateApps->Count();
+    for ( TInt i = 0; i < count; i++ )
+        {
+        __ASSERT_ALWAYS( &aCertificateApps[i], User::Leave( KErrArgument ) );
+        }
+    iCertificateApps->Close();
+    delete iCertificateApps;
+    iCertificateApps = aCertificateApps;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMapping::Entry() const
+// Returns the certificate part of mapping 
+// -----------------------------------------------------------------------------
+//
+CCTCertInfo* CWimCertStoreMapping::Entry() const
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMapping::Entry()" ) );
+    return iEntry;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMapping::CertificateApps()
+// Returns an array of applications from mapping entry the certificate supports
+// -----------------------------------------------------------------------------
+//
+const RArray<TUid>& CWimCertStoreMapping::CertificateApps() const
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMapping::CertificateApps()" ) );
+    return *iCertificateApps;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMapping::IsApplicable()
+// Returns boolean value indicating if given applicaton is supported by
+// the certificate of mapping entry
+// -----------------------------------------------------------------------------
+//
+TBool CWimCertStoreMapping::IsApplicable( const TUid& aApplication ) const
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMapping::IsApplicable()" ) );
+    TInt count = iCertificateApps->Count();
+    for ( TInt i = 0; i < count; i++ )
+        {
+        TUid app = ( *iCertificateApps )[i];
+        if ( app == aApplication )
+            {
+            return ETrue;
+            }
+        }
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMapping::Trusted()
+// Returns boolean value indicating if the certificate in mapping 
+// entry is trusted
+// -----------------------------------------------------------------------------
+//
+TBool CWimCertStoreMapping::Trusted() const
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMapping::Trusted()" ) );
+    return iTrusted;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMapping::SetTrusted()
+// Sets mapping entry to state of trusted or not trusted ( true/false )
+// -----------------------------------------------------------------------------
+//
+void CWimCertStoreMapping::SetTrusted( TBool aTrusted )
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMapping::SetTrusted()" ) );
+    iTrusted = aTrusted;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/src/WimCertStoreMappings.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,165 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This implementation represents an array of mapping entries 
+*               (certificate infos) with trusted settings
+*
+*/
+
+
+// INCLUDE FILES
+
+#include "WimCertStoreMappings.h"
+#include "WimTrace.h"
+//#include "WimDebug.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMappings::NewL()
+// Two-phased constructor
+// -----------------------------------------------------------------------------
+//
+CWimCertStoreMappings* CWimCertStoreMappings::NewL()
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMappings::NewL()" ) );
+    CWimCertStoreMappings* self = new( ELeave ) CWimCertStoreMappings();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMappings::CWimCertStoreMappings()
+// Default constructor
+// -----------------------------------------------------------------------------
+//
+CWimCertStoreMappings::CWimCertStoreMappings()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMappings::ConstructL()
+// Second phase constructor
+// -----------------------------------------------------------------------------
+//
+void CWimCertStoreMappings::ConstructL()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMappings::~CWimCertStoreMappings()
+// Destructor. 
+// -----------------------------------------------------------------------------
+//
+CWimCertStoreMappings::~CWimCertStoreMappings()
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMappings::~CWimCertStoreMappings()" ) );
+    iMappings.ResetAndDestroy();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMappings::Count()
+// Returns the count of mapping entries from the internal array.
+// -----------------------------------------------------------------------------
+//
+TInt CWimCertStoreMappings::Count() const
+    {
+    return iMappings.Count();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMappings::AddL()
+// Adds an mapping entry to the internal array.
+// -----------------------------------------------------------------------------
+//
+void CWimCertStoreMappings::AddL( const CWimCertStoreMapping* aEntry )
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMappings::AddL()" ) );
+    User::LeaveIfError( iMappings.Append( aEntry ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMappings::Index()
+// Returns the index of mapping entry from the internal array using given
+// certificate info.
+// -----------------------------------------------------------------------------
+//
+TInt CWimCertStoreMappings::Index( const CCTCertInfo& aCertInfo )
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMappings::Index()" ) );
+    TInt count = iMappings.Count();
+    TInt ix = KErrNotFound;
+    for ( TInt i = 0; i < count; i++ )
+        {
+        CWimCertStoreMapping* mapping = ( iMappings )[i];
+        if ( aCertInfo == *( mapping->Entry() ) )
+            {
+            ix = i;
+            i = count; // End this loop
+            }
+        }
+    return ix;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertStoreMapping* CWimCertStoreMappings::Mapping()
+// Returns the mapping entry from the internal array using given index
+// -----------------------------------------------------------------------------
+//
+CWimCertStoreMapping* CWimCertStoreMappings::Mapping( TInt aIndex )
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMappings::Mapping()" ) );
+    return ( iMappings )[aIndex];
+    }
+
+// -----------------------------------------------------------------------------
+// CCTCertInfo& CWimCertStoreMappings::Entry()
+// Returns the certificate info from mapping entry using given index
+// -----------------------------------------------------------------------------
+//
+const CCTCertInfo& CWimCertStoreMappings::Entry( TInt aIndex )
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMappings::Entry()" ) );
+    CWimCertStoreMapping* mapping = ( iMappings )[aIndex];
+    return *mapping->Entry();
+    }
+
+// -----------------------------------------------------------------------------
+// CCTCertInfo& CWimCertStoreMappings::EntryByHandleL()
+// Returns the certificate info from the mapping entry using given handle
+// -----------------------------------------------------------------------------
+//
+const CCTCertInfo& CWimCertStoreMappings::EntryByHandleL( TInt aHandle ) const
+    {
+    _WIMTRACE ( _L( "CWimCertStoreMappings::EntryByHandleL()" ) );
+    CCTCertInfo* info = NULL;
+    TInt count = iMappings.Count();
+    for ( TInt i = 0; i < count; i++ )
+        {
+        CWimCertStoreMapping* mapping = ( iMappings )[i];
+        if ( aHandle == mapping->Entry()->Handle().iObjectId )
+            {
+            info = mapping->Entry();
+            i = count; // End this loop
+            }
+        }
+    if ( !info )
+        {
+        User::Leave( KErrNotFound );
+        }
+    return *info;
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/src/WimKeyStore.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,946 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of Wim key store interface
+*
+*/
+
+
+// INCLUDE FILES
+
+#include "WimKeyStore.h"
+#include "WimKeyDetails.h"
+#include "WimToken.h"
+#include "WimPin.h"
+#include "WimAuthenticationObject.h"
+#include "WimTrace.h"
+#include "WimTokenListener.h"
+#include "WimImplementationUID.hrh"
+#include "WimRSASigner.h"
+#include "WimConsts.h"
+#include <mctauthobject.h>
+#include <ct.h>
+#include <asymmetric.h>
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::CWimKeyStore()
+// Default constructor
+// -----------------------------------------------------------------------------
+//
+CWimKeyStore::CWimKeyStore( CWimToken& aToken ) :
+                            CActive( EPriorityNormal ),
+                            iToken( aToken )
+
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::NewL()
+// Two-phased constructor
+// -----------------------------------------------------------------------------
+//
+CWimKeyStore* CWimKeyStore::NewL( CWimToken& aToken )
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::NewL()" ) );
+    CWimKeyStore* self = new( ELeave ) CWimKeyStore( aToken );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::ConstructL()
+// Second phase constructor
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::ConstructL()
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::ConstructL()" ) );
+    iCWimKeyDetails = CWimKeyDetails::NewL( Token() );
+    iKeyNumbers = new( ELeave )CArrayFixFlat<TUint8>(1);
+    iPhase = EIdle;
+    iPhaseOriginal = EIdle;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::~CWimKeyStore()
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CWimKeyStore::~CWimKeyStore()
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::~CWimKeyStore()" ) );
+    Cancel();
+    TInt count = iKeyInfos.Count();
+    for ( TInt i = 0; i < count; i++ )
+        {
+        iKeyInfos[i]->Release();
+        }
+    iKeyInfos.Close();
+
+    if ( iKeyNumbers )
+        {
+        iKeyNumbers->Reset();
+        delete iKeyNumbers;
+        }
+
+    delete iSignature;
+
+    if ( iCWimKeyDetails )
+        {
+        delete iCWimKeyDetails;
+        iCWimKeyDetails = NULL;
+        }
+
+    delete iKeyId;
+    }
+// -----------------------------------------------------------------------------
+// CWimKeyStore::DoRelease()
+// Deletes this interface when Release() for this instance is called.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::DoRelease()
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::DoRelease()" ) );
+    delete this;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::Token()
+// Returns a reference to current token of this key store interface.
+// -----------------------------------------------------------------------------
+//
+MCTToken& CWimKeyStore::Token()
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::Token()" ) );
+    return iToken;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::List()
+// Lists all the keys in the store that match the filter.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::List( RMPointerArray<CCTKeyInfo>& aKeys,
+                         const TCTKeyAttributeFilter& aFilter,
+                         TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::List()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    iKeyList = &aKeys;
+    iKeyFilter = aFilter;
+    iPhase = EGetKeyList;
+    iPhaseOriginal = EGetKeyList;
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    SetActive();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::Open()
+// Open an RSA key for signing
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::Open( const TCTTokenObjectHandle& aHandle,
+                        MRSASigner*& aSigner,
+                        TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::Open()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    //Check whether handle matches.
+    if ( aHandle.iTokenHandle == Token().Handle() )
+        {
+        TRAPD( err, iSigner = CWimRSASigner::NewL( *this ) );
+        if ( err ) //OOM
+            {
+            iPhase = EIdle;
+            User::RequestComplete( iOriginalRequestStatus, err );
+            }
+        else
+           {
+            aSigner = iSigner;
+            iOpenSigninKeyHandle = aHandle;
+            iPhase = ECreateRSASignerObject;
+            TRequestStatus* status = &iStatus;
+            User::RequestComplete( status, KErrNone );
+            SetActive();
+           }
+        }
+
+    else
+        {
+        User::RequestComplete( iOriginalRequestStatus, KErrArgument );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::CancelOpen()
+// Cancels an ongoing Open operation
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::CancelOpen()
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::CancelOpen()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::ExportPublic()
+// Returns the public key in DER-encoded ASN-1.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::ExportPublic( const TCTTokenObjectHandle& aHandle,
+                                 HBufC8*& aPublicKey,
+                                 TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::ExportPublic()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    if ( aHandle.iTokenHandle == Token().Handle() )
+        {
+    
+            TRAPD( err, iPublicKey = HBufC8::NewL( KPublicKeyLength ) );
+
+            if ( err )
+                {
+                User::RequestComplete( iOriginalRequestStatus, err );
+                }
+            else
+                {
+                iExportKeyIdIndex = aHandle.iObjectId;
+                aPublicKey = iPublicKey;
+                iPhase = EStartExportPublicKey;
+                TRequestStatus* status = &iStatus;
+                User::RequestComplete( status, KErrNone );
+                SetActive();
+                }
+         
+           
+        }
+    else
+        {
+        User::RequestComplete( iOriginalRequestStatus, KErrBadHandle );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::CancelExportPublic()
+// Cancels an ongoing Export operation.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::CancelExportPublic()
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::CancelExportPublic()" ) );
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::Open()
+//Open an DSA key for signing. Not Supported.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::Open( const TCTTokenObjectHandle& /*aHandle*/,
+                         MDSASigner*& /*aSigner*/,
+                         TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::Open()" ) );
+    TRequestStatus* stat = &aStatus;
+    User::RequestComplete(stat, KErrNotSupported );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::Open()
+// Open a RSA key for private decryption. Not Supported.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::Open( const TCTTokenObjectHandle& /*aHandle*/,
+                         MCTDecryptor*& /*aDecryptor*/,
+                         TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::Open()" ) );
+    TRequestStatus* stat = &aStatus;
+    User::RequestComplete( stat, KErrNotSupported );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::Open()
+// Open a DH key for key agreement. Not Supported.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::Open( const TCTTokenObjectHandle& /*aHandle*/,
+                         MCTDH*& /*aDH*/,
+                         TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::Open()" ) );
+    TRequestStatus* stat = &aStatus;
+    User::RequestComplete( stat, KErrNotSupported );
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimKeyStore::RunL()
+// Core operations are done here.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::RunL()
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::RunL()" ) );
+
+    if ( !iListDone &&
+         iPhase != EGetKeyList &&
+         iPhase != ECheckGetKeyList )
+        {
+        iPhaseOriginal = iPhase;
+        iPhase = EGetKeyList;
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        SetActive();
+        }
+    else
+        {
+        switch ( iPhase )
+            {
+        case EGetKeyList:
+            {
+            TInt count = iKeyInfos.Count();
+
+            for ( TInt i = 0; i < count; i++ )
+                {
+                iKeyInfos[i]->Release();
+                }
+
+            iKeyInfos.Reset();
+            delete iCWimKeyDetails;
+            iCWimKeyDetails = NULL;
+            iKeyNumbers->Reset();
+            iCWimKeyDetails = CWimKeyDetails::NewL( Token() );
+            iStatus = KRequestPending;
+            iPhase = ECheckGetKeyList;
+            iCWimKeyDetails->GetKeyList( iKeyInfos, *iKeyNumbers, iStatus );
+            SetActive();
+            break;
+            }
+        case ECheckGetKeyList:
+            {
+            if ( iStatus.Int() == KErrNone )
+                {
+                iListDone = ETrue;
+                iKeyIndex = 0;
+                iPhase = EFilterKeys;
+                TRequestStatus* status = &iStatus;
+                User::RequestComplete( status, KErrNone );
+                SetActive();
+                }
+            else // No keys found or iWimKeyDetails->Restore call has
+                 // been cancelled or failed
+                {
+                iPhase = EIdle;
+                iPhaseOriginal = EIdle;
+                User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+                }
+            break;
+            }
+        case EFilterKeys:
+            {
+            DoFilterKeysL();
+            break;
+            }
+        case EGetKey:
+            {
+            TInt count = iKeyInfos.Count();
+            TInt i;
+
+            for ( i = 0; i < count; i++ )
+                {
+                if ( iKeyInfos[i]->Handle().iObjectId == iHandle )
+                    {
+                    // Make a copy of key info
+                    *iInfo = CreateKeyInfoL( i );
+                    i = count + 1;
+                    }
+                }
+            if ( i == count )
+                {
+                User::RequestComplete( iOriginalRequestStatus, KErrNotFound );
+                }
+            else
+                {
+                User::RequestComplete( iOriginalRequestStatus, KErrNone );
+                }
+            iPhase = EIdle;
+            iPhaseOriginal = EIdle;
+            break;  
+            }
+            
+        case ECreateRSASignerObject:
+            {
+            TBool found = EFalse;
+            TInt i;
+
+            for ( i = 0; i<iKeyInfos.Count() && !found; i++ )
+                {
+                //Check if the handle matches.
+                if ( iKeyInfos[i]->Handle().iObjectId ==
+                    iOpenSigninKeyHandle.iObjectId )
+                    {
+                    found = ETrue;
+                    }
+                if ( found )
+                    {
+                    //Check whether found key can do RSA sign.
+                    if ( iKeyInfos[i]->Algorithm() != CKeyInfoBase::ERSA )
+                        {
+                        //Set flag to false, the key does not do RSA sign.
+                        found = EFalse;
+                        }
+                    else
+                        {
+                        //Set label for new signing key
+                        iSigner->SetLabelL( iKeyInfos[i]->Label() );
+                        //Set objectId
+                        iSigner->SetObjectId( iKeyInfos[i]->Handle().iObjectId );
+                        }
+                    }
+                }
+            if ( found )
+                {
+                User::RequestComplete( iOriginalRequestStatus, KErrNone );
+                }
+            else
+                {
+                delete iSigner;
+                iSigner = NULL;
+                User::RequestComplete( iOriginalRequestStatus, KErrBadHandle );
+                }
+            iPhase = EIdle;
+            iPhaseOriginal = EIdle;
+            break;
+            }
+        case EStartNonRepudiableRSASign:
+            {
+            TBool found = EFalse;
+            TInt i = 0;
+
+            for ( ; i < iKeyInfos.Count() && !found; i++ )
+                {
+                 if ( iKeyInfos.operator[]( i )->Handle().iObjectId ==
+                 iRSAKeyIdIndex )
+                     {
+                     found = ETrue;
+                     TRAPD( err, iKeyId = iKeyInfos[i]->ID().AllocL() )
+
+                     if ( err )
+                         {
+                         User::RequestComplete( iOriginalRequestStatus, err );
+                         }
+                     else
+                         {
+                         iCWimKeyDetails->Sign( *iDigest,
+                                        *iKeyId,
+                                        iSignature,
+                                        iStatus );
+                         iPhase = ESignCompleted;
+                         SetActive();
+                         }
+                     }
+                }
+            //Key was not found, no need for signature
+           if ( !found )
+              {
+              iPhase = EIdle;
+              iPhaseOriginal = EIdle;
+              delete iSignature;
+              iSignature = NULL;
+              User::RequestComplete( iOriginalRequestStatus, KErrBadHandle );
+              }
+        	break;
+            }
+        case ESignCompleted:
+            {
+            //No need for KeyId anymore
+            delete iKeyId;
+            iKeyId = NULL;
+
+            //Check whether signing failed
+            if ( iStatus.Int() != KErrNone )
+                {
+                delete iSignature;
+                iSignature = NULL;
+                User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+                }
+            else //Sign was succesful.
+                {
+                 //Create signature and complete operation
+                RInteger signature = RInteger::NewL( *iSignature );
+                CleanupStack::PushL( signature );
+                *iRSASignature = CRSASignature::NewL( signature );
+                CleanupStack::Pop();
+                delete iSignature;
+                iSignature = NULL;
+                User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+                }
+            iPhase = EIdle;
+            iPhaseOriginal = EIdle;
+            break;
+            }
+        case EStartExportPublicKey:
+            {
+            TInt i = 0;
+            TBool found = EFalse;
+            
+            for( i = 0; i < iKeyInfos.Count() && !found; i++ )
+                {
+            	//Check if the objectIds matches
+            	if( iKeyInfos[i]->Handle().iObjectId == iExportKeyIdIndex )
+            	    {
+            		found = ETrue;
+            	    }	
+                }
+               
+            if( !found )
+                {
+            	iPhase = EIdle;
+            	iPhaseOriginal = EIdle;
+            	delete iPublicKey;
+            	iPublicKey = NULL;
+            	User::RequestComplete( iOriginalRequestStatus, KErrNotFound );
+                }
+            else
+                {
+            	iKeyId = iKeyInfos[iExportKeyIdIndex]->ID().AllocL();
+                iCWimKeyDetails->ExportPublicKeyL( *iKeyId,
+                                               iPublicKey,
+                                               iStatus );
+
+                iPhase = EExportPublicKeyDone;
+                SetActive();
+                }
+            
+            break;
+            }
+        case EExportPublicKeyDone:
+            {
+            delete iKeyId;
+            iKeyId = NULL;
+            iPhase = EIdle;
+            iPhaseOriginal = EIdle;
+            User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+            break;
+            }
+        default:
+            {
+            // Here we should not be
+            iPhase = EIdle;
+            iPhaseOriginal = EIdle;
+            User::RequestComplete( iOriginalRequestStatus, KErrCorrupt );
+            break;
+            }
+        }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::NonRepudiableRSASign()
+// Perform signing operation
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::NonRepudiableRSASign( const TCTTokenObjectHandle& aHandle,
+                                         const TDesC8& aDigest,
+                                         CRSASignature*& aSignature,
+                                         TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::NonRepudiableRSASign()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    TRAPD( err, iSignature = HBufC8::NewL( KMaxSignatureLength ) );
+
+    if ( err ) //OOM
+        {
+        User::RequestComplete( iOriginalRequestStatus, err );
+        return;
+        }
+
+    iRSASignature = &aSignature;
+    iRSAKeyIdIndex = aHandle.iObjectId;
+    iDigest = &aDigest;
+
+    iPhase = EStartNonRepudiableRSASign;
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimKeyStore::DoFilterKeysL()
+// Core operations are done here.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::DoFilterKeysL()
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::DoFilterKeysL()" ) );
+    if ( iPhaseOriginal == EGetKeyList )
+        {
+        if ( iKeyIndex < iKeyInfos.Count() )
+            {
+            // If usage is given in filter and handled key (in iKeyIndex) has
+            // also same usage, take with
+            //
+            // OR, (if filter usage is 0 or EAllKeyUsages) AND handled key
+            // usage is also 0 AND (key id length in filter is 0 OR handled
+            // key id is equal to key id in filter), take with
+            //
+            if ( ( ( iKeyFilter.iUsage & iKeyInfos[iKeyIndex]->Usage() ) ||
+               ( ( ( iKeyFilter.iUsage == 0 ) || ( iKeyFilter.iUsage ==
+               EPKCS15UsageAll ) ) &&
+               ( iKeyInfos[iKeyIndex]->Usage() == 0 ) ) ) &&
+               ( iKeyFilter.iKeyId.Length() == 0 ||
+                !iKeyInfos[iKeyIndex]->ID().Compare( iKeyFilter.iKeyId ) ) )
+                {
+                // Make a copy of key info
+                CCTKeyInfo* copy = CreateKeyInfoL( iKeyIndex );
+                // Call Release() for copy, if leave occurs
+                CleanupReleasePushL( *copy );
+                User::LeaveIfError( iKeyList->Append ( copy ) );
+                CleanupStack::Pop( copy );
+                }
+            iKeyIndex++;
+            TRequestStatus* status = &iStatus;
+            User::RequestComplete( status, KErrNone );
+            SetActive();
+            }
+        else
+            {
+            // All keys are listed or there are not any
+            iPhase = EIdle;
+            iPhaseOriginal = EIdle;
+            User::RequestComplete( iOriginalRequestStatus, KErrNone );
+            }
+        }
+    else
+        {
+        iPhase = iPhaseOriginal;
+        iPhaseOriginal = EIdle;
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        SetActive();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimKeyStore::CreateKeyInfoL()
+// Creates a new key info from internal array.
+// -----------------------------------------------------------------------------
+//
+CCTKeyInfo* CWimKeyStore::CreateKeyInfoL( TInt aIndex )
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::CreateKeyInfoL()" ) );
+    // Create protector
+    MCTAuthenticationObject* protector = NULL;
+    TUint thishandle = iKeyNumbers->At ( aIndex );
+    protector = MakeAuthObjectL( thishandle );
+    
+    if ( protector )
+        {
+        CleanupStack::PushL( protector );
+        }
+
+    HBufC* wlabel = HBufC::NewLC( ( iKeyInfos )[aIndex]->Label().Length() );
+    wlabel->Des().Copy( ( iKeyInfos )[aIndex]->Label() );
+
+#ifdef __SECURITY_PLATSEC_ARCH__
+    CCTKeyInfo* copy = CCTKeyInfo::NewL( ( iKeyInfos ) [aIndex]->ID(),
+                                         ( iKeyInfos ) [aIndex]->Usage(),
+                                         ( iKeyInfos ) [aIndex]->Size(),
+                                         protector,
+                                         wlabel,
+                                         ( iKeyInfos ) [aIndex]->Token(),
+                                         ( iKeyInfos ) [aIndex]->Handle().iObjectId,
+                                         ( iKeyInfos ) [aIndex]->UsePolicy(),
+                                         ( iKeyInfos ) [aIndex]->ManagementPolicy(),
+                                         ( iKeyInfos ) [aIndex]->Algorithm(),
+                                         ( iKeyInfos ) [aIndex]->AccessType(),
+                                         ( iKeyInfos ) [aIndex]->Native(),
+                                         ( iKeyInfos ) [aIndex]->StartDate(),
+                                         ( iKeyInfos ) [aIndex]->EndDate() );
+#else
+   CCTKeyInfo* copy = CCTKeyInfo::NewL( ( iKeyInfos ) [aIndex]->ID(),
+                                         ( iKeyInfos ) [aIndex]->Usage(),
+                                         ( iKeyInfos ) [aIndex]->Size(),
+                                         protector,
+                                         wlabel,
+                                         ( iKeyInfos ) [aIndex]->Token(),
+                                         ( iKeyInfos ) [aIndex]->Handle().iObjectId,
+                                         ( iKeyInfos ) [aIndex]->Owner(),
+                                         ( iKeyInfos ) [aIndex]->Users(),
+                                         ( iKeyInfos ) [aIndex]->Algorithm(),
+                                         ( iKeyInfos ) [aIndex]->AccessType(),
+                                         ( iKeyInfos ) [aIndex]->Native(),
+                                         ( iKeyInfos ) [aIndex]->StartDate(),
+                                         ( iKeyInfos ) [aIndex]->EndDate() );
+#endif
+
+    CleanupStack::Pop( wlabel );
+    if ( protector )
+        {
+        CleanupStack::Pop( protector );
+        }
+    return copy;
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimKeyStore::MakeAuthObjectL()
+// Lists authentication objects and matches each on given handle.
+// When match is found, one instance is created and returned.
+// -----------------------------------------------------------------------------
+//
+MCTAuthenticationObject* CWimKeyStore::MakeAuthObjectL( TInt aHandle )
+    {
+    
+    if( !iPinNRs )
+	    {
+	    TInt ret = iToken.WimSecModule()->PinNrEntriesL( iPinNRs );
+	   
+	    if ( ret != KErrNone )
+	        {
+	        User::Leave( ret );
+	        }	
+	    }
+    
+        
+    if ( iPinNRs ) // If PINs were found
+        {
+        TUid pintype = {WIM_PIN_G_UID}; // The first one is always PIN-G
+        TInt count = iPinNRs->Count();
+        TUint32 status = 0;
+
+        for ( TInt i = 0; i < count; i++ )
+            {
+            if ( aHandle == (*iPinNRs)[i]->PinNumber() )
+                {
+                CWimAuthenticationObject* me =
+                        CWimAuthenticationObject::NewLC(
+                                            iToken,
+                                         *( *iPinNRs )[i],
+                                          ( *iPinNRs )[i]->Label(),
+                                             pintype,
+                                          ( *iPinNRs )[i]->PinNumber(),
+                                             status );
+                 CleanupStack::Pop( me );
+                 return me;
+                }
+            pintype.iUid = WIM_PIN_NR_UID; // The others are always PIN-NRs
+            }
+        }
+    return NULL;    
+    }
+// -----------------------------------------------------------------------------
+// void CWimKeyStore::RunError()
+// Unexpected error in RunL (e.g. Leave) leads us here.
+// -----------------------------------------------------------------------------
+//
+TInt CWimKeyStore::RunError( TInt aError )
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::RunError()" ) );
+
+    iPhase = EIdle;
+    iPhaseOriginal = EIdle;
+    User::RequestComplete( iOriginalRequestStatus, aError );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimKeyStore::DoCancel()
+// Cancels outgoing async. calls.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::DoCancel()
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::DoCancel()" ) );
+
+    if ( iCWimKeyDetails && iPhase == ECheckGetKeyList )
+        {
+        if ( iCWimKeyDetails->IsActive() )
+            {
+            iCWimKeyDetails->CancelList();
+            }
+        }
+    else if ( iCWimKeyDetails && iPhase == ESignCompleted )
+        {
+        if ( iCWimKeyDetails->IsActive() )
+            {
+            iCWimKeyDetails->CancelSign();
+            delete iSignature;
+            iSignature = NULL;
+            }
+        }
+    else if ( iCWimKeyDetails && iPhase == EExportPublicKeyDone )
+        {
+        if ( iCWimKeyDetails->IsActive() )
+            {
+            iCWimKeyDetails->CancelExport();
+            }
+        }
+    iPhase = EIdle;
+    iPhaseOriginal = EIdle;
+    delete iKeyId;
+    iKeyId = NULL;
+    User::RequestComplete( iOriginalRequestStatus, KErrCancel );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::CancelList()
+// Cancels an ongoing List operation. Sets an internal flag to true.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::CancelList()
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::CancelList()" ) );
+
+    if ( TokenRemoved() )
+        {
+        return;
+        }
+
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::GetKeyInfo()
+// Retrieves a key according to given handle.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::GetKeyInfo( TCTTokenObjectHandle aHandle,
+                               CCTKeyInfo*& aInfo,
+                               TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::GetKeyInfo()" ) );
+
+    if ( !EnteringAllowed( aStatus ) )
+        {
+        return;
+        }
+
+    if ( aHandle.iTokenHandle == Token().Handle() )
+        {
+        iInfo = &aInfo;
+        iHandle = aHandle.iObjectId;
+        iPhase = EGetKey;
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        SetActive();
+        }
+    else
+        {
+        User::RequestComplete( iOriginalRequestStatus, KErrArgument );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::CancelGetKeyInfo()
+// Cancels an ongoing GetKeyInfo operation.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyStore::CancelGetKeyInfo()
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::CancelGetKeyInfo()" ) );
+
+    if ( TokenRemoved() )
+        {
+        return;
+        }
+
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::EnteringAllowed()
+//
+// -----------------------------------------------------------------------------
+//
+TBool CWimKeyStore::EnteringAllowed( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::EnteringAllowed()" ) );
+    if ( TokenRemoved() )
+        {
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete( status, KErrHardwareNotAvailable );
+        return EFalse;
+        }
+
+    // If this active object is in running, don't accept entering
+    if ( IsActive() )
+        {
+        // If the caller status is the same as the status, that activated
+        // this object, just return
+        if ( &aStatus == iOriginalRequestStatus )
+            {
+            return EFalse;
+            }
+        else
+            {
+            // Otherwise complete it with error
+            TRequestStatus* status = &aStatus;
+            User::RequestComplete( status, KErrInUse );
+            return EFalse;
+            }
+        }
+    else
+        {
+        iOriginalRequestStatus = &aStatus;
+        aStatus = KRequestPending;
+        return ETrue;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyStore::TokenRemoved()
+// Returns true or false indicating if token is removed
+// -----------------------------------------------------------------------------
+//
+TBool CWimKeyStore::TokenRemoved()
+    {
+    _WIMTRACE ( _L( "CWimKeyStore::TokenRemoved()" ) );
+    // If token listener is not alive, then token is removed
+    if ( iToken.TokenListener()->TokenStatus() != KRequestPending )
+        {
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/src/WimRSASigner.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,213 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of Wim RSA signer interface
+*
+*/
+
+
+#include "WimKeyStore.h"
+#include "WimRSASigner.h"
+#include <hash.h>
+#include <mctkeystoreuids.h>            // KRSARepudiableSignerUID
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimRSASigner::CWimRSASigner()
+//
+// -----------------------------------------------------------------------------
+//
+CWimRSASigner::CWimRSASigner( CWimKeyStore& aClient )
+		: MCTSigner<CRSASignature*>( aClient.Token() ),iClient( aClient )
+	{                               
+	iHandle.iTokenHandle = aClient.Token().Handle();
+	}
+
+// -----------------------------------------------------------------------------
+// CWimRSASigner* CWimRSASigner::NewL()
+// Creates new Instance of CWimRSASigner
+// -----------------------------------------------------------------------------
+//
+CWimRSASigner* CWimRSASigner::NewL( CWimKeyStore& aClient )
+    {
+    CWimRSASigner* self = new( ELeave ) CWimRSASigner( aClient );
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimRSASigner::~CWimRSASigner()
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CWimRSASigner::~CWimRSASigner()
+	{
+    delete iLabel;
+	delete iDigest;
+        delete iDigestBuf;
+	}
+
+// -----------------------------------------------------------------------------
+// CWimRSASigner::SetLabelL()
+// Sets label for signin key object
+// -----------------------------------------------------------------------------
+//
+void CWimRSASigner::SetLabelL( const TDesC& aLabel )
+    {
+    iLabel = aLabel.AllocL();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimRSASigner::SetObjectId()
+// Sets object id -points to a certain key
+// -----------------------------------------------------------------------------
+//
+void CWimRSASigner::SetObjectId( const TInt aObjectId )
+    {
+    iHandle.iObjectId = aObjectId;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimRSASigner::Release()
+// Release object
+// -----------------------------------------------------------------------------
+//
+void CWimRSASigner::Release()
+	{
+	MCTTokenObject::Release();
+	}
+
+// -----------------------------------------------------------------------------
+// CWimRSASigner::Label() const
+// Returns the object's human-readable label
+// -----------------------------------------------------------------------------
+//
+const TDesC& CWimRSASigner::Label() const
+	{
+	return *iLabel;
+	}
+
+// -----------------------------------------------------------------------------
+// CWimRSASigner::Token()
+// Returns a reference to the associated token
+// -----------------------------------------------------------------------------
+//
+MCTToken& CWimRSASigner::Token() const
+	{
+	return iClient.Token();
+	}
+
+// -----------------------------------------------------------------------------
+// CWimRSASigner::Type()
+// Returns a UID representing the type of the token object. The
+// meanings of possible UIDs should be documented in the
+// documentation for the interface that returns them.
+// -----------------------------------------------------------------------------
+//
+TUid CWimRSASigner::Type() const
+	{
+	return KRSARepudiableSignerUID;
+	}
+
+// -----------------------------------------------------------------------------
+// CWimRSASigner::Handle()
+// Returns a handle for the object. The primary purpose of the
+// handle is to allow token objects to be 'passed' between
+// processes. See TCTTokenObjectHandle for more details.
+// -----------------------------------------------------------------------------
+//
+TCTTokenObjectHandle CWimRSASigner::Handle() const
+	{
+	return iHandle;
+	}
+
+// -----------------------------------------------------------------------------
+// CWimRSASigner::SignMessage()
+// Sign some data. The data is hashed before the signature is created using 
+// the SHA-1 algorithm.
+// -----------------------------------------------------------------------------
+//
+void CWimRSASigner::SignMessage( const TDesC8& aPlaintext, 
+  				                 CRSASignature*& aSignature, 
+  				                 TRequestStatus& aStatus )
+	{
+    if( iDigest )
+        {
+        delete iDigest;
+        iDigest = NULL;
+        }
+    if( iDigestBuf )
+        {
+        delete iDigestBuf;
+        iDigest = NULL;
+        }
+
+	// Hash the data on the client side
+	TRAPD( err, iDigest = CSHA1::NewL() );
+
+	if ( err == KErrNone )
+		{
+	    iDigest->Update( aPlaintext );
+	    TRAP( err, iDigestBuf = HBufC8::NewL( iDigest->HashSize() ) );
+	    
+	    if (err != KErrNone )
+	       {
+	       TRequestStatus* status = &aStatus;
+		     User::RequestComplete( status, err );
+	       return;
+	    	 }
+	    
+	    TPtr8 tempPtr = iDigestBuf->Des();
+	    tempPtr.Copy( iDigest->Final() );	
+	    Sign( *iDigestBuf, aSignature, aStatus );
+		}
+    else
+        {
+		TRequestStatus* status = &aStatus;
+		User::RequestComplete( status, err );
+        }
+	}
+
+// -----------------------------------------------------------------------------
+// CWimRSASigner::Sign()
+// Perform a raw signing operation.
+// -----------------------------------------------------------------------------
+//
+void CWimRSASigner::Sign( const TDesC8& aPlaintext, 
+  				          CRSASignature*& aSignature, 
+  				          TRequestStatus& aStatus )
+	{
+	iClient.NonRepudiableRSASign( Handle(), aPlaintext, aSignature, aStatus );
+	}
+
+// -----------------------------------------------------------------------------
+// CWimRSASigner::CancelSign()
+// Cancel an ongoing sign
+// -----------------------------------------------------------------------------
+//
+void CWimRSASigner::CancelSign()
+	{
+    iClient.Cancel();
+	}
+
+// -----------------------------------------------------------------------------
+// CWimRSASigner::DoRelease()
+// Releases this object.
+// -----------------------------------------------------------------------------
+//
+void CWimRSASigner::DoRelease()
+	{
+	delete this;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/src/WimToken.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,382 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A token represents one instance of a particular kind of 
+*               cryptographic module
+*
+*/
+
+
+// INCLUDE FILES
+
+#include "WimToken.h"
+#include "WimCertStore.h"
+#include "WimAuthenticationObjectList.h"
+#include "WimAuthenticationObject.h"
+#include "WimKeyStore.h"
+#include "WimSecModuleMgr.h"
+#include "WimImplementationUID.hrh"
+#include "WimTokenListener.h"
+#include "WimTrace.h"
+#include <mctkeystoreuids.h>            // KInterfaceKeyStore
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimToken::CWimToken()
+// Default constructor.
+// -----------------------------------------------------------------------------
+//
+CWimToken::CWimToken( CWimSecModule* aWimSecModule, MCTTokenType& aTokenType )
+          :iWimSecModule( aWimSecModule ),
+           iTokenType( aTokenType )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimToken::ConstructL()
+// Second phase constructor
+// -----------------------------------------------------------------------------
+//
+void CWimToken::ConstructL()
+    {
+    _WIMTRACE ( _L( "CWimToken::ConstructL()" ) );
+    iLabel = WimSecModule()->Label().AllocL();
+    iWimTokenListener = CWimTokenListener::NewL( iWimSecModule );
+    iWimTokenListener->StartListening(); //Start listening
+    iCount = 0;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimToken::NewL()
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimToken* CWimToken::NewL( CWimSecModule* aWimSecModule, 
+                            MCTTokenType& aTokenType )
+    {
+    _WIMTRACE ( _L( "CWimToken::NewL()" ) );
+    // First parameter should not be NULL
+    __ASSERT_ALWAYS( aWimSecModule, User::Leave( KErrCorrupt ) );
+    CWimToken* self = new( ELeave ) CWimToken( aWimSecModule, aTokenType );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimToken::~CWimToken()
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CWimToken::~CWimToken()
+    {
+    _WIMTRACE ( _L( "CWimToken::~CWimToken()" ) );        
+    delete iLabel;
+    iWimSecModule = NULL;
+    delete iWimTokenListener;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimToken::Label()
+// Get the label from current token
+// -----------------------------------------------------------------------------
+//
+const TDesC& CWimToken::Label()
+    {
+    _WIMTRACE ( _L( "CWimToken::Label()" ) );
+    return reinterpret_cast<TDesC&>( *iLabel );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimToken::Information()
+// Returns the specified information string about the token
+// -----------------------------------------------------------------------------
+//
+const TDesC& CWimToken::Information( TTokenInformation aRequiredInformation )
+    {
+    _WIMTRACE ( _L( "CWimToken::Information()" ) );
+    if ( TokenRemoved() )
+        {
+        return KNullDesC;
+        }
+
+    if ( iWimSecModule )
+        {
+        switch( aRequiredInformation ) 
+           {
+            case EVersion: // Returns the version from current token
+                {   
+                return WimSecModule()->Version();
+                }
+            case ESerialNo: // Returns the Serialnumber from current token
+                {
+                return WimSecModule()->SerialNumber();
+                }
+            case EManufacturer: // Returns the Manufacturer from current token
+                {
+                return WimSecModule()->Manufacturer();
+                }
+            default:    // Returns empty string 
+                break;
+             }
+        }
+    return KNullDesC;
+    }
+
+// -----------------------------------------------------------------------------
+// MCTTokenType& CWimToken::TokenType()
+// Returns the associated token type.
+// -----------------------------------------------------------------------------
+//
+MCTTokenType& CWimToken::TokenType()
+    {
+    _WIMTRACE ( _L( "CWimToken::TokenType()" ) );
+    return iTokenType;
+    }
+
+// -----------------------------------------------------------------------------
+// TCTTokenHandle CWimToken::Handle()
+// Returns the token's handle. TCTTokenHandle defines a handle to a subclass 
+// of the MCTToken class
+// WimSecModule()->TokenNumber retrieves the token actually exists. 
+// Values 0..7 are for hardware tokens. Value 255 is for SoftId-token.
+// -----------------------------------------------------------------------------
+//
+TCTTokenHandle CWimToken::Handle()
+    {
+    _WIMTRACE ( _L( "CWimToken::Handle()" ) );
+    const TInt tokenNumber = WimSecModule()->TokenNumber();
+    return TCTTokenHandle( TokenType().Type(), tokenNumber );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimToken::DoGetInterface()
+// Returns a valid interface and KErrNone, or interface = NULL and 
+// KErrNotSupported if it isn't supported by this token
+// -----------------------------------------------------------------------------
+// 
+void CWimToken::DoGetInterface( TUid aRequiredInterface,
+                                MCTTokenInterface*& aReturnedInterface,
+                                TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimToken::DoGetInterface()" ) );
+
+    if ( TokenRemoved() )
+        {
+        Release();
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete( status, KErrHardwareNotAvailable );             
+        return;
+        }
+    
+	    TInt error = KErrNone;
+
+	    if ( TokenType().Type().iUid == WIM_IMPLEMENTATION_UID )
+	        {
+	        TRAP( error, MakeInterfaceL( aRequiredInterface, aReturnedInterface ) );
+	        }
+	    else
+	        {
+	        error = KErrArgument;
+	        }
+
+	    TRequestStatus* status = &aStatus;
+	    User::RequestComplete( status, error );
+
+	    // If something went wrong, this interface must be released, 
+	    // because framework has just before incremented references
+	    if ( error != KErrNone )
+	        {
+	        Release();
+	        }	
+    }
+
+// -----------------------------------------------------------------------------
+// CWimToken::MakeInterfaceL()
+// At first checks if interface is supported. Note: support is depending on
+// Uids that are indicated in resource file.
+// Calls actual interface maker. All leavable functions are gathered into this.
+// -----------------------------------------------------------------------------
+//
+void CWimToken::MakeInterfaceL( TUid aRequiredInterface,
+                                MCTTokenInterface*& aReturnedInterface )
+    {
+    _WIMTRACE ( _L( "CWimToken::MakeInterfaceL()" ) );
+
+    RCPointerArray <CCTTokenTypeInfo> tokenTypes;
+
+    TCurrentTokenType filter;
+
+    CCTTokenTypeInfo::ListL( tokenTypes, filter );
+
+    if ( tokenTypes.Count() != 1 ) // There shoud be only one Wim implementation
+        {
+        tokenTypes.Close();
+        User::Leave( KErrCorrupt );
+        }
+
+    // Check that given interface uid is found from resource file
+    TInt count = tokenTypes[0]->Interfaces().Count();
+    TInt i = 0;
+
+    for ( ; i < count; i++ )
+        {
+        if ( tokenTypes[0]->Interfaces()[i].iUid == aRequiredInterface.iUid )
+            {
+            i = count + 1;
+            }
+        }
+
+    tokenTypes.Close();
+
+    if ( i == count )
+        {
+        User::Leave( KErrNotSupported );
+        }
+
+    switch ( aRequiredInterface.iUid )
+        {
+        case KInterfaceCertStore:   // Read Only Cert Store Interface.
+            {
+            iCertStoreIf = CWimCertStore::NewL( *this );
+            aReturnedInterface = iCertStoreIf;
+            break;
+            }
+        case KInterfaceWritableCertStore:
+            {                       // Writable Cert Store Interface
+            iCertStoreWritableIf = CWimCertStore::NewL( *this );
+            aReturnedInterface = iCertStoreWritableIf;
+            break;
+            }
+        case KInterfaceKeyStore:    // KeyStore Interface
+            {
+            iKeyStoreIf = CWimKeyStore::NewL( *this );
+            aReturnedInterface = iKeyStoreIf;
+            break;
+            }
+        case KCTInterfaceAuthenticationObject:
+            {                       // Authentication Object Interface
+            iAuthObjectListIf = CWimAuthenticationObjectList::NewL( *this );
+            aReturnedInterface = iAuthObjectListIf;
+            break;
+            }
+        default: // Should be checked in the caller function
+            { 
+            User::Leave( KErrCorrupt );             
+            break;
+            }
+        }
+    }
+// -----------------------------------------------------------------------------
+// CWimToken::DoCancelGetInterface()
+// Nothing to do
+// -----------------------------------------------------------------------------
+//
+TBool CWimToken::DoCancelGetInterface()
+    {
+    _WIMTRACE ( _L( "CWimToken::DoCancelGetInterface()" ) );
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimToken::ReferenceCount()
+// Returns a reference to reference counter.
+// -----------------------------------------------------------------------------
+//
+TInt& CWimToken::ReferenceCount()
+    {
+    return iCount;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimToken::NotifyOnRemoval( TRequestStatus& aStatus )
+// Notifies the client when the token has been removed.
+// -----------------------------------------------------------------------------
+//
+void CWimToken::NotifyOnRemoval( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimToken::NotifyOnRemoval()" ) );
+    iWimTokenListener->SetClientStatus( aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimToken::CancelNotify()
+// Cancels the NotifyOnRemoval request.
+// -----------------------------------------------------------------------------
+//
+void CWimToken::CancelNotify()
+    {
+    _WIMTRACE ( _L( "CWimToken::CancelNotify()" ) );
+    if ( TokenRemoved() )
+        {
+        return;
+        }
+    iWimTokenListener->ClearClientStatus();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimToken::WimSecModule()
+// Returns a pointer to current security module
+// -----------------------------------------------------------------------------
+//
+CWimSecModule* CWimToken::WimSecModule()
+    {
+    return iWimSecModule;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimToken::TokenListener()
+// Returns a pointer to token listener
+// -----------------------------------------------------------------------------
+//
+CWimTokenListener* CWimToken::TokenListener()
+    {
+    return iWimTokenListener;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimToken::TokenRemoved()
+//
+// -----------------------------------------------------------------------------
+//
+TBool CWimToken::TokenRemoved()
+    {
+    if ( TokenListener()->TokenStatus() == KRequestPending )
+        {
+        return EFalse;
+        }
+    else
+        {
+        return ETrue;
+        }
+    }
+// -----------------------------------------------------------------------------
+// TCurrentTokenType::Accept( const CCTTokenTypeInfo& ) const
+// Returns true if current token type is same as given token type
+// -----------------------------------------------------------------------------
+//
+TBool TCurrentTokenType::Accept( const CCTTokenTypeInfo& aInfo ) const
+    {
+    if ( aInfo.Type().iUid == WIM_IMPLEMENTATION_UID )
+        {
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;
+        }   
+    }               
+    
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/src/WimTokenListener.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,173 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Listens removal event from WimServer
+*
+*/
+
+
+// INCLUDE FILES
+
+#include "WimTokenListener.h"
+#include "WimTrace.h"
+//#include "WimDebug.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimTokenListener::CWimTokenListener()
+// Default constructor
+// -----------------------------------------------------------------------------
+//
+CWimTokenListener::CWimTokenListener( CWimSecModule* aWimSecModule )
+                                    : CActive ( EPriorityNormal ),
+                                      iWimSecModule( aWimSecModule ),
+                                      iClientStatus( NULL )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenListener::ConstructL()
+// Second phase constructor
+// -----------------------------------------------------------------------------
+//
+void CWimTokenListener::ConstructL()
+    {
+    _WIMTRACE ( _L( "CWimTokenListener::ConstructL()" ) );
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenListener::NewL()
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimTokenListener* CWimTokenListener::NewL( CWimSecModule* aWimSecModule )
+    {
+    _WIMTRACE ( _L( "CWimTokenListener::NewL()" ) );
+    CWimTokenListener* self = new( ELeave ) CWimTokenListener( aWimSecModule );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenListener::~CWimTokenListener()
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CWimTokenListener::~CWimTokenListener()
+    {
+    _WIMTRACE ( _L( "CWimTokenListener::~CWimTokenListener()" ) );
+    ClearClientStatus(); // Complete UI's request if needed
+    if ( iWimSecModule && ( iTokenStatus == KRequestPending ) )
+        {
+        iWimSecModule->CancelNotifyOnRemoval(); // Cancel listening in WimServer   
+        }
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenListener::StartListening()
+// Start listening of Scard removal status
+// -----------------------------------------------------------------------------
+//
+void CWimTokenListener::StartListening()
+    {
+    _WIMTRACE ( _L( "CWimTokenListener::StartListening()" ) );
+    iStatus = KRequestPending;
+    iTokenStatus = KRequestPending;
+    iWimSecModule->NotifyOnRemoval( iStatus );
+    SetActive();    
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenListener::SetClientStatus()
+// Store client status
+// -----------------------------------------------------------------------------
+//
+void CWimTokenListener::SetClientStatus( TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimTokenListener::SetClientStatus()" ) );
+    iClientStatus = &aStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenListener::ClearClientStatus()
+// If client request is still pending complete request with KErrCancel
+// -----------------------------------------------------------------------------
+//
+void CWimTokenListener::ClearClientStatus()
+    {
+    _WIMTRACE ( _L( "CWimTokenListener::ClearClientStatus()" ) );
+    // If request is still pending, complete it with KErrCancel
+    // RequestComplete sets iClientStatus to NULL
+    if ( iClientStatus )
+        {
+        User::RequestComplete( iClientStatus, KErrCancel );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenListener::RunL()
+// Complete asyncronous request
+// -----------------------------------------------------------------------------
+//
+void CWimTokenListener::RunL()
+    {
+    switch ( iStatus.Int() )
+        {
+        case KErrNone:
+            {
+            iTokenStatus = KErrHardwareNotAvailable;
+            break;
+            }
+        case KErrCancel:
+            {
+            iTokenStatus = KErrCancel;
+            break;
+            }
+        default:
+            {
+            iTokenStatus = iStatus.Int();
+            break;
+            }
+        }
+
+    if ( iClientStatus ) // Complete the request if pending
+        {
+        User::RequestComplete( iClientStatus, iStatus.Int() );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenListener::DoCancel()
+// Nothing to do here
+// -----------------------------------------------------------------------------
+//
+void CWimTokenListener::DoCancel()
+    {
+    _WIMTRACE ( _L( "CWimTokenListener::DoCancel()" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenListener::TokenStatus()
+// Return the staus of token
+// -----------------------------------------------------------------------------
+//
+TInt CWimTokenListener::TokenStatus()
+    {
+    _WIMTRACE ( _L( "CWimTokenListener::TokenStatus()" ) );
+    return iTokenStatus;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimPlugin/src/WimTokenType.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,251 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This class is instantiated via ECom for a particular token type
+*
+*/
+
+
+// INCLUDE FILES
+
+#include "WimTokenType.h"
+#include "WimToken.h"
+#include "WimImplementationUID.hrh"
+#include <ecom/implementationproxy.h>
+#include "WimTrace.h"
+//#include "WimDebug.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimTokenType::CWimTokenType()
+// Default constructor
+// -----------------------------------------------------------------------------
+//
+CWimTokenType::CWimTokenType()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenType::ConstructL()
+// Second phase constructor
+// -----------------------------------------------------------------------------
+//
+void CWimTokenType::ConstructL()
+    {
+    _WIMTRACE ( _L( "CWimTokenType::ConstructL()" ) );
+    iWimSecModuleMgr = CWimSecModuleMgr::NewL(); 
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenType::NewL()
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimTokenType* CWimTokenType::NewL() 
+    {
+    CWimTokenType* self = new( ELeave ) CWimTokenType();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenType::~CWimTokenType()
+// Destructor.
+// -----------------------------------------------------------------------------
+//
+CWimTokenType::~CWimTokenType()
+    {
+    _WIMTRACE ( _L( "CWimTokenType::~CWimTokenType()" ) );
+    delete iWimSecModuleMgr;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenType::List()
+// List all the tokens of this type.
+// -----------------------------------------------------------------------------
+//
+void CWimTokenType::List( RCPointerArray<HBufC>& aTokens,  
+                          TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimTokenType::List" ) );
+    aStatus = KRequestPending;
+    iWimSecModuleMgr->GetEntries( aTokens, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenType::CancelList()
+// Cancel a list operation.
+// -----------------------------------------------------------------------------
+//
+void CWimTokenType::CancelList()
+    {
+    _WIMTRACE ( _L( "CWimTokenType::CancelList" ) );
+    iWimSecModuleMgr->CancelList();
+    }
+
+// -----------------------------------------------------------------------------
+// CTokenTypeImplementation::OpenToken() 
+// Opens new token, which name is specified in aTokenInfo
+// This is not true asynchronous function.
+// -----------------------------------------------------------------------------
+//
+void CWimTokenType::OpenToken( const TDesC& aTokenInfo, 
+                               MCTToken*& aToken,
+                               TRequestStatus& aStatus )
+    { 
+    _WIMTRACE ( _L( "CWimTokenType::OpenToken with name" ) );
+    TInt err   = KErrNone;
+    TInt i     = 0;
+
+    aStatus    = KRequestPending;
+
+    // Get the right Wim and pass it to CWimToken to be created.
+    // Stack Wim count for efficiency reasons
+    TInt count = iWimSecModuleMgr->WimCount(); 
+    for ( i = 0; i < count && err == KErrNone; i++ ) 
+        {
+        HBufC* label = NULL;    // from heap
+        // Get Wim label
+        TRAP( err, label = iWimSecModuleMgr->WimLabelByIndexL( i ).AllocL() );
+        if ( err == KErrNone ) 
+            {
+            // If labels match...
+            if ( !aTokenInfo.Compare( label->Des() ) )
+                {
+                // Create token
+                TRAP( err, aToken = CWimToken::NewL( iWimSecModuleMgr->GetWimSecModuleByIndexL( i ), *this ) );
+                i = count + 1; // This completes for loop and separates
+                               // from normal for loop end (i == count)
+                if ( err == KErrNone )
+                    {
+                    IncReferenceCount();
+                    }
+                }
+            }
+        delete label;
+        }
+
+    if ( i == count && err == KErrNone ) // Not match found
+        {
+        err = KErrNotFound;
+        }
+
+    TRequestStatus* r = &aStatus;
+    User::RequestComplete( r, err );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenType::OpenToken()
+// Open new token, The handle of the required token is used to get needed 
+// information. Before opening new token we need to compare token numbers.
+// This is not true asynchronous function.
+// -----------------------------------------------------------------------------
+//
+void CWimTokenType::OpenToken( TCTTokenHandle aHandle,
+                               MCTToken*& aToken,
+                               TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimTokenType::OpenToken with handle" ) );
+    TInt err   = KErrNone;
+    TInt i     = 0;
+    TInt count = 0;
+
+    aStatus = KRequestPending; 
+
+    // Current tokentype and requested token's tokentype must be the same
+    if ( Type() == aHandle.iTokenTypeUid )
+        {
+        // Count of security modules:
+        count = iWimSecModuleMgr->WimCount();
+        // For effectivity reasons, stack the given handle
+        TInt mytokennumber = aHandle.iTokenId;      
+        // Let's go through all Wims and try to match handles
+        for ( i = 0; i < count && err == KErrNone; i++ )
+            {
+            // Stack Wim handle
+            TInt histokennumber = 0;    
+            TRAP( err, histokennumber = iWimSecModuleMgr->
+                                        WimTokenNumberByIndexL( i ) );
+            if ( err == KErrNone )
+                {
+                if ( mytokennumber == histokennumber )
+                    {   
+                    HBufC* label = NULL;// From heap
+                    // Let's get Wim label and use another 
+                    // API function to get token info
+                    TRAP( err, label = iWimSecModuleMgr->
+                                       WimLabelByIndexL( i ).AllocL() );
+                    if ( err == KErrNone )
+                        {
+                        // The completion of the next statement is handled 
+                        // in the associated function
+                        OpenToken( label->Des(), aToken, aStatus );
+                        delete label;
+                        return; // Must quit here, RequestComplete is done
+                        }
+                    delete label;   // Here we go if error in last TRAP
+                    i = count + 1;  // This completes for loop and
+                                    // separates from normal for loop end
+                    }
+                }
+            } // for loop...
+        } // if ( Type()...
+
+    if ( i == count && err == KErrNone ) // No match found 
+        {
+        err = KErrNotFound;
+        }
+
+    TRequestStatus* r = &aStatus;
+    User::RequestComplete( r, err );
+
+    }
+// -----------------------------------------------------------------------------
+// CWimTokenType::CancelOpenToken()
+// Cancel an OpenToken operation.
+// -----------------------------------------------------------------------------
+//
+void CWimTokenType::CancelOpenToken()
+    {
+    _WIMTRACE ( _L( "CWimTokenType::CancelOpenToken" ) );
+    // It's not really async, so you can't cancel.
+    }
+
+// -----------------------------------------------------------------------------
+// TImplementationProxy ImplementationTable[] 
+// An array listing the NewL functions of all the plugins.
+// -----------------------------------------------------------------------------
+//
+const TImplementationProxy ImplementationTable[] = 
+    {
+    {{WIM_IMPLEMENTATION_UID},     (TProxyNewLPtr) CWimTokenType::NewL} //CARD-WIM
+    };
+
+// -----------------------------------------------------------------------------
+// TImplementationProxy* ImplementationGroupProxy()
+// This function is needed by ECom and is the only one exported function
+// -----------------------------------------------------------------------------
+//
+EXPORT_C const TImplementationProxy* 
+                ImplementationGroupProxy( TInt& aTableCount )
+    {
+    aTableCount = sizeof( ImplementationTable ) / sizeof( TImplementationProxy );
+
+    return ImplementationTable;
+    }
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/group/WimServer.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,83 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project build file
+*
+*/
+
+#include <platform_paths.hrh>
+// Uncomment MACRO and define below to enable trace logging
+//MACRO __WIM_ENABLE_TRACES
+//#define __WIM_ENABLE_TRACES
+
+TARGET        WimServer.exe
+TARGETTYPE    exe
+
+UID           0x1000008D 0x101F79DD
+
+CAPABILITY    CAP_SERVER NetworkControl
+VENDORID      VID_DEFAULT
+
+USERINCLUDE   ../../inc             // Common inc
+USERINCLUDE   ../inc                // WimServer inc
+
+APP_LAYER_SYSTEMINCLUDE              // RMmCustomAPI.h
+
+
+// WIM Server source files
+SOURCE        ../src/WimApduImpl.cpp
+SOURCE        ../src/WimMemMgmt.cpp
+SOURCE        ../src/WimResponse.cpp
+SOURCE        ../src/WimScardListener.cpp
+SOURCE        ../src/WimServer.cpp
+SOURCE        ../src/WimSession.cpp
+SOURCE        ../src/WimSessionRegistry.cpp
+SOURCE        ../src/WimSimFileHandler.cpp
+SOURCE        ../src/WimTokenHandler.cpp
+SOURCE        ../src/WimUtilityFuncs.cpp
+SOURCE        ../src/WimTrustSettingsHandler.cpp
+SOURCE        ../src/WimTrustSettingsStore.cpp
+SOURCE        ../src/WimCertUtil.cpp
+SOURCE        ../src/WimBTSapObserver.cpp
+SOURCE        ../src/WimSatRefreshObserver.cpp
+SOURCE        ../src/WimAuthObjHandler.cpp
+SOURCE        ../src/WimCallbackImpl.cpp
+SOURCE        ../src/WimCertHandler.cpp
+SOURCE        ../src/WimKeyMgmtHandler.cpp
+SOURCE        ../src/WimOmaProvisioning.cpp
+SOURCE        ../src/WimJavaProvisioning.cpp
+SOURCE        ../src/WimSecurityDlgHandler.cpp
+SOURCE        ../src/WimSignTextHandler.cpp
+SOURCE        ../src/WimTimer.cpp
+SOURCE        ../src/WimCleanup.cpp
+
+STATICLIBRARY Wimi.lib  // WIMI and WIM Library
+
+LIBRARY         random.lib
+LIBRARY       Scard.lib             // Smart Card Server
+LIBRARY       Asn1.lib              // Used to decode trusted usage OID's
+LIBRARY       Customapi.lib         // CustomAPI (used in SIM file reading)
+LIBRARY       Etel.lib Etelmm.lib   // RTelServer, RMobilePhone
+LIBRARY       Estlib.lib Euser.lib  // Symbian basic libraries
+LIBRARY       Ctframework.lib       // Crypto token framework
+LIBRARY       Efsrv.lib             // File server
+LIBRARY       Edbms.lib             // Database server
+LIBRARY       X509.lib              // X509 certificate
+LIBRARY       WimUtil.lib           // WimUtil module
+LIBRARY       Hash.lib              // Hash operations
+LIBRARY       Crypto.lib            // CCertificate
+LIBRARY       Wtlscert.lib          // Used in certificate handling
+LIBRARY       SatClient.lib         // SAT Refresh
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimApduImpl.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,189 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  APDU Interface between C and Symbian code. Implementations
+*               for WimApdu callbacks.
+*
+*/
+
+
+#ifndef CWIMAPDU_H
+#define CWIMAPDU_H
+
+//  INCLUDES
+#include "Scard.h"
+#include "WimScardListener.h"
+
+
+// CONSTANTS
+const TInt KMaxApduLen     = 262;
+const TInt KMaxReaderCount = 8;
+
+const TInt KDefaulCloseChannelTimeout = 0;  //Timeout in microseconds
+const TUint8 KManageChannelIns        = 0x70;
+const TUint8 KManageChannelParamOpen  = 0x00;
+const TUint8 KManageChannelParamClose = 0x80;
+
+
+// FORWARD DECLARATIONS
+class CScardComm;
+class RScard;
+
+
+// CLASS DECLARATION
+
+/**
+*  WIM APDU interface.
+*  Interface between C and Symbian code. 
+*  Methods for sending and retrieve APDUs.
+*
+*  @since Series60 2.1
+*/
+class CWimApdu : public CActive
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Destructor.
+        */
+         virtual ~CWimApdu();
+
+        /**
+        * Two-phased constructor.
+        */
+        static CWimApdu* NewL();
+
+
+    public: // New functions
+
+        /**
+        * Opens a connection to a reader.
+        * @param aUiReaderId Reader ID
+        * @return status of the operation.
+        */
+        TUint8 Open( TUint8 aUiReaderId );
+
+        /**
+        * Closes a connection to a reader.
+        * @param aUiReaderId Reader ID
+        * @return status of the operation.
+        */
+        TUint8 Close( TUint8 aUiReaderId );
+
+        /**
+        * Sends an ISO 7816 APDU to reader.
+        * @param aUiReaderId Reader ID
+        * @param aApdu APDU to be sent
+        * @param aUiApduLength legth of the APDU
+        * @return status of the operation
+        */
+        TUint8 SendAPDU( TUint8  aUiReaderId,
+                         TUint8* aApdu,
+                         TUint16 aUiApduLength );
+        /**
+        * Cancel apdu sending
+        */                 
+        void CancelApduSending();                 
+
+        /**
+        * Gets a list of reader statusses.
+        * @return status of the operation
+        */
+        TUint8 RequestListL();
+
+        /**
+        * Returns response APDU from latest SendAPDU call, 
+        * does not return SW-bytes.
+        * @return response APDU
+        */
+        TPtrC8 ResponseApdu() const;
+
+        /**
+        * Returns SW-bytes from latest SendApdu call.
+        * @return SW bytes
+        */
+        TUint16 ResponseSW() const;
+
+        /**
+        * Returns a list of reader statusses from 
+        * latest RequestList call.
+        * @return reader status list
+        */
+        const TBuf8<KMaxReaderCount>& StatusList() const;
+
+        /**
+        * Returns the length of reader status list.
+        * @return lenght of reader status list.
+        */
+        TUint8 StatusListLength() const;
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CWimApdu();
+        
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * From CActive. Stops ActiveSchedulerWait when got APDU response.
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * From CActive. Cancellation function
+        * @return void
+        */
+        void DoCancel();
+
+        /**
+        * Wait until asynchronous call is completed
+        * @return void
+        */
+        void SetActiveAndWait();
+
+    private:    // Data
+
+        // APDU responses are stored here. Owned.
+        HBufC8*                           iResponseBuffer;
+        // SW-bytes of the response.
+        TUint16                           iResponseSW;
+        // Statusses of the readers found
+        TBuf8<KMaxReaderCount>            iReaderStatusses;
+        // How many readers found.
+        TUint8                            iReaderStatusLength;
+        // Status of the response. Possible values in WimDefs.h.
+        TUint8                            iResponseStatus;
+        // Array containing CSardComm* object for each reader found. Owned.
+        CArrayFixFlat<CScardComm*>*       iReaderComm;
+        // Array of supported reader names
+        CArrayFixFlat<TScardReaderName>*  iReaderNames;
+        //Pointer to CScard
+        RScard*                           iServer;
+        // Array of Scard listeners
+        CArrayPtrFlat<CWimScardListener>* iWimScardListenerArray;
+        // Synchronous wait for async request
+        CActiveSchedulerWait              iWait;
+        
+        TUint8                            iUiReaderId;
+
+    };
+
+#endif      // CWIMAPDU_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimAuthObjHandler.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,294 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  WIM Authentication Object Handler
+*
+*/
+
+
+
+#ifndef CWIMAUTHOBJHANDLER_H
+#define CWIMAUTHOBJHANDLER_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <secdlg.h>
+#include "WimResponse.h"
+#include "WimUtilityFuncs.h"
+
+// FORWARD DECLARATIONS
+class CWimSecurityDlgHandler;
+class CWimMemMgmt;
+class CWimUtilityFuncs;
+
+// CONSTANTS
+_LIT( KUnblockingPinLabel, "Unblocking PIN" );
+
+// CLASS DECLARATION
+
+/**
+*  WIM Authentication Object Handler.
+*  Handles authentication objects, such as PIN.
+*
+*  @since Series60 2.1
+*/
+class CWimAuthObjHandler : public CActive
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimAuthObjHandler* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimAuthObjHandler();
+
+    public: // New functions
+        
+        /**
+        * Get PIN count from the WIM card.
+        * @param aMessage Encapsulates a client request.
+        * @return void 
+        */
+        void GetPINCountL( const RMessage2& aMessage ) const;
+        
+        /**
+        * Get reference list for PINs.
+        * @param aMessage Encapsulates a client request.
+        * @param aWimMgmt Pointer to WIM reference management class.
+        * @return void
+        */
+        void GetPINRefListL( const RMessage2& aMessage,
+                             CWimMemMgmt* aWimMgmt );
+
+        /**
+        * Get detailed information about the PIN.
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void GetPINInfoL( const RMessage2& aMessage ) ;
+        
+        /**
+        * Get detailed information about the PINs.
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void GetPINsInfoL( const RMessage2& aMessage );
+        
+        /**
+        * Verifies PIN number.
+        * @since Series60 2.6
+        * @param aMessage Encapsulates a client request.
+        * @param aShowDialog Tells whether to show security dialog
+                             for PIN query or not.
+        * @return void
+        */
+        void VerifyPINRequestL( const RMessage2& aMessage, TBool aShowDialog );
+        
+        /**
+        * Cancel Verifies PIN number.
+        * @since Series60 3.0
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void CancelVerifyPin( const RMessage2& aMessage ); 
+        
+        /**
+        * Verifies Disabled PIN status.
+        * @since Series60 3.0
+        * @param aMessage Encapsulates a client request.
+        * @param aShowDialog Tells whether to show security dialog
+                             for PIN query or not.
+        * @return void
+        */
+        void VerifyDisabledPINRequestL( const RMessage2& aMessage );
+        
+        /**
+        * Changes a PIN number.
+        * @since Series60 2.6
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void ChangePINRequestL( const RMessage2& aMessage );
+        
+        /**
+        * Cancel Changes a PIN number.
+        * @since Series60 3.0
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void CancelChangePin( const RMessage2& aMessage ); 
+        
+        /**
+        * Enables/disables PIN query.
+        * @since Series60 2.6
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void EnablePINReqL( const RMessage2& aMessage );
+        
+        /**
+        * Enables/disables PIN query.
+        * @since Series60 3.0
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void CancelEnablePin( const RMessage2& aMessage ); 
+       
+        /**
+        * Unblocks blocked PIN.
+        * @since Series60 2.6
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void UnblockPinReqL( const RMessage2& aMessage );
+        
+        /**
+        * Cancel Unblocks blocked PIN.
+        * @since Series60 3.0
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void CancelUnblockPin( const RMessage2& aMessage ); 
+        
+        /**
+        * Retrive authentication object's info
+        * @since S60 3.2
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void RetrieveAuthObjectsInfo( const RMessage2& aMessage );
+    
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CWimAuthObjHandler();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Continue Verify PIN request after PIN is asked. Calls WIMI.
+        * @since Series60 2.6
+        * @return void
+        */
+        void VerifyPINAskPIN();
+        void ContinueVerifyPINReqL();
+
+        /**
+        * Continue Change PIN request after PIN is asked. Calls WIMI.
+        * @since Series60 2.6
+        * @return void
+        */
+        void ChangePINAskPIN();
+        void ContinueChangePINReqL();
+
+        /**
+        * Continue Enable/Disable PIN request after PIN is asked. Calls WIMI.
+        * @since Series60 2.6
+        * @return void
+        */
+        void EnablePINAskPIN();
+        void ContinueEnablePINReqL();
+
+        /**
+        * Continue Unblock PIN request after PIN is asked. Calls WIMI.
+        * @since Series60 2.6
+        * @return void
+        */
+        void UnblockPINAskPIN();
+        void ContinueUnblockPinReqL();
+
+        /**
+        * From CActive. Asyncronous PIN query ready. Call ContinueXXX
+        * function depending what we are requesting.
+        */
+        void RunL();
+
+        /**
+        * From CActive. Cancel asynchronous request.
+        */
+        void DoCancel();
+
+        /**
+        * From CActive. Handle leave from RunL()
+        * @param aError leave code from RunL()
+        */
+        TInt RunError( TInt aError );
+
+    private:    // Data
+        // Enumerator for ongoing request
+        enum TAuthObjectRequest
+            {
+            EVerifyPINAskPIN,
+            EVerifyPINCallBackResponse,
+            EChangePINAskPIN,
+            EChangePINCallBackResponse,       
+            EEnablePINAskPIN,
+            EEnablePINCallBackResponse,    
+            EDisablePINAskPIN,
+            EDisablePINCallBackResponse,
+            EUnblockPINAskPIN,
+            EUnblockPINCallBackResponse,
+            EShowPINBlocked,
+            EShowCardIsRemoved,
+            EWIMIError,
+            EIdle
+            };
+
+        // Pointer to utility function class. Owned.
+        CWimUtilityFuncs*       iWimUtilFuncs;
+        // Pointer to security handler class. Owned.
+        CWimSecurityDlgHandler* iWimSecDlg;
+        // Authentication object ongoing request 
+        TAuthObjectRequest      iRequest;
+      
+        // PIN value that user has given
+        TPINValue               iPinValue;
+        // Old PIN value in PIN change
+        TPINValue               iOldPinValue;
+        // New PIN value in Change PIN and Unblock PIN
+        TPINValue               iNewPinValue;
+        // Unblocking PIN
+        TPINValue               iUnblockingPinValue;
+        // Enable/Disable PIN query 
+        TBool                   iEnablePinQuery;
+        
+        TBool                   iRetry;
+        
+        TBool                   iShowDialog;
+        
+        CWimResponse*           iResponseID;
+        
+        TWimReqTrId*            iTrId;
+        
+        TPINParams              iPinParams;
+        
+        TPINParams              iUnblockingPinParams;
+        TBool                   iDisablePINBlocked; 
+        TBool                   iUnblockPING;
+        
+        WIMI_Ref_pt             iPinGRef;
+                 
+    };
+
+#endif      // CWIMAUTHOBJHANDLER_H  
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimBTSapObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,102 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observes the state of Bluetooth Sap. When the state is
+*               changed into connected, connection to smart card is closed and
+*               when the state is changed into not connected, initialize
+*               connection to smart card back.
+*
+*/
+
+
+#ifndef CWIMBTSAPOBSERVER_H
+#define CWIMBTSAPOBSERVER_H
+
+
+//  INCLUDES
+#include <e32base.h>
+#include <e32property.h> // RProperty
+
+// FORWARD DECLARATIONS
+class CWimServer;
+
+// CLASS DECLARATION
+
+/**
+*  Publish and subscribe Observer class
+*  This class listens P/S events
+*
+*  @lib SwimReader.lib
+*  @since Series60 1.2
+*/
+class CWimBTSapObserver : public CActive
+    {
+    public: // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */ 
+        static CWimBTSapObserver* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CWimBTSapObserver();
+
+    public: // New functions
+        
+        /**
+        * Starts listener
+        * @return void 
+        */
+        void Start();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */ 
+        CWimBTSapObserver();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * This function starts listening card state from System agent
+        * @return void
+        */
+        void StartListening();
+        /**
+        * From CActive. Handle asyncronous event response
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * From CActive. Handle Cancel call
+        * @return void
+        */
+        void DoCancel();
+
+    private:    // Data
+        // Bluetooth Sap status property
+        RProperty       iProperty;
+        // Pointer to WimServer.
+        CWimServer*     iWimSvr;
+    };
+
+#endif      // CWIMBTSAPOBSERVER_H
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimCallbackImpl.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,319 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A class with static operations that provides implementation
+*               for the WIM callback functions. Used by the WIM server.
+*
+*/
+
+
+#ifndef CWIMCALLBACK_H
+#define CWIMCALLBACK_H
+
+//  INCLUDES
+#include <e32base.h>
+#include "Wimi.h"       //WIMI definitions
+
+// FORWARD DECLARATIONS
+class CWimResponse;
+
+// CLASS DECLARATION
+
+/**
+*  WIM Callback implementation.
+*  Static callback funtions.
+*
+*  @since Series60 2.1
+*/
+class CWimCallBack : public CBase
+    {
+    public:
+
+        /**
+        * Respond to InitOK operation
+        * @param aStatus - WIMI status
+        * @return void
+        */
+        static void InitOkResp( WIMI_STAT aStatus );
+  
+        /**
+        * Response to CloseDown request
+        * @param aStatus - WIMI status
+        * @return void
+        */
+        static void CloseDownResp( WIMI_STAT aStatus );
+
+        /**
+        * Complete response
+        * @param aTrId - transaction id
+        * @param aStatus - WIMI status
+        * @return void
+        */
+        static void CompleteResponse( WIMI_TransactId_t aTrId,
+                                      WIMI_STAT aStatus );
+
+        /* ------------ Digital signature ----------------------------------- */
+        /**
+        * Respond to the digital signature operation. Completes client
+        * request
+        * @since Series60 2.6
+        * @param aTrId - transaction id
+        * @param aStatus - operation status 
+        * @param aSignLen - signature length
+        * @param aSign - signature 
+        * @return void
+        */
+        static void SignResp( WIMI_TransactId_t aTrId,
+                              WIMI_STAT aStatus,
+                              TUint8 aSignLen,
+                              TUint8* aSign );
+
+        /**
+        * Write signed text to client's memory area. Called by SignResp().
+        * @since Series60 2.6
+        * @param aTrId - transaction id
+        * @param aSignLen - signature length
+        * @param aSign - signature 
+        * @return void
+        */
+        static void SignRespL( CWimResponse* aTrId,
+                               TUint8 aSignLen,
+                               TUint8* aSign );
+
+        /**
+        * Set request status of SignTextHandler. Used when continuing signing
+        * operation if wrong PIN entered.
+        * @since Series60 2.6
+        * @param aStatus - RequestStatus of SignTextHandler
+        * @return void
+        */
+        static void SetSignTextRequestStatus( TRequestStatus* aStatus );
+
+        /* ------------ Certificate management ------------------------------ */
+        /** 
+        * Respond to the certificate fetch operation
+        * @param aTrId - transaction id
+        * @param aStatus - operation status 
+        * @param aCertRef - the reference to certificate that was fetched
+        * @param aCertLen - certificate content length
+        * @param aCert - certificate content 
+        * @return void
+        */
+        static void CertificateResp( WIMI_TransactId_t aTrId,
+                                     WIMI_STAT aStatus,
+                                     WIMI_Ref_t* aCertRef,
+                                     TUint16 aCertLen,
+                                     TUint8* aCert );
+
+        /**
+        * Respond to the certificate delete operation
+        * @since Series60 2.6
+        * @param aTrId - transaction id
+        * @param aStatus - operation status
+        * @return void
+        */
+        static void CertificateDeleteResp( WIMI_TransactId_t aTrId,
+                                           WIMI_STAT aStatus );
+
+        /**
+        * Respond to the certificate store operation
+        * @since Series60 2.6
+        * @param aTrId - transaction id
+        * @param aStatus - operation status
+        * @param aCertRef - the reference to certificate that was stored
+        * @return void
+        */
+        static void CertificateStoreResp( WIMI_TransactId_t aTrId,
+                                          WIMI_STAT aStatus,
+                                          WIMI_Ref_t* aCertRef );
+
+
+        /* ------------ PIN management -------------------------------------- */
+        /**
+        * Response to VerifyPIN request
+        * @since Series60 2.6
+        * @param aTrId - transaction id
+        * @param aStatus - operation status
+        * @return void
+        */
+        static void VerifyPINResp( WIMI_TransactId_t aTrId, WIMI_STAT aStatus );
+
+        /**
+        * Response to ChangePIN request
+        * @since Series60 2.6
+        * @param aTrId - transaction id
+        * @param aStatus - operation status
+        * @return void
+        */
+        static void ChangePINResp( WIMI_TransactId_t aTrId, WIMI_STAT aStatus );
+
+        /**
+        * Response to UnblockPIN request
+        * @since Series60 2.6
+        * @param aTrId - transaction id
+        * @param aStatus - operation status
+        * @return void
+        */
+        static void UnblockPINResp( WIMI_TransactId_t aTrId,
+                                    WIMI_STAT aStatus );
+
+        /**
+        * Response to EnablePIN request
+        * @since Series60 2.6
+        * @param aTrId - transaction id
+        * @param aStatus - operation status
+        * @return void
+        */
+        static void EnablePINResp( WIMI_TransactId_t aTrId, WIMI_STAT aStatus );
+
+        /* ------------ Hardware driver support ----------------------------- */
+        /**
+        * Respond to CardInserted operation
+        * @param aReader - Reader ID
+        * @param aStatus - Status of operation
+        * @param aWIMRef - Reference to WIMI
+        * @return void
+        */
+        static void CardInsertedResp( TUint8 aReader,
+                                      WIMI_STAT aStatus,
+                                      WIMI_Ref_t* aWIMRef );
+
+        /**
+        * Open connection to card
+        * @param aReader - Reader
+        * @return KWimStatusOK/KWimStatusIOError
+        */
+        static TUint8 Open( TUint8 aReader );
+
+        /**
+        * Close connection to the card
+        * @param aReader - Reader
+        * @return KWimStatusOK
+        */
+        static TUint8 Close( TUint8 aReader );
+
+        /**
+        * APDU Request
+        * @param aReader - Reader
+        * @param aApdu - APDU
+        * @param aApduLen - ADDU length
+        * @return void
+        */
+        static void APDUReq( TUint8 aReader, TUint8* aApdu, TUint16 aApduLen );
+
+        /**
+        * Get ATR bytes request
+        * @param aReader - Reader
+        * @return void
+        */
+        static void GetATRReq( TUint8 aReader );
+
+        /**
+        * Get reader list reguest
+        * @return void
+        */
+        static void GetReaderListReq();
+
+        /**
+        * Read content of SIM file.
+        * @param aReaderId -  Reader ID
+        * @param aPath - Path to the file to read
+        * @param aOffset - Offset from the beginning of the file
+        * @param aSize - Amount of data to read, aSize=0 means that whole
+        *                    file must be read
+        * @return void
+        */
+        static void ReadSimFileReq( TUint8 aReaderId,
+                                    TUint8* aPath,
+                                    TUint16 aOffset,          
+                                    TUint16 aSize );
+
+        /**
+        * Response for OMA Smart Card Provisioning file request.
+        * @param aTrId - Transaction ID, contains message information
+        * @param aStatus - Operation status 
+        * @param aFileLen - Provisioning file length
+        * @param aFile - Provisioning file content
+        * @return void
+        */
+        static void OmaProvisioningResp( WIMI_TransactId_t aTrId,
+                                         WIMI_STAT aStatus,
+                                         TUint16 aFileLen,
+                                         TUint8 *aFile );
+                                         
+        /**
+        * Cancel pin operation
+        * Stop the APDU sending
+        */                                 
+        static void CancelPinOperation();
+        
+        /**
+        * Cancel Wim Initialize 
+        * Stop the APDU sending
+        */
+        static void CancelWimInitialize();
+        
+        /**
+        * This function is called by CWimServer destructor,
+        * to delete the gApdu object.
+        */
+        static void CWimCallBack::DeletegApdu();
+                             
+    private:
+
+        /** 
+        * Respond to the certificate fetch operation
+        * @param aTrId - transaction id
+        * @param aStatus - operation status 
+        * @param aWimiRef - the reference to WIMI
+        * @param aCertLen - certificate content length
+        * @param aCert - certificate content 
+        * @return void
+        */
+        static void CertificateRespL( CWimResponse* aTrId,
+                                      WIMI_STAT aStatus,
+                                      WIMI_Ref_t* aWimiRef,
+                                      TUint16 aCertLen,
+                                      TUint8* aCert );
+
+        /**
+        * Read content of SIM file. Leaving function, 
+        * leave is trapped in ReadSimFileReg
+        * @param aReaderId - Reader ID
+        * @param aPath - Path to the file to read
+        * @param aOffset - Offset from the beginning of the file
+        * @param aSize - Amount of data to read, aSize=0 means that whole
+        *                file must be read
+        * @return void
+        */
+        static void DoReadSimFileReqL( TUint8 aReaderId,
+                                       TUint8* aPath,
+                                       TUint16 aOffset,          
+                                       TUint16 aSize );
+
+        /**
+        * Copy OMA Provisioning file to client memory
+        * @param aTrId - Transaction ID, contains message information
+        * @param aFileLen - Provisioning file length
+        * @param aFile - Provisioning file content
+        * @return void
+        */
+        static void OmaProvisioningRespL( CWimResponse* aTrId,
+                                          TUint16 aFileLen,
+                                          TUint8* aFile );
+
+    };
+
+#endif      // CWIMCALLBACK_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimCertHandler.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,213 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  WIM Certificate handler
+*
+*/
+
+
+
+#ifndef CWIMCERTHANDLER_H
+#define CWIMCERTHANDLER_H
+
+//  INCLUDES
+#include "WimClsv.h"
+
+// FORWARD DECLARATIONS
+class CWimMemMgmt;
+class CWimUtilityFuncs;
+
+// CLASS DECLARATION
+
+/**
+*  Class for handling certificates in WIM card
+*  
+*  @since Series60 2.1
+*/
+class CWimCertHandler : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimCertHandler* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimCertHandler();
+
+    public: // New functions
+        
+        /**
+        * Fetches certificates from WIM card.
+        * @param aMessage Encapsulates a client request.
+        * @param aWimMgmt Pointer to WIM reference management class.
+        */
+        void GetCertificatesFromWimL( const RMessage2& aMessage, 
+                                      CWimMemMgmt* aWimMgmt );
+        
+        /**
+        * Fetches certificate extra information from WIM card.
+        * Extra information includes trusted usage and CDF referense
+        * information.
+        * @param aMessage Encapsulates a client request.
+        * @param aWimMgmt Pointer to WIM reference management class.
+        */
+        void GetExtrasFromWimL( const RMessage2& aMessage, 
+                                CWimMemMgmt* aWimMgmt );
+        
+        /**
+        * Fetches count of certicates in certain WIM card.
+        * @param aMessage Encapsulates a client request.
+        * @param aWimMgmt Pointer to WIM reference management class.
+        */
+        void GetCerticateCountL( const RMessage2& aMessage, 
+                                 CWimMemMgmt* aWimMgmt ) const;
+
+
+        /**
+        * Stores certificate to the WIM card.
+        * @since Series60 2.6
+        * @param aRequest Enumerator used in message 
+                          passing between client and server.   
+        * @param aMessage Encapsulates a client request.
+        */
+        void StoreCertificateL( TWimServRqst aRequest,
+                                const RMessage2& aMessage ) const;
+
+        /**
+        * Removes certificate from a WIM card.
+        * @since Series60 2.6
+        * @param aMessage Encapsulates a client request.
+        * @param aWimMgmt Pointer to WIM reference management class.
+        */
+        void RemoveCertificateL( const RMessage2& aMessage,
+                                 CWimMemMgmt* aWimMgmt ) const;
+        
+        /**
+        * Fetches certificate details.
+        * @param aOpCode Enumerator used in message 
+                          passing between client and server.   
+        * @param aMessage Encapsulates a client request.
+        */
+        void GetCertificateDetailsL( TWimServRqst aOpCode,
+                                      const RMessage2& aMessage ) ;
+
+        /**
+        * Exports Public Key of certificate
+        * @since Series60 2.6
+        * @param aMessage Encapsulates a client request.
+        */
+        void ExportPublicKeyL( const RMessage2& aMessage ) const;
+        
+        
+        TBool SanityCheck( TUint32 aCertRef );
+        
+        TBool CheckReadCapsForUsage( const RMessage2& aMsg,
+                                       TUint8 aUsage );
+        
+        
+        WIMI_STAT ResolveCertUsage( const RMessage2& aMsg,
+                                                TUint8& aUsage );
+
+        WIMI_STAT GetCertificateInfo( WIMI_Ref_pt aCertRef,
+                                                  TUint8& aUsage );
+    private:
+
+        CWimCertHandler();
+        void ConstructL();
+
+        /**
+        * Fetches certificate from the WIM card.
+        * @param aTmpWimRef Reference(id) of certain WIM card.
+        * @param aUsage     Certificate usage. Client/CA.
+        * @param aCertNum   Certificate number.
+        * @param aCertRefLst    Pointer to certificate reference list.
+        * @param aCertInfoLst   Pointer to certificate info list.
+        * @param aMessage   Encapsulates a client request.
+        * @return Status returned by WIMI. See in wimclsv.h.
+        */
+        WIMI_STAT GetCertificateFromWimRefL( WIMI_Ref_t* aTmpWimRef,
+                                             TInt8 aUsage,
+                                             TUint8& aCertNum,
+                                             TUint32* aCertRefLst,
+                                             TWimCertInfo* aCertInfoLst,  
+                                             const RMessage2& aMessage );
+
+        /**
+        * Copies certificate information to client's allocated memory area.
+        * @param aCertInfo  Certificate information to be copied.
+        * @param aCert      Certificate reference.
+        * @param aMessage   Encapsulates a client request.
+        * @return TInt      KErrNone or KErrArgument
+        */
+        TInt CopyCertificateInfo( TWimCertInfo& aCertInfo,
+                                   WIMI_Ref_t* aCert,  
+                                   const RMessage2& aMessage );
+
+        /**
+        * Fetches certificate extra information from the WIM card.
+        * @param aTmpWimRef Reference(id) of certain WIM card.
+        * @param aUsage     Certificate usage. Client/CA.
+        * @param aKeyHash   Certificate key hash.
+        * @param aMessage   Encapsulates a client request.
+        * @return Status returned by WIMI. See in WimClsv.h.
+        */
+        WIMI_STAT GetExtrasFromWimRefL( WIMI_Ref_t* aTmpWimRef,                                  
+                                        TInt8 aUsage,
+                                        TDesC8& aKeyHash,
+                                        const RMessage2& aMessage );
+
+        /**
+        * Copies certificate extra information to client's allocated
+        * memory area. Extra information includes trusted usage OID's
+        * and certificate location information.
+        * @param aCert            Certificate reference.
+        * @param aMessage         Encapsulates a client request.
+        */
+        void CopyCertExtrasInfoL( WIMI_Ref_t* aCert,
+                                  const RMessage2& aMessage );
+
+        /**
+        * Get count of certificates in WIM
+        * @param aRef       WIM card reference pointer.
+        * @param aCertCount Count of certificates in WIM card pointed by aRef
+        * @param aUsage     Certificate usage.
+        * @return Status returned by WIMI. See in wimclsv.h.
+        */
+        WIMI_STAT GetCertificateCountByWIM( WIMI_Ref_t* aRef, 
+                                            TUint8& aCertCount, 
+                                            TUint8 aUsage ) const;
+
+        /**
+        * Parse Public Key from certificate.
+        * @since Series60 2.6
+        * @param aCertData   Certificate binary data
+        * @param aPublicKey  Public Key
+        * @param aCertType   Certificate type (X509/WTLS)
+        */
+        void ParseCertPublicKeyL( const TDesC8& aCertData,
+                                  TDes8& aPublicKey,
+                                  const TUint8 aCertType ) const;
+
+
+    private:    // Data
+        CWimUtilityFuncs* iWimUtilFuncs;
+        RArray<TUint32> iCertRefLst;
+    };
+
+#endif      // CWIMCERTHANDLER_H
+    
+//End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimCertUtil.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,405 @@
+/*
+* Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface which handles certificate related operations
+*
+*/
+
+
+
+#ifndef WIMCERTUTIL_H
+#define WIMCERTUTIL_H
+
+
+//INCLUDES
+#include "WimClsv.h"
+#include "Wimi.h"
+#include <ct.h> 
+
+
+// FORWARD DECLARATIONS
+class CWimCertInfo;
+class CCTCertInfo;
+class CWimUtilityFuncs;
+
+// CONSTANTS
+typedef HBufC8* PHBufC8;
+typedef TPtr8* PTPtr8;
+
+
+// CLASS DECLARATION
+/**
+*  Utility class that handles certificate related operations.
+
+*  @since Series60 3.0
+*/
+class CWimCertUtil : public CActive
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        * @param aToken -Reference to current token
+        */
+        static CWimCertUtil* NewL( MCTToken& aToken );
+
+        /**
+        * Destructor
+        */
+        virtual ~CWimCertUtil();
+        
+    public: // New functions
+
+        /**
+        * Restores certificates from WIM cache. If Restore cannot find
+        * any certificate, it will return KErrNotFound to caller.
+        * @param  aArray    -Array where new certificates are 
+        *                   inserted. Caller is responsible 
+        *                   to deallocate CWimCertInfo -objects
+        *                   by calling ResetAndDestroy.(IN/OUT)
+        * @param  aStatus   -Status from caller.         
+        */
+        void Restore( RPointerArray<CWimCertInfo>& aArray, 
+                      TRequestStatus& aStatus );
+
+        
+        /** 
+        * Cancels outgoing Restore operation. Sets an internal flag to true. 
+        * After necessary cleanup, caller is signalled with KErrCancel 
+        * -error code.
+        */
+        void CancelRestore();
+        
+        /**
+        * Retrieves the actual certificate. In case of other cert than
+        * Url cert the binary encoded certificate is written into the 
+        * aEncodedCert parameter. In case of Url cert the data is 
+        * the actual url.
+        * @param  aIndex. Used to point iCertRefLst and iCertInfoArr 
+        *         -arrays for correct certificate.
+        * @param  aEncodedCert. A buffer to put the certificate in. 
+        * @param  aStatus. A request status that is completed when the 
+        *         operation has finished.(IN/OUT)
+        */
+        void RetrieveCertByIndexL( const TInt aIndex,
+                                   TDes8& aEncodedCert, 
+                                   TRequestStatus& aStatus );
+
+    private:
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * C++ default constructor.
+        * @param aToken -Reference to current token
+        */
+        CWimCertUtil( MCTToken& aToken );
+
+        /**
+        * Get count of certificates in WIM
+        * @param aRef       WIM card reference pointer.
+        * @param aCertCount Count of certificates in WIM card pointed by aRef
+        * @param aUsage     Certificate usage.
+        * @return Status returned by WIMI. See in WimClsv.h.
+        */
+        WIMI_STAT GetCertificateCountByWIM( WIMI_Ref_t* aRef, 
+                                            TUint8& aCertCount, 
+                                            TUint8 aUsage ) const;
+        /**
+        * Get certificate extra data
+        * @param aWimRef         WIM card reference pointer.
+        * @param aUsage          Certificate usage.
+        * @param aKeyHash        Key hash of certificate
+        * @param aCertExtrasInfo Returned extra data
+        * @return Status returned by WIMI.
+        */
+        WIMI_STAT GetExtrasFromWimRefL( 
+                                    WIMI_Ref_t* aWimRef,
+                                    TInt8 aUsage,
+                                    TDesC8& aKeyHash,
+                                    TCertExtrasInfo& aCertExtrasInfo ) const;
+
+        /**
+        * Allocates memory for the array which is filled by server.
+        * @param  aWimCertInfoArr    -Array to be initialized 
+        * @param  aCount             -Count of elements in the array         
+        */
+        void AllocWimCertInfoL( TWimCertInfo* aWimCertInfoArr, TInt aCount );
+        
+        /**
+        * Deallocates memory from the array.
+        */
+        void DeallocWimCertInfo();   
+        
+        /**
+        * Allocates memory for a struct which is filled by server.
+        */
+        void AllocMemoryForCertDetailsL();
+
+        /**
+        * Creates new certificate objects which can be returned to the caller.
+        */
+        void CreateNewCertObjectsL();
+        
+        /**
+        * Creates new wim certificate objects.
+        */
+        void CreateNewWimCertObjectL();
+
+        /**
+        * Gets trusted usages.
+        */
+        void GetTrustedUsagesL();
+
+        /**
+        * Completion of trusted usages.
+        */
+        void TrustedUsagesDoneL();
+
+        /**
+        * Sets own iStatus to KRequestPending, and signals it 
+        * with User::RequestComplete() -request. This gives chance 
+        * to activescheduler to run other active objects. After a quick
+        * visit in activescheduler, signal returns to RunL() and starts next
+        * phase of operation. 
+        */
+        void SignalOwnStatusAndComplete();
+        
+        /**
+        * Copies data to caller's buffer by using pointer.
+        */
+        void CopyRetrievedCertData();
+
+        /**
+        * DeAllocates memory from member variables, which are used
+        * when communicating with WIM.
+        */
+        void DeallocCertHBufs();
+
+        /**
+        * If user has cancelled initialization process, dealloc references 
+        * from loaded certs. 
+        */
+        void DeallocReferences();
+
+        /**
+        * Returns certificate format according to received index.
+        * @param aIndex -index of the certificate to be returned.
+        * @return TCertificateFormat -format of the certificate
+        */
+        TCertificateFormat GetCertFormatByIndex( TInt aIndex );
+
+        /**
+        * Copy certificate extra data
+        * @param aCert           Reference to certificate
+        * @param aCertExtrasInfo Returned extra data
+        */
+        void CopyCertExtrasInfoL( WIMI_Ref_t* aCert,
+                                  TCertExtrasInfo& aCertExtrasInfo ) const;
+
+        /**
+        * Return count of certificates in WIM
+        * @param aType           Certificate type
+        * @return Count of certificates
+        */
+        TUint8 CertCount( TWimEntryType aType );
+
+        /**
+        * Get certificate reference list
+        * @param aCertAddrLst
+        * @param aCertInfoArr
+        * @param aCertEntryType
+        */
+        void CertRefLstL( TCertificateAddressList aCertAddrLst, 
+                          TWimCertInfo* aCertInfoArr, 
+                          TWimEntryType aCertEntryType );
+
+        /**
+        * Get certificate extra data
+        * @param aKeyId
+        * @param aCertExtrasInfo
+        * @param aUsage
+        * @param aStatus
+        */
+        void GetCertExtrasL( const TPtr8* aKeyId, 
+                             TCertExtrasInfo& aCertExtrasInfo,
+                             TUint aUsage,
+                             TRequestStatus& aStatus );
+
+        /**
+        * Get certificate details
+        * @param aCertAddr
+        * @param aWimCertDetails
+        */
+        void CertDetailsL( const TCertificateAddress aCertAddr, 
+                           TWimCertDetails& aWimCertDetails );
+
+        /**
+        *
+        * @param aTmpWimRef
+        * @param aUsage
+        * @param aCertNum
+        * @param aCertRefLst
+        * @param aCertInfoLst
+        * @return Error code returned by WIMI
+        */
+        WIMI_STAT GetCertificateFromWimRefL( WIMI_Ref_t* aTmpWimRef,
+                                             TInt8 aUsage,
+                                             TUint8& aCertNum,
+                                             TUint32* aCertRefLst,
+                                             TWimCertInfo* aCertInfoLst );
+
+        /**
+        * Copy certificate info
+        * @param aCertInfo
+        * @param aCert
+        */
+        void CopyCertificateInfo( TWimCertInfo& aCertInfo,
+                                  WIMI_Ref_t* aCert );
+
+    private: //from CActive
+        
+        /**
+        * Different phases are handled here.
+        */
+        void RunL();
+
+        /**
+        * Cancellation function
+        * Deallocates member variables and completes client status with
+        * KErrCancel error code.
+        */
+        void DoCancel();
+
+        /**
+        * The active scheduler calls this function if this active 
+        * object's RunL() function leaves. 
+        * Handles necessary cleanup and completes request with
+        * received error code.
+        * @param aError -The error code which caused this function call.
+        * @return TInt  -Error code to activescheduler, is always KErrNone.
+        */ 
+        TInt RunError( TInt aError );
+
+    private:
+
+        /**
+        * Seven different phases, which are used to 
+        * Read certificates from WIM cache, create new certificate objects and
+        * retrieve certificate
+        */
+        enum TPhase
+            {
+            EListCertsFromWim,
+            ECreateNewCertObjects,
+            EGetTrustedUsages,
+            ECertObjectsDone,
+            ETrustedUsagesDone,
+            ERetrieveCertificate,
+            ERetrievingCompleted
+            };
+
+        //Client status is stored here while operation
+        //on the server side is done.
+        TRequestStatus*                 iClientStatus;
+        //Array which is used to contain new certificate objects.
+        //Not owned. Caller is responsible to destroy array.
+        RPointerArray<CWimCertInfo>*    iArray;
+        //Details of the certificate. Owned.
+        TWimCertDetails                 iWimCertDetails;
+        //Reference to current token. Needed in CCTCertInfo creation.
+        MCTToken&                       iToken;
+        //Typedefs for the reference to certificate. Owned.
+        TCertificateAddressList         iCertRefLst; 
+        // Certificate information structure. Owned.
+        TWimCertInfo*                   iCertInfoArr;
+        //Used to handle different phases.
+        TPhase                          iPhase;
+        //Index to point which certificate we want to be retrieved
+        TInt                            iCertRetrieveIndex;
+        //Used to inform the size of the array, needed in array construction/
+        //destruction.
+        TInt                            iArraySize;
+        //The count of certificates
+        TUint8                          iCertCount;
+        //Pointer to HBufC8*. This is used as an array when listing every 
+        //certificate from WIM to an array during startup. Owned.
+        PHBufC8*                        iLabel;
+        //Pointer to HBufC8*. This is used as an array when listing every 
+        //certificate from WIM to an array during startup. Owned.
+        PHBufC8*                        iKeyId;
+        //Pointer to HBufC8*. This is used as an array when listing every 
+        //certificate from WIM to an array during startup. Owned.
+        PHBufC8*                        iCAId;
+        //Pointer to HBufC8*. This is used as an array when listing every 
+        //certificate from WIM to an array during startup. Owned.
+        PHBufC8*                        iIssuerHash;
+        //Pointer to iLabel. Also used as an array. Owned.        
+        PTPtr8*                         iLabelPtr;
+        //Pointer to iKeyId. Also used as an array. Owned.        
+        PTPtr8*                         iKeyIdPtr;
+        //Pointer to iCAId. Also used as an array. Owned.        
+        PTPtr8*                         iCAIdPtr;
+        //Pointer to iIssuerHash. Also used as an array. Owned.
+        PTPtr8*                         iIssuerHashPtr;
+        //Modifiable 8-bit descriptor which points
+        //to caller's descriptor. We copy retrieved certificate
+        //data to this descriptor. Owned.
+        TDes8*                          iEncodedCert;
+        //Buffer which is used to contain certificate data. Owned.
+        HBufC8*                         iCertHBufOne;
+        //Pointer to iCertHBufOne. Owned.
+        TPtr8*                          iCertHBufOnePtr;
+        //Buffer which is used to contain certificate data. Owned.        
+        HBufC8*                         iCertHBufTwo;
+        //Pointer to iCertHBufTwo. Owned.
+        TPtr8*                          iCertHBufTwoPtr;
+        //Buffer which is used to contain certificate data. Owned.        
+        HBufC8*                         iCertHBufThree;
+        //Pointer to iCertHBufThree. Owned.
+        TPtr8*                          iCertHBufThreePtr;
+        //Buffer which is used to contain certificate data. Owned.        
+        HBufC8*                         iCertHBufFour;
+        //Pointer to iCertHBufFour. Owned.
+        TPtr8*                          iCertHBufFourPtr;
+        //ActiveSchedulerWaiter for certificate extra information
+        //fetching.
+        CActiveSchedulerWait            iActiveSchedulerWait;
+        //Pointer for trusted usage buffer
+        HBufC*                          iTrustedUsages;
+        //Pointer to trusted usage buffer pointer
+        TPtr*                           iTrustedUsagesPtr;
+        //Index pointing to certificate elements
+        TUint8                          iIndex;
+        //Pointer to one certificate info, owned
+        CCTCertInfo*                    iCert;
+        //Pointer to one WIM specific certificate info, owned
+        CWimCertInfo*                   iCertInfo;
+        //An array of trusted usage oids
+        RArray<HBufC*>*                 iOids;
+        //Package structure for certificate extra info
+        TCertExtrasInfo                 iCertExtrasInfo;
+        //Pointer for key identifier buffer
+        HBufC8*                         iKeyIdBuf;
+        //Used to point right keyId when retrieving extra data
+        TPtr8*                          iKeyIdPointer;
+        //Pointer to utility functions. Owned.
+        CWimUtilityFuncs*               iWimUtilFuncs;
+    };
+
+#endif  //WIMCERTUTIL_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimCleanup.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,85 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Cleanup macros and definitions
+*
+*/
+
+#ifndef WIMCLEANUP_H
+#define WIMCLEANUP_H
+
+#include "wimi.h"
+
+
+//
+// CleanupStack functions for WIMI data
+//
+
+inline void CleanupPushWimBufL( WIMI_BinData_t& aWimData )
+    {
+    CleanupStack::PushL( TCleanupItem( WSL_OS_Free, aWimData.pb_buf ) );
+    }
+
+inline void CleanupPushWimRefL( WIMI_Ref_t* aWimRef )
+    {
+    CleanupStack::PushL( TCleanupItem( free_WIMI_Ref_t, aWimRef ) );
+    }
+
+void FreeRefList( void* aRefList );
+
+inline void CleanupPushWimRefListL( WIMI_RefList_t aWimRefList )
+    {
+    CleanupStack::PushL( TCleanupItem( FreeRefList, aWimRefList ) );
+    }
+
+
+//
+// CleanupResetAndDestroyPushL() function
+//
+
+template <class T>
+class CleanupResetAndDestroy
+    {
+public:
+    inline static void PushL( T& aRef );
+private:
+    static void ResetAndDestroy( TAny *aPtr );
+    };
+
+template <class T>
+inline void CleanupResetAndDestroyPushL( T& aRef );
+
+template <class T>
+inline void CleanupResetAndDestroy<T>::PushL( T& aRef )
+    {
+    CleanupStack::PushL( TCleanupItem( &ResetAndDestroy, &aRef ) );
+    }
+
+template <class T>
+void CleanupResetAndDestroy<T>::ResetAndDestroy( TAny *aPtr )
+    {
+    if( aPtr )
+        {
+        static_cast<T*>( aPtr )->ResetAndDestroy();
+        }
+    }
+
+template <class T>
+inline void CleanupResetAndDestroyPushL( T& aRef )
+    {
+    CleanupResetAndDestroy<T>::PushL( aRef );
+    }
+
+
+#endif // WIMCLEANUP_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimJavaProvisioning.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,130 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#ifndef CWIMJAVAPROVISIONING_H
+#define CWIMJAVAPROVISIONING_H
+
+//  INCLUDES
+#include "Wimi.h"    //WIMI functions and definitions
+#include "JavaUtils.h"  //Java Provisioning Smart Card API types
+
+// CONSTANTS
+const TUint8 KWimProvACIFFileOID[]      = {0x01, 0x03, 0x06, 0x01, 0x04, 0x01, 0x2A, 0x02, 0x6E, 0x03, 0x01, 0x01, 0x01 };
+const TInt   KWimProvACIFFileOidLength           = 13;
+
+const TUint8 KWimProvACIFFileOIDTaged[] = {0x06, 0x0C, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x2A, 0x02, 0x6E, 0x03, 0x01, 0x01, 0x01 };
+
+const TInt   KWimProvACIFFileOidLengthTaged      = 14;
+
+const TInt   KWimJavaOidLengthTaged              = 16;
+
+const TInt   KJavaFilePathMaxLength                = 8;
+
+// FORWARD DECLARATION
+class CWimUtilityFuncs;
+
+// CLASS DECLARATION
+
+/**
+*  Class for handling Java Provisioning files.
+*  
+*  @since Series60 3.2
+*/
+class CWimJavaProvisioning : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimJavaProvisioning* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimJavaProvisioning();
+
+    public: // New functions
+        
+        /**
+        * Write size of ACIF file to client memory
+        * @param aMessage Client message
+        * @return void
+        */
+        void ACIFFileSizeL( const RMessage2& aMessage );
+        
+        void ACFFileSizeL( const RMessage2& aMessage );
+        /**
+        * Write content of ACIF file to client memory
+        * @param aMessage Client message
+        * @return void
+        */
+        void ACIFFileContentL( const RMessage2& aMessage );
+        
+        void ACFFileContentL( const RMessage2& aMessage );
+        
+        void LabelAndPath( const RMessage2& aMessage ); 
+        
+        
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CWimJavaProvisioning();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Initialize path and size member variables with values got from WIMI.
+        * @return void
+        */
+        void InitializePathsAndSizes();
+        
+        void InitializeSize();
+        /**
+        * Parse size of ACIF file if not given in DODF-JavaProv file
+        * @return void
+        */
+        void ParseACIFFileSize();
+
+       
+    private:    // Data
+        // Reference to WIM. Not owned.
+        WIMI_Ref_t*               iWimRef;
+        
+        // Path of bootstrap file. Length is 0 if not exists.
+        TBuf8<KJavaFilePathMaxLength> iPathACIF;
+        
+        TBuf8<KJavaFilePathMaxLength> iPathACF;
+        // Size of ACIF file
+        TInt                      iACIFFileSize;
+        
+        TInt                      iACFFileSize;
+        // Flag to tell if provisiong file infos are initialized
+        TBool                     iFileInfosInitialized;
+        
+        // Pointer to CWimUtilityFuncs. Owned.
+        CWimUtilityFuncs*         iWimUtilityFuncs;
+    };
+
+#endif      // CWIMJAVAPROVISIONING_H
+    
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimKeyMgmtHandler.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,97 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Wim key management handler
+*
+*/
+
+
+
+#ifndef CWIMKEYMGMTHANDLER_H
+#define CWIMKEYMGMTHANDLER_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// FORWARD DECLARATIONS
+class CWimMemMgmt;
+class CWimUtilityFuncs;
+
+// CLASS DECLARATION
+
+/**
+*  WIM key management handler
+*  
+*
+*  @since Series60 2.6
+*/
+class CWimKeyMgmtHandler : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimKeyMgmtHandler* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimKeyMgmtHandler();
+
+    public: // New functions
+        
+        /**
+        * Checks if the given key exists.
+        * @param    aMessage Client message
+        * @return   void
+        */
+        void DoesKeyExistL( const RMessage2& aMessage );
+
+        /**
+        * Fetches the details of the given key.
+        * @param    aMessage Client message
+        * @return   void
+        */
+        void GetKeyDetailsL( const RMessage2& aMessage );
+
+        /**
+        * Fetches the list of keys in WIM.
+        * @param    aMessage Client message
+        * @param    aWimMgmt Pointer to CWimMemMgmt class
+        * @return   void
+        */
+        void GetKeyListL( const RMessage2& aMessage,
+                          CWimMemMgmt* aWimMgmt ) const;
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CWimKeyMgmtHandler();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    private:    // Data
+        // Pointer to Utility functions class
+        CWimUtilityFuncs* iWimUtilFuncs;
+
+    };
+
+#endif      // CWIMKEYMGMTHANDLER_H 
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimMemMgmt.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,133 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  WIM memomy management
+*
+*/
+
+
+
+#ifndef CWIMMEMMGMT_H
+#define CWIMMEMMGMT_H
+
+//  INCLUDES
+#include "Wimi.h"            //WIMI definitions
+#include <e32base.h>
+
+
+// DATA TYPES
+enum TWimRefType
+    {
+    EWimiRefpt,
+    EWimiRefListt,
+    };
+
+struct TWimiAllocRef
+    {
+    union 
+        {
+        WIMI_Ref_pt ref;
+        WIMI_RefList_t refLst;
+        };
+    
+    TWimRefType refType;
+    };
+
+
+// CLASS DECLARATION
+
+/**
+*  WIM memomy management.
+*  
+*  @since Series60 2.1
+*/
+class CWimMemMgmt : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimMemMgmt* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimMemMgmt();
+
+    public: // New functions
+        
+        /**
+        * Sets active memory reference to iWimRef member variable.
+        * @param aRef active reference.
+        */
+        void SetWIMRef( WIMI_Ref_pt aRef );
+
+        /**
+        * Retrieves active reference.
+        * @return Active reference.
+        */
+        WIMI_Ref_pt WimRef();
+
+        /**
+        * Creates and append a new WIMI_Alloc_Ref item to iRefs array.
+        * @param aLst reference list where to add the new item.
+        */
+        void AppendWIMRefLstL( WIMI_RefList_t aLst );
+
+        /**
+        * Creates and appends a new WIMI_Alloc_Ref item to iRefs array.
+        * @param aRef Reference to be added.
+        */
+        void AppendWIMRefL( WIMI_Ref_pt aRef );        
+        
+        /**
+        * Removes reference from the list and releases allocated memory.
+        * @param aRef Reference to be freed.
+        */
+        void FreeRef( WIMI_Ref_pt );
+
+        /**
+        * Frees the reference(s) pointed by a client.
+        * @param aMessage Encapsulates a client request.
+        */
+        void FreeWIMRefs( const RMessage2& aMessage );
+
+        /**
+        * Frees the list of reference(s) pointed by a client.
+        * @param aMessage Encapsulates a client request.
+        */
+        void FreeRefLst( const RMessage2& aMessage );
+
+        /**
+        * Checks if the reference is valid
+        * @param aRef Reference to be checked.
+        * @return TBool ETrue if aRef is valid.
+        */
+        TBool ValidateWIMRefL( WIMI_Ref_pt aRef );
+
+
+    private:
+
+        CWimMemMgmt();
+        void ConstructL();
+        void CleanUp();
+
+    private:    // Data
+        RPointerArray<TWimiAllocRef> iRefs;
+        WIMI_Ref_pt iWimRef;
+    };
+
+#endif      // CWIMMEMMGMT_H
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimOmaProvisioning.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,142 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  WIM OMA Provisioning handler. 
+*
+*/
+
+
+
+#ifndef CWIMOMAPROVISIONING_H
+#define CWIMOMAPROVISIONING_H
+
+//  INCLUDES
+#include "Wimi.h"    // WIMI functions and definitions
+#include "ProvSC.h"  // OMA Provisioning Smart Card API types
+
+// CONSTANTS
+const TUint8 KWimProvBootstrapFileOID[]      = {0x67, 0x2B, 0x05, 0x01};
+const TUint8 KWimProvConfig1FileOID[]        = {0x67, 0x2B, 0x05, 0x02};
+const TUint8 KWimProvConfig2FileOID[]        = {0x67, 0x2B, 0x05, 0x03};
+const TInt   KWimProvFileOidLength           = 4;
+
+const TUint8 KWimProvBootstrapFileOIDTaged[] =
+    {0x06, 0x04, 0x67, 0x2B, 0x05, 0x01};
+const TUint8 KWimProvConfig1FileOIDTaged[]   =
+    {0x06, 0x04, 0x67, 0x2B, 0x05, 0x02};
+const TUint8 KWimProvConfig2FileOIDTaged[]   = 
+    {0x06, 0x04, 0x67, 0x2B, 0x05, 0x03};
+const TInt   KWimProvFileOidLengthTaged      = 6;
+
+const TInt   KWimOidLengthTaged              = 14;
+
+const TInt KFilePathMaxLength                = 8;
+
+// FORWARD DECLARATION
+class CWimUtilityFuncs;
+
+// CLASS DECLARATION
+
+/**
+*  Class for handling OMA Provisioning files.
+*  
+*  @since Series60 2.6
+*/
+class CWimOmaProvisioning : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimOmaProvisioning* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimOmaProvisioning();
+
+    public: // New functions
+        
+        /**
+        * Write size of OMA provisioning file to client memory
+        * @param aMessage Client message
+        * @return void
+        */
+        void OmaFileSizeL( const RMessage2& aMessage );
+
+        /**
+        * Write content of OMA provisioning file to client memory
+        * @param aMessage Client message
+        * @return void
+        */
+        void OmaFileContentL( const RMessage2& aMessage );
+        
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CWimOmaProvisioning();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Initialize path and size member variables with values got from WIMI.
+        * @return void
+        */
+        void InitializePathsAndSizes();
+
+        /**
+        * Parse size of OMA Provisioning file if not given in DODF-PROV file
+        * @param aOmaType Type of file
+        * @return void
+        */
+        void ParseFileSize( TOMAType aOmaType );
+
+       
+    private:    // Data
+        // Reference to WIM. Not owned.
+        WIMI_Ref_t*               iWimRef;
+        
+        // Path of bootstrap file. Length is 0 if not exists.
+        TBuf8<KFilePathMaxLength> iPathBootstrap;
+        
+        // Path of config1 file. Length is 0 if not exists.
+        TBuf8<KFilePathMaxLength> iPathConfig1;
+        
+        // Path of config2 file. Length is 0 if not exists.
+        TBuf8<KFilePathMaxLength> iPathConfig2;
+        
+        // Size of Bootstrap file
+        TInt                      iBootstrapFileSize;
+        
+        // Size of Config1 file
+        TInt                      iConfig1FileSize;
+        
+        // Size of Config2 file
+        TInt                      iConfig2FileSize;
+        
+        // Flag to tell if provisiong file infos are initialized
+        TBool                     iFileInfosInitialized;
+        
+        // Pointer to CWimUtilityFuncs. Owned.
+        CWimUtilityFuncs*         iWimUtilityFuncs;
+    };
+
+#endif      // CWIMOMAPROVISIONING_H
+    
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimResponse.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,77 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is a header file for class that is used a transaction id
+*                for the callback functions
+*
+*/
+
+
+#ifndef WIMRESPONSE_H
+#define WIMRESPONSE_H
+
+//  INCLUDES
+#include "Wimi.h"       // WIMI definitions
+#include "WimOpcode.h"
+
+#include <e32std.h>
+
+// CLASS DECLARATION
+
+/**
+*  WIMI response.
+*  Holds messages for completing after WIMI response.
+*  
+*  @since Series60 2.1
+*/
+class CWimResponse : public CBase
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Constructor.
+        */
+        CWimResponse( RMessage2 aMessage );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CWimResponse();
+    
+    public: // New functions
+
+        /**
+        * Delete myself
+        * @return void
+        */
+        void CompleteMsgAndDelete();
+
+    public:     // Data
+    
+        // Message to be completed
+        RMessage2     iMessage;
+        // Status of the WIMI call
+        WIMI_STAT    iStatus; 
+        // Any internal error 
+        TInt         iError;
+        // Operation code
+        TWimServRqst iOpcode;
+
+    };
+
+#endif      // WIMRESPONSE_H
+
+// End of File
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimSatRefreshObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,110 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observes 'SIM file changed' events from SAT. If changed file
+*               is WIM related, WimiLib's cache is cleared and WimiLib closed.
+*               Prevents WIM from operating with out-dated cache.
+*
+*/
+
+
+#ifndef CWIMSATREFRESHOBSERVER_H
+#define CWIMSATREFRESHOBSERVER_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <msatrefreshobserver.h>
+
+// FORWARD DECLARATIONS
+class RSatRefresh;
+class RSatSession;
+class CWimServer;
+
+#if defined SAT_REFRESH_TIMER_TRIGGER
+class CSatRefreshTimerTrigger;
+#endif
+
+// CLASS DECLARATION
+
+/**
+*  Notifies WimServer when SAT refresh notifications arrive.
+*
+*  @since 3.0
+*/
+class CWimSatRefreshObserver : public CBase, public MSatRefreshObserver
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CWimSatRefreshObserver* NewL();
+
+        /**
+        * Destructor.
+        */
+        ~CWimSatRefreshObserver();
+
+    public: // Functions from base classes
+
+		/**
+		* From MSatRefreshObserver
+		* @param aType is not used, because we lose file path and thus have to
+		   react for every refresh request
+		* @param aFiles is not used, because we lose file path and thus have to
+		   react for every refresh request
+		* @return boolean whether we allow refresh or not
+		*/
+        TBool AllowRefresh( TSatRefreshType /*aType*/,
+                            const TSatRefreshFiles& /*aFiles*/ );
+
+		/**
+		* From MSatRefreshObserver.
+		* @param aType is not used, because we lose file path and thus have to
+		   react for every refresh request
+		* @param aFiles is not used, because we lose file path and thus have to
+		   react for every refresh request
+		* @return void
+		*/
+		void Refresh( TSatRefreshType /*aType*/, 
+		              const TSatRefreshFiles& /*aFiles*/ );
+
+    private: // New functions
+
+        /**
+        * C++ default constructor.
+        */
+        CWimSatRefreshObserver();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    private: // Data
+
+        /// SAT refresh event client
+		RSatRefresh* iRefreshClient;
+        /// SAT session object
+		RSatSession* iSatSession;
+        /// Pointer to WimServer.
+		CWimServer* iWimSvr;
+#if defined SAT_REFRESH_TIMER_TRIGGER
+		/// Simulated Sat Event trigger
+		CSatRefreshTimerTrigger* iTimerTrigger;
+#endif
+    };
+
+#endif      // CWIMSATREFRESHOBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimScardListener.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,95 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Listens for Smard Card events
+*
+*/
+
+#ifndef CWIMSCARDLISTENER_H
+#define CWIMSCARDLISTENER_H
+
+//  INCLUDES
+#include <e32std.h>
+#include "Scard.h"
+#include "ScardListener.h"
+
+// FORWARD DECLARATIONS
+class CWimServer;
+
+
+// CLASS DECLARATION
+
+/**
+*  A class for listening card events.
+*  Each listener can listen only one reader at time, so every reader
+*  has its own CrWimScardListener.
+*  The maximum amount of listeners is 8.
+*
+*  @since Series60 2.1
+*/
+class CWimScardListener : public CScardListener
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        * @param aScard Pointer to RScard object
+        * @param aUiReaderID ReaderID
+        * @param aName Reader name
+        * @return void
+        */
+        static CWimScardListener* NewL( RScard* aScard,
+                                        TUint8 aUiReaderID,
+                                        const TScardReaderName& aName );
+
+        /**
+        * Destructor.
+        */
+        ~CWimScardListener();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        * @param aScard Pointer to RScard object
+        * @param aUiReaderID ReaderID
+        * @param aName Reader name
+        * @return void
+        */
+        CWimScardListener( RScard* aScard,
+                           TUint8 aUiReaderID,
+                           const TScardReaderName& aName );
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * From CScardListener. Process event notified by Scard listener
+        * @param aEvent Event from Scard
+        * @return void
+        */
+        virtual void ProcessEvent( const TScardServiceStatus aEvent );
+
+    private:
+        // Reader ID
+        TUint8       iUiReaderID;
+        // Name of reader we want the listen
+        TScardReaderName iName;
+        // Pointer to CWimServer
+        CWimServer* iServer;
+        
+    };
+
+#endif      // CWIMSCARDLISTENER_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimSecurityDlgHandler.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,205 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Wrapper class for security dialog management
+*
+*/
+
+
+
+#ifndef CWIMSECURITYDLGHANDLER_H
+#define CWIMSECURITYDLGHANDLER_H
+
+//  INCLUDES
+#include    <e32base.h>
+#include    <secdlg.h>  // Symbian security dialog interface
+#include    <data_caging_path_literals.hrh>
+//#include    <PKIDlg.h>
+
+// CONSTANTS
+_LIT( KWimSecDlgsDllName, "CTSecDlgs.dll" );        // Security dialogs DLL
+
+// CLASS DECLARATION
+
+/**
+*  Wrapper for security dialog management
+*
+*  @since Series60 2.6
+*/
+class CWimSecurityDlgHandler : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimSecurityDlgHandler* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimSecurityDlgHandler();
+
+    public: // New functions
+        
+        /**
+        * Shows a security dialog to enable/disable PIN query.
+        * @param aEnable TRUE = enable query, FALSE = disable query.
+        * @param aRetry is it first time or retry.
+        * @param aPINParams PIN parameters.
+        * @param aPINValue returned PIN value.
+        * @param aStatus Status of request.
+        * @return   void
+        */
+        void EnablePIN( TBool aEnable,
+                        TBool aRetry,
+                        const TPINParams& aPINParams, 
+                        TPINValue& aPINValue,
+                        TRequestStatus& aStatus );
+
+
+        /**
+        * Shows a security dialog for changing PIN value.
+        * @param aRetry Is it first time or retry?
+        * @param aPINParams PIN parameters.
+        * @param aOldPINValue old PIN to be chanced.
+        * @param aNewPINValue New PIN to set up.
+        * @param aStatus Status of request.
+        * @return   void
+        */
+        void ChangePINValue( TBool aRetry,
+                             const TPINParams& aPINParams,
+                             TPINValue& aOldPINValue,
+                             TPINValue& aNewPINValue,
+                             TRequestStatus& aStatus );
+
+        /**
+        * Shows the note about blocked PIN to the user.
+        * @param aPINParams PIN parameters.
+        * @param aStatus Status of request.
+        * @return   void
+        */
+        void ShowPINBlocked( const TPINParams& aPINParams, 
+                             TRequestStatus& aStatus );
+        
+        /**
+        * Shows the note about total blocked PIN to the user.
+        * @param aPINParams PIN parameters.
+        * @param aStatus Status of request.
+        * @return   void
+        */
+        void ShowPINTotalBlocked( const TPINParams& aPINParams, 
+                                  TRequestStatus& aStatus );
+        /**
+        * Shows the note about card removing to the user.
+        * @param aStatus Status of request.
+        * @return   void
+        */                     
+        void ShowCardRemoved( TRequestStatus& aStatus );
+
+        /**
+        * Shows a security dialog for fetching PIN and PUK 
+        * values for unblocking blocked PIN.
+        * @param aRetry is it first time or retry.
+        * @param aBlockedPINParams Blocked PIN parameters.
+        * @param aUnblockingPINParams Unblocking PIN parameters.
+        * @param aUnblockingPINValue Unblocking PIN value.
+        * @param aNewPINValue New PIN to set up.
+        * @param aStatus Status of request.
+        * @return   void
+        */
+        void UnblockPIN( TBool aRetry,
+                         const TPINParams& aBlockedPINParams,
+                         const TPINParams& aUnblockingPINParams,
+                         TPINValue& aUnblockingPINValue, 
+                         TPINValue& aNewPINValue,
+                         TRequestStatus& aStatus );
+
+        /**
+        * Shows a security dialog for asking user to enter PIN code.
+        * @param aRetry is it first time or retry.
+        * @param aPINParams PIN parameters.
+        * @param aPINValue PIN value to be query.
+        * @param aStatus Status of request.
+        * @return   void
+        */
+        void EnterPIN( TBool aRetry, 
+                       const TPINParams& aPINParams, 
+                       TPINValue& aPINValue,
+                       TRequestStatus& aStatus );
+                       
+        /**
+        * Close the ongoing dialog 
+        * @param
+        * @return void 
+        */
+        void Cancel();               
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CWimSecurityDlgHandler();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+
+        /**
+        * Load and get new instance of security dialog. Completes status
+        * if call to DoLoadSecurityDialogL() leaves (Dll load fails).
+        * @return Error code (KErrNone means dialog loaded succesfully)
+        * If something else than KErrNone status is completed with same error.
+        */
+        TInt LoadSecurityDialog( TRequestStatus& aStatus );
+        
+        /**
+        * Load and get new instance of PKI dialog. Completes status
+        * if call to DoLoadPKIDialogL() leaves (Dll load fails).
+        * @return Error code (KErrNone means dialog loaded succesfully)
+        * If something else than KErrNone status is completed with same error.
+        */
+        TInt LoadPKIDialog( TRequestStatus& aStatus );
+        
+        /**
+        * Load and get new instance of security dialog. Leaves if load fails.
+        * Leave is trapped in LoadSecurityDialog().
+        * @return void
+        */
+        void DoLoadSecurityDialogL();
+        
+        /**
+        * Load and get new instance of PKI dialog. Leaves if load fails.
+        * Leave is trapped in LoadPKIDialog().
+        * @return void
+        */
+        void DoLoadPKIDialogL();
+        
+    private:    // Data
+        // Pointer to security dialog class. Owned.
+        MSecurityDialog* iSecurityDlg;
+        
+        //Pointer to PKI dialog class Owned
+        //MPKIDialog*      iPKIDlg;
+        
+        // Pointer to RLibrary object. Owned.
+        RLibrary         iLibrary;
+         
+    };
+
+#endif      // CWIMSECURITYDLGHANDLER_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimServer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,458 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Server accepts requests from client threads and forwards them
+*               to the relevant server-side client session. It also handles the
+*               creation of server-side client sessions as a result of requests
+*               for connection from client threads.
+*
+*/
+
+
+
+#ifndef CWIMSERVER_H
+#define CWIMSERVER_H
+
+//  INCLUDES
+#include "Wimi.h"       // WIMI definitions
+#include "WimClsv.h"
+#include "WimTimer.h"
+
+// CONSTANTS
+_LIT( KWimServer, "CWimServer" );
+
+/*
+* ==============================================================================
+    WimServer's policy
+* ==============================================================================
+*/
+// Total number of policy ranges
+const TUint KWimServerRangeCount = 16;
+
+/**
+* Definition of the ranges of IPC numbers in Wim server.
+* NOTE: Adding new functions to server will mess up policy checking.
+* @see TWimServRqst
+*/
+const TInt wimRanges[KWimServerRangeCount] =
+    {
+    ENon,             // Range 0;  'ENon', Opcode has not been assigned yet.
+    EWimInitialize,   // Range 1, functions 1-5; WIM mgmt functions EAlwaysPass
+    ECloseWIMAfter,   // Range 2, function 6;    Set closing time for WIM
+    EGetCloseWIMAfter,// Range 3, functions 7-8; Get WIM closing time info
+    EWIMClose,        // Range 4, function 9;    Closes the WIM
+    ENotifyOnRemoval, // Range 5, funcs 10-14; Token removal & free mem (internal)
+    EGetPINCount,     // Range 6, functions 15-18; PIN info functions
+    EChangePINReq,    // Range 7, functions 19-21; PIN & Key mgmt, PIN modif.
+    EVerifyPinReq,    // Range 8, functions 22-25; PIN & Key mgmt, Pin&Key read
+    EGetWIMCertLst,   // Range 9, functions 26-27; Cert info
+    EGetWIMCertDetails,// Range 10, funcs 28-33; Cert read & manip, PK export, sign text
+    EGetOMAFileSize,   // Range 11, functions 34-35; OMA provisioning
+    EGetTrustSettings, // Range 12, functions 36;    Get trust settings
+    ESetApplicability, // Range 13, function 37-40;  Modify trust settings
+    ECancelTrustSettings,  // Range 14, function 41; Cancel any trust operation
+    ECancelTrustSettings+1 // Range 15, 42-; N/A function/end-of-range check
+    };                                    // -> ENotSupported
+
+// Policy to implement for each of the ranges in range table.
+const TUint8 wimElementsIndex[KWimServerRangeCount] =
+    {
+    CPolicyServer::ENotSupported, // applies to 0th range
+    CPolicyServer::EAlwaysPass,   // applies to 1st range
+    3,                            // Policy "3" applies to 2nd range
+    2,                            // Policy "2" applies to 3rd range
+    3,                            // Policy "3" applies to 4th range
+    CPolicyServer::EAlwaysPass,   // applies to 5th range
+    2,                            // Policy "2" applies to 6th range
+    3,                            // Policy "3" applies to 7th range
+    2,                            // Policy "2" applies to 8th range
+    CPolicyServer::EAlwaysPass,   // applies to 9th range
+    CPolicyServer::ECustomCheck,  // applies to 10th range
+    2,                            // Policy "2" applies to 11th range
+    CPolicyServer::EAlwaysPass,   // Applies to 12th range (get trust)
+    CPolicyServer::ECustomCheck,  // Applies to 13th range (modify trust)
+    CPolicyServer::EAlwaysPass,   // Applies to 14th range (cancel trust)
+    CPolicyServer::ENotSupported  // applies to 15th range (out of range IPC)
+    };
+
+// Specific capability checks.
+const CPolicyServer::TPolicyElement wimElements[] =
+    {
+        // policy "0"; fail call if ReadUserData not present
+        {
+        _INIT_SECURITY_POLICY_C1( ECapabilityReadUserData ),
+        CPolicyServer::EFailClient
+        },
+        // policy "1"; fail call if WriteUserData not present
+        {
+        _INIT_SECURITY_POLICY_C1( ECapabilityWriteUserData ),
+        CPolicyServer::EFailClient
+        },
+        // policy "2"; fail call if ReadDeviceData not present
+        {
+        _INIT_SECURITY_POLICY_C1( ECapabilityReadDeviceData ),
+        CPolicyServer::EFailClient
+        },
+        // policy "3"; fail call if WriteDeviceData not present
+        {
+        _INIT_SECURITY_POLICY_C1( ECapabilityWriteDeviceData ),
+        CPolicyServer::EFailClient
+        }
+    };
+
+// Packs all the security definitions into a policy.
+const CPolicyServer::TPolicy wimPolicy =
+    {
+    CPolicyServer::EAlwaysPass, // all connect attempts should pass
+    KWimServerRangeCount,       // number of ranges
+    wimRanges,                  // ranges array
+    wimElementsIndex,           // elements<->ranges index
+    wimElements,                // array of elements
+    };
+
+// FORWARD DECLARATIONS
+class CWimSession;
+class CWimMemMgmt;
+class CWimSessionRegistry;
+class CWimTrustSettingsStore;
+class CWimSatRefreshObserver;
+class CWimBTSapObserver;
+
+// CLASS DECLARATION
+
+#ifdef WIMSERVER_SHUTDOWN
+/**
+ * Implements shutdown of the server.  When the last client disconnects, this
+ * class is activated, and when the timer expires, causes the server to
+ * close.
+ *
+ *  @lib
+ *  @since S60 
+ */
+class CShutdown : public CTimer
+    {  
+    public:
+    
+        inline CShutdown();
+        
+        inline void ConstructL();
+        
+        inline void Start();
+        
+    private:
+        
+        void RunL();
+    };
+
+#endif //WIMSERVER_SHUTDOWN
+
+
+/**
+*  Main class of the server.
+*
+*  @since Series60 2.1
+*/
+
+class CWimServer : public CPolicyServer, public MWimTimerListener   // for policy checking
+    {
+
+    public:  // Constructor and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CWimServer* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CWimServer();
+
+
+    public: // New functions
+
+        /**
+        * Creates a new session.
+        * @param aVersion Version of the server.
+        * @return Pointer to sharable session.
+        */
+        virtual CSession2* NewSessionL( const TVersion &aVersion,
+                                        const RMessage2& aMessage ) const;
+
+        /**
+        * Panics the server
+        * @param aPanic Server panic reasons
+        * @return void
+        */
+        static void PanicServer( TWimServerPanic aPanic );
+
+        /**
+        * Get all sessions of the server
+        * @param aSessions Array of sessions. Empty array constructed in
+        *        a calling function
+        * @return void
+        */
+        void GetSessionsL( RArray<CWimSession*>& aSessions ) const;
+
+        /**
+        * Get pointer to WimSessionRegistry
+        * @return pointer to WimSessionRegistry
+        */
+        CWimSessionRegistry* WimSessionRegistry();
+
+        /**
+        * Get pointer to WimServer object
+        * @return Pointer to WimServer object
+        */
+        static CWimServer* Server();
+
+        /**
+        * Initializes WIMI if not yet initialized.
+        * In initalization WIM data from card is fetched to WIMI.
+        * @return void
+        */
+        void WimInitialize( const RMessage2& aMessage );
+        
+        /**
+        * Cancel Initializes WIMI if not yet initialized.
+        * Stop the apdu sending
+        * @return void
+        */
+        void CancelWimInitialize( const RMessage2& aMessage );
+
+        /**
+        * Set WimInitialized flag
+        * @param aInitialized ETrue/EFalse whether WIM is initialized
+        * @return void
+        */
+        static void SetWimInitialized( TBool aInitialized, TInt aStatus  );
+
+        /**
+        * Get TrustSettingsStore pointer
+        * @param void
+        * @return pointer to TrustSettingsStore
+        */
+
+        CWimTrustSettingsStore* WimTrustSettingsStore();
+
+        /**
+        * Tells if currently requested service is accessing physical token.
+        * @return  TBool  Is current service request accessing token or not.
+        */
+        TBool IsAccessingToken();
+
+        /**
+        * Tell that currently requested service is accessing physical token.
+        * @param  TBool  Is current service request accessing token.
+        */
+        void SetIsAccessingToken( TBool aValue );
+
+        /**
+        * Tells if there's been completed SIM Refresh operation.
+        * Returns ETrue if SIM Refresh notification is received in the middle
+        * of service request that accesses physical token.
+        * Server shall re-initialize itself at earliest convenience.
+        * @see IsAccessingToken()
+        * @return  TBool  Event from SAT received during service.
+        */
+        TBool RefreshNotificationReceived();
+
+        /**
+        * Tell about completed SIM Refresh operation.
+        * Set ETrue if SIM Refresh notification is received in the middle of
+        * service request that accesses physical token.
+        * Server shall re-initialize itself at earliest convenience.
+        * @see IsAccessingToken()
+        * @param  TBool  Refresh event received from SAT.
+        */
+        void SetRefreshNotificationReceived( TBool aValue );
+        
+        /**
+        * Return the pointer of Timer
+        */
+        CWimTimer* WimTimer();
+        
+        /**
+        * Interface derived from MWimTimerListener
+        */
+        void TimerExpired();
+        
+#ifdef WIMSERVER_SHUTDOWN
+        void AddSession();
+
+        void DropSession();
+#endif //WIMSERVER_SHUTDOWN
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CWimServer();
+
+        /**
+        * Constructor
+        * @param aPriority The priority of this active object.
+        * @return void
+        */
+        CWimServer( TInt aPriority );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Initializes callback functions.
+        */
+        void InitializeCallbackFunctions();
+
+        /**
+        * From CPolicyServer. Checks client's capabilities.
+        * @param aMsg       Message from client.
+        * @param aAction    IN/OUT; What to do in case of failure.
+        * @param aMissing   IN/OUT; A list of missing security attributes.
+        * @return           EPass if checking was passed, EFail otherwise.
+        */
+            CPolicyServer::TCustomResult
+        CustomSecurityCheckL( const RMessage2& aMsg,
+                              TInt& aAction,
+                              TSecurityInfo& aMissing );
+
+        /**
+        * Resolves usage (CA/User) for a certificate.
+        * @param aMsg       Message from client
+        * @param aUsage     Certificate usage (CA/User).
+        * @return           WIMI_Ok if ok, error code otherwise.
+        */
+        WIMI_STAT ResolveCertUsage( const RMessage2& aMsg,
+                                    TUint8& aUsage );
+
+        /**
+        * Fetches certificate info. Wrapper for WIMI call.
+        * @param aMsg       Message from client
+        * @param aUsage     Certificate usage (CA/User).
+        * @return           WIMI_Ok if ok, error code otherwise.
+        */
+        WIMI_STAT GetCertificateInfo( WIMI_Ref_pt aCertRef,
+                                      TUint8& aUsage );
+
+        /**
+        * Resolves which kind of certificate (CA/User) client is accessing.
+        * @param aMsg       Message from client
+        * @param aUsage     Certificate usage (CA/User).
+        * @return void
+        */
+        void ResolveStoreCertReqL( const RMessage2& aMsg,
+                                   TUint8& aUsage );
+
+        /**
+        * Resolves which kind of certificate client is accessing.
+        * @param aMsg       Message from client
+        * @param aUsage     Certificate usage (CA/User).
+        * @return           WIMI_Ok if ok, error code otherwise.
+        */
+        WIMI_STAT ResolveRemoveCertReqL( const RMessage2& aMsg,
+                                         TUint8& aUsage );
+
+        /**
+        * Resolves which kind of certificate client is accessing.
+        * @param aMsg       Message from client
+        * @param aUsage     Certificate usage (CA/User).
+        * @return ETrue if successful, EFalse otherwise.
+        */
+        TBool ResolveTrustModficationReqL( const RMessage2& aMsg,
+                                           TUint8& aUsage );
+
+        /**
+        * Resolves which kind of key (CA/User) client requests.
+        * @param aMsg       Message from client
+        * @param aUsage     Certificate usage (CA/User).
+        * @return           WIMI_Ok if ok, error code otherwise.
+        */
+        WIMI_STAT ResolveExportPublicReqL( const RMessage2& aMsg,
+                                           TUint8& aUsage );
+
+        /**
+        * Check if client has sufficient read capability for service in question.
+        * @param aMsg       Message from client
+        * @param aUsage     Certificate usage (CA/User).
+        * @return           EPass if checking was passed, EFail otherwise
+        */
+            CPolicyServer::TCustomResult
+        CheckReadCapsForUsage( const RMessage2& aMsg,
+                               TUint8 aUsage );
+
+        /**
+        * Check if client has sufficient write capability for service in question.
+        * @param aMsg       Message from client
+        * @param aUsage     Certificate usage (CA/User).
+        * @return           EPass if checking was passed, EFail otherwise
+        */
+            CPolicyServer::TCustomResult
+        CheckWriteCapsForUsage( const RMessage2& aMsg,
+                                TUint8 aUsage );
+
+    public:     // Data
+
+        // Status of the last initialization action
+        static TInt iWimStatus;
+        // Flag to tell if WIM is already initialized
+        static TBool iWimInitialized;
+
+        WIMI_Callbacks_t     iWimCallBack;
+    private:    // Data
+        // Pointer to Trust Settings Store instance. Owned.
+        CWimTrustSettingsStore* iWimTrustSettingsStore;
+        // Session counter
+        TInt                 iSessionCount;
+        // Pointer to CWimSessionRegistry
+        CWimSessionRegistry* iWimSessionRegistry;
+        // Pointer to CServer object
+        static CWimServer*   iWimServer;
+        // Callback structure for WIMI
+       
+        /**
+        * Current service is accessing physical token.
+        * Used to determine if SIM Refresh can be allowed.
+        */
+        TBool                iIsAccessingToken;
+        /**
+        * Informs server of completed SIM Refresh operation.
+        * Is set if SIM Refresh notification is received in the middle of
+        * service request that accesses physical token.
+        * Server shall re-initialize itself at earliest convenience.
+        */
+        TBool                iRefreshNotificationReceived;
+        /**
+        * SAT refresh event observer. Owned.
+        *
+        */
+   		CWimSatRefreshObserver* iRefreshObserver;
+        /**
+        * BT Sap refresh event observer. Owned.
+        *
+        */
+   		CWimBTSapObserver* iBTSapObserver;
+   		  
+   		  // Pointer to Timer. Owned
+   		  CWimTimer* iWimTimer;
+
+#ifdef WIMSERVER_SHUTDOWN   		  
+   		CShutdown iShutdown;
+#endif   		
+    };
+
+#endif      // CWIMSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimSession.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,176 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Represents a session for a client thread on the server-side.
+*
+*/
+
+#ifndef CWIMSESSION_H
+#define CWIMSESSION_H
+
+#include "WimClsv.h"
+#include "WimTimer.h"
+#include "Wimi.h"            //WIMI definitions
+
+// FORWARD DECLARATION
+class CWimServer;
+class CWimCertHandler;
+class CWimAuthObjHandler;
+class CWimTokenHandler;
+class CWimKeyMgmtHandler;
+class CWimSignTextHandler;
+class CWimMemMgmt;
+class CWimUtilityFuncs;
+class CWimUtilityFuncs;
+class CWimOmaProvisioning;
+class CWimJavaProvisioning;
+class CWimTrustSettingsHandler;
+
+/**
+*  A session acts as a channel of communication between the client and
+*  the server.
+*  A client thread can have multiple concurrent sessions with a server.
+*
+*  @since Series60 2.1
+*/
+class CWimSession : public CSession2, public MWimTimerListener
+    {
+
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CWimSession* NewL( CWimServer* aWimServer );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CWimSession();
+
+    public: // New functions
+
+        /**
+        * Handles the servicing of client requests to the server.
+        * @param    aMessage Encapsulates a client request.
+        * @return   void
+        */
+        virtual void ServiceL( const RMessage2& aMessage );
+
+        /**
+        * Complete NotifyOnRemoval message, meaning that card is removed.
+        * @return   void
+        */
+        void NotifyComplete();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CWimSession();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL( CWimServer* aWimServer );
+
+        /**
+        * Handles client requests and forwards
+        * them to appropriate handler class.
+        * @param    aMessage Encapsulates a client request.
+        * @return   void
+        */
+        void DispatchMessageL( const RMessage2& aMessage );
+
+        /**
+        * Fetches the list of the references of WIMs currently associated
+        * with readers.
+        * @return   void
+        */
+        void GetWimRefListL();
+
+        /**
+        * Fetches the count of WIM cards in use.
+        * @return   void
+        */
+        void GetWimCountL();
+
+        /**
+        * Timer for closing connection to the WIM card.
+        * @return   void
+        */
+        void TimerExpired();
+
+        /**
+        * NotifyOnRemoval message received. Store the message for completing.
+        * @return   void
+        */
+        void NotifyOnRemovalL();
+
+        /**
+        * Cancel NotifyOnRemoval. Complete notification message with KErrCancel.
+        * @return   void
+        */
+        void CancelNotifyOnRemoval();
+
+        /**
+        * Check if current request accesses HW.
+        * @param	TInt	Request ID
+        * @return   TBool
+        */
+        TBool RequestAccessesHW( TInt aFunction );
+
+        /**
+        * Re-initializes WIMlib.
+        * Executed when card data has been changed.
+        * @return   void
+        */
+        void RefreshWimi();
+
+    private:    // Data
+        // total number of resources allocated
+        TInt                      iResourceCount;
+        // Pointer to the server. Not owned.
+        CWimServer*               iWimSvr;
+        // Pointer for memory management. Owned.
+        CWimMemMgmt*              iWimMgmt;
+        // Pointer to timer. Owned.
+        //CWimTimer*                iTimer;
+        // Certificate Handler class pointer. Owned.
+        CWimCertHandler*          iWimCertHandler;
+        // Authentication Object Handler class pointer. Owned.
+        CWimAuthObjHandler*       iWimAuthObjHandler;
+        // Token Handler class pointer. Owned.
+        CWimTokenHandler*         iWimTokenHandler;
+        // Key Management Handler class pointer. Owned.
+        CWimKeyMgmtHandler*       iWimKeyMgmtHandler;
+        // Pointer to Sign Text handler. Owned.
+        CWimSignTextHandler*      iWimSignTextHandler;
+        // Utility functions. Owned.
+        CWimUtilityFuncs*         iWimUtilFuncs;
+        // Pointer to OMA Provisioning class. Owned.
+        CWimOmaProvisioning*      iWimOmaProvisioning;
+        
+        CWimJavaProvisioning*     iWimJavaProvisioning;
+        // Pointer to WimTrustSettingsHandler. Owned.
+        CWimTrustSettingsHandler* iWimTrustSettingsHandler;
+        // NotifyOnRemoval Message, to be completed. Owned.
+        RMessage2*                iNotifyMessage;
+        // Message to be server. Owned.
+        RMessage2*                iMessage;
+    };
+
+#endif      // CWIMSESSION_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimSessionRegistry.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,94 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Registry of WimServer sessions
+*
+*/
+
+
+
+#ifndef CWIMSESSIONREGISTRY_H
+#define CWIMSESSIONREGISTRY_H
+
+//  INCLUDES
+#include <e32base.h>
+
+
+// FORWARD DECLARATIONS
+class CWimSession;
+
+
+// CLASS DECLARATION
+
+/**
+* This class holds array of sessions of server.
+*
+* @since Series60 2.1
+*/
+class CWimSessionRegistry : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimSessionRegistry* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CWimSessionRegistry();
+
+    public:  // New functions
+
+        /**
+        * Add session to array
+        * @param aSession Session to be added
+        * @return void
+        */
+        void AddSessionL( CWimSession* aSession );
+
+        /**
+        * Get array of sessions
+        * @param aSessions Session array
+        * @return void
+        */
+        void GetSessionsL( RArray<CWimSession*>& aSessions ) const;
+
+        /**
+        * Remove session from sessions array
+        * @param aSession Session to be removed
+        * @return void
+        */
+        void RemoveSession( CWimSession* aSession );
+
+    private:
+    
+        /**
+        * C++ default constructor.
+        */
+        CWimSessionRegistry();
+        
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    private:
+        // Array of sessions
+        RArray<CWimSession*> iSessions;
+        
+    };
+
+#endif      // CWIMSESSIONREGISTRY_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimSignTextHandler.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,165 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  WIM Sign Text Handler
+*
+*/
+
+
+
+#ifndef CWIMSIGNTEXTHANDLER_H
+#define CWIMSIGNTEXTHANDLER_H
+
+//  INCLUDES
+#include <secdlg.h>
+#include "WimResponse.h"
+#include "WimUtilityFuncs.h"
+
+// FORWARD DECLARATIONS
+class CWimUtilityFuncs;
+class CWimSecurityDlgHandler;
+
+// CLASS DECLARATION
+
+/**
+*  WIM Sign Text Handler.
+*  Handles Sign Text operations. 
+*
+*  @since Series60 2.6
+*/
+class CWimSignTextHandler : public CActive
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimSignTextHandler* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimSignTextHandler();
+
+    public: // New functions
+        
+        /**
+        * Start the SignText operation.
+        * @param aMessage Encapsulates a client request.
+        * @return void 
+        */
+        void SignTextL( const RMessage2& aMessage );
+      
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CWimSignTextHandler();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Continues signing operation after signing PIN has asked from user.
+        * Calls WIMI_SignReq() method which take care of actual sign operation.
+        * Response (signed text) to call is handled in CWimCallBack::SignResp().
+        * @return void 
+        */
+        void ContinueSigningL();
+
+        /**
+        * Ask PIN from user. Shows PIN query dialog.
+        * @return void 
+        */
+        void AskPin();
+
+        /**
+        * Get parameters for PIN. iKeyReferense has to be set before
+        * this function is used.
+        * @param aPinParams PIN parameters that has to be set
+        * @return void 
+        */
+        void GetPinParamsL( TPINParams& aPinParams ) const;
+
+        /**
+        * Clean member data
+        * @return void 
+        */
+        void CleanUp();
+
+        /**
+        * From CActive. RunL: Handles signing operation as state machine.
+        */
+        void RunL();
+
+        /**
+        * From CActive. DoCancel: Asyncronous request cancelled
+        */
+        void DoCancel();
+
+        /**
+        * From CActive. The active scheduler calls this function if this active
+        * object's RunL() function leaves.
+        * Handles necessary cleanup and completes request with
+        * received error code.
+        * @param aError Leave code
+        * @return Error code to Active Scheduler, is always zero.
+        */ 
+        TInt RunError( TInt aError );
+
+    private:    // Data
+
+        // Enumerator for ongoing sign text state
+        enum TSignTextState
+            {
+            EAskPin,
+            ECallbackResponse,
+            EShowPinBlocked,
+            EShowCardIsRemoved,
+            EWimiError,
+            ESigningDone
+            };
+
+        // Pointer to utility function class. Owned.
+        CWimUtilityFuncs*       iWimUtilFuncs;
+        // Pointer to security handler class. Owned.
+        CWimSecurityDlgHandler* iWimSecDlg;
+        // PIN for signing
+        TPINValue               iSigningPin;
+        // Pointer to WimResponse for completing the client request. 
+        // Deleted here or in callback function.
+        CWimResponse*           iResponseID;
+        // Transaction ID. This is deleted in CWimCallBack::SignResp() 
+        // or here in case of WIMI error.
+        TWimReqTrId*            iTrId;
+        // Key reference. Owned.
+        TAny*                   iKeyReference;
+        // State of signing operation
+        TSignTextState          iSigningState;
+        // Buffer for data to be signed. Owned.
+        HBufC8*                 iSigningDataBuf;
+        // Pointer to data to be signer. Owned.
+        TPtr8*                  iSigningDataPtr;
+        // Flag to tell if PIN query is retry or not
+        TBool                   iRetry;
+        // PIN parameters
+        TPINParams              iPinParams;
+                
+    };
+
+#endif      // CWIMSIGNTEXTHANDLER_H  
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimSimFileHandler.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,136 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  WIM SIM Certificate handler. Handles WIMI's ReadFile requests
+*               to card not supporting logical channels
+*
+*/
+
+
+
+#ifndef CWIMSIMFILEHANDLER_H
+#define CWIMSIMFILEHANDLER_H
+
+//  INCLUDES
+#include <rmmcustomapi.h>
+
+// CONSTANTS
+const TUint KMaxSimFileSize = 10000; // Maximum size allocated for file
+
+// CLASS DECLARATION
+
+/**
+*  Class for handling SIM file reading. Calls CustomAPI's function
+*  to read the file.
+*  
+*  @since Series60 2.1
+*/
+class CWimSimFileHandler : public CActive
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimSimFileHandler* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimSimFileHandler();
+
+    public: // New functions
+        
+        /**
+        * Reads SIM file
+        * @param aReader     Reader ID
+        * @param aPath       Path to the file to read
+        * @param aOffset     Offset from the beginning of the file.
+        * If the Elementary File pointed to by FileID is linear fixed or cyclic 
+        * (this is the case for EF DIR), then the least significant byte of 
+        * aOffSet denotes the record number, while the most significant byte in
+        * aOffSet denotes the start byte within that record. The record number 
+        * starts fron 1 and therefore 0x0100 is sent as the offset.
+        * @param aSize       Amount of data to read, aSize = 0 means that whole
+        *                    file must be read
+        * @return void
+        */
+        void ReadSimFileL( TUint8 aReader,
+                           const TDes8& aPath,
+                           TUint16 aOffset,
+                           TUint16 aSize );
+        
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CWimSimFileHandler();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Open CustomAPI for communication
+        * @return void
+        */
+        void OpenCustomApiL();
+
+        /**
+        * Handle received file
+        * @return void
+        */
+        void FileReceived();
+
+        /**
+        * Wait until asynchronous call is completed
+        * @return void
+        */
+        void SetActiveAndWait();
+
+        /**
+        * From CActive. Handles asynchrounous file reading response
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * From CActive. Cancellation function
+        * @return void
+        */
+        void DoCancel();
+
+        
+    private:    // Data
+        // Pointer to CustomAPI instance. Owned.
+        RMmCustomAPI*               iCustomApi;
+        // Pointer to Etel server. Owned.
+        RTelServer*                 iEtelServer;
+        // Pointer to response bytes buffer. Owned.
+        HBufC8*                     iResponseBytesBuf;
+        // Pointer to response bytes pointer. Owned.
+        TPtr8*                      iResponseBytesPtr;
+        // Reader number
+        TUint8                      iReaderNumber;
+        // Synchronous wait for async request
+        CActiveSchedulerWait        iWait;
+        // SIM file info structure
+        RMmCustomAPI::TSimFileInfo  iSimFileInfo;
+
+    };
+
+#endif      // CWIMSIMFILEHANDLER_H
+    
+//End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimTimer.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,154 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  A timer class that calls the function TimerExpired for the 
+*               registered classes of type MWimTimerListener
+*
+*/
+
+
+
+#ifndef CWIMTIMER_H
+#define CWIMTIMER_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// Interface for the listener
+class MWimTimerListener
+    {
+    public:
+        virtual void TimerExpired() = 0;
+        virtual ~MWimTimerListener(){}
+    };  
+
+
+// CLASS DECLARATION
+
+/**
+*  Timer class.
+*  
+*  @since Series60 2.6
+*/
+class CWimTimer : public CActive, public MBeating
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimTimer* NewL( MWimTimerListener* aTimerListener );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimTimer();
+
+    public: // New functions
+        
+        /**
+        * Set timeout value for closing WIM connection
+        * @param aMessage Client message
+        * @return void
+        */
+        void SetCloseAfter( const RMessage2& aMessage );
+
+        /**
+        * Resets timer
+        * @return void
+        */
+        void ResetTimer();
+
+        /**
+        * Time remaining. Write value to client.
+        * @return void
+        */
+        void TimeRemainingL( const RMessage2& aMessage ) const;
+        
+        /**
+        * Time reamining, Used in Server side
+        */
+        TInt TimeRemaining() const;
+        
+        /**
+        * Get delay set by SetCloseAfter. Write value to client.
+        * @return void
+        */
+        void GetCloseAfterL( const RMessage2& aMessage ) const;
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CWimTimer();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL( MWimTimerListener* aTimerListener );
+
+        /**
+        * From CActive Handles an active object’s request completion event
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * From CActive Cancellation of an outstanding request
+        * @return void
+        */
+        void DoCancel();
+
+        /**
+        * Set timeout value for closing WIM connection
+        * @param aCloseAfter Timeout value in seconds
+        * @return void
+        */
+        void DoSetCloseAfter( TInt aCloseAfter );
+
+        /**
+        * From MBeating. Timer beat has occurred, increase beat counter.
+        * @return void
+        */
+        void Beat();
+
+        /**
+        * From MBeating. Synchronize.
+        * @return void
+        */
+        void Synchronize();
+
+        /**
+        * Start heart beating
+        * @return void
+        */
+        void StartHeartBeat();
+
+    private:    // Data
+        // Delay in microseconds
+        TTimeIntervalMicroSeconds32 iDelay;
+        // Interface for calling listeners. Not owned.
+        MWimTimerListener*          iTimerListener;
+        // Asynchronous timer
+        RTimer                      iTimer;
+        // Pointer to Heartbeat instance. Owned.
+        CHeartbeat*                 iHeartbeat;
+        // Heartbeat count
+        TUint                       iHeartBeatCount;
+         
+    };
+
+#endif      // CWIMTIMER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimTokenHandler.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,102 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  WIM Token handler
+*
+*/
+
+
+
+#ifndef CWIMTOKENHANDLER_H
+#define CWIMTOKENHANDLER_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// FORWARD DECLARATIONS
+class CWimMemMgmt;
+class CWimTimer;
+class CWimUtilityFuncs;
+
+// CLASS DECLARATION
+
+
+/**
+*  Class for token handling
+*
+*  @lib WimServer.lib
+*  @since Series60 2.1
+*/
+class CWimTokenHandler : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimTokenHandler* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimTokenHandler();
+
+    public: // New functions
+        
+        /**
+        * Fetches WIM card info.
+        * @param aMessage Encapsulates a client request.
+        * @param aWimMgmt Pointer to memory management class.
+        * @return void
+        */
+        void GetWIMInfoL( const RMessage2& aMessage,
+                          CWimMemMgmt* const aWimMgmt ) const;
+
+        /**
+        * Checks if the WIM is already opened.
+        * @param aMessage Encapsulates a client request.
+        * @param aTimer Pointer to timer class.
+        * @return void
+        */
+        void IsWIMOpenL( const RMessage2& aMessage,
+                         CWimTimer* const aTimer, 
+                         CWimMemMgmt* const aWimMgmt ) const;
+
+        /**
+        * Closes a connection to a WIM card.
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void CloseWIM( const RMessage2& aMessage ) const;
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CWimTokenHandler();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    private:    // Data
+        // Pointer to utility class
+        CWimUtilityFuncs* iWimUtilFuncs;
+         
+    };
+
+#endif      // CWIMTOKENHANDLER_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimTrustSettingsHandler.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,160 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  WIM Trust Settings Store handler
+*
+*/
+
+
+
+#ifndef CWIMTRUSTSETTINGSHANDLER_H
+#define CWIMTRUSTSETTINGSHANDLER_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// FORWARD DECLARATIONS
+class CWimTrustSettingsStore;
+class CWimCertInfo;
+
+// CLASS DECLARATION
+
+/**
+*  Class for handling certificates in WIM card
+*  
+*  @since Series60 3.0
+*/
+class CWimTrustSettingsHandler : public CActive
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimTrustSettingsHandler* NewL( CWimTrustSettingsStore* aWimTrustSettingsStore );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimTrustSettingsHandler();
+
+    public: // New functions
+        
+        /**
+        * Fetches trust settings for given certificate. 
+        * 
+        * @return void
+        */
+        void GetTrustSettingsL( const RMessage2& aMessage );
+
+        /**
+        * Set applicability for given certificate. New certificate entry is
+        * set if one not found from database (trust flag is set to EFalse).
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void SetApplicabilityL( const RMessage2& aMessage );
+
+        /**
+        * Set trust flag for given certificate. New certificate entry is set
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void SetTrustL( const RMessage2& aMessage );
+
+        /**
+        * Set default trust settings for given certificate. If certificate not
+        * found from database new entry is inserted.
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void SetDefaultTrustSettingsL( const RMessage2& aMessage );
+
+        /**
+        * Remove trust settings of given certificate. If certificate
+        * is not found, message is completed with KErrNotFound
+        * @param aMessage Encapsulates a client request.
+        * @return void
+        */
+        void RemoveTrustSettingsL( const RMessage2& aMessage );
+
+        /**
+        * Cancel any issued asynchronous call
+        * @return void
+        */
+        void CancelDoing();
+
+    private:  // From CActive
+
+        /**
+        * From CActive. Handles completion of asynchrounous operation
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * From CActive. Cancellation function
+        * @return void
+        */
+        void DoCancel();
+
+        /**
+        * From CActive. Handle trapped leave.
+        * @param aError Leave error code
+        * @return Error code
+        */
+        TInt RunError( TInt aError );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CWimTrustSettingsHandler( CWimTrustSettingsStore* aWimTrustSettingsStore );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    private:    // Data
+
+        // Pointer to Trust Settings Store instance. Owned.
+        CWimTrustSettingsStore* iWimTrustSettingsStore;
+        // Pointer CWimCertInfo object. Owned.
+        CWimCertInfo*           iCertInfo;
+        // Saved message.
+        RMessage2               iMessage;
+        // Flag to save trusted flag.
+        TBool                   iTrusted;
+        // Array to save applications.
+        RArray<TUid>            iApplications;
+
+        // Enumerator for ongoing phase
+        enum TPhase
+            {
+            EGetTrustSettings,
+            ESetDefaultTrustSettings,
+            ESetApplicability,
+            ESetTrust,
+            ERemoveTrustSettings
+            };
+
+        // Currect phase of Trust Settings Store operation
+        TPhase                  iPhase;
+
+    };
+
+#endif      // CWIMTRUSTSETTINGSHANDLER_H
+    
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimTrustSettingsStore.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,425 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implements WIM TrustSettingsStore for WIM certificates
+*
+*/
+
+
+
+#ifndef CWIMTRUSTSETTINGSSTORE_H
+#define CWIMTRUSTSETTINGSSTORE_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <cctcertinfo.h>
+#include <f32file.h>
+#include <d32dbms.h>
+#include "WimDefs.h"    // TTSSCertLocation
+#include <data_caging_path_literals.hrh>
+
+// CONSTANTS
+
+// The location of wim trust setting storage
+// The path is taken from data_caging_path_literals
+_LIT( KWimTrustSettingsDBFile, "WimTrustSettingsStore.dat" );
+
+// Object identifier (OID) for server authentication
+_LIT( KIpKpServerAuth, "2.5.29.37.1" ); 
+// Object identifier (OID) for JavaMidlet certificates
+_LIT( KIpKpJavaMidlet, "1.3.6.1.4.1.42.2.110.2.2.2.1" ); 
+// Object identifier (OID) for code signer certificates
+_LIT( KWimCodeSigningOID, "1.3.6.1.5.5.7.3.3" );
+
+// Default value for trusted flag
+const TBool KDefaultTrustFlag = ETrue;
+// Maximum length of SQL query clause
+const TInt KMaxSQLLength = 100;
+// Trusting applications
+const TInt KTrustUidWapBearer     = 268479059;
+const TInt KTrustUidAppController = 268452523;
+const TInt KTrustUidInternet      = 268441661;
+const TInt KTrustUidJavaMidlet    = 270506792;
+
+// FORWARD DECLARATION
+
+class CWimCertUtil;
+class CWimCertInfo;
+
+// CLASS DECLARATION
+
+/**
+*  This class implements services for trust settings.
+*  Class includes functions for creating DB, fetching, updating and 
+*  deleting trust settings.
+*
+*  @lib WimPlugin.lib
+*  @since Series60 2.1
+*/
+class CWimTrustSettingsStore : public CActive
+    {
+    public:  // Constructor and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimTrustSettingsStore* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimTrustSettingsStore();
+
+    public: // New functions
+        
+        /**
+        * Fetches trust settings for given certificate. 
+        * Acts like an asynchronous for caller but not activates itself.
+        * @param  aCert (IN) Certificate
+        * @param  aTrusted  (OUT) Is certificate trusted
+        * @param  aApplications  (OUT) Array of applications supported 
+        *         by certificate
+        * @param  aStatus (IN/OUT) Request Status of asynchronous call
+        * @return void
+        */
+        void GetTrustSettings( const CWimCertInfo& aCert,
+                               TBool& aTrusted,
+                               RArray<TUid>& aApplications, 
+                               TRequestStatus& aStatus );
+
+        /**
+        * Set applicability for given certificate. Calls DoSetApplicabilityL,
+        * which handles actual operation. New certificate entry is set if
+        * one not found from database (trust flag is set to EFalse).
+        * Acts like an asynchronous for caller but not activates itself.
+        * @param aCert (IN) Certificate
+        * @param aApplications (IN) Array of applications supported by 
+        *        certificate
+        * @param aStatus Request (IN/OUT) Status of asynchronous call.
+        * @return void
+        */
+        void SetApplicability( const CWimCertInfo& aCert,
+                               const RArray<TUid>& aApplications,
+                               TRequestStatus& aStatus );
+
+        /**
+        * Set trust flag for given certificate. Calls DoSetTrustL,
+        * which handles actual operation. New certificate entry is set if
+        * one not found from database.
+        * Acts like an asynchronous for caller but not activates itself.
+        * @param aCert (IN) Certificate
+        * @param aTrusted (IN) Is certificate trusted
+        * @param aStatus (IN/OUT) Request Status of asynchronous call.
+        * @return void
+        */
+        void SetTrust( const CWimCertInfo& aCert,
+                       TBool aTrusted,
+                       TRequestStatus& aStatus );
+
+        /**
+        * Set default trust settings for given certificate. If certificate not
+        * found from database new entry is inserted.
+        * Acts like an asynchronous for caller but not activate itself.
+        * @param aCert (IN) Certificate
+        * @param aAddApps (IN) Are default applications inserted 
+        *        (ETrue means yes)
+        * @param aStatus (IN/OUT) Request Status of asynchronous call
+        * @return void
+        */
+        void SetDefaultTrustSettings( const CWimCertInfo& aCert,
+                                      TBool aAddApps,
+                                      TRequestStatus& aStatus );
+
+        /**
+        * Remove trust settings of given certificate. If certificate
+        * is not found, return with status.Int() = KErrNotFound
+        * Acts like an asynchronous for caller but not activates itself.
+        * @param aCert (IN) Certificate
+        * @param aStatus (IN/OUT) Request Status of asynchronous call
+        * @return void
+        */
+        void RemoveTrustSettings( const CWimCertInfo& aCert,
+                                  TRequestStatus& aStatus );
+
+        /**
+        * Delete TrustSettingsStore instance and release all resources
+        * @return void
+        */
+        void CloseD();
+
+        /**
+        * Cancel any issued asynchronous call
+        * @return void
+        */
+        void CancelDoing();
+
+    private:
+
+        /**
+        * Default constructor.
+        */
+        CWimTrustSettingsStore();
+
+        /**
+        * 2nd phase constructor
+        */
+        void ConstructL();
+
+        /**
+        * Fetches trust settings for given certificate
+        * @param aCert (IN) Certificate
+        * @param aTrusted (OUT) Is certificate trusted
+        * @param aApplications (OUT) Array of applications supported 
+        *        by certificate
+        * @return void
+        */
+        void DoGetTrustSettingsL( const CWimCertInfo& aCert,
+                                  TBool& aTrusted,
+                                  RArray<TUid>& aApplications );
+
+        /**
+        * Set applicability for given certificate. If certificate is not 
+        * allready in database insert new entry.
+        * @param aCert (IN) Certificate
+        * @param aTrusted (IN) Is certificate trusted
+        * @param aApplications (IN) Array of applications supported 
+        *        by certificate
+        * @return void
+        */
+        void DoSetApplicabilityL( const CWimCertInfo& aCert,
+                                  const RArray<TUid>& aApplications );
+
+        /**
+        * Set trust flag for given certificate. If certificate is not 
+        * allready in database insert new entry.
+        * @param aCert (IN) Certificate
+        * @param aTrusted (IN) Is certificate trusted
+        * @return void
+        */
+        void DoSetTrustL( const CWimCertInfo& aCert,
+                          TBool aTrusted );
+
+        /**
+        * Set default trust settings for given certificate
+        * @param aCert (IN) Certificate
+        * @param aAddApps (IN) Are default applications inserted 
+        *        (ETrue means yes)
+        * @return void
+        */
+        void DoSetDefaultTrustSettingsL( const CWimCertInfo& aCert,
+                                         TBool aAddApps );
+
+        /**
+        * Remove trust settings of given certificate. If certificate not 
+        * found, leave with error code KErrNotFound
+        * @param aCert (IN) Certificate
+        * @return void
+        */
+        void DoRemoveTrustSettingsL( const CWimCertInfo& aCert );
+
+        /**
+        * Get database ID for given certificate. 
+        * Returns certificate ID = KErrNotFound if matching ID not found.
+        * @param aCert (IN) Certificate
+        * @param aCertID (OUT) Certificate's database ID
+        * @return void
+        */
+        void GetCertificateIDL( const CWimCertInfo& aCert,
+                                TInt& aCertificateID );
+
+        /**
+        * Insert certificate to Certificates table
+        * @param aCert (IN) Certificate
+        * @param aTrusted (IN) Is certificate trusted or not
+        * @return void
+        */
+        void InsertCertificateL( const CWimCertInfo& aCert, 
+                                 TBool aTrusted );
+
+        
+        /**
+        * Fetch certificates trusted flag
+        * @param aCertificateID (IN) Certificate's database ID
+        * @param aTrusted (OUT) Is certificate trusted or not
+        * @return void
+        */
+        void GetTrustedL( TInt aCertificateID,  
+                          TBool& aTrusted );
+
+        /**
+        * Set trusted flag for certificate
+        * @param aCertificateID (IN) Certificate's database ID
+        * @param aTrusted (IN) Is certificate trusted or not
+        * @return void
+        */
+        void SetTrustedL( TInt aCertificateID,  
+                          TBool aTrusted );
+        /**
+        * Remove certificate from Certificates table
+        * @param aCertificateID (IN) Certificate's database ID
+        * @return void
+        */
+        void RemoveCertificateL( TInt aCertificateID );
+
+        /**
+        * Remove all applications of given certificate
+        * @param aCertificateID (IN) Certificate
+        * @return void
+        */
+        void RemoveApplicationsL( TInt aCertificateID );
+
+        /**
+        * Get all applications of given certificate
+        * @param aCertificateID (IN) Certificate's database ID
+        * @param aApplications (OUT) Array of applications supported 
+        *        by certificate
+        * @return void
+        */
+        void GetApplicationsL( TInt aCertificateID, 
+                               RArray<TUid>& aApplications );
+
+        /**
+        * Set applications for given certificate
+        * @param aCertificateID (IN) Certificate database ID
+        * @param aApplications (IN) Array of applications supported 
+        *        by certificate
+        * @return void
+        */
+        void InsertApplicationsL( TInt aCertificateID, 
+                                  const RArray<TUid>& aApplications );
+        
+        /**
+        * Decide default applications for given certificate.
+        * Default applications are decided regarding the certificate's:
+        *   - format
+        *   - extented usage data
+        *   - trusted usage data
+        * @param aCert (IN) Certificate
+        * @param aApplications (OUT) List of applications returned
+        * @return void
+        */
+        void DefaultApplicationsL( const CWimCertInfo& aCert,
+                                   RArray<TUid>& aApplications );
+
+        /**
+        * Decide default applications by OID's. 
+        * @param aCert (IN) Certificate
+        * @param aApplications (OUT) List of applications returned
+        * @return void
+        */
+        void DefaultAppsByOIDsL( const CWimCertInfo& aCert,
+                                 RArray<TUid>& aApplications );
+
+        /**
+        * Create database. Leaves if error occurs.
+        * @return void
+        */
+        void CreateDBL() const;
+
+        /**
+        * Insert default appUid selection rules. Leaves if error occurs.
+        * @return void
+        */
+        void InsertDefaultAppRulesL() const;
+
+        /**
+        * Extracts certificate extensions. Leaves if error occurs.
+        * @return void
+        */
+        void ExtractExtensionL();
+
+        /**
+        * Makes a SHA-1 hash of certificate label
+        * @param aString (IN) String to be hashed
+        * @return 8 bit string of label hash
+        */
+        HBufC8* GetHashL( TDesC8& aString );
+
+    private: // From base class CActive 
+
+        /**
+        * Handle asyncronous response
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * Handle asyncronous call cancel
+        * @return void
+        */
+        void DoCancel();
+
+        /**
+        * Handles RunL function leaves
+        * @param aError  Leaving code.
+        * @return TInt
+        */
+        TInt RunError( TInt aError );
+
+    private:    // Data
+
+        enum TPhase
+            {
+            EIdle,
+            ERetrieve,
+            ECheckRestore,
+            ECheckInitializeCertStore,
+            ECheckRetrieve
+            };
+
+        // The state of this active object
+        TPhase iPhase;
+
+        // Used for saving caller status. Not owned
+        TRequestStatus* iOriginalRequestStatus;
+
+        //Database session for WimTrustSettingsStore
+
+        RFs iDBSession;
+         
+        //Database for WimTrustSettingsStore
+        RDbNamedDatabase iDatabase;
+
+        //Flag to tell if compact operation for dbhas to be done in destructor
+        TBool            iCompact;
+
+        // For file session
+        RFs iFs;
+
+        // Pointer to CertUtil.Owned
+        CWimCertUtil* iWimCertUtil;
+
+        // Pointer to current wim specific certificate info
+        const CWimCertInfo* iWimCert;
+
+        // Pointer to current Symbian specific certificate info
+        const CCTCertInfo* iCert;
+
+        // Boolean indicating if default applications are added or not
+        TBool iAddApps;
+
+        // Pointer to whole certificate data buffer
+        HBufC8* iEncodedCertBuf;
+
+        // Pointer to certificate data buffer
+        TPtr8* iEncodedCertPtr;
+
+        // Temporal array for certificate infos. 
+        // This array is used to fetch certificate infos from WimClient.
+        // Owned.
+        RPointerArray<CWimCertInfo> iCertInfos;
+    };
+
+#endif      // CWIMTRUSTSETTINGSSTORE_H
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/inc/WimUtilityFuncs.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,123 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Header for utility functions
+*
+*/
+
+
+
+#ifndef CWIMUTILITYFUNCS_H
+#define CWIMUTILITYFUNCS_H
+
+//  INCLUDES
+#include "WimConsts.h"      //Error codes
+#include "Wimi.h"           //WIMI definitions
+
+// DATA TYPES
+
+// Type of request
+enum TWimReqType
+    {
+    EWimMgmtReq
+    };
+
+// Request type and transaction id
+struct TWimReqTrId
+    {
+    TAny*       iReqTrId;
+    TWimReqType iReqType;
+    };
+
+
+// CLASS DECLARATION
+
+/**
+*  Utility functions for WimServer
+*
+*  @since Series 60 2.1
+*/
+class CWimUtilityFuncs : public CBase  
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimUtilityFuncs* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimUtilityFuncs();
+
+    public: // New functions
+        
+        /**
+        * Map WIMI error to WIM errors
+        * @param aStatus WIMI error code
+        * @return WIM error code 
+        */
+        static TInt MapWIMError( WIMI_STAT aStatus );
+
+        /**
+        * Get SIM/SWIM state
+        * @return SIM/SWIM state: KErrNone if OK
+        *                         If not OK some other system wide state
+        */
+        static TInt SimState();
+
+        /**
+        * Utility function that reads a descriptor from the clients address
+        * space. The caller has to free the returned HBufC8.
+        * @param aIndex Message slot index to be read
+        * @param aMessage Message
+        * @return Pointer to allocated HBufC8 buffer.
+        */
+        HBufC8* DesLC( const TInt aIndex,
+                       const RMessage2& aMessage ) const;
+   
+       
+        /**
+        * Creates a new ReqTrId item.
+        * @param aAny Pointer to TAny
+        * @param aReqType Request type
+        * @return Structure which contains transaction ID and request type
+        */
+        TWimReqTrId* TrIdLC( TAny* aAny, TWimReqType aReqType ) const;
+
+        /**
+        * Maps WIMI's certificate location value to WimServer's location type
+        * TWimCertificateCDF
+        * @param aCertCDF WIMI's certificate location value
+        * @return WimServer's location value
+        */
+        TUint8 MapCertLocation( const TUint8 aCertCDF ) const;
+
+    private:
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * C++ default constructor.
+        */
+        CWimUtilityFuncs();
+
+    };
+
+#endif      // CWIMUTILITYFUNCS_H 
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimApduImpl.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,645 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Apdu handling between WimServer and Scard
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimApduImpl.h"
+#include    "WimConsts.h"   // Error codes
+#include    "WimDefs.h"
+#include    "ScardBase.h"
+#include    "ScardConnectionRequirement.h"
+#include    "ScardComm.h"
+#include    "ScardReaderQuery.h"
+#include    "WimUtilityFuncs.h"
+#include    "WimTrace.h"
+
+//APDU for retrieving response from WIM-card.
+TUint8 iResponseAPDU[] = {0x80, 0xc0, 0x00, 0x00, 0x00};
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+CWimApdu::CWimApdu() : CActive( EPriorityStandard )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::CWimApdu | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimApdu::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimApdu* CWimApdu::NewL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::NewL | Begin"));
+    CWimApdu* self = new( ELeave ) CWimApdu();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimApdu::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimApdu::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::ConstructL | Begin"));
+    CActiveScheduler::Add( this );
+    iReaderComm = new( ELeave ) CArrayFixFlat<CScardComm*>( 1 );
+    //Reserve space for each possible reader.
+    iReaderComm->SetReserveL( KMaxReaderCount );
+    iReaderNames = new( ELeave ) CArrayFixFlat<TScardReaderName>( 1 );
+    //Reserve space for each possible reader.
+    iReaderNames->SetReserveL( KMaxReaderCount );
+    iServer = RScard::NewL();
+    iResponseBuffer = HBufC8::NewL( KMaxApduLen );
+    iWimScardListenerArray = new( ELeave ) CArrayPtrFlat<CWimScardListener>(1);
+    }
+
+// Destructor
+CWimApdu::~CWimApdu()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::~CWimApdu | Begin"));
+    
+    Cancel();
+    delete iResponseBuffer;
+    delete iReaderNames;
+
+    if ( iReaderComm )
+        {
+        for ( TUint8 i( 0 ); i < iReaderComm->Count(); i++ )
+            {
+            delete (*iReaderComm)[i];
+            (*iReaderComm)[i] = 0;
+            }
+        delete iReaderComm; 
+        }
+
+    delete iServer;
+
+    if ( iWimScardListenerArray )
+        {
+        iWimScardListenerArray->ResetAndDestroy();
+        delete iWimScardListenerArray;
+        }
+    }
+                  
+// -----------------------------------------------------------------------------
+// CWimApdu::RequestList
+// List readers and get cababilities of each card
+// -----------------------------------------------------------------------------
+//
+TUint8 CWimApdu::RequestListL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::RequestListL | Begin"));
+    CScardReaderQuery* query = NULL;  //Class used to list resources 
+                                   //owned by Smart Card Server.
+    CArrayFixFlat<TScardReaderName>* readerNames = NULL;
+    CArrayFixFlat<TScardReaderName>* groupNames = NULL;
+    TInt8 position = 0;
+    TInt error;
+
+    //Reset member data associated with query data.
+    iReaderStatusLength = 0;
+    iReaderStatusses.Delete( 0, KMaxReaderCount );
+    iReaderStatusses.Zero();
+
+    TUint8 i;
+    for ( i = 0; i < iReaderComm->Count(); i++ )
+        {
+        delete (*iReaderComm)[i];
+        (*iReaderComm)[i] = NULL;
+        }
+    iReaderComm->Delete( 0, iReaderComm->Count() );
+    iReaderNames->Delete( 0, iReaderNames->Count() );
+
+    TRAP(
+        error,
+        query = CScardReaderQuery::NewL();
+        readerNames = 
+            new( ELeave ) CArrayFixFlat<TScardReaderName>( KMaxReaderCount );
+        groupNames =
+            new( ELeave ) CArrayFixFlat<TScardReaderName>( KMaxReaderCount );
+        query->ListGroupsL( groupNames )
+        );
+
+    if ( error )
+        {
+        delete query;
+        readerNames->Reset();
+        delete readerNames;
+        groupNames->Reset();
+        delete groupNames;
+
+        iResponseStatus = KWimApduNoMemory;
+
+        //any return value <> 0 means error by WIMlib specs
+        return KWimStatusIOError;
+        }
+
+    // Get readers from all groups and add them to readerNames.
+    for ( i = 0; i < groupNames->Count(); i++ )
+        {
+        //Get reader names from this group.
+        TRAP( error, query->ListReadersL( readerNames, (*groupNames)[i] ) );
+        
+        if ( error )
+            {
+            delete query;
+            readerNames->Reset();
+            delete readerNames;
+            groupNames->Reset();
+            delete groupNames;
+
+            iResponseStatus = KWimApduNoMemory;
+
+            return KWimStatusIOError;
+            }
+
+        //Add all reader names found from this group to iReaderNames.
+        for ( TInt8 k = 0; k < readerNames->Count(); k++ )
+            {
+            //Should do something if maxreadernames == readerNames->Count()!
+            TRAP( error, iReaderNames->AppendL( (*readerNames)[k] ) );
+
+            if ( error )
+                {
+                delete query;
+                readerNames->Reset();
+                delete readerNames;
+                groupNames->Reset();
+                delete groupNames;
+
+                iResponseStatus = KWimApduNoMemory;
+
+                return KWimStatusIOError;
+                }
+            position++;
+            }
+        }
+
+    //Create CScardComm object for each found reader.
+    for ( TUint8 j = 0; j < iReaderNames->Count(); j++ )
+        {
+        TBuf8<1> tempStatus;        //Buffer used to hold 1 status byte.
+        TScardConnectionRequirement rest; //Connection requirements used in
+                                          //the creation of CScardComm object.
+        TScardReaderName name;
+
+        CScardComm* tempComm = NULL;
+        //Set rest to explicit value (name of the current reader) and
+        //create CScardComm according to these values. Also check that
+        //the found reader name (name) is really what we were looking for
+        //(is this needed?). If everything is ok, add created CScardComm
+        //to iReaderComm, else NULL.
+        iStatus = KRequestPending;
+        TRAP( error,
+            rest.SetExplicitL( (*iReaderNames)[j] );
+            tempComm = CScardComm::NewL( iServer, rest, name, iStatus )
+            );
+        
+        SetActiveAndWait();
+
+        if ( error || iStatus.Int() != KErrNone || ( name != (*iReaderNames)[j] ) )
+            {
+            iReaderComm->AppendL( NULL );
+            _WIMTRACE2(_L("WIM | WIMServer | CWimApdu::RequestListL | CScardComm::NewL leaved with %d"), error);
+             
+             delete tempComm;
+             tempComm = NULL;
+             delete query;
+             readerNames->Reset();
+             delete readerNames;
+             groupNames->Reset();
+             delete groupNames;
+            
+            User::Leave ( KErrHardwareNotAvailable );
+            }
+        else    //all ok.
+            {
+            TRAP( error,
+                iReaderComm->AppendL( tempComm )
+                );
+
+            if ( error )
+                {
+                delete tempComm;
+                tempComm = NULL;
+                iReaderComm->AppendL( NULL );
+                }
+            else    //all ok.
+                {
+                //Get capabilities of the card. With this value GetCapabilities
+                //puts status to tempStatus.
+                TRAP( error,
+                    (*iReaderComm)[j]->GetCapabilitiesL( KCardStatus,
+                    tempStatus ) );
+                _WIMTRACE3(_L("WIM | WIMServer | CWimApdu::RequestListL | GetCapabilitiesL error = %d, Card status = %d"), error, (TUint8)*tempStatus.Ptr());
+                _WIMTRACE2(_L("WIM|WIMServer|CWimApdu::RequestListL|tempStatus.Size() = %d"), tempStatus.Size());
+
+                if ( error == KErrNoMemory )
+                    {
+                    delete query;
+                    readerNames->Reset();
+                    delete readerNames;
+                    groupNames->Reset();
+                    delete groupNames;
+
+                    iResponseStatus = KWimApduNoMemory;
+                    return ( TUint8 )KErrCouldNotConnect;
+                    }
+     
+                else if ( error == KErrNone && tempStatus.Size() && *tempStatus.Ptr() )
+                    {
+                    iReaderStatusLength++;
+                    iReaderStatusses.Append( tempStatus );
+                    _WIMTRACE(_L("WIM|WIMServer|CWimApdu::RequestListL|Reader status appended"));
+                    }   //else if
+                else
+                    {
+                    _WIMTRACE2(_L("WIM|WIMServer|CWimApdu::RequestListL|Leave with error %d"), error);
+                    User::Leave( error );
+                    }
+                }   //else
+            }   //else
+        }   //for
+
+    //Add Listeners to readers 
+    for ( TInt y = 0; y < iReaderNames->Count(); y++ )
+        {
+        CWimScardListener* wimScardListener;                       
+        TRAP( error, wimScardListener = CWimScardListener::NewL( iServer,
+            ( TUint8 )y, iReaderNames->At( y ) ) );
+        iWimScardListenerArray->AppendL( wimScardListener );
+        }
+
+    iResponseStatus = KWimApduOk;
+
+    delete query;   
+    readerNames->Reset();   
+    delete readerNames;
+    groupNames->Reset();
+    delete groupNames;
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimApdu::Open
+// Open connection to Scard
+// -----------------------------------------------------------------------------
+//
+TUint8 CWimApdu::Open( TUint8 aUiReaderId )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::Open | Begin"));
+    
+    if ( !iServer ) //No Scard
+        {
+        TRAPD( error, iServer = RScard::NewL() );
+        
+        if ( error != KErrNone )
+            {
+            iResponseStatus = KWimApduTransmiossionError;
+            return KWimStatusIOError;
+            }
+        }
+
+    //If aUiReaderId is valid and connection to reader is not opened...
+    if ( ( aUiReaderId < iReaderComm->Count() ) &&
+        ( (*iReaderComm)[aUiReaderId] == 0 ) )
+        {
+        _WIMTRACE(_L("WIM | WIMServer | CWimApdu::Open | Reader not opened"));
+        //...open connection, try to find the reader with name
+        //specified in iReaderNames.
+        TScardConnectionRequirement rest;
+        TScardReaderName name;
+        iStatus = KRequestPending;
+
+        TRAPD( error, 
+            rest.SetExplicitL( (*iReaderNames)[aUiReaderId] );
+            (*iReaderComm)[aUiReaderId] =
+                CScardComm::NewL( iServer, rest, name, iStatus ) );
+        
+        SetActiveAndWait();
+
+        _WIMTRACE3(_L("WIM | WIMServer | CWimApdu::Open | Error=%d, iStatus=%d"),
+        	error, iStatus.Int());
+
+        if ( error == KErrNone && iStatus.Int() == KErrNone )
+            {//Add listener to opened reader and append it to array.
+            CWimScardListener* wimScardListener;
+            TRAP( error,
+                wimScardListener = CWimScardListener::NewL( iServer,
+                                                            aUiReaderId,
+                                                            name );
+                iWimScardListenerArray->AppendL( wimScardListener );
+                );
+            }
+
+        if ( error == KErrNoMemory || iStatus.Int() == KErrNoMemory )
+            {
+            iResponseStatus = KWimApduNoMemory;
+            return ( TUint8 )KWimCardDriverInitError;
+            }
+        else if ( error || name != (*iReaderNames)[aUiReaderId]
+            || iStatus.Int() != KErrNone )
+            {
+            iResponseStatus = KWimApduTransmiossionError;
+            return KWimStatusIOError;
+            }
+        else
+            {
+            iResponseStatus = KWimApduOk;
+            return KWimStatusOK; //WIMSTA_OK;
+            }
+        }
+    else
+        {
+        iResponseStatus = KWimApduOk;
+        return KWimStatusOK; //WIMSTA_OK;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimApdu::Close
+// Close connection to card
+// -----------------------------------------------------------------------------
+//
+TUint8 CWimApdu::Close( TUint8 aUiReaderId )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::Close | Begin"));
+
+    if ( ( aUiReaderId < iReaderComm->Count() ) &&
+        ( (*iReaderComm)[aUiReaderId] != 0 ) )
+        {
+        delete (*iReaderComm)[aUiReaderId];
+        (*iReaderComm)[aUiReaderId] = 0;
+        }
+    
+    if ( iWimScardListenerArray->Count() > aUiReaderId )
+        {
+        delete iWimScardListenerArray->At( aUiReaderId );
+        iWimScardListenerArray->Delete( aUiReaderId );
+        }
+    iResponseStatus = KWimApduOk;
+    return KWimStatusOK; //WIMSTA_OK;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimApdu::SendAPDU
+// Send APDU to card
+// -----------------------------------------------------------------------------
+//
+TUint8 CWimApdu::SendAPDU(
+    TUint8  aUiReaderId,
+    TUint8* aApdu,
+    TUint16 aUiApduLength )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::SendAPDU | Begin"));
+    //clean SW
+    iResponseSW = 0;
+    TPtr8 responsePtr = iResponseBuffer->Des();
+    //clean buffer
+    responsePtr.Zero();
+    if ( ( aUiReaderId < iReaderComm->Count() ) &&
+        ( (*iReaderComm)[ aUiReaderId ] != 0 ) )
+        {
+        iUiReaderId = aUiReaderId;
+        
+        iStatus = KRequestPending;
+        //If apdu to be sent was ManageChannel, 
+        //use CScardComms ManageChannel function.
+        if ( ( aUiApduLength >= 4 ) && ( aApdu[1] == KManageChannelIns ) )
+            {
+            switch ( aApdu[2] )
+                {
+                case KManageChannelParamOpen:
+                    {
+                    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::SendAPDU | OPEN CHANNEL"));
+                    //Last parameter is timeout. No timeout used. 
+                    (*iReaderComm)[aUiReaderId]->ManageChannel(
+                        EOpenAnyChannel, aApdu[3], responsePtr, iStatus, 0 );
+                    break;
+                    }
+                case KManageChannelParamClose:
+                    {
+                    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::SendAPDU | CLOSE CHANNEL"));
+                    // Check whether state of the SIM/SWIM is OK
+                    if ( CWimUtilityFuncs::SimState() != KErrNone ) 
+                        {
+                        _WIMTRACE(_L("WIM | WIMServer | CWimApdu::SendAPDU | SIM not ready"));
+                        // SIM/SWIM not OK, just return KWimStatusOK to WimLib
+                        // so WimLib can continue properly
+                        return KWimStatusOK;
+                        }
+                    else // Card OK, close the opened channel
+                        {
+                        // Close channel with 5 second timeout
+                        (*iReaderComm)[aUiReaderId]->ManageChannel( 
+                                                ECloseChannel,
+                                                aApdu[3],
+                                                responsePtr,
+                                                iStatus,
+                                                KDefaulCloseChannelTimeout );
+                        }
+                    break;
+                    }
+                default:    // APDU is not valid.
+                    {
+                    iResponseStatus = KWimApduFormatError;
+                    return KWimStatusOK; //WIMSTA_OK;
+                    //break; //unreachable
+                    }
+                }
+            }
+        else
+            {
+            TPtrC8 commandAPDU( aApdu, aUiApduLength );
+
+            //Transmit APDU to card. 
+            (*iReaderComm)[aUiReaderId]->TransmitToCard( commandAPDU, 
+                responsePtr,  iStatus, 0, (TUint8)( aApdu[0] & 0x0f ) );
+            
+            }
+        SetActiveAndWait(); // Wait APDU response
+        
+        if ( iStatus != KErrNone ) 
+            {
+            iResponseStatus = KWimApduTransmiossionError;
+            responsePtr.SetLength( 0 );
+            return KWimStatusIOError;
+            } 
+        
+        if ( responsePtr.Size() >= 2 ) //At least SW-bytes are needed (2 of'em).
+            {
+            //Response has to be retrieved.
+            if ( responsePtr[responsePtr.Size() - 2] == 0x61 ) 
+                {
+                iStatus = KRequestPending;
+                iResponseAPDU[0] = aApdu[0];
+                iResponseAPDU[4] = responsePtr[responsePtr.Size() - 1];
+                TPtrC8 commandAPDU( iResponseAPDU, 5 );
+
+                //Transmit APDU to card. Timeout not used.
+                (*iReaderComm)[aUiReaderId]->TransmitToCard( commandAPDU,
+                    responsePtr, iStatus, 0, (TUint8)( aApdu[0] & 0x0f ) );
+                
+                SetActiveAndWait(); // Wait APDU response
+
+                if ( iStatus != KErrNone ) 
+                    {
+                    iResponseStatus = KWimApduTransmiossionError;
+                    responsePtr.SetLength( 0 );
+                    return KWimStatusIOError;
+                    } 
+                
+                //At least SW-bytes are needed (2 of them).
+                else if ( responsePtr.Size() < 2 ) 
+                    {
+                    iResponseStatus = KWimApduFormatError;   
+                    responsePtr.SetLength( 0 );
+                    return KWimStatusOK;
+                    }
+                }
+            iResponseStatus = KWimApduOk;
+            iResponseSW = 
+                ( TUint16 )( ( responsePtr[responsePtr.Size() - 2] << 8 )
+                | ( responsePtr[responsePtr.Size() - 1] ) );
+
+            responsePtr.SetLength( responsePtr.Size() - 2 );//All but SW-bytes.
+            return KWimStatusOK;
+            }
+        else
+            {
+            iResponseStatus = KWimApduFormatError;
+            responsePtr.SetLength( 0 );
+            return KWimStatusOK; //WIMSTA_OK;
+            }
+        }
+    else
+        {
+        //Not valid card.
+        iResponseStatus = KWimApduReaderNotValid;
+        responsePtr.SetLength( 0 );
+        return KWimStatusOK; //WIMSTA_OK;
+        }           
+    }
+
+// -----------------------------------------------------------------------------
+// CWimApdu::ResponseApdu
+// Return response APDU
+// -----------------------------------------------------------------------------
+//
+TPtrC8 CWimApdu::ResponseApdu() const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::ResponseApdu | Begin"));
+    return iResponseBuffer->Des();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimApdu::ResponseSW
+// Return Response SW
+// -----------------------------------------------------------------------------
+//
+TUint16 CWimApdu::ResponseSW() const
+    {
+    _WIMTRACE2(_L("WIM | WIMServer | CWimApdu::ResponseSW | iResponse = %04x"),
+    	iResponseSW );
+    return iResponseSW;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimApdu::StatusList
+// Return reader statusses
+// -----------------------------------------------------------------------------
+//
+const TBuf8<KMaxReaderCount>& CWimApdu::StatusList() const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::StatusList | Begin"));
+    return iReaderStatusses;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimApdu::StatusListLength
+// Return status list length
+// -----------------------------------------------------------------------------
+//
+TUint8 CWimApdu::StatusListLength() const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::StatusListLength | Begin"));
+    return iReaderStatusLength;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimApdu::RunL
+// Stop ActiveSchedulerWait after APDU response
+// -----------------------------------------------------------------------------
+//
+void CWimApdu::RunL()
+    {
+    _WIMTRACE2(_L("WIM | WIMServer | CWimApdu::RunL, status: %d"), iStatus.Int());
+    iWait.AsyncStop();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimApdu::DoCancel
+// Cancel asyncronous request
+// -----------------------------------------------------------------------------
+//
+void CWimApdu::DoCancel()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::DoCancel | Begin"));
+    (*iReaderComm)[iUiReaderId]->CancelTransmit();
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::DoCancel | End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimApdu::SetActiveAndWait
+// Wait until asynchronous call is completed
+// -----------------------------------------------------------------------------
+//
+void CWimApdu::SetActiveAndWait()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::SetActiveAndWait | Begin"));
+    SetActive();
+    iWait.Start();
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::SetActiveAndWait | End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimApdu::CancelApduSending
+// -----------------------------------------------------------------------------
+//    
+void CWimApdu::CancelApduSending()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimApdu::CancelApduSending | Begin"));
+	if( IsActive() )
+	    {
+		Cancel();
+	    }
+	_WIMTRACE(_L("WIM | WIMServer | CWimApdu::CancelApduSending | End"));    
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimAuthObjHandler.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1417 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Services for authentication object management
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimServer.h"
+#include    "Wimi.h"            //WIMI definitions
+#include    "WimClsv.h"
+#include    "WimAuthObjHandler.h"
+#include    "WimMemMgmt.h"
+#include    "WimResponse.h"
+#include    "WimUtilityFuncs.h"
+#include    "WimSecurityDlgHandler.h"
+#include    "WimTrace.h"
+#include    "WimCallbackImpl.h"
+#include    "WimCleanup.h"
+#include    "JavaUtils.h"
+#include    <random.h>
+
+#ifdef _DEBUG
+_LIT( KWimAuthObjPanic, "WimAuthObj" );
+#endif
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::CWimAuthObjHandler
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimAuthObjHandler::CWimAuthObjHandler() : CActive( EPriorityStandard )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimAuthObjHandler::CWimAuthObjHandler | Begin"));
+    iDisablePINBlocked = EFalse;
+    iUnblockPING = EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimAuthObjHandler::ConstructL | Begin"));
+    CActiveScheduler::Add( this );
+    iWimUtilFuncs = CWimUtilityFuncs::NewL();
+    iWimSecDlg = CWimSecurityDlgHandler::NewL();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimAuthObjHandler* CWimAuthObjHandler::NewL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimAuthObjHandler::NewL | Begin"));
+    CWimAuthObjHandler* self = new( ELeave ) CWimAuthObjHandler;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+    
+// Destructor
+CWimAuthObjHandler::~CWimAuthObjHandler()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimAuthObjHandler::~CWimAuthObjHandler | Begin"));
+    Cancel();
+    delete iWimUtilFuncs;
+    delete iWimSecDlg;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::GetPINCountL
+// Fetches the count of PINs in WIM.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::GetPINCountL( const RMessage2& aMessage ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimAuthObjHandler::GetPINCountL | Begin"));
+    WIMI_Ref_pt pWimStruct = const_cast<WIMI_Ref_pt>( aMessage.Ptr0() ); 
+    TUint16 pinNum;
+    WIMI_RefList_t refList;
+    WIMI_STAT status = WIMI_Ok; 
+    
+    status = WIMI_GetPINList( pWimStruct, &pinNum, &refList );
+    
+    if ( status == WIMI_Ok )
+        {
+        free_WIMI_RefList_t( refList );
+        TPckgBuf<TUint> pckg( pinNum );
+        aMessage.WriteL( 1, pckg );
+        }
+    aMessage.Complete( CWimUtilityFuncs::MapWIMError( status ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::GetPINRefListL
+// Get reference list for PINs.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::GetPINRefListL( 
+    const RMessage2& aMessage, 
+    CWimMemMgmt* aWimMgmt )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimAuthObjHandler::GetPINRefListL | Begin"));
+    WIMI_Ref_pt pWimStruct = const_cast<WIMI_Ref_pt>( aMessage.Ptr0() );
+    __ASSERT_ALWAYS( pWimStruct, User::Leave( KErrArgument ) );
+    HBufC8* buf = iWimUtilFuncs->DesLC( 2, aMessage );
+    TUint32* pinArr = ( TUint32* )( buf->Des().Ptr() );
+    TUint16 pinNum;
+    WIMI_RefList_t pinRefLst;
+    WIMI_STAT status = WIMI_Ok;
+       
+    status = WIMI_GetPINList( pWimStruct, &pinNum, &pinRefLst );
+    
+    if ( status == WIMI_Ok )
+        {
+        aWimMgmt->AppendWIMRefLstL( pinRefLst );    // takes ownership
+        TPckgBuf<TUint32> lstAddr( ( TUint32 ) pinRefLst );
+        for ( TUint8 index = 0; index < pinNum; index++ )
+            {
+            pinArr[index] = ( TUint32 ) pinRefLst[index];
+            }
+            
+        iPinGRef =  const_cast< WIMI_Ref_pt >( pinRefLst[0] );
+        
+        aMessage.WriteL( 1, lstAddr );
+        aMessage.WriteL( 2, buf->Des() );
+        }
+    CleanupStack::PopAndDestroy( buf );
+    aMessage.Complete( CWimUtilityFuncs::MapWIMError( status ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::GetPINInfoL
+// Get detailed information about the PIN.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::GetPINInfoL( const RMessage2& aMessage ) 
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimAuthObjHandler::GetPINInfoL | Begin"));
+    WIMI_Ref_pt pPinStruct = const_cast<WIMI_Ref_pt>( aMessage.Ptr0() );
+    __ASSERT_ALWAYS( pPinStruct, User::Leave( KErrArgument ) );
+    TUint8 flags;
+    TUint8 minLength;
+    TUint8 pinNumber = 0;
+    WIMI_BinData_t ptLabel;
+    WIMI_STAT status = WIMI_Ok;
+    
+    if ( pPinStruct )
+        {
+        iPinValue.Zero();
+        TRequestStatus status1;
+        CWimCallBack::SetSignTextRequestStatus( &status1 );
+        status = WIMI_VerifyPINReq( NULL,pPinStruct, 
+                             ( TUint8 )iPinValue.Length(),
+                             ( TUint8* )iPinValue.Ptr() );
+            
+        if ( status != WIMI_Ok )
+            {
+        	aMessage.Complete( CWimUtilityFuncs::MapWIMError( status ) );
+        	return;
+            }
+             
+        User::WaitForRequest( status1 );   
+        CWimCallBack::SetSignTextRequestStatus( NULL );          
+        WIMI_Ref_t* cmeWimRef = NULL;
+        
+        status = WIMI_GetPINStatus( pPinStruct,
+                                    &cmeWimRef,
+                                    &flags,
+                                    &minLength,
+                                    &pinNumber,
+                                    &ptLabel );
+
+        if ( status == WIMI_Ok )
+            {
+            // Code MAY NOT leave before cmeWimRef and ptLabel.pb_buf are deallocated.
+
+            TPckgBuf<TWimPinStruct> infoPckg;
+            TInt readErr = aMessage.Read( 1, infoPckg );
+            if( readErr )
+                {
+                free_WIMI_Ref_t( cmeWimRef );
+                WSL_OS_Free( ptLabel.pb_buf );
+                // Code can leave after this point.
+                User::Leave( readErr );
+                }
+
+            TBuf<KLabelLen> label;
+            label.Copy( TPtr8( ptLabel.pb_buf,
+                               ptLabel.ui_buf_length, 
+                               ptLabel.ui_buf_length ) );
+            
+            // Possible values of iStatus are:
+            // EEnabled		    = 0x80,
+            // EChangeDisabled	= 0x40,
+            // EUnblockDisabled	= 0x20,
+            // EDisableAllowed	= 0x10,
+        
+            if( status1.Int() == KErrLocked )
+                {
+                infoPckg().iStatus = flags & KPINStatusMask;
+                infoPckg().iStatus = infoPckg().iStatus | KWimAuthObjectBlocked;	
+                }
+            else if( iDisablePINBlocked )
+                {
+                infoPckg().iStatus = flags & KPINStatusMask;
+            	infoPckg().iStatus = infoPckg().iStatus | KWimAuthObjectBlocked;
+                }
+            else
+                {
+                infoPckg().iStatus = flags & KPINStatusMask;	
+                }
+            
+            infoPckg().iPinNumber = pinNumber;
+            infoPckg().iLabel = label;
+
+            TInt writeErr = aMessage.Write( 1, infoPckg );
+
+            free_WIMI_Ref_t( cmeWimRef );
+            WSL_OS_Free( ptLabel.pb_buf );
+            // Code can leave after this point.
+            User::LeaveIfError( writeErr );
+            }
+        }
+    else
+        {
+        status = WIMI_ERR_BadParameters;
+        }
+    aMessage.Complete( CWimUtilityFuncs::MapWIMError( status ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::GetPINsInfoL
+// Get detailed information about the all of the PINs on a certain SecMod.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::GetPINsInfoL( const RMessage2& aMessage ) 
+    {
+    //Get pin number and reflist
+    _WIMTRACE(_L("WIM | WIMServer | CWimAuthObjHandler::GetPINsInfoL | Begin"));
+    WIMI_Ref_pt pWimStruct = const_cast<WIMI_Ref_pt>( aMessage.Ptr0() ); 
+    
+    TUint16 pinNum;
+    WIMI_RefList_t refList;
+    WIMI_STAT status = WIMI_Ok;
+   
+    status = WIMI_GetPINList( pWimStruct, &pinNum, &refList );
+    CleanupPushWimRefListL( refList );
+
+    CArrayFixFlat<TWimPinStruct>* pinsInfo = new( ELeave ) CArrayFixFlat<TWimPinStruct>( pinNum );
+    CleanupStack::PushL( pinsInfo );
+
+    RArray<WIMI_Ref_pt> pinRefsArray;
+    CleanupClosePushL( pinRefsArray );
+   
+    if( status == WIMI_Ok )
+        {
+        if( pinNum != aMessage.Int2() )
+            {
+            status = WIMI_ERR_Internal;
+            CleanupStack::PopAndDestroy( 3, refList );  // pinRefsArray, pinsInfo, refList
+            aMessage.Complete( CWimUtilityFuncs::MapWIMError( status ) );
+            return;
+            }
+        for ( TUint8 index = 0; index < pinNum; index++ )
+            {
+            pinRefsArray.Append( refList[index] );
+            }
+        }
+    else
+        {
+        CleanupStack::PopAndDestroy( 3, refList );  // pinRefsArray, pinsInfo, refList
+        aMessage.Complete( CWimUtilityFuncs::MapWIMError( status ) );
+        return;
+        }
+
+    //Get pin details bt pin reference
+    for ( TUint8 index = 0; index < pinNum; index++ )
+        {
+        WIMI_Ref_pt pPinStruct = pinRefsArray[ index ];
+
+	    __ASSERT_ALWAYS( pPinStruct, User::Leave( KErrArgument ) );
+
+        TUint8 flags;
+        TUint8 minLength;
+        TUint8 pinNumber = 0;
+        WIMI_BinData_t ptLabel;
+        WIMI_STAT status = WIMI_Ok;
+        
+        TRequestStatus status1;
+        
+        iPinValue.Zero();
+        
+        CWimCallBack::SetSignTextRequestStatus( &status1 );
+
+        status = WIMI_VerifyPINReq( NULL,pPinStruct, 
+                 ( TUint8 )iPinValue.Length(),
+                 ( TUint8* )iPinValue.Ptr() );
+        
+        _WIMTRACE2(_L("WIM | WIMServer | CWimAuthObjHandler::GetPINsInfoL status %d "), status );    
+
+        if ( status != WIMI_Ok )
+            {
+            CleanupStack::PopAndDestroy( 3, refList );  // pinRefsArray, pinsInfo, refList
+            aMessage.Complete( CWimUtilityFuncs::MapWIMError( status ) );
+            return;
+            }
+
+        User::WaitForRequest( status1 );
+
+        CWimCallBack::SetSignTextRequestStatus( NULL );
+        
+        WIMI_Ref_t* cmeWimRef = NULL;
+        
+        status = WIMI_GetPINStatus( pPinStruct,
+                        &cmeWimRef,
+                        &flags,
+                        &minLength,
+                        &pinNumber,
+                        &ptLabel );
+        
+        if ( status == WIMI_Ok )
+            {
+            free_WIMI_Ref_t( cmeWimRef );
+            CleanupPushWimBufL( ptLabel );
+
+            TWimPinStruct pinStruct;
+            pinStruct.iLabel.Copy( TPtr8( ptLabel.pb_buf,
+                    ptLabel.ui_buf_length,
+                    ptLabel.ui_buf_length ) );
+            CleanupStack::PopAndDestroy( ptLabel.pb_buf );
+
+            // Possible values of iStatus are:
+            // EEnabled		    = 0x80,
+            // EChangeDisabled	= 0x40,
+            // EUnblockDisabled	= 0x20,
+            // EDisableAllowed	= 0x10,
+
+            if( status1.Int() == KErrLocked )
+                {
+                pinStruct.iStatus = flags & KPINStatusMask;
+                pinStruct.iStatus = pinStruct.iStatus | KWimAuthObjectBlocked;
+                }
+            else if( iDisablePINBlocked )
+                {
+                pinStruct.iStatus = flags & KPINStatusMask;
+                pinStruct.iStatus = pinStruct.iStatus | KWimAuthObjectBlocked;
+                }
+            else
+                {
+                pinStruct.iStatus = flags & KPINStatusMask;
+                }
+            pinStruct.iPinNumber = pinNumber;
+
+            pinsInfo->AppendL( pinStruct );
+            }
+        else
+            {
+            status = WIMI_ERR_BadParameters;
+            break;
+            }
+        }
+
+    TInt16 length = ( TInt16 )pinsInfo->Count()*( sizeof( TWimPinStruct ) );
+
+    TPtrC8 pinInfoPtr;
+    
+    pinInfoPtr.Set( (TText8*)&(*pinsInfo)[0], length );  
+
+    if( status == WIMI_Ok )
+        {
+        aMessage.WriteL( 1, pinInfoPtr );
+        }
+
+    CleanupStack::PopAndDestroy( 3, refList );  // pinRefsArray, pinsInfo, refList
+
+    aMessage.Complete( CWimUtilityFuncs::MapWIMError( status ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::VerifyDisabledPINRequestL
+// Verifies Disabled PIN number.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::VerifyDisabledPINRequestL( 
+     const RMessage2& aMessage )
+    {
+    __ASSERT_DEBUG( iResponseID == NULL, User::Panic( KWimAuthObjPanic, KErrGeneral ) );
+    iResponseID = new ( ELeave )CWimResponse( aMessage );
+    iResponseID->iOpcode = EVerifyDisabledPinReq;
+    
+    if( iDisablePINBlocked ) 
+    	{   
+        iResponseID->iStatus = WIMI_ERR_PINBlocked;
+        iResponseID->CompleteMsgAndDelete();
+        iResponseID = NULL;
+    	}
+    else
+    	{    
+        iResponseID->iStatus = WIMI_Ok;
+        iResponseID->CompleteMsgAndDelete();
+        iResponseID = NULL;
+    	}
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::VerifyPINRequestL
+// Verifies PIN number.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::VerifyPINRequestL(
+    const RMessage2& aMessage,
+    TBool aShowDialog )
+    {
+    _WIMTRACE(_L("WIM|WIMServer|CWimAuthObjHandler::VerifyPINRequestL|Begin"));
+
+    __ASSERT_DEBUG( iResponseID == NULL, User::Panic( KWimAuthObjPanic, KErrGeneral ) );
+    iResponseID = new ( ELeave )CWimResponse( aMessage );
+    iResponseID->iOpcode = EVerifyPinReq;
+    
+    __ASSERT_DEBUG( iTrId == NULL, User::Panic( KWimAuthObjPanic, KErrGeneral ) );
+    iTrId = iWimUtilFuncs->TrIdLC( iResponseID, EWimMgmtReq );
+    CleanupStack::Pop( iTrId );
+    
+    iShowDialog = aShowDialog;
+
+    if ( aShowDialog ) // Ask PIN from user
+        {
+        _WIMTRACE(_L("WIM|WIMServer|CWimAuthObjHandler::Verify|Show dialog"));
+        TPckgBuf<TPINParams> infoPckg;
+        aMessage.ReadL( 1, infoPckg );
+        _WIMTRACE(_L("WIM|WIMServer|CWimAuthObjHandler::Verify|PINParamas read"));
+        
+        iPinParams.iPINLabel = infoPckg().iPINLabel;
+        iPinParams.iTokenLabel = infoPckg().iTokenLabel;
+        iPinParams.iMinLength = infoPckg().iMinLength;
+	    iPinParams.iMaxLength = infoPckg().iMaxLength;
+	    
+        _WIMTRACE(_L("WIM|WIMServer|CWimAuthObjHandler::Verify|Call dialog"));
+        
+        iRetry = EFalse;
+        
+        VerifyPINAskPIN();
+         
+        }
+    else // Do not ask PIN from user, just try if PIN is blocked with empty PIN
+        {
+        iRequest = EVerifyPINAskPIN;
+        iStatus = KRequestPending;
+        SetActive();
+        iPinValue.Zero();
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::VerifyPINAskPIN
+//
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::VerifyPINAskPIN()
+    {
+	iRequest = EVerifyPINAskPIN;
+    iStatus = KRequestPending;
+    SetActive();
+    iWimSecDlg->EnterPIN( iRetry,
+                          iPinParams,
+                          iPinValue,
+                          iStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::ContinueVerifyPINReqL
+// Continue verify PIN request. Calls WIMI.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::ContinueVerifyPINReqL( ) 
+    {
+    __ASSERT_DEBUG( iResponseID, User::Panic( KWimAuthObjPanic, KErrGeneral ) );
+    WIMI_Ref_pt pPINref = const_cast<WIMI_Ref_pt>( (iResponseID->iMessage).Ptr0() );
+     
+    HBufC8* pinBuf = HBufC8::NewLC( iPinValue.Length() );
+    TPtr8 pinPtr = pinBuf->Des();
+    pinPtr.Copy( iPinValue );
+    
+    if ( iShowDialog )
+        {
+        iStatus = KRequestPending;
+        TRequestStatus* status = &iStatus;
+    	
+        iRequest = EVerifyPINCallBackResponse;
+        SetActive();
+
+        iResponseID->iStatus = WIMI_VerifyPINReq( iTrId,
+                                             pPINref, 
+                                             ( TUint8 )pinPtr.Length(),
+                                             ( TUint8* )pinPtr.Ptr() );
+
+        if ( iResponseID->iStatus != WIMI_Ok )
+            {
+            iRequest = EWIMIError;
+            User::RequestComplete( status, iResponseID->iStatus );	 
+            }
+        }
+    else
+        {
+        iResponseID->iStatus = WIMI_VerifyPINReq( iTrId,
+                                         pPINref,
+                                         ( TUint8 )pinPtr.Length(),
+                                         ( TUint8* )pinPtr.Ptr() );
+
+        if ( iResponseID->iStatus != WIMI_Ok )
+            {
+            iResponseID->CompleteMsgAndDelete();
+            iResponseID = NULL;
+            delete iTrId;
+            iTrId = NULL;
+            }
+        }
+        
+    CleanupStack::PopAndDestroy( pinBuf );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::CancelVerifyPin
+// Cancel verify Pin operation
+// -----------------------------------------------------------------------------
+//    
+void CWimAuthObjHandler::CancelVerifyPin( const RMessage2& aMessage )  
+    {
+    if( IsActive() )
+        {
+        Cancel();	
+        }
+        
+    aMessage.Complete( KErrNone ); 
+    } 
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::EnablePINReqL
+// Enables/disables PIN query.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::EnablePINReqL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM|WIMServer|CWimAuthObjHandler::EnablePINReqL|Begin"));
+
+    __ASSERT_DEBUG( iResponseID == NULL, User::Panic( KWimAuthObjPanic, KErrGeneral ) );
+    iResponseID = new( ELeave )CWimResponse( aMessage );
+    iResponseID->iOpcode =EEnablePINReq;
+    
+    __ASSERT_DEBUG( iTrId == NULL, User::Panic( KWimAuthObjPanic, KErrGeneral ) );
+    iTrId = iWimUtilFuncs->TrIdLC( iResponseID, EWimMgmtReq );
+    CleanupStack::Pop( iTrId );
+    
+    TPckgBuf<TPINStateRequest> statePckg;
+    aMessage.ReadL( 1, statePckg );
+
+    TPckgBuf<TPINParams> infoPckg;
+    aMessage.ReadL( 2, infoPckg );
+    
+    iPinParams.iPINLabel = infoPckg().iPINLabel;
+    iPinParams.iTokenLabel = infoPckg().iTokenLabel;
+    iPinParams.iMinLength = infoPckg().iMinLength;
+	iPinParams.iMaxLength = infoPckg().iMaxLength;
+
+    iEnablePinQuery = statePckg().iEnable;
+    
+    iRetry = EFalse;
+    
+    EnablePINAskPIN();
+
+    }
+    
+void CWimAuthObjHandler::EnablePINAskPIN()
+    {
+    if ( iEnablePinQuery )
+        {
+        iRequest = EEnablePINAskPIN;
+        }
+    else
+        {
+        iRequest = EDisablePINAskPIN;
+        }
+   
+    iStatus = KRequestPending;
+	SetActive();
+    // Query PIN code from the user by using security dialog
+    iWimSecDlg->EnablePIN( iEnablePinQuery,
+                           iRetry,
+                           iPinParams,
+                           iPinValue,
+                           iStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::ContinueEnablePINReqL
+// Continue enable/disable PIN query request. Calls WIMI.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::ContinueEnablePINReqL() 
+    {
+    __ASSERT_DEBUG( iResponseID, User::Panic( KWimAuthObjPanic, KErrGeneral ) );
+    WIMI_Ref_pt pPINref = const_cast<WIMI_Ref_pt>( (iResponseID->iMessage).Ptr0() );
+
+    HBufC8* pinBuf = HBufC8::NewLC( iPinValue.Length() );
+    TPtr8 pinPtr = pinBuf->Des();
+    pinPtr.Copy( iPinValue );
+    
+    iStatus = KRequestPending;
+    TRequestStatus* status = &iStatus;
+    
+    if ( iEnablePinQuery )
+        {
+        iRequest = EEnablePINCallBackResponse;
+        }
+    else
+        {
+        iRequest = EDisablePINCallBackResponse;
+        }
+    SetActive();
+
+    iResponseID->iStatus = WIMI_EnablePINReq( iTrId,
+                                             pPINref,          
+                                             ( TUint8 )pinPtr.Length(),
+                                             ( TUint8* )pinPtr.Ptr(),                     
+                                             iEnablePinQuery );
+
+    if ( iResponseID->iStatus != WIMI_Ok )   
+        {
+        iRequest = EWIMIError;
+        User::RequestComplete( status, iResponseID->iStatus );
+        }
+    CleanupStack::PopAndDestroy( pinBuf );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::CancelEnablePinL
+// Cancel enable Pin operation
+// -----------------------------------------------------------------------------
+//    
+void CWimAuthObjHandler::CancelEnablePin( const RMessage2& aMessage )  
+    {
+    if( IsActive() )
+        {
+        Cancel();	
+        }
+        
+    aMessage.Complete( KErrNone ); 
+    } 
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::ChangePINRequestL
+// Changes a PIN number.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::ChangePINRequestL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimAuthObjHandler::ChangePINRequestL | Begin"));
+
+    __ASSERT_DEBUG( iResponseID == NULL, User::Panic( KWimAuthObjPanic, KErrGeneral ) );
+    iResponseID = new ( ELeave ) CWimResponse( aMessage );
+    iResponseID->iOpcode = EChangePINReq;
+    
+    __ASSERT_DEBUG( iTrId == NULL, User::Panic( KWimAuthObjPanic, KErrGeneral ) );
+    iTrId = iWimUtilFuncs->TrIdLC( iResponseID, EWimMgmtReq );
+    CleanupStack::Pop( iTrId ); 
+
+    TPckgBuf<TPINParams> infoPckg;
+    aMessage.ReadL( 1, infoPckg );
+    
+    iPinParams.iPINLabel = infoPckg().iPINLabel;
+    iPinParams.iTokenLabel = infoPckg().iTokenLabel;
+    iPinParams.iMinLength = infoPckg().iMinLength;
+	iPinParams.iMaxLength = infoPckg().iMaxLength;
+    
+    iRetry = EFalse;
+    
+    ChangePINAskPIN();
+    }
+   
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::ChangePINAskPIN
+//
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::ChangePINAskPIN()
+    {
+	iRequest = EChangePINAskPIN;
+	iStatus = KRequestPending;
+	SetActive();
+    // Query PIN code from the user by using security dialog
+    iWimSecDlg->ChangePINValue( iRetry,
+                                iPinParams, 
+                                iOldPinValue, 
+                                iNewPinValue, 
+                                iStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::ContinueChangePINReqL
+// Continue change PIN request. Calls WIMI.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::ContinueChangePINReqL() 
+    {
+    __ASSERT_DEBUG( iResponseID, User::Panic( KWimAuthObjPanic, KErrGeneral ) );
+    WIMI_Ref_pt pPINref = const_cast<WIMI_Ref_pt>( (iResponseID->iMessage).Ptr0() );
+  
+    HBufC8* pinOldBuf = HBufC8::NewLC( iOldPinValue.Length() );
+    HBufC8* pinNewBuf = HBufC8::NewLC( iNewPinValue.Length() );
+
+    TPtr8 oldPin = pinOldBuf->Des();
+    oldPin.Copy( iOldPinValue );
+    TPtr8 newPin = pinNewBuf->Des();
+    newPin.Copy( iNewPinValue );
+    
+    iStatus = KRequestPending;
+    TRequestStatus* status = &iStatus;
+    iRequest = EChangePINCallBackResponse;
+    SetActive();
+
+    iResponseID->iStatus = WIMI_ChangePINReq( iTrId,
+                                             pPINref,
+                                             ( TUint8 )oldPin.Length(),
+                                             ( TUint8* )oldPin.Ptr() ,
+                                             ( TUint8 )newPin.Length(),
+                                             ( TUint8* )newPin.Ptr() );
+    if ( iResponseID->iStatus != WIMI_Ok )
+        {
+        iRequest = EWIMIError;
+        User::RequestComplete( status, iResponseID->iStatus );
+        }
+    CleanupStack::PopAndDestroy( 2, pinOldBuf ); // pinNewBuf, pinOldBuf
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::CancelChangePin
+// Cancel change Pin operation
+// -----------------------------------------------------------------------------
+//    
+void CWimAuthObjHandler::CancelChangePin( const RMessage2& aMessage )  
+    {
+    if( IsActive() )
+        {
+        Cancel();	
+        }
+        
+    aMessage.Complete( KErrNone ); 
+    }     
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::UnblockPinReqL
+// Unblocks blocked PIN.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::UnblockPinReqL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimAuthObjHandler::UnblockPinReqL | Begin"));
+
+    __ASSERT_DEBUG( iResponseID == NULL, User::Panic( KWimAuthObjPanic, KErrGeneral ) );
+    iResponseID = new ( ELeave ) CWimResponse( aMessage );
+    iResponseID->iOpcode = EUnblockPinReq;
+    
+    __ASSERT_DEBUG( iTrId == NULL, User::Panic( KWimAuthObjPanic, KErrGeneral ) );
+    iTrId = iWimUtilFuncs->TrIdLC( iResponseID, EWimMgmtReq );
+    CleanupStack::Pop( iTrId );
+    
+    TPckgBuf<TPINParams> blockedPINPckg;
+    aMessage.ReadL( 1, blockedPINPckg );
+    
+    iPinParams.iPINLabel = blockedPINPckg().iPINLabel;
+    iPinParams.iTokenLabel = blockedPINPckg().iTokenLabel;
+    iPinParams.iMinLength = blockedPINPckg().iMinLength;
+	iPinParams.iMaxLength = blockedPINPckg().iMaxLength;
+
+    iUnblockingPinParams.iPINLabel = KUnblockingPinLabel;
+    iUnblockingPinParams.iTokenLabel = blockedPINPckg().iTokenLabel;
+    iUnblockingPinParams.iMinLength = blockedPINPckg().iMinLength;
+    iUnblockingPinParams.iMaxLength = KMaxPINLength;
+
+    iRetry = EFalse;
+    
+    UnblockPINAskPIN();
+    }   
+
+void CWimAuthObjHandler::UnblockPINAskPIN()
+    {
+	iRequest = EUnblockPINAskPIN;
+	iStatus = KRequestPending;
+    SetActive();
+    // Query PIN code from the user by using security dialog
+    iWimSecDlg->UnblockPIN( iRetry,
+                            iPinParams,
+                            iUnblockingPinParams,
+                            iUnblockingPinValue, 
+                            iNewPinValue, 
+                            iStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::ContinueUnblockPinReqL
+// Continue Unblock PIN request. Calls WIMI.
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::ContinueUnblockPinReqL() 
+    {
+    __ASSERT_DEBUG( iResponseID, User::Panic( KWimAuthObjPanic, KErrGeneral ) );
+    WIMI_Ref_pt pPINref = const_cast< WIMI_Ref_pt>( (iResponseID->iMessage).Ptr0() );
+    
+    if( iPinGRef == pPINref )
+        {
+    	iUnblockPING = ETrue;
+        }
+    else
+        {
+        iUnblockPING = EFalse;	
+        }
+        
+    HBufC8* unblockPinBuf = HBufC8::NewLC( iUnblockingPinValue.Length() );
+    HBufC8* newPinBuf = HBufC8::NewLC( iNewPinValue.Length() );
+
+    TPtr8 unblockingPin = unblockPinBuf->Des();
+    unblockingPin.Copy( iUnblockingPinValue );
+
+    TPtr8 newPin = newPinBuf->Des();
+    newPin.Copy( iNewPinValue );
+    
+    iStatus = KRequestPending;
+    TRequestStatus* status =&iStatus;
+    iRequest = EUnblockPINCallBackResponse;
+    SetActive();
+
+    iResponseID->iStatus = WIMI_UnblockPINReq( iTrId,
+                                              pPINref,
+                                              ( TUint8 )unblockingPin.Length(),
+                                              ( TUint8* )unblockingPin.Ptr(),
+                                              ( TUint8 )newPin.Length(),
+                                              ( TUint8* )newPin.Ptr() );
+    
+    if ( iResponseID->iStatus != WIMI_Ok )
+        {
+        iRequest = EWIMIError;
+        User::RequestComplete( status, iResponseID->iStatus );
+        }
+    CleanupStack::PopAndDestroy( 2, unblockPinBuf ); // newPinBuf, unblockPinBuf
+    
+    }
+    
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::CancelUnblockPinL
+// Cancel Unblock Pin operation
+// -----------------------------------------------------------------------------
+//    
+void CWimAuthObjHandler::CancelUnblockPin( const RMessage2& aMessage )  
+    {
+    if( IsActive() )
+        {
+        Cancel();	
+        }
+        
+    aMessage.Complete( KErrNone ); 
+    }    
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::RunL
+// Continue authentication request after PIN is asked
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::RunL()
+    {
+    _WIMTRACE3(_L("WIM|WIMServer|CWimAuthObjHandler::RunL|iRequest=%d, status=%d"), iRequest, iStatus.Int());
+
+    switch ( iRequest )
+        {
+        // Verify PIN request
+        case EVerifyPINAskPIN:
+            {
+            iRetry = ETrue;
+
+            if( iStatus.Int() == KErrCancel )
+                {
+                _WIMTRACE2(_L("WIM|WIMServer|CWimAuthObjHandler::RunL|User cancel %d "), iStatus.Int());
+                if( iResponseID )
+                    {
+                    iResponseID->iStatus = WIMI_ERR_UserCancelled;
+                    iResponseID->CompleteMsgAndDelete();
+                    iResponseID = NULL;
+                    }
+                if( iTrId )
+                    {
+                    delete iTrId;
+                    iTrId = NULL;
+                    }
+
+                }
+            else
+                {
+                if( iShowDialog )
+                    {
+                    CWimCallBack::SetSignTextRequestStatus( &iStatus );
+                    }
+                ContinueVerifyPINReqL();
+                }
+            break;
+            }
+
+        case EVerifyPINCallBackResponse:
+            {
+            CWimCallBack::SetSignTextRequestStatus( NULL );
+            if( iStatus.Int() == WIMI_ERR_BadPIN )
+                {
+                VerifyPINAskPIN();
+                }
+            else if ( iStatus.Int() == WIMI_ERR_PINBlocked )
+                {
+                iRequest = EShowPINBlocked;
+                iWimSecDlg->ShowPINBlocked( iPinParams, iStatus );
+                SetActive();
+                }
+            else if ( iStatus.Int() == WIMI_ERR_CardIOError )
+                {
+                iRequest = EShowCardIsRemoved;
+                iStatus = KRequestPending;
+                TRequestStatus* status = &iStatus;
+                SetActive();
+                User::RequestComplete( status, KErrNone );
+                }
+            else if ( iStatus.Int() == WIMI_ERR_UserCancelled )
+                {
+                iStatus = KRequestPending;
+                iRequest = EIdle;
+                TRequestStatus* status = &iStatus;
+                SetActive();
+                User::RequestComplete( status, KErrNone );
+                }
+            else
+                {
+                iStatus = KRequestPending;
+                iRequest = EIdle;
+                TRequestStatus* status = &iStatus;
+                SetActive();
+                User::RequestComplete( status, KErrNone );
+                }
+            break;
+            }
+
+        // Change PIN request
+        case EChangePINAskPIN:
+            {
+            iRetry = ETrue;
+            if( iStatus.Int() == KErrCancel )
+                {
+                if( iResponseID )
+                    {
+                    iResponseID->iStatus = WIMI_ERR_UserCancelled;
+                    iResponseID->CompleteMsgAndDelete();
+                    iResponseID = NULL;
+                    }
+                if( iTrId )
+                    {
+                    delete iTrId;
+                    iTrId = NULL;
+                    }
+                }
+            else
+                {
+                CWimCallBack::SetSignTextRequestStatus( &iStatus );
+                ContinueChangePINReqL();
+                }
+            break;
+            }
+
+        case EChangePINCallBackResponse:
+            {
+            CWimCallBack::SetSignTextRequestStatus( NULL );
+            if( iStatus.Int() == WIMI_ERR_BadPIN )
+                {
+                ChangePINAskPIN();
+                }
+            else if ( iStatus.Int() == WIMI_ERR_PINBlocked )
+                {
+                iRequest = EShowPINBlocked;
+                iWimSecDlg->ShowPINBlocked( iPinParams, iStatus );
+                SetActive();
+                }
+             else if ( iStatus.Int() == WIMI_ERR_CardIOError )
+                {
+                iRequest = EShowCardIsRemoved;
+                iStatus = KRequestPending;
+                TRequestStatus* status = &iStatus;
+                SetActive();
+                User::RequestComplete( status, KErrNone );
+                }
+             else if ( iStatus.Int() == WIMI_ERR_UserCancelled )
+                {
+                iStatus = KRequestPending;
+                iRequest = EIdle;
+                TRequestStatus* status = &iStatus;
+                SetActive();
+                User::RequestComplete( status, KErrNone );
+                }
+             else
+                {
+                iStatus = KRequestPending;
+                iRequest = EIdle;
+                TRequestStatus* status = &iStatus;
+                SetActive();
+                User::RequestComplete( status, KErrNone );
+                }
+            break;
+            }
+
+        // Enable/Disable PIN query request
+        case EEnablePINAskPIN:    // Flow trough
+        case EDisablePINAskPIN:
+            {
+            iRetry = ETrue;
+            if( iStatus.Int() == KErrCancel )
+                {
+                if( iResponseID )
+                    {
+                    iResponseID->iStatus = WIMI_ERR_UserCancelled;
+                    iResponseID->CompleteMsgAndDelete();
+                    iResponseID = NULL;
+                    }
+                if( iTrId )
+                    {
+                    delete iTrId;
+                    iTrId = NULL;
+                    }
+                }
+            else
+                {
+                CWimCallBack::SetSignTextRequestStatus( &iStatus );
+                ContinueEnablePINReqL();
+                }
+            break;
+            }
+
+        case EEnablePINCallBackResponse:
+        case EDisablePINCallBackResponse:
+            {
+            CWimCallBack::SetSignTextRequestStatus( NULL );
+            if( iStatus.Int() == WIMI_ERR_BadPIN )
+                {
+                EnablePINAskPIN();
+                }
+            else if ( iStatus.Int() == WIMI_ERR_PINBlocked )
+                {
+                iRequest = EShowPINBlocked;
+                iWimSecDlg->ShowPINBlocked( iPinParams, iStatus );
+                SetActive();
+                if( iEnablePinQuery )
+                    {
+                    iDisablePINBlocked = ETrue;
+                    }
+                }
+             else if ( iStatus.Int() == WIMI_ERR_CardIOError )
+                {
+                iRequest = EShowCardIsRemoved;
+                  iStatus = KRequestPending;
+                TRequestStatus* status = &iStatus;
+                SetActive();
+                User::RequestComplete( status, KErrNone );
+                  }
+             else if ( iStatus.Int() == WIMI_ERR_UserCancelled )
+                {
+                iStatus = KRequestPending;
+                iRequest = EIdle;
+                TRequestStatus* status = &iStatus;
+                SetActive();
+                User::RequestComplete( status, KErrNone );
+                }
+            else
+                {
+                iStatus = KRequestPending;
+                iRequest = EIdle;
+                TRequestStatus* status = &iStatus;
+                SetActive();
+                User::RequestComplete( status, KErrNone );
+                }
+            break;
+            }
+
+        // Unblock PIN request
+        case EUnblockPINAskPIN:
+            {
+            iRetry = ETrue;
+            if( iStatus.Int() == KErrCancel )
+                {
+                if( iResponseID )
+                    {
+                    iResponseID->iStatus = WIMI_ERR_UserCancelled;
+                    iResponseID->CompleteMsgAndDelete();
+                    iResponseID = NULL;
+                    }
+                if( iTrId )
+                    {
+                    delete iTrId;
+                    iTrId = NULL;
+                    }
+                }
+            else
+                {
+                CWimCallBack::SetSignTextRequestStatus( &iStatus );
+                ContinueUnblockPinReqL();
+                }
+            break;
+            }
+        case EUnblockPINCallBackResponse:
+           {
+            CWimCallBack::SetSignTextRequestStatus( NULL );
+            if( iStatus.Int() == WIMI_ERR_BadPIN )
+                {
+                UnblockPINAskPIN();
+                }
+            else if ( iStatus.Int() == WIMI_ERR_PINBlocked )
+                {
+                iRequest = EShowPINBlocked;
+                iWimSecDlg->ShowPINTotalBlocked( iPinParams, iStatus );
+                SetActive();
+                }
+            else if ( iStatus.Int() == WIMI_ERR_CardIOError )
+                {
+                iRequest = EShowCardIsRemoved;
+                iStatus = KRequestPending;
+                TRequestStatus* status = &iStatus;
+                SetActive();
+                User::RequestComplete( status, KErrNone );
+              }
+            else if ( iStatus.Int() == WIMI_ERR_UserCancelled )
+                {
+                iStatus = KRequestPending;
+                iRequest = EIdle;
+                TRequestStatus* status = &iStatus;
+                SetActive();
+                User::RequestComplete( status, KErrNone );
+                }
+            else
+                {
+                iStatus = KRequestPending;
+                iRequest = EIdle;
+                TRequestStatus* status = &iStatus;
+                SetActive();
+                User::RequestComplete( status, KErrNone );
+
+                if( iDisablePINBlocked && iUnblockPING )
+                    {
+                    iDisablePINBlocked = EFalse;
+                    }
+                }
+            break;
+           }
+
+        case EShowPINBlocked:
+           {
+           if( iResponseID )
+                {
+                iResponseID->iStatus = WIMI_ERR_PINBlocked;
+                iResponseID->CompleteMsgAndDelete();
+                iResponseID = NULL;
+                }
+            if( iTrId )
+                {
+                delete iTrId;
+                iTrId = NULL;
+                }
+
+           iStatus = KRequestPending;
+           iRequest = EIdle;
+           TRequestStatus* status = &iStatus;
+           SetActive();
+           User::RequestComplete( status, KErrNone );
+           break;
+           }
+
+       case EShowCardIsRemoved:
+           {
+           if( iResponseID )
+                {
+                iResponseID->iStatus = WIMI_ERR_CardIOError;
+                iResponseID->CompleteMsgAndDelete();
+                iResponseID = NULL;
+                }
+            if( iTrId )
+                {
+                delete iTrId;
+                iTrId = NULL;
+                }
+
+           iStatus = KRequestPending;
+           iRequest = EIdle;
+           TRequestStatus* status = &iStatus;
+           SetActive();
+           User::RequestComplete( status, KErrNone );
+           break;
+           }
+
+        case EWIMIError:
+           {
+           CWimCallBack::SetSignTextRequestStatus( NULL );
+           if( iResponseID )
+                {
+                iResponseID->iStatus = ( TUint )iStatus.Int();
+                iResponseID->CompleteMsgAndDelete();
+                iResponseID = NULL;
+                }
+            if( iTrId )
+                {
+                delete iTrId;
+                iTrId = NULL;
+                }
+           break;
+           }
+
+        // Idle request, do nothing
+        case EIdle:
+            _WIMTRACE(_L("WIM|WIMServer|CWimAuthObjHandler::RunL|Idle"));
+            break;
+
+        // Illegal request
+        default:
+            _WIMTRACE(_L("WIM|WIMServer|CWimAuthObjHandler::RunL|Unknown request"));
+            __ASSERT_DEBUG( EFalse, User::Panic( KWimAuthObjPanic, KErrNotSupported ) );
+            break;
+        }
+
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::DoCancel
+// Asynchronous request cancelled
+// -----------------------------------------------------------------------------
+//        
+void CWimAuthObjHandler::DoCancel()
+    {
+    _WIMTRACE(_L("WIM|WIMServer|CWimAuthObjHandler::DoCancel"));
+    if( iRequest == EEnablePINCallBackResponse  || 
+        iRequest == EUnblockPINCallBackResponse ||
+        iRequest == EDisablePINCallBackResponse ||
+        iRequest == EChangePINCallBackResponse  ||
+        iRequest == EVerifyPINCallBackResponse )
+	    {
+	    CWimCallBack::CancelPinOperation();	
+	    }
+	if( iRequest == EEnablePINAskPIN ||
+	    iRequest == EUnblockPINAskPIN ||
+	    iRequest == EDisablePINAskPIN ||
+	    iRequest == EChangePINAskPIN ||
+	    iRequest == EVerifyPINAskPIN ) 
+	    {
+		iWimSecDlg->Cancel();
+	    }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::RunError
+// RunL leaved, handle error here. Note that message is completed by
+// CWimResponse that is deleted by CleanupStack when some function leaves.
+// -----------------------------------------------------------------------------
+//
+TInt CWimAuthObjHandler::RunError( TInt aError )
+    {
+    _WIMTRACE(_L("WIM|WIMServer|CWimAuthObjHandler::RunError"));
+    CWimCallBack::SetSignTextRequestStatus( NULL );
+    if( iResponseID )
+        {
+    	iResponseID->iStatus = ( TUint16 ) aError;
+        iResponseID->CompleteMsgAndDelete();
+        iResponseID = NULL;
+        }
+    
+    if( iTrId )
+        {
+    	delete iTrId;
+        iTrId = NULL;
+        }
+    
+    return KErrNone;
+    }
+    
+    
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::RetrieveAuthObjectsInfo
+// -----------------------------------------------------------------------------
+//
+void CWimAuthObjHandler::RetrieveAuthObjectsInfo( const RMessage2& aMessage ) 
+    {
+    //Get pin number and reflist
+    _WIMTRACE(_L("WIM | WIMServer | RetrieveAuthObjectsInfo() | start "));
+    WIMI_Ref_t* wimRef = WIMI_GetWIMRef( 0 );
+    
+    TInt count = aMessage.Int2();
+    
+    TInt authIdLength = count * sizeof( TInt );
+    TInt authobjLength = count* sizeof( TJavaPINParams );
+    
+    RArray<TInt> authIdList( count );
+    
+    TInt temp = 0;
+    for( TInt i = 0; i < count ; i++ )
+        {
+    	authIdList.Append(temp);
+        }
+        
+    RArray<TJavaPINParams> authobjsList( count );
+    
+    TPtr8 authIdLstPtr( (TText8*)&authIdList[0], authIdLength, authIdLength );
+      
+    TInt err = aMessage.Read(0, authIdLstPtr );
+    if ( err!= KErrNone )
+       {
+       aMessage.Complete( err );	
+       return;
+       }
+   
+    for ( TInt i = 0 ; i < authIdList.Count() ; i++ )
+        {
+    	TJavaPINParams authobject;
+    	WIMI_STAT status = WIMI_Ok;
+    	
+    	TUint32 authId = authIdList[i];
+    	
+    	WIMI_BinData_t ptLabel;
+    	TUint16 flags;
+        TUint8 pinNumber = 0;
+        TUint8 minLength;
+        TUint8 maxLength;
+        TUint8 pinType;
+        TUint8 storedLength;
+        TUint8 PinReference;
+        TUint8 padChar;
+        
+        status = WIMI_GetAuthObjInfo( wimRef, 
+                                      &authId,
+                                      &ptLabel,
+                                      &flags,
+                                      &pinNumber,
+                                      &minLength,
+                                      &maxLength,
+                                      &pinType,
+                                      &storedLength,
+                                      &PinReference,
+                                      &padChar );                              
+                                      
+        if( status == WIMI_Ok )
+            {
+            TBuf<KLabelLen> label;
+            label.Copy( TPtr8( ptLabel.pb_buf, 
+                               ptLabel.ui_buf_length, 
+                               ptLabel.ui_buf_length ) );
+                               
+        	authobject.iPINLabel = label;
+        	authobject.iFlags = flags;
+        	authobject.iAuthId = authId;
+        	authobject.iPinNumber =pinNumber;
+	        authobject.iMinLength = minLength;
+	        authobject.iMaxLength = maxLength;
+	        authobject.iPinType = pinType;
+	        authobject.iStoredLength = storedLength;
+	        authobject.iPinReference = PinReference;
+	        authobject.iPadChar = padChar;
+	        
+	        authobjsList.Append( authobject );
+            }
+		else
+			{
+			_WIMTRACE2(_L("WIM | WIMServer | RetrieveAuthObjectsInfo() | WIMI_GetAuthObjInfo returns error %d"), status);
+			//information did not found or error occured so return empty authOjbect
+            TBuf<KLabelLen> label;
+        	authobject.iPINLabel = label;
+        	authobject.iFlags = KErrNotFound;
+        	authobject.iPinNumber =KErrNotFound;
+	        authobject.iMinLength = KErrNotFound;
+	        authobject.iMaxLength = KErrNotFound;
+	        authobject.iPinType = KErrNotFound;
+	        authobject.iStoredLength = KErrNotFound;
+	        authobject.iPinReference = KErrNotFound;
+	        authobject.iPadChar = KErrNotFound;
+	        authobjsList.Append( authobject );
+			}
+        }
+        
+    TPtrC8 authObjsInfoLstPtr;
+    authObjsInfoLstPtr.Set( (TText8*)&authobjsList[0], authobjLength );
+    
+    err = aMessage.Write( 1, authObjsInfoLstPtr );
+    free_WIMI_Ref_t( wimRef );
+    
+    aMessage.Complete( err );
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimBTSapObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,200 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observes the state of Bluetooth Sap. When the state is
+*               changed into connected, connection to smart card is closed and
+*               when the state is changed into not connected, initialize
+*               connection to smart card back.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimBTSapObserver.h"
+#include    "WimServer.h"
+#include    "WimSession.h"
+#include    "WimTrace.h"
+
+#if defined BT_SAP_TEST_BY_CHARGER
+#include    <PSVariables.h>
+#else
+//#include    <BTSapInternalPSKeys.h>         // Property values
+#include    <BTSapDomainPSKeys.h>
+#endif // BT_SAP_TEST_BY_CHARGER
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimBTSapObserver::CWimBTSapObserver
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimBTSapObserver::CWimBTSapObserver()
+    : CActive( EPriorityNormal )
+    {
+    _WIMTRACE(_L("WIM|CWimBTSapObserver::CWimBTSapObserver|Begin"));
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimBTSapObserver::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimBTSapObserver::ConstructL()
+    {
+    _WIMTRACE(_L("WIM|CWimBTSapObserver::ConstructL|Begin"));
+    iWimSvr = CWimServer::Server();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimBTSapObserver::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimBTSapObserver* CWimBTSapObserver::NewL()
+    {
+    _WIMTRACE(_L("WIM|CWimBTSapObserver::NewL|Begin"));
+    CWimBTSapObserver* self = new( ELeave ) CWimBTSapObserver ();
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CWimBTSapObserver::~CWimBTSapObserver()
+    {
+    _WIMTRACE(_L("WIM|CWimBTSapObserver::~CWimBTSapObserver|Begin"));
+    Cancel();
+    iProperty.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimBTSapObserver::Start
+// Start listening publish and subscribe events
+// -----------------------------------------------------------------------------
+//
+void CWimBTSapObserver::Start()
+    {
+    _WIMTRACE(_L("WIM|CWimBTSapObserver::Start|Begin"));
+    if ( !IsActive() ) // If already active, don't activate
+        {
+        StartListening(); //Start listening
+        }    
+    }
+
+// -----------------------------------------------------------------------------
+// CWimBTSapObserver::StartListening
+// Start listening card status from publish and subscribe
+// -----------------------------------------------------------------------------
+//
+void CWimBTSapObserver::StartListening()
+    {
+    _WIMTRACE(_L("WIM|CWimBTSapObserver::StartListening|Begin"));
+    iStatus = KRequestPending;
+#if defined BT_SAP_TEST_BY_CHARGER
+    TInt err = iProperty.Attach( KUidSystemCategory, 
+                                 KPSUidChargerStatusValue );
+ 
+#else
+    TInt err = iProperty.Attach( KPSUidBluetoothSapConnectionState,
+                                 KBTSapConnectionState );
+#endif // BT_SAP_TEST_BY_CHARGER
+    if ( err == KErrNone )
+        {
+        iProperty.Subscribe( iStatus );
+        SetActive();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimBTSapObserver::RunL
+// Got event from publish and subscribe
+// -----------------------------------------------------------------------------
+//
+void CWimBTSapObserver::RunL()
+    {
+    _WIMTRACE(_L("WIM|CWimBTSapObserver::RunL|Begin"));
+    //Notify on bluetooth event
+    TInt btState;
+    iProperty.Get( btState );
+    switch ( btState )
+        {
+#if defined BT_SAP_TEST_BY_CHARGER
+        case EPSChargerStatusUninitialized: // Flow through
+        case EPSChargerDisconnected:        // Flow through
+        case EPSChargerNotCharging: // Charger not charging, no actions
+#else
+        case EBTSapNotConnected:    // Flow through
+        case EBTSapConnecting:      // BT Sap not connected, no actions
+#endif // BT_SAP_TEST_BY_CHARGER
+            {
+            StartListening();
+            break;
+            }
+#if defined BT_SAP_TEST_BY_CHARGER
+        case EPSChargerConnected:
+#else
+        case EBTSapConnected:
+#endif // BT_SAP_TEST_BY_CHARGER
+            {
+            if ( CWimServer::iWimInitialized )
+                {
+                // Wim initialized, can close WIMI immediately.
+                // NOTE: Is it ok to run lengthy operations here?
+                RArray<CWimSession*> sessions;
+                TRAPD( err, iWimSvr->GetSessionsL( sessions ) );
+
+                if ( !err )  // Got sessions correctly
+                    {
+                    // Loop through all sessions and notify all clients that are
+                    // requesting the notification
+                    for ( TInt i( 0 ); i < sessions.Count(); i++ )
+                        {
+                        sessions[i]->NotifyComplete();
+                        }
+                    sessions.Reset();
+                    // Close WIMI
+                    WIMI_CloseDownReq();
+                    _WIMTRACE(_L("WIM | CWimSatRefreshObserver::Refresh | WIMI closed."));
+                    }
+                }
+            else
+                {
+                _WIMTRACE(_L("WIM | CWimSatRefreshObserver::Refresh | WIMI already closed."));
+                }
+            }
+        }
+    _WIMTRACE(_L("WIM|CWimBTSapObserver::RunL|End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimBTSapObserver::DoCancel
+// Cancel asynchronous request
+// -----------------------------------------------------------------------------
+//
+void CWimBTSapObserver::DoCancel()
+    {
+    _WIMTRACE(_L("WIM|CWimBTSapObserver::DoCancel|Begin"));
+    iProperty.Cancel();
+     _WIMTRACE(_L("WIM|CWimBTSapObserver::DoCancel|End"));
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimCallbackImpl.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,758 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This file contain the implementation of CWimCallBack class.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimCallbackImpl.h"
+#include    "WimSession.h"
+#include    "WimServer.h"
+#include    "WimResponse.h"
+#include    "WimApduImpl.h"
+#include    "WimSimFileHandler.h"
+#include    "WimUtilityFuncs.h"
+#include    "WimConsts.h"
+#include    "WimTrace.h"
+#include    <x509cert.h>
+
+// These variables are static because static function calls from WIMI
+static CWimApdu* gApdu = NULL;
+static CWimSimFileHandler* gSimFileHandler = NULL;
+static TRequestStatus* gStatus = NULL;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::InitOkResp
+// Respond to InitOK operation
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::InitOkResp( WIMI_STAT aStatus )
+    {
+    _WIMTRACE2(_L("WIM|WIMServer|CWimCallBack::InitOkResp|Begin aStatus=%d"), aStatus);
+    CWimServer::iWimStatus = CWimUtilityFuncs::MapWIMError( aStatus );   
+    
+    if ( aStatus == WIMI_Ok )
+        {
+        CWimServer::SetWimInitialized( ETrue, KErrNone ); // WIM has initialized
+        _WIMTRACE(_L("WIM|WIMServer|CWimCallBack::InitOkResp|Initialized=True"));
+        }
+    else
+        {
+        if( aStatus == WIMI_ERR_UserCancelled )
+	        {
+	        CWimServer::iWimStatus = KErrCancel;
+	        CWimServer::SetWimInitialized( EFalse, KErrCancel );
+            WIMI_CloseDownReq();
+	        }
+        else
+	        {
+	        CWimServer::SetWimInitialized( EFalse, CWimServer::iWimStatus ); // WIM has not initialized	
+            WIMI_CloseDownReq();
+	        }
+        
+        _WIMTRACE(_L("WIM|WIMServer|CWimCallBack::InitOkResp|Initialized=False"));
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::CloseDownResp
+// Respond to CloseDown operation
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::CloseDownResp( WIMI_STAT aStatus )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::CloseDownResp | Begin"));
+    CWimServer::iWimStatus = CWimUtilityFuncs::MapWIMError( aStatus );
+    CWimServer::SetWimInitialized( EFalse, CWimServer::iWimStatus ); // WIM has not initialized
+    delete gSimFileHandler; // Close connection to CustomAPI
+    gSimFileHandler = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::CompleteResponse
+// Complete response
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::CompleteResponse(
+    WIMI_TransactId_t aTrId,
+    WIMI_STAT aStatus )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::CompleteResponse | Begin"));
+    TWimReqTrId* trIdType = ( TWimReqTrId* )aTrId;
+    CWimResponse* pTrId = ( CWimResponse* )( trIdType->iReqTrId );
+    pTrId->iStatus = aStatus;
+    pTrId->CompleteMsgAndDelete();
+    delete trIdType;
+    }
+
+/* ------------ Digital signature ------------------------------------------- */
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::SetSignTextRequestStatus
+// Set RequestStatus of SignTextHandler
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::SetSignTextRequestStatus( TRequestStatus* aStatus )
+    {
+    gStatus = aStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::SignResp
+// Respond to the digital signature operation
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::SignResp(
+    WIMI_TransactId_t aTrId, 
+    WIMI_STAT aStatus,
+    TUint8 aSignLen,
+    TUint8* aSign )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::SignResp | Begin"));
+
+    TWimReqTrId* trIdType = ( TWimReqTrId* )aTrId;
+    CWimResponse* trId = ( CWimResponse* )( trIdType->iReqTrId );
+    trId->iStatus = aStatus;
+
+    // In case PIN was incorrect try ask PIN again, don't complete message
+    // If PIN is blocked show note and don't complete message yet.
+    if ( aStatus != WIMI_ERR_BadPIN && aStatus != WIMI_ERR_PINBlocked && aStatus != WIMI_ERR_CardIOError )
+        {
+        if ( trId->iStatus == WIMI_Ok )
+            {
+            TRAP( trId->iError, SignRespL( trId, aSignLen, aSign ) );
+            }
+        WIMI_Ref_pt pWimRefTemp = NULL;
+        pWimRefTemp = WIMI_GetWIMRef( 0 );
+        if ( pWimRefTemp )  // Close the WIM
+            {
+            WIMI_CloseWIM( pWimRefTemp );
+            free_WIMI_Ref_t( pWimRefTemp );
+            }
+        trId->CompleteMsgAndDelete(); 
+        delete trIdType;
+        }
+
+    // Complete SignTextHandler status
+    if ( gStatus )
+        {
+        User::RequestComplete( gStatus, aStatus );
+        }
+    else // SignTextHandler not active, complete message with error if not done
+        {
+        if ( aStatus == WIMI_ERR_BadPIN || aStatus == WIMI_ERR_PINBlocked || aStatus == WIMI_ERR_CardIOError )
+            {
+            trId->CompleteMsgAndDelete();
+            delete trIdType;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::SignRespL
+// Write signed text to client memory. Signature allocated in WIMI is freed 
+// also by WIMI.
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::SignRespL(
+    CWimResponse* aTrId,
+    TUint8 aSignLen,
+    TUint8* aSign )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::SignRespL | Begin"));
+
+    RMessage2& message = aTrId->iMessage;
+
+    TPtr8 signaturePtr( aSign, aSignLen, aSignLen );
+
+    message.WriteL( 3, signaturePtr );
+    }
+
+/* ------------ Certificate management -------------------------------------- */
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::CertificateResp
+// Respond to Certificate fetch operation
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::CertificateResp( 
+    WIMI_TransactId_t aTrId,
+    WIMI_STAT aStatus,
+    WIMI_Ref_t* aCertRef,
+    TUint16 aCertlen,
+    TUint8* aCert )
+    {
+    if ( aTrId )
+    	{
+        _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::CertificateResp | Begin"));
+        TWimReqTrId* trIdType = ( TWimReqTrId* )aTrId;
+        CWimResponse* pTrId = ( CWimResponse* )( trIdType->iReqTrId );
+        pTrId->iStatus = aStatus;
+        if ( pTrId->iStatus == WIMI_Ok)
+            {
+            TRAP( pTrId->iError,
+                CertificateRespL( pTrId, aStatus, aCertRef, aCertlen, aCert ) );
+            }
+        pTrId->CompleteMsgAndDelete(); 
+        delete trIdType;
+    	}
+    else
+    	{
+    	_WIMTRACE(_L("WIM | WIMServer | CWimCallBack::CertificateResp | certhandler starts this"));
+    	if ( gStatus )
+	        {
+	        TPtrC8 certPtr( aCert, aCertlen );
+	        CX509Certificate* cert = NULL;
+	        TRAPD( err, cert =  CX509Certificate::NewL( certPtr ) );
+	        _WIMTRACE2(_L("WIM | WIMServer | CWimCallBack::CertificateResp | x509 err %d"), err );
+	        User::RequestComplete( gStatus, err );
+	        delete cert;
+	        cert = NULL;
+	        }
+    	}
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::CertificateRespL
+// Respond to the certificate fetch operation
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::CertificateRespL(
+    CWimResponse* aTrId,
+    WIMI_STAT /*aStatus*/,
+    WIMI_Ref_t* /*aWimiRef*/,
+    TUint16 aCertLen,
+    TUint8* aCert )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CertificateRespL | Begin"));
+    _WIMTRACE2(_L("WIM | WIMServer | The length of certificate is %d"), aCertLen);
+    
+    RMessage2& message = aTrId->iMessage;
+        
+    if ( aTrId->iStatus == WIMI_Ok )
+        {
+        TPtr8 certPtr( aCert, aCertLen, aCertLen );
+        message.WriteL( 2, certPtr );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::CertificateDeleteResp
+// Respond to the certificate delete operation
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::CertificateDeleteResp( 
+    WIMI_TransactId_t aTrId,
+    WIMI_STAT aStatus )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::CertificateDeleteResp | Begin"));
+    CompleteResponse( aTrId, aStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::CertificateStoreResp
+// Respond to the certificate store operation
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::CertificateStoreResp(
+    WIMI_TransactId_t aTrId,
+    WIMI_STAT aStatus,
+    WIMI_Ref_t* /*aCertRef*/ )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::CertificateStoreResp | Begin"));
+    TWimReqTrId* trIdType = ( TWimReqTrId* )aTrId;
+    CWimResponse* pTrId = (CWimResponse*)( trIdType->iReqTrId );
+    pTrId->iStatus = aStatus;
+
+    pTrId->CompleteMsgAndDelete();
+    delete trIdType;
+    }
+
+/* ------------ PIN management ---------------------------------------------- */
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::VerifyPINResp
+// Respond to Verify PIN operation
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::VerifyPINResp( WIMI_TransactId_t aTrId, WIMI_STAT aStatus )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::VerifyPINResp | Begin"));
+    if( aTrId )
+	    {
+	    TWimReqTrId* trIdType = ( TWimReqTrId* )aTrId;
+	    CWimResponse* trId = ( CWimResponse* )( trIdType->iReqTrId );
+	    trId->iStatus = aStatus;
+
+	    // In case PIN was incorrect try ask PIN again, don't complete message
+	    // If PIN is blocked show note and don't complete message yet.
+        if ( aStatus != WIMI_ERR_BadPIN && aStatus != WIMI_ERR_PINBlocked && aStatus != WIMI_ERR_CardIOError )
+	        { 	
+	        trId->CompleteMsgAndDelete(); 
+	        delete trIdType;
+	        }
+	        
+	    if ( gStatus )
+	        {
+	        User::RequestComplete( gStatus, aStatus );
+	        }
+	    else // SignTextHandler not active, complete message with error if not done
+	        {
+	        if ( aStatus == WIMI_ERR_BadPIN || aStatus == WIMI_ERR_PINBlocked || aStatus == WIMI_ERR_CardIOError )
+	            {
+	            trId->CompleteMsgAndDelete();
+	            delete trIdType;
+	            }
+	        }
+	    }
+    else
+        {
+    	if ( gStatus )
+	        {
+	        User::RequestComplete( gStatus, CWimUtilityFuncs::MapWIMError( aStatus ) );
+	        }
+        }    	 	
+    }
+    
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::ChangePINResp
+// Respond to Change PIN operation
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::ChangePINResp( WIMI_TransactId_t aTrId, WIMI_STAT aStatus )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::ChangePINResp | Begin"));
+
+    TWimReqTrId* trIdType = ( TWimReqTrId* )aTrId;
+    CWimResponse* trId = ( CWimResponse* )( trIdType->iReqTrId );
+    trId->iStatus = aStatus;
+
+    // In case PIN was incorrect try ask PIN again, don't complete message
+    // If PIN is blocked show note and don't complete message yet.
+    if ( aStatus != WIMI_ERR_BadPIN && aStatus != WIMI_ERR_PINBlocked && aStatus != WIMI_ERR_CardIOError )
+        {
+        if( CWimServer::Server()->WimTimer()->TimeRemaining() == 0 )
+            {
+            _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::ChangePINResp | TimeRemaing =0 "));
+            WIMI_Ref_pt pWimRefTemp = NULL;
+            pWimRefTemp = WIMI_GetWIMRef( 0 );
+            if ( pWimRefTemp )  // Close the WIM
+                {
+                WIMI_CloseWIM( pWimRefTemp );
+                free_WIMI_Ref_t( pWimRefTemp );
+                }
+            }    	
+        trId->CompleteMsgAndDelete(); 
+        delete trIdType;
+        }
+    
+     
+    // Complete SignTextHandler status
+    if ( gStatus )
+        {
+        User::RequestComplete( gStatus, aStatus );
+        }
+    else // SignTextHandler not active, complete message with error if not done
+        {
+        if ( aStatus == WIMI_ERR_BadPIN || aStatus == WIMI_ERR_PINBlocked || aStatus == WIMI_ERR_CardIOError )
+            {
+            trId->CompleteMsgAndDelete();
+            delete trIdType;
+            }
+        }
+      _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::ChangePINResp | 10"));   
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::UnblockPINResp
+// Respond to Unblock PIN operation
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::UnblockPINResp( WIMI_TransactId_t aTrId, WIMI_STAT aStatus )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::UnblockPINResp | Begin"));
+
+    TWimReqTrId* trIdType = ( TWimReqTrId* )aTrId;
+    CWimResponse* trId = ( CWimResponse* )( trIdType->iReqTrId );
+    trId->iStatus = aStatus;
+
+    // In case PIN was incorrect try ask PIN again, don't complete message
+    // If PIN is blocked show note and don't complete message yet.
+  
+    if ( aStatus != WIMI_ERR_BadPIN && aStatus != WIMI_ERR_PINBlocked && aStatus != WIMI_ERR_CardIOError )
+        {
+        _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::SignResp | TimeRemaing =0 "));
+        WIMI_Ref_pt pWimRefTemp = NULL;
+        pWimRefTemp = WIMI_GetWIMRef( 0 );
+ 
+        if ( pWimRefTemp )  // Close the WIM
+            {
+            WIMI_CloseWIM( pWimRefTemp );
+            free_WIMI_Ref_t( pWimRefTemp );
+            }
+        
+        //  WIMI_InitializeReq( &CWimServer::Server()->iWimCallBack );
+        
+        trId->CompleteMsgAndDelete(); 
+        delete trIdType;
+        }
+
+    // Complete SignTextHandler status
+    if ( gStatus )
+        {
+        User::RequestComplete( gStatus, aStatus );
+        }
+    else // SignTextHandler not active, complete message with error if not done
+        {
+        if ( aStatus == WIMI_ERR_BadPIN || aStatus == WIMI_ERR_PINBlocked || aStatus == WIMI_ERR_CardIOError )
+            {
+            trId->CompleteMsgAndDelete();
+            delete trIdType;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::EnablePINResp
+// Respond to Enable PIN Response
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::EnablePINResp( WIMI_TransactId_t aTrId, WIMI_STAT aStatus )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::EnablePINResp | Begin"));
+     
+    TWimReqTrId* trIdType = ( TWimReqTrId* )aTrId;
+    CWimResponse* trId = ( CWimResponse* )( trIdType->iReqTrId );
+    trId->iStatus = aStatus;
+
+    // In case PIN was incorrect try ask PIN again, don't complete message
+    // If PIN is blocked show note and don't complete message yet.
+    if ( aStatus != WIMI_ERR_BadPIN && aStatus != WIMI_ERR_PINBlocked && aStatus != WIMI_ERR_CardIOError )
+        {
+        if( CWimServer::Server()->WimTimer()->TimeRemaining() == 0 )
+            {
+            _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::SignResp | TimeRemaing =0 "));
+            WIMI_Ref_pt pWimRefTemp = NULL;
+            pWimRefTemp = WIMI_GetWIMRef( 0 );
+            if ( pWimRefTemp )  // Close the WIM
+                {
+                WIMI_CloseWIM( pWimRefTemp );
+                free_WIMI_Ref_t( pWimRefTemp );
+                }
+            }    	
+        trId->CompleteMsgAndDelete(); 
+        delete trIdType;
+        }
+
+    // Complete SignTextHandler status
+    if ( gStatus )
+        {
+        User::RequestComplete( gStatus, aStatus );
+        }
+    else // SignTextHandler not active, complete message with error if not done
+        {
+        if ( aStatus == WIMI_ERR_BadPIN || aStatus == WIMI_ERR_PINBlocked || aStatus == WIMI_ERR_CardIOError )
+            {
+            trId->CompleteMsgAndDelete();
+            delete trIdType;
+            }
+        }
+    }
+
+/* ------------ Hardware driver support ------------------------------------- */
+// -----------------------------------------------------------------------------
+// CWimCallBack::CardInsertedResp
+// Respond to CardInserted operation
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::CardInsertedResp(
+    TUint8 /*aReader*/,
+    WIMI_STAT /*aStatus*/,
+    WIMI_Ref_t* /*aWIMRef*/ )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::CardInsertedResp | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::Open
+// Open connection to card
+// -----------------------------------------------------------------------------
+//
+TUint8 CWimCallBack::Open( TUint8 aReader )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::Open | Begin"));
+    __ASSERT_ALWAYS( gApdu, User::Panic( _L( "Null pointer" ), KErrGeneral ) );
+    return gApdu->Open( aReader );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::Close
+// Close connection to card
+// -----------------------------------------------------------------------------
+//
+TUint8 CWimCallBack::Close( TUint8 aReader )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::Close | Begin"));
+    __ASSERT_ALWAYS( gApdu, User::Panic( _L( "Null pointer" ), KErrGeneral ) );
+
+    TUint8 ret;
+    ret = gApdu->Close( aReader );
+    
+     _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::Close | 1"));
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::APDUReq
+// APDU Request
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::APDUReq( TUint8 aReader, TUint8* aApdu, TUint16 aApdulen )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::APDUReq | Begin"));
+    __ASSERT_ALWAYS( gApdu, User::Panic( _L( "Null pointer" ), KErrGeneral ) );
+    
+    WIMI_BinData_t* ret_apdu =
+        ( WIMI_BinData_t* )WSL_OS_Malloc( sizeof( WIMI_BinData_t ) );
+    TUint16 sw;
+
+    TUint8 status = gApdu->SendAPDU( aReader, aApdu, aApdulen );
+    
+    sw = gApdu->ResponseSW();
+    TPtrC8 ptr = gApdu->ResponseApdu();
+    ret_apdu->pb_buf = ( TUint8* )ptr.Ptr();
+    ret_apdu->ui_buf_length = ( TUint16 )ptr.Length();
+    
+    WIMI_APDUResp( aReader, status, ret_apdu, sw );
+    WSL_OS_Free( ret_apdu );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::GetATRReq
+// Not supported in Series 60
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::GetATRReq( TUint8 /*aReader*/ )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::GetATRReq | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::GetReaderListReq
+// Get reader list request
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::GetReaderListReq()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::GetReaderListReq | Begin"));
+    WIMI_BinData_t* list = 
+        ( WIMI_BinData_t * )WSL_OS_Malloc( sizeof( WIMI_BinData_t ) ) ;
+
+    TInt ret = KErrNone;
+    TUint8 retval = KErrNone;
+
+    if ( !gApdu )
+        {
+        TRAP( ret, gApdu = CWimApdu::NewL() ); // New CWimApdu
+        }
+
+    if ( ret != KErrNone )
+        {
+        _WIMTRACE2(_L("WIM|WIMServer|CWimCallBack::GetReaderListReq|CWimApdu::NewL() leaved with %d"), ret);
+        retval = KWimStatusIOError;
+        list->ui_buf_length = 0;
+        list->pb_buf = NULL;
+        }
+    else
+        {
+        TRAP( ret, retval = gApdu->RequestListL() );
+    
+        if ( ret != KErrNone )
+            {
+            retval = KWimStatusIOError;
+            }
+        list->ui_buf_length = gApdu->StatusListLength();
+        _WIMTRACE2(_L("WIM|WIMServer|CWimCallBack::GetReaderListReq|statuslistlength=%d"), list->ui_buf_length);
+        list->pb_buf = (TUint8*)gApdu->StatusList().Ptr();
+        }
+    _WIMTRACE2(_L("WIM|WIMServer|CWimCallBack::GetReaderListReq|retval=%d"), retval);
+
+    if ( retval == KErrNone )
+        {
+        WIMI_GetReaderListResp( WIMI_APDU_OK, list );
+        }
+    else
+        {
+        WIMI_GetReaderListResp( WIMI_APDU_TRANSMISSION_ERROR, list );
+        }
+    WSL_OS_Free( list );
+    }
+
+/* ------------ SIM file reading and OMA Provisioning ----------------------- */
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::ReadSimFileReq
+// Read SIM file request
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::ReadSimFileReq( TUint8 aReaderId,
+                                   TUint8* aPath,
+                                   TUint16 aOffset,          
+                                   TUint16 aSize )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::ReadSimFileReq | Begin"));
+
+    TRAPD( ret, DoReadSimFileReqL( aReaderId, aPath, aOffset, aSize ) );
+
+    if ( ret != KErrNone )  // DoReadSimFileReq leaved
+        {
+        _WIMTRACE2(_L("WIM | WIMServer | CWimCallBack::ReadSimFileReq | Trapped Leave, ret = %d"), ret );
+
+        WIMI_BinData_t responseBytes;
+        responseBytes.pb_buf = NULL;
+        responseBytes.ui_buf_length = 0;
+        TUint8 status = WIMI_Err;
+        // WIMI call with zero buffer
+        WIMI_SIM_ReadFileResp( aReaderId, status, &responseBytes );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::ReadSimFileReq
+// Read SIM file request
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::DoReadSimFileReqL( TUint8 aReaderId,
+                                      TUint8* aPath,
+                                      TUint16 aOffset,          
+                                      TUint16 aSize )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::DoReadSimFileReqL | Begin"));
+
+    if ( !gSimFileHandler ) 
+        {
+        gSimFileHandler = CWimSimFileHandler::NewL();
+        }
+
+    RMmCustomAPI::TSimFilePath filePath;
+    filePath.Copy( aPath, KSimFilePathLength ); // SIM file path is 8 bytes
+
+    gSimFileHandler->ReadSimFileL( aReaderId,
+                                   filePath,
+                                   aOffset,
+                                   aSize );
+
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::DoReadSimFileReqL | End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::OmaProvisioningResp
+// Response to OMA Provisioning Smart Card file request
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::OmaProvisioningResp( WIMI_TransactId_t aTrId,
+                                        WIMI_STAT aStatus,
+                                        TUint16 aFileLen,
+                                        TUint8* aFile )
+    {
+    _WIMTRACE2(_L("WIM | WIMServer | CWimCallBack::OmaProvisioningResp, aFileLen = %d"), aFileLen);
+
+    TWimReqTrId* trIdType = ( TWimReqTrId* )aTrId;
+    CWimResponse* pTrId = ( CWimResponse* )( trIdType->iReqTrId );
+    pTrId->iStatus = aStatus;
+
+    if ( pTrId->iStatus == WIMI_Ok )
+        {
+        TRAP( pTrId->iError, OmaProvisioningRespL( pTrId, aFileLen, aFile ) );
+        _WIMTRACE2(_L("WIM | WIMServer | CWimCallBack::OmaProvisioningResp, TRAP(OmaProvisioningRespL)=%d"), pTrId->iError);
+        }
+
+    pTrId->CompleteMsgAndDelete(); 
+    delete trIdType;
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::OmaProvisioningResp | End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::OmaProvisioningRespL
+// Write OMA Provisioning Smart Card file to client memory
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::OmaProvisioningRespL( CWimResponse* aTrId,
+                                         TUint16 aFileLen,
+                                         TUint8* aFile )
+    {
+    _WIMTRACE2(_L("WIM | WIMServer | CWimCallBack::OmaProvisioningRespL, aFileLen = %d"), aFileLen);
+
+    RMessage2& message = aTrId->iMessage;
+        
+    TOmaProv omaProvisioning;
+    omaProvisioning.iSize = aFileLen;
+
+    TPckgBuf<TOmaProv> omaFilePckg( omaProvisioning );
+    message.ReadL( 0, omaFilePckg );
+
+    TPtr8 omaFilePtr( aFile, aFileLen, aFileLen );
+    message.WriteL( 1, omaFilePtr );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::CancelPinOperation
+// Cancel pin operation by stop apdu sending
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::CancelPinOperation()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::CancelPinOperation Begin"));
+	gApdu->CancelApduSending();
+	
+	WIMI_APDUResp( 0, WIMI_ERR_UserCancelled, NULL, 0 );
+	
+	_WIMTRACE(_L("WIM | WIMServer | CWimCallBack::CancelPinOperation End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCallBack::CancelWimInitialize
+// Cancel Wim Initialize by stop apdu sending
+// -----------------------------------------------------------------------------
+//    
+void CWimCallBack::CancelWimInitialize()
+    {
+	 _WIMTRACE(_L("WIM | WIMServer | CWimCallBack::CancelWimInitialize Begin"));
+	gApdu->CancelApduSending();
+	
+	WIMI_APDUResp( 0, WIMI_ERR_UserCancelled, NULL, 0 );
+	
+	_WIMTRACE(_L("WIM | WIMServer | CWimCallBack::CancelWimInitialize End"));
+    }
+    
+// -----------------------------------------------------------------------------
+// CWimCallBack::DeletegApdu
+//
+// -----------------------------------------------------------------------------
+//
+void CWimCallBack::DeletegApdu()
+    {
+	if ( gApdu )
+	    {
+		delete gApdu;
+		gApdu= NULL;
+	    }
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimCertHandler.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1232 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Certificate management methods
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "Wimi.h"            // wimi definitions
+#include    "WimCertHandler.h"
+#include    "WimMemMgmt.h"
+#include    "WimSession.h"
+#include    "WimResponse.h"
+#include    "WimUtilityFuncs.h"
+#include    <asn1enc.h>         // asn.1 encoding
+#include    <asn1dec.h>         // asn.1 decoding
+#include    <x509cert.h>        // cx509certificate
+#ifndef SYMBIAN_ENABLE_SPLIT_HEADERS
+#include    <x509keys.h>        // cx509rsapublickey
+#else
+#include    <x509keys.h>        // cx509rsapublickey
+#include    <x509keyencoder.h>        // cx509rsapublickey
+#endif
+#include    <wtlscert.h>        // cwtlscertificate
+#include    <wtlskeys.h>        // cwtlsrsapublickey
+#include    "WimTrace.h"
+#include    "WimCallbackImpl.h"
+#include    "WimCleanup.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::CWimCertHandler
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimCertHandler::CWimCertHandler()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::CWimCertHandler | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimCertHandler::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::ConstructL | Begin"));
+    iWimUtilFuncs = CWimUtilityFuncs::NewL();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimCertHandler* CWimCertHandler::NewL() 
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::NewL | Begin"));
+    CWimCertHandler* self = new( ELeave ) CWimCertHandler;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+    
+// Destructor
+CWimCertHandler::~CWimCertHandler()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::~CWimCertHandler | Begin"));
+    delete iWimUtilFuncs;
+
+    for( TInt index = 0; index < iCertRefLst.Count(); ++index )
+        {
+        WIMI_Ref_t* ref = reinterpret_cast< WIMI_Ref_t* >( iCertRefLst[ index ] );
+        _WIMTRACE2(_L("WIM | WIMServer | CWimCertHandler::~CWimCertHandler, -ref 0x%08x"), ref);
+        free_WIMI_Ref_t( ref );
+        iCertRefLst[ index ] = 0;
+        }
+    iCertRefLst.Reset();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::GetCertificatesFromWimL
+// Fetches certificates from WIM card.
+// -----------------------------------------------------------------------------
+//
+void CWimCertHandler::GetCertificatesFromWimL(
+    const RMessage2& aMessage, 
+    CWimMemMgmt* aWimMgmt )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::GetCertificatesFromWimL | Begin"));
+    WIMI_STAT callStatus = WIMI_Ok;
+    TUint8 certNum = 0;
+    WIMI_Ref_t* temp = NULL;
+
+    HBufC8* certRefLst = iWimUtilFuncs->DesLC( 0, aMessage );
+    HBufC8* certInfoLst = iWimUtilFuncs->DesLC( 1, aMessage );
+
+    TWimEntryType certEntryType = ( TWimEntryType ) aMessage.Int2();
+
+    TUint32* pCertRefLst = ( TUint32* )( certRefLst->Des().Ptr() );
+    TWimCertInfo* pCertInfoLst = ( TWimCertInfo* )( certInfoLst->Des().Ptr() );
+
+    temp = aWimMgmt->WimRef();
+    if ( !temp )
+        { 
+        temp = WIMI_GetWIMRef( 0 );
+        aWimMgmt->SetWIMRef( temp );    // takes ownership
+        }
+
+    if ( temp )
+        {
+        if ( EWimEntryTypeAll == certEntryType || 
+             EWimEntryTypeCA == certEntryType )
+            {
+            callStatus = GetCertificateFromWimRefL( temp, WIMI_CU_CA,
+                                                    certNum, pCertRefLst,
+                                                    pCertInfoLst, aMessage );
+
+            }
+        if ( callStatus == WIMI_Ok && ( EWimEntryTypeAll == certEntryType || 
+                                   EWimEntryTypePersonal == certEntryType ) )
+            {
+            callStatus = GetCertificateFromWimRefL( temp, WIMI_CU_Client,
+                                                    certNum, pCertRefLst,
+                                                    pCertInfoLst, aMessage );
+
+            }
+        
+        //record the ref for sanity checking, deallocate old refs first
+        for( TInt index = 0; index < iCertRefLst.Count(); ++index )
+            {
+            WIMI_Ref_t* ref = reinterpret_cast< WIMI_Ref_t* >( iCertRefLst[ index ] );
+            _WIMTRACE2(_L("WIM | WIMServer | CWimCertHandler::GetCertificatesFromWimL, -ref 0x%08x"), ref);
+            free_WIMI_Ref_t( ref );
+            iCertRefLst[ index ] = 0;
+            }
+        iCertRefLst.Reset();
+        for( TInt index = 0; index < certNum; ++index )
+            {
+            _WIMTRACE2(_L("WIM | WIMServer | CWimCertHandler::GetCertificatesFromWimL, +ref 0x%08x"), pCertRefLst[ index ]);
+            iCertRefLst.AppendL( pCertRefLst[ index ] );
+            }
+        
+        aMessage.WriteL( 0, certRefLst->Des() );
+        aMessage.WriteL( 1, certInfoLst->Des() );
+        }
+    else
+        {
+        callStatus = WIMI_ERR_OutOfMemory;
+        }
+    CleanupStack::PopAndDestroy( 2, certRefLst );   // certInfoLst, certRefLst
+    aMessage.Complete( CWimUtilityFuncs::MapWIMError( callStatus ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::GetCertificateFromWimRefL
+// Fetches certificate from the WIM card.
+// -----------------------------------------------------------------------------
+//
+WIMI_STAT CWimCertHandler::GetCertificateFromWimRefL(
+    WIMI_Ref_t* aTmpWimRef,
+    TInt8 aUsage,
+    TUint8& aCertNum,
+    TUint32* aCertRefLst,
+    TWimCertInfo* aCertInfoLst,
+    const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::GetCertificateFromWimRefL | Begin"));
+    TUint8 tempCrtCount;
+    WIMI_RefList_t refList = NULL;
+    WIMI_STAT callStatus = WIMI_Ok;
+
+    if ( aTmpWimRef )
+        {
+        callStatus = WIMI_GetCertificateListByWIM( aTmpWimRef, 
+                                                   aUsage, 
+                                                   &tempCrtCount, 
+                                                   &refList );
+
+        if ( callStatus == WIMI_Ok )
+            {
+            // If the certifcate length is 0,
+            // the step increases by 1.
+            TInt step = 0;
+            TInt err = KErrNone;
+            for ( TUint8 certIndex = 0; certIndex < tempCrtCount; certIndex++ )
+                {
+                TInt current = aCertNum + certIndex - step;
+                err = CopyCertificateInfo( aCertInfoLst[current], refList[certIndex], aMessage );
+
+                if ( err == KErrNone )
+                    {
+                    // transfers ownership of refList item to aCertRefLst
+                    aCertRefLst[current] = reinterpret_cast< TUint32 >( refList[certIndex] );
+                    refList[certIndex] = NULL;
+                    }
+                else // KErrArgument
+                    {
+                    // ingore certificate info and continue with the next
+                	step++;
+                    free_WIMI_Ref_t( refList[certIndex] );
+                    }
+                }
+            //variable step is equal to the number of certificate in CDF whose 
+            //length is set as 0.     
+            aCertNum = static_cast< TUint8 >( aCertNum + tempCrtCount - step );
+
+            // Because list items are moved to aCertRefLst, only refList array
+            // needs to be freed. Cannot use free_WIMI_RefList_t() as it would
+            // delete also items contained in refList.
+            WSL_OS_Free( refList );
+            }
+        }
+
+    return callStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::CopyCertificateInfo
+// Copies certificate information to client's allocated memory area.
+// This function MAY NOT leave.
+// -----------------------------------------------------------------------------
+//
+TInt CWimCertHandler::CopyCertificateInfo(
+    TWimCertInfo& aCertInfo,
+    WIMI_Ref_t* aCert,
+    const RMessage2& /*aMessage*/ )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::CopyCertificateInfo | Begin"));
+    WIMI_Ref_t* tempRef = NULL;
+    WIMI_BinData_t ptLabel;
+    WIMI_BinData_t ptKeyID;
+    WIMI_BinData_t ptCAID;
+    WIMI_BinData_t ptIssuerHash;
+    WIMI_BinData_t ptTrustedUsage;
+    TUint8 uiCDFRefs;
+    TUint8 usage;
+    TUint8 type;
+    TUint16 certLen;
+    TUint8 modifiable = 0;
+    WIMI_STAT callStatus = WIMI_GetCertificateInfo( 
+                                aCert,
+                                &tempRef,
+                                &ptLabel,
+                                &ptKeyID, /* Key Id (hash)*/
+                                &ptCAID,
+                                &ptIssuerHash,
+                                &ptTrustedUsage,
+                                &uiCDFRefs,
+                                &usage,  /* 0 = client, 1 = CA */
+                                &type,   /* WTLSCert(1), 
+                                            X509Cert(2), 
+                                            X968Cert(3), 
+                                            CertURL(4) */ 
+                                &certLen,   /* cert. content or URL length */
+                                &modifiable );
+
+    if ( callStatus == WIMI_Ok )
+        {
+        free_WIMI_Ref_t( tempRef );
+
+        // To make sure the length of the certificate is not zero
+        _WIMTRACE2(_L("WIM | WIMServer | CWimCertHandler::CopyCertificateInfoL | certLen %d"), certLen);
+        if ( certLen == 0 )
+            {
+            WSL_OS_Free( ptLabel.pb_buf );
+            WSL_OS_Free( ptKeyID.pb_buf );
+            WSL_OS_Free( ptCAID.pb_buf );
+            WSL_OS_Free( ptIssuerHash.pb_buf );
+            WSL_OS_Free( ptTrustedUsage.pb_buf );
+        	return KErrArgument;
+            }
+
+        // it is x509cert
+        if ( type == 2 && certLen != 0 )
+            {
+            //use this rough sanity checking for temp
+            if ( certLen < 10 )
+                {
+                _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::CopyCertificateInfoL | cert is malformated, return KErrArgument"));
+                WSL_OS_Free( ptLabel.pb_buf );
+                WSL_OS_Free( ptKeyID.pb_buf );
+                WSL_OS_Free( ptCAID.pb_buf );
+                WSL_OS_Free( ptIssuerHash.pb_buf );
+                WSL_OS_Free( ptTrustedUsage.pb_buf );
+                return KErrArgument;
+                }
+            }
+        _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::CopyCertificateInfoL | X509 check ok"));
+
+        aCertInfo.iLabel.Copy(
+            TPtr8(
+                ptLabel.pb_buf, 
+                ptLabel.ui_buf_length, 
+                ptLabel.ui_buf_length ) );
+
+        aCertInfo.iKeyId.Copy(
+            TPtr8(
+                ptKeyID.pb_buf, 
+                ptKeyID.ui_buf_length, 
+                ptKeyID.ui_buf_length ) );
+        
+        aCertInfo.iCAId.Copy(
+            TPtr8(
+                ptCAID.pb_buf, 
+                ptCAID.ui_buf_length, 
+                ptCAID.ui_buf_length ) );
+        
+        aCertInfo.iIssuerHash.Copy(
+            TPtr8(
+                ptIssuerHash.pb_buf, 
+                ptIssuerHash.ui_buf_length, 
+                ptIssuerHash.ui_buf_length ) );
+
+        aCertInfo.iUsage = usage;
+        aCertInfo.iType = type;
+        aCertInfo.iCertlen = certLen;
+        aCertInfo.iModifiable = modifiable;
+        
+        // Certificate location
+        aCertInfo.iCDFRefs = iWimUtilFuncs->MapCertLocation( uiCDFRefs );
+
+        //Allocate enough memory for OID
+        aCertInfo.iTrustedUsageLength = ptTrustedUsage.ui_buf_length * 16;
+
+        WSL_OS_Free( ptLabel.pb_buf );
+        WSL_OS_Free( ptKeyID.pb_buf );
+        WSL_OS_Free( ptCAID.pb_buf );
+        WSL_OS_Free( ptIssuerHash.pb_buf );
+        WSL_OS_Free( ptTrustedUsage.pb_buf );
+        }
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::GetExtrasFromWimL
+// Fetches certificate's extra info from WIM card. In this case it is
+// trusted usage info.
+// -----------------------------------------------------------------------------
+//
+void CWimCertHandler::GetExtrasFromWimL(
+    const RMessage2& aMessage, 
+    CWimMemMgmt* aWimMgmt )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::GetExtrasFromWimL | Begin"));
+
+    WIMI_STAT callStatus = WIMI_Ok;
+    TInt8 certUsage = 0;
+    
+    HBufC8* keyIdBuf = iWimUtilFuncs->DesLC( 0, aMessage );
+    TPtrC8 keyIdHash = keyIdBuf->Des();
+
+    WIMI_Ref_t* wimTempRef = aWimMgmt->WimRef();
+    if ( !wimTempRef )
+        { 
+        wimTempRef = WIMI_GetWIMRef( 0 );
+        aWimMgmt->SetWIMRef( wimTempRef );  // takes ownership
+        }
+
+    if ( wimTempRef )
+        {
+        TWimEntryType certEntryType = static_cast< TWimEntryType >( aMessage.Int2() );
+        switch ( certEntryType )
+            {
+            case EWimEntryTypeCA:
+                {
+                certUsage = WIMI_CU_CA;
+                break;
+                }
+            case EWimEntryTypeAll: //Flow through
+            case EWimEntryTypePersonal:
+                {
+                certUsage = WIMI_CU_Client;
+                break;
+                }
+            default:
+                {
+                callStatus = WIMI_ERR_BadParameters;
+                break;
+                }
+            }
+
+        if ( callStatus == WIMI_Ok )
+            {
+            callStatus = GetExtrasFromWimRefL( wimTempRef,
+                                               certUsage,
+                                               keyIdHash,
+                                               aMessage );
+            }
+        }
+    else
+        {
+        callStatus = WIMI_ERR_BadReference;
+        }
+
+    CleanupStack::PopAndDestroy( keyIdBuf );
+    aMessage.Complete( CWimUtilityFuncs::MapWIMError( callStatus ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::GetExtrasFromWimRefL
+// Fetches extra information (e.g. certs trusted usage) from the WIM card.
+// -----------------------------------------------------------------------------
+//
+WIMI_STAT CWimCertHandler::GetExtrasFromWimRefL(
+    WIMI_Ref_t* aTmpWimRef,
+    TInt8 aUsage,
+    TDesC8& aKeyHash,
+    const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::GetExtrasFromWimRefL | Begin"));
+  
+    TUint8 tempCertCount = 0;
+    WIMI_RefList_t certRefList = NULL;
+    WIMI_STAT callStatus = WIMI_Ok;
+    TInt certIndex = 0;
+    TPtrC8 keyHash;
+
+    if ( aTmpWimRef )
+        {
+        // List all certificates (by WIM and usage)
+        callStatus = WIMI_GetCertificateListByWIM( aTmpWimRef, 
+                                                   aUsage, 
+                                                   &tempCertCount, 
+                                                   &certRefList );
+        }
+    else
+        {
+        callStatus = WIMI_ERR_BadReference;
+        }
+    CleanupPushWimRefListL( certRefList );
+    
+    if ( callStatus == WIMI_Ok )
+        {
+        WIMI_Ref_t* tempRef = NULL;
+        WIMI_BinData_t ptLabel;
+        WIMI_BinData_t ptKeyID;
+        WIMI_BinData_t ptCAID;
+        WIMI_BinData_t ptIssuerHash;
+        WIMI_BinData_t ptTrustedUsage;
+        TUint8 uiCDFRefs;
+        TUint8 usage;
+        TUint8 certType;
+        TUint16 certLen;
+        TUint8 modifiable = 0;
+
+        for ( TInt i = 0; i < tempCertCount; i++ )
+            {
+            // Get info for each certificate until we find valid cert
+            callStatus = WIMI_GetCertificateInfo( certRefList[i],
+                                                  &tempRef,
+                                                  &ptLabel,
+                                                  &ptKeyID,
+                                                  &ptCAID,
+                                                  &ptIssuerHash,
+                                                  &ptTrustedUsage,
+                                                  &uiCDFRefs,
+                                                  &usage,
+                                                  &certType,   
+                                                  &certLen,
+                                                  &modifiable );
+            if ( callStatus == WIMI_Ok )
+                {
+                free_WIMI_Ref_t( tempRef );
+
+                // Code MAY NOT leave before ptLabel.pb_buf, ptKeyID.pb_buf,
+                // ptCAID.pb_buf, ptIssuerHash.pt_buf, and ptTrustedUsage.pb_buf
+                // are deallocated.
+
+                keyHash.Set( ptKeyID.pb_buf, ptKeyID.ui_buf_length );
+
+                // Compare given and fetched key hash
+                if ( keyHash.Compare( aKeyHash ) == 0 &&
+                     certType == WIMI_CT_X509 ) //Match
+                    {
+                    certIndex = i; // Found one
+                    i = tempCertCount; // Stop looping
+                    callStatus = WIMI_Ok;
+                    }
+                else // Cert not supported
+                    {
+                    callStatus = WIMI_ERR_UnsupportedCertificate;
+                    }
+
+                WSL_OS_Free( ptLabel.pb_buf );
+                WSL_OS_Free( ptKeyID.pb_buf );
+                WSL_OS_Free( ptCAID.pb_buf );
+                WSL_OS_Free( ptIssuerHash.pb_buf );
+                WSL_OS_Free( ptTrustedUsage.pb_buf );
+                // Code can leave after this point.
+                }
+            }
+
+        if ( callStatus == WIMI_Ok )
+            {
+            CopyCertExtrasInfoL( certRefList[certIndex], aMessage );
+            }
+
+        CleanupStack::PopAndDestroy( certRefList );
+        }
+
+    return callStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::CopyCertExtrasInfoL
+// Copies certs extra information to client's allocated memory area.
+// -----------------------------------------------------------------------------
+//
+void CWimCertHandler::CopyCertExtrasInfoL(
+    WIMI_Ref_t* aCert,
+    const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::CopyCertExtrasInfoL | Begin"));
+    TUint8 pushedItemCount = 0;
+    WIMI_Ref_t* tempref = NULL;
+    WIMI_BinData_t ptLabel;
+    WIMI_BinData_t ptKeyID;
+    WIMI_BinData_t ptCAID;
+    WIMI_BinData_t ptIssuerHash;
+    WIMI_BinData_t ptTrustedUsage;
+    TUint8 uiCDFRefs;
+    TUint8 usage;
+    TUint8 type;
+    TUint16 certlen;
+    TUint8 modifiable = 0;
+    TBool found = ETrue;
+
+    TCertExtrasInfo certExtraInfo;
+    certExtraInfo.iCDFRefs = 0;
+    certExtraInfo.iTrustedUsage = NULL;
+
+    WIMI_STAT callStatus = WIMI_GetCertificateInfo( 
+                                aCert,
+                                &tempref,
+                                &ptLabel,
+                                &ptKeyID, /* Key Id (hash)*/
+                                &ptCAID,
+                                &ptIssuerHash,
+                                &ptTrustedUsage,
+                                &uiCDFRefs,
+                                &usage,  /* 0 = client, 1 = CA */
+                                &type,   
+                                &certlen,   /* cert. content or URL length */
+                                &modifiable); 
+    if ( callStatus == WIMI_Ok )
+        {
+        free_WIMI_Ref_t( tempref );
+        WSL_OS_Free( ptLabel.pb_buf );
+        WSL_OS_Free( ptKeyID.pb_buf );
+        WSL_OS_Free( ptCAID.pb_buf );
+        WSL_OS_Free( ptIssuerHash.pb_buf );
+
+        CleanupPushWimBufL( ptTrustedUsage );
+        pushedItemCount++;
+
+        TPtrC8 undecodedUsage;
+        undecodedUsage.Set( ptTrustedUsage.pb_buf ); 
+
+        if ( ptTrustedUsage.ui_buf_length == 0 ) // No OIDs
+            {
+            found = EFalse;
+            }
+
+        // DECODE OIDs
+        TASN1DecObjectIdentifier decoder;
+        RPointerArray<HBufC> decodedOIDArray;
+        CleanupResetAndDestroyPushL( decodedOIDArray );
+        pushedItemCount++;
+        HBufC* decodedOIDs = NULL;
+        TInt oidsLength = 0;    // length of total OID buffer
+        TInt err;
+
+        for ( TInt position = 0; found; )   //Loop until no OIDs found anymore
+            {
+            if ( undecodedUsage.Length() > position ) //Don't go over buffer
+                {
+                TRAP( err, decodedOIDs = decoder.DecodeDERL( undecodedUsage, position ) );
+                if ( err == KErrNone ) //Found OID
+                    {
+                    CleanupStack::PushL( decodedOIDs );
+                    if ( decodedOIDs->Length() )
+                        {
+                        found = ETrue;
+                        decodedOIDArray.AppendL( decodedOIDs );
+                        oidsLength += decodedOIDs->Length();
+                        CleanupStack::Pop( decodedOIDs );
+                        }
+                    else    // Not found OID from buffer
+                        {
+                        found = EFalse;    
+                        CleanupStack::PopAndDestroy( decodedOIDs );
+                        }
+                    decodedOIDs = NULL;
+                    }
+                else    // Error in OID parsing -> Not found OID
+                    {
+                    found = EFalse;
+                    }
+                }
+            else    // undecoded OID buffer seeked through
+                {
+                found = EFalse;
+                }
+            }
+
+        _LIT( KDelimeter16, " " ); //Delimeter between OIDs
+        TInt trustedUsagesBufMaxLength = oidsLength + decodedOIDArray.Count();
+        TPtr trustedUsage( NULL, 0, trustedUsagesBufMaxLength );
+
+        if ( oidsLength > 0 ) // OID's found
+            {
+            // Alloc new buffer for all OID's
+            HBufC* trustedUsagesBuf = HBufC::NewLC( trustedUsagesBufMaxLength );
+            pushedItemCount++;
+
+            trustedUsage.Set( trustedUsagesBuf->Des() );
+       
+            // Add OID's to one buffer from separate buffers
+            for ( TInt i = 0; i < decodedOIDArray.Count(); i++ )
+                {
+                if ( i == 0 ) //First one
+                    {
+                    trustedUsage.Copy( decodedOIDArray[i]->Des() );
+                    }
+                else // Append other OIDs, with delimeter
+                    {
+                    trustedUsage.Append( KDelimeter16 );
+                    trustedUsage.Append( decodedOIDArray[i]->Des() );
+                    }
+                }
+            }
+
+        TPckgBuf<TCertExtrasInfo> wimCertExtraPckg( certExtraInfo );
+        aMessage.ReadL( 1, wimCertExtraPckg );
+        
+        wimCertExtraPckg().iCDFRefs = iWimUtilFuncs->MapCertLocation( uiCDFRefs );
+        
+        if ( oidsLength > 0 ) // OID's found, write buffer to client
+            {
+            aMessage.WriteL( 3, trustedUsage );
+            }
+        aMessage.WriteL( 1, wimCertExtraPckg );
+
+        CleanupStack::PopAndDestroy( pushedItemCount, ptTrustedUsage.pb_buf );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::GetCerticateCountL
+// Fetches count of certicates in certain WIM card.
+// -----------------------------------------------------------------------------
+//
+void CWimCertHandler::GetCerticateCountL(
+    const RMessage2& aMessage, 
+    CWimMemMgmt* aWimMgmt ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::GetCerticateCountL | Begin"));
+    WIMI_STAT callStatus = WIMI_Ok;
+    TWimEntryType certEntryType = ( TWimEntryType )aMessage.Int1();
+    
+    __ASSERT_ALWAYS( certEntryType != EWimEntryTypeAll ||
+        certEntryType != EWimEntryTypeCA ||
+        certEntryType != EWimEntryTypePersonal, User::Leave( KErrArgument ) );
+
+    WIMI_Ref_t* wimRef = NULL;
+    TUint8 certCount = 0;
+
+    wimRef = aWimMgmt->WimRef();
+    if ( !wimRef )
+        {
+        wimRef = WIMI_GetWIMRef( 0 );
+        aWimMgmt->SetWIMRef( wimRef );  // takes ownership
+        }
+
+    if ( wimRef )
+        {
+        if ( EWimEntryTypeAll == certEntryType || 
+            EWimEntryTypeCA == certEntryType )
+            {
+            callStatus = GetCertificateCountByWIM( wimRef, 
+                                                   certCount, 
+                                                   WIMI_CU_CA );            
+            }
+
+        if ( callStatus == WIMI_Ok && ( EWimEntryTypeAll == certEntryType || 
+                                     EWimEntryTypePersonal == certEntryType ) )
+            {
+            callStatus = GetCertificateCountByWIM( wimRef, 
+                                                   certCount, 
+                                                   WIMI_CU_Client );
+            }
+        }
+    else
+        {
+        callStatus = WIMI_ERR_OutOfMemory;
+        }
+
+    if ( callStatus == WIMI_Ok )
+        {
+        _WIMTRACE2(_L("WIM | WIMServer | CWimCertHandler::GetCerticateCountL | count=%d"), certCount);
+        TPckgBuf<TUint8> pckg( certCount );
+        aMessage.WriteL( 0, pckg );
+        }
+    aMessage.Complete( CWimUtilityFuncs::MapWIMError( callStatus ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::GetCertificateCountByWIM
+// Fetches count of certicates in certain WIM card.
+// This function MAY NOT leave.
+// -----------------------------------------------------------------------------
+//
+WIMI_STAT CWimCertHandler::GetCertificateCountByWIM(
+    WIMI_Ref_t* aRef, 
+    TUint8& aCertCount, 
+    TUint8 aUsage ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::GetCertificateCountByWIM | Begin"));
+    
+    // Get the number of certificates from smart card.
+    TUint8 certNum = 0;
+    WIMI_RefList_t refList ;
+    WIMI_STAT callStatus = WIMI_GetCertificateListByWIM( aRef, 
+                                                         aUsage,
+                                                         &certNum, 
+                                                         &refList );
+
+    if ( callStatus != WIMI_Ok )   
+        {
+    	return callStatus;
+        }
+    
+    // Find out how many certificate has zero length
+    TInt certLenZero = 0;
+    TInt certMalformat = 0;
+    for ( TInt i = 0; i < certNum ; i++ )
+	    {
+	    WIMI_Ref_t* tempRef = NULL;
+	    WIMI_BinData_t ptLabel;
+	    WIMI_BinData_t ptKeyID;
+	    WIMI_BinData_t ptCAID;
+	    WIMI_BinData_t ptIssuerHash;
+	    WIMI_BinData_t ptTrustedUsage;
+	    TUint8 uiCDFRefs;
+	    TUint8 usage;
+	    TUint8 type;
+	    TUint16 certLen;
+	    TUint8 modifiable = 0;
+	    callStatus = WIMI_GetCertificateInfo( 
+	                                refList[i],
+	                                &tempRef,
+	                                &ptLabel,
+	                                &ptKeyID, /* Key Id (hash)*/
+	                                &ptCAID,
+	                                &ptIssuerHash,
+	                                &ptTrustedUsage,
+	                                &uiCDFRefs,
+	                                &usage,  /* 0 = client, 1 = CA */
+	                                &type,   /* WTLSCert(1), 
+	                                            X509Cert(2), 
+	                                            X968Cert(3), 
+	                                            CertURL(4) */ 
+	                                &certLen,   /* cert. content or URL length */
+	                                &modifiable );
+
+	    if ( callStatus == WIMI_Ok )
+	        {
+	        free_WIMI_Ref_t( tempRef );
+	        
+	        if ( certLen == 0 )
+	            {
+	            certLenZero++;
+	            }
+
+            // it is x509cert
+            if ( type == 2 && certLen != 0 )
+                {
+
+                //use this rough sanity checking
+                if ( certLen < 10 )
+                    {
+                    certMalformat++;
+                    }
+                }
+
+            WSL_OS_Free( ptLabel.pb_buf );
+            WSL_OS_Free( ptKeyID.pb_buf );
+            WSL_OS_Free( ptCAID.pb_buf );
+            WSL_OS_Free( ptIssuerHash.pb_buf );
+            WSL_OS_Free( ptTrustedUsage.pb_buf );
+	        }
+	    }
+
+    // only return the number of ceritifcates that have non-zero length
+    if ( callStatus == WIMI_Ok )
+        {
+        aCertCount = static_cast< TUint8 >( aCertCount + certNum - certLenZero - certMalformat );
+        }
+
+    free_WIMI_RefList_t( refList );
+
+    return callStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::StoreCertificateL
+// Stores certificate to the WIM card.
+// -----------------------------------------------------------------------------
+//
+void CWimCertHandler::StoreCertificateL( 
+    TWimServRqst /*aOpcode*/,
+    const RMessage2& aMessage ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::StoreCertificateL | Begin"));
+    aMessage.Complete( KErrNotSupported );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::RemoveCertificateL
+// Removes certificate from a WIM card.
+// -----------------------------------------------------------------------------
+//
+void CWimCertHandler::RemoveCertificateL( 
+    const RMessage2& aMessage,
+    CWimMemMgmt* /*aWimMgmt*/ ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::RemoveCertificateL | Begin"));
+    aMessage.Complete( KErrNotSupported );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::SanityCheck
+// -----------------------------------------------------------------------------
+//
+TBool CWimCertHandler::SanityCheck( TUint32 aCertRef )
+    {
+    TInt certNum = iCertRefLst.Count();
+    if ( certNum == 0 )
+        {
+        return EFalse;
+        }
+    
+    for ( TInt index = 0; index < certNum; ++index )
+        {
+        if( aCertRef == iCertRefLst[ index ] )
+            {
+            return ETrue;
+            }
+        }
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::GetCertificateDetailsL
+// Fetches certificate details.
+// -----------------------------------------------------------------------------
+//
+void CWimCertHandler::GetCertificateDetailsL(
+    TWimServRqst aOpCode, 
+    const RMessage2& aMessage ) 
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::GetCertificateDetailsL | Begin"));
+    TBool IsOk = SanityCheck( (TUint32)aMessage.Ptr0() );
+    if ( ! IsOk  )
+        {
+        aMessage.Panic(_L("WIM"), KErrBadHandle );
+        return;
+        }
+    
+    //capability checking
+    TUint8 usage = 255;
+    WIMI_STAT callStatus = ResolveCertUsage( aMessage, usage );
+    if ( WIMI_Ok == callStatus )
+        {
+        if( !CheckReadCapsForUsage( aMessage, usage  ) )
+              {
+              aMessage.Complete(KErrPermissionDenied);  
+              return;
+              }
+        }
+
+    //capabilty ok, go to fetch the details of the certificate.
+    WIMI_Ref_pt pCertRef = const_cast<WIMI_Ref_pt>( aMessage.Ptr0() );
+    CWimResponse* responseID = new( ELeave ) CWimResponse( aMessage );
+    CleanupStack::PushL( responseID );
+    TWimReqTrId* trId = iWimUtilFuncs->TrIdLC( responseID, EWimMgmtReq );
+    responseID->iOpcode = aOpCode;
+    CleanupStack::Pop( 2, responseID ); // trId, responseID
+
+    WIMI_STAT certReqStatus = WIMI_CertificateReq( trId, pCertRef );
+    if ( certReqStatus != WIMI_Ok )
+        {
+        responseID->iStatus = certReqStatus;
+        responseID->CompleteMsgAndDelete();
+        delete trId;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::ResolveCertUsage
+// Resolves usage (CA/User) for a certificate.
+// -----------------------------------------------------------------------------
+//
+WIMI_STAT CWimCertHandler::ResolveCertUsage( const RMessage2& aMsg,
+                                        TUint8& aUsage )
+    {
+    _WIMTRACE(_L("CWimServer::ResolveCertUsage | Begin"));
+
+    // aMsg.Ptr0 contains reference to certificate
+    
+    WIMI_Ref_pt pCertRef = const_cast< WIMI_Ref_pt >( aMsg.Ptr0() );
+    _WIMTRACE2(_L("CWimServer::ResolveCertUsage | Begin aMsg.Ptr0() = %d"), aMsg.Ptr0());
+
+    WIMI_STAT callStatus = GetCertificateInfo( pCertRef, aUsage );
+
+    _WIMTRACE(_L("CWimServer::ResolveCertUsage | End"));
+    return callStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::GetCertificateInfo
+// Fetches certificate info. Wrapper for WIMI call.
+// -----------------------------------------------------------------------------
+//
+WIMI_STAT CWimCertHandler::GetCertificateInfo( WIMI_Ref_pt aCertRef,
+                                          TUint8& aUsage )
+    {
+    _WIMTRACE(_L("CWimServer::GetCertificateInfo | Begin"));
+
+    WIMI_Ref_pt     pWimRef = NULL;
+    WIMI_BinData_t  ptLabel;
+    WIMI_BinData_t  ptKeyID;
+    WIMI_BinData_t  ptCAID;
+    WIMI_BinData_t  ptIssuerHash;
+    WIMI_BinData_t  ptTrustedUsage;
+    TUint8          uiCDFRefs;
+    TUint8          type;
+    TUint16         certLen;
+    TUint8          modifiable = 0;
+    _WIMTRACE(_L("CWimServer::GetCertificateInfo | Begin 1"));
+    WIMI_STAT callStatus = WIMI_GetCertificateInfo(
+                                aCertRef,
+                                &pWimRef,
+                                &ptLabel,
+                                &ptKeyID, // Key Id (hash)
+                                &ptCAID,
+                                &ptIssuerHash,
+                                &ptTrustedUsage,
+                                &uiCDFRefs,
+                                &aUsage,  // 0 = client, 1 = CA
+                                &type,    // WTLSCert(1),
+                                          // X509Cert(2),
+                                          // X968Cert(3),
+                                          // CertURL(4)
+                                &certLen, // cert. content or URL length
+                                &modifiable );
+    _WIMTRACE(_L("CWimServer::GetCertificateInfo | Begin 2"));
+    // Don't need references anymore
+    if ( callStatus == WIMI_Ok )
+        {
+        free_WIMI_Ref_t( pWimRef );
+        WSL_OS_Free( ptLabel.pb_buf );
+        WSL_OS_Free( ptKeyID.pb_buf );
+        WSL_OS_Free( ptCAID.pb_buf );
+        WSL_OS_Free( ptIssuerHash.pb_buf );
+        WSL_OS_Free( ptTrustedUsage.pb_buf );
+        }
+
+    _WIMTRACE(_L("CWimServer::GetCertificateInfo | End"));
+    return callStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::GetCertificateInfo
+// Fetches certificate info. Wrapper for WIMI call.
+// -----------------------------------------------------------------------------
+//
+TBool CWimCertHandler::CheckReadCapsForUsage( const RMessage2& aMsg,
+                               TUint8 aUsage )
+    {
+    TBool result = EFalse;
+    
+    switch ( aUsage )
+        {
+        case WIMI_CU_CA:
+            {
+            // CA certificate reading doesn't require any capability.
+            _WIMTRACE(_L("CWimCertHandler::CheckReadCapsForUsage: CA cert read req, OK."));
+            result = ETrue;
+            break;
+            }
+        case WIMI_CU_Client:
+            {
+            // User certificate reading requires ReadUserData capability.
+            if ( aMsg.HasCapability( ECapabilityReadUserData ))
+                {
+                result = ETrue;
+                _WIMTRACE(_L("CWimCertHandler::CheckReadCapsForUsage: User cert read capa PASS"));
+                }
+            else
+                {
+                result = EFalse;
+                _WIMTRACE(_L("CWimCertHandler::CheckReadCapsForUsage: User cert read capa FAIL"));
+                }
+            break;
+            }
+        default:
+            {
+            _WIMTRACE(_L("CWimCertHandler::CheckReadCapsAccordingToUsage: FAIL:Unknown usage."));
+            result = EFalse;
+            break;
+            }
+        }
+    _WIMTRACE(_L("CWimCertHandler::CheckReadCapsForUsage | End"));
+    return result;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::ExportPublicKeyL
+// Export public key from certificate.
+// -----------------------------------------------------------------------------
+//
+void CWimCertHandler::ExportPublicKeyL( const RMessage2& aMessage ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimPublicKeyHandler::ExportPublicKeyParamsL | Begin"));
+
+    TUint8 certType = 0;
+
+    TPckgBuf<TExportPublicKey> keyExportPckg;
+    aMessage.ReadL( 0, keyExportPckg );
+    
+    HBufC8* publicKeyBuf = HBufC8::NewLC( KPublicKeyLength );
+
+    TBuf8<KKeyIdLen> keyIdBuf = keyExportPckg().iKeyId;
+
+    WIMI_STAT callStatus = WIMI_Ok;
+    WIMI_BinData_t ptCertData;
+    ptCertData.pb_buf = NULL;
+    ptCertData.ui_buf_length = 0;
+    WIMI_Ref_t* pCert = NULL;
+    WIMI_TransactId_t trId = ( void* )EInitializationCertListHashing;
+    TUint8 certCount = 0;
+    WIMI_RefList_t certRefList = NULL;
+
+    // Check firs the Client certs
+    callStatus = WIMI_GetCertificateListByKeyHash( ( TUint8* )keyIdBuf.Ptr(),
+                                                   WIMI_CU_Client,
+                                                   &certCount,
+                                                   &certRefList );
+    if ( callStatus == WIMI_Ok )
+        {
+        if ( certCount == 0 ) // Not found client certs
+            {
+            free_WIMI_RefList_t( certRefList );
+            certRefList = NULL;
+
+            // Check CA certs
+            callStatus = WIMI_GetCertificateListByKeyHash(
+                                                    ( TUint8* )keyIdBuf.Ptr(),
+                                                    WIMI_CU_CA,
+                                                    &certCount,
+                                                    &certRefList );
+            }
+        }
+
+    if ( callStatus == WIMI_Ok )
+        {
+        CleanupPushWimRefListL( certRefList );
+        if ( certCount == 0 ) // No certificates found for key
+            {
+            CleanupStack::PopAndDestroy( certRefList );
+            callStatus = WIMI_ERR_CertNotFound;
+            }
+        }
+
+    if ( callStatus == WIMI_Ok )
+        {
+        WIMI_Ref_t* tempRef = NULL;
+        WIMI_BinData_t ptLabel;
+        WIMI_BinData_t ptKeyID;
+        WIMI_BinData_t ptCAID;
+        WIMI_BinData_t ptIssuerHash;
+        WIMI_BinData_t ptTrustedUsage;
+        TUint8 uiCDFRefs;
+        TUint8 usage;
+
+        TUint16 certLen;
+        TUint8 modifiable = 0;
+
+        for ( TInt i = 0; i < certCount; i++ )
+            {
+            // Get info for each certificate until we find valid cert
+            callStatus = WIMI_GetCertificateInfo( certRefList[i],
+                                                  &tempRef,
+                                                  &ptLabel,
+                                                  &ptKeyID,
+                                                  &ptCAID,
+                                                  &ptIssuerHash,
+                                                  &ptTrustedUsage,
+                                                  &uiCDFRefs,
+                                                  &usage,
+                                                  &certType,   
+                                                  &certLen,
+                                                  &modifiable );
+            if ( callStatus == WIMI_Ok )
+                {
+                WSL_OS_Free( ptLabel.pb_buf );
+                WSL_OS_Free( ptKeyID.pb_buf );
+                WSL_OS_Free( ptCAID.pb_buf );
+                WSL_OS_Free( ptIssuerHash.pb_buf );
+                WSL_OS_Free( ptTrustedUsage.pb_buf );
+                free_WIMI_Ref_t( tempRef );
+
+                // Certificate has to be WTLS or X509, not URL
+                if ( certType == WIMI_CT_X509 || certType == WIMI_CT_WTLS )
+                    {
+                    pCert = certRefList[i]; // Found one
+                    i = certCount; // Stop looping
+                    }
+                else // Cert not supported
+                    {
+                    callStatus = WIMI_ERR_UnsupportedCertificate;
+                    }
+                }
+            }
+    
+        // Retrieve certificate data from WIM
+        if ( callStatus == WIMI_Ok )
+            {
+            callStatus = WIMI_CertificateReqT( trId, pCert, &ptCertData );
+            if ( callStatus == WIMI_Ok )
+                {
+                CleanupPushWimBufL( ptCertData );
+
+                TPtrC8 certPtr( ptCertData.pb_buf, ptCertData.ui_buf_length );
+                TPtr8 publicKeyPtr = publicKeyBuf->Des();
+
+                TRAPD( parseOk, ParseCertPublicKeyL( certPtr, publicKeyPtr, certType ) );
+                if ( parseOk )
+                    {
+                    aMessage.WriteL( 1, publicKeyPtr );
+                    }
+                else
+                    {
+                    callStatus = WIMI_ERR_CertParseError;
+                    }
+
+                CleanupStack::PopAndDestroy( ptCertData.pb_buf );
+                }
+            }
+        
+        CleanupStack::PopAndDestroy( certRefList );
+        }
+
+    CleanupStack::PopAndDestroy( publicKeyBuf );
+
+    aMessage.Complete( CWimUtilityFuncs::MapWIMError( callStatus ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::ParseCertPublicKeyL
+// Parse public key from certificate.
+// -----------------------------------------------------------------------------
+//
+void CWimCertHandler::ParseCertPublicKeyL(
+    const TDesC8& aCertData,
+    TDes8& aPublicKey,
+    const TUint8 aCertType ) const
+    {
+    CCertificate* certificate = NULL;
+    CRSAPublicKey* publicKey = NULL;
+
+    switch ( aCertType )
+        {
+        case WIMI_CT_WTLS:
+            {
+            certificate = CWTLSCertificate::NewLC( aCertData );
+            publicKey = CWTLSRSAPublicKey::NewLC( certificate->PublicKey().KeyData() );
+            break;
+            }
+    
+        case WIMI_CT_X509:
+            {
+            certificate = CX509Certificate::NewLC( aCertData );
+            publicKey = CX509RSAPublicKey::NewLC( certificate->PublicKey().KeyData() );
+            break;
+            }
+        default:
+            {
+            _WIMTRACE2(_L("WIM|WIMServer|CWimCertHandler::ParseCertPublicKeyL, type %d not supported"), aCertType);
+            User::Leave( KErrNotSupported );
+            break;
+            }
+        }
+
+    TX509RSAKeyEncoder encoder( *publicKey, ESHA1 );
+    CASN1EncBase* encoded = encoder.EncodeKeyLC();
+
+    TUint pos = 0;
+    aPublicKey.SetLength( KPublicKeyLength );
+    // Check that Max. length is not exceeded
+    if ( encoded->LengthDER() > static_cast< TUint >( KPublicKeyLength ) )
+        {
+        _WIMTRACE(_L("WIM|WIMServer|CWimCertHandler::ParseCertPublicKeyL, too long public key"));
+        User::Leave( KErrBadDescriptor );
+        }
+    // Write encoded key to prealloced buffer
+    encoded->WriteDERL( aPublicKey, pos );
+
+    CleanupStack::PopAndDestroy( 3, certificate );  // encoded, publicKey, certificate
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimCertUtil.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1311 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Utility functions for certificate related functionality
+*
+*/
+
+
+
+#include    "WimCertUtil.h"
+#include    "WimTrace.h"
+#include    "WimCertInfo.h"
+#include    "WimUtilityFuncs.h"
+#include    "WimCleanup.h"
+#include    <cctcertinfo.h>
+#include    <asn1dec.h>         // ASN.1 decoding
+
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::CWimCertUtil()
+// Default constructor
+// -----------------------------------------------------------------------------
+CWimCertUtil::CWimCertUtil( MCTToken& aToken )
+    : CActive( EPriorityStandard ),
+      iToken( aToken )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::NewL()
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+CWimCertUtil* CWimCertUtil::NewL( MCTToken& aToken )
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::NewL" ) );
+    CWimCertUtil* self = new( ELeave ) CWimCertUtil( aToken );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self ); //self
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::ConstructL()
+// Second phase
+// -----------------------------------------------------------------------------
+void CWimCertUtil::ConstructL()
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::ConstructL" ) );
+    CActiveScheduler::Add( this );
+    iWimUtilFuncs = CWimUtilityFuncs::NewL();
+    _WIMTRACE ( _L( "CWimCertUtil::ConstructL() completed" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::Restore()
+// Returns CCTCertInfo objects in array
+// -----------------------------------------------------------------------------
+void CWimCertUtil::Restore( RPointerArray<CWimCertInfo>& aArray, 
+                            TRequestStatus& aStatus )
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::Restore" ) );
+    iClientStatus = &aStatus;
+    aStatus = KRequestPending;
+    iArray = &aArray;
+    iPhase = EListCertsFromWim;
+    SignalOwnStatusAndComplete();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::CancelRestore()
+// Cancels outgoing Restore operation. Sets an internal flag to true. 
+// After necessary cleanup, caller is signalled with KErrCancel 
+// -error code.
+// -----------------------------------------------------------------------------
+void CWimCertUtil::CancelRestore()
+    {
+    _WIMTRACE ( _L( "CWimCertUtil::CancelRestore" ) );
+    Cancel(); 
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::RetrieveCertByIndexL()
+// Retrieves the actual certificate.
+// -----------------------------------------------------------------------------
+
+void CWimCertUtil::RetrieveCertByIndexL( const TInt aIndex,
+                                         TDes8& aEncodedCert, 
+                                         TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "WimServer|CWimCertUtil::RetrieveCertByIndexL" ) );
+    //Check that index is valid
+    __ASSERT_ALWAYS( aIndex <= iArraySize && iCertRefLst,
+        User::Leave( KErrArgument )  );
+    iClientStatus = &aStatus;
+    iCertRetrieveIndex = aIndex;
+    iEncodedCert = &aEncodedCert;
+    aStatus = KRequestPending;
+    iPhase = ERetrieveCertificate;
+    SignalOwnStatusAndComplete();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::SignalOwnStatusAndComplete()       
+// Sets own iStatus to KRequestPending, and signals it 
+// with User::RequestComplete() -request. This gives chance 
+// active scheduler to run other active objects. After a quick
+// visit in active scheduler, signal returns to RunL() and starts next
+// phase of operation. 
+// -----------------------------------------------------------------------------
+void CWimCertUtil::SignalOwnStatusAndComplete()
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::SignalOwnStatusAndComplete()" ) );
+    iStatus = KRequestPending;
+    SetActive();
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+    }
+    
+// -----------------------------------------------------------------------------
+// CWimCertUtil::~CWimCertUtil()
+// Allocated memory is released.
+// -----------------------------------------------------------------------------
+CWimCertUtil::~CWimCertUtil()
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::~CWimCertUtil()" ) );
+    Cancel();
+    DeallocWimCertInfo();
+    DeallocCertHBufs();
+    DeallocReferences();
+    delete iTrustedUsages;
+    delete iTrustedUsagesPtr;
+    delete iKeyIdBuf;
+    delete iKeyIdPointer;
+    delete iWimUtilFuncs;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::RunL()
+// This has eight different phases which are explained here:
+// 1. EListCertsFromWim:Allocate member variables for arrays usage. 
+//    Array is passed as an argument to server and it is filled with 
+//    certificate information found from WIM.
+// 2. ECreateNewCertObjects: New certificate objects are created based on 
+//    received information on step one. A little bit of conversion is 
+//    required. Objects are inserted to an array.
+// 3. ERetrieveCertificate:Allocate member variables for struct, 
+//    which is used to fetch certificate details
+// 4. ERetrievingCompleted: Check cancellation. If not cancelled,
+//    copy information to caller's buffer. 
+// 5. EAddCertificate: Adds certificate to WIM.
+// 6. EAddCertificateCompleted: Certificate is added successfully. Deallocate
+//                              variables and complete request.
+// 7. ERemove: Before removing, we will check for cancellation. After that
+//    cancellation is too late.
+// 8. ERemoveCompleted: Removal operation completed ok. Deallocte variables and
+//    complete request
+// 9. EGetCertExtras: Extra data is fetched and async. waiter needs to be 
+//    stopped
+// -----------------------------------------------------------------------------
+void CWimCertUtil::RunL()
+    {
+    _WIMTRACE3(_L("WimServer|CWimCertUtil::RunL(), iStatus=%d, iPhase=%d"), iStatus.Int(), iPhase);
+    //Check for error
+    if ( iStatus.Int() != KErrNone )
+        {
+        //failed to retrieve certificate
+        if ( iPhase == ERetrievingCompleted )
+            {
+             DeallocCertHBufs();
+             _WIMTRACE2 ( _L( "CWimCertUtil::RunL() failed to retrieve \
+                 certificate, ERROR = %d" ),iStatus.Int() );
+            }
+       
+        User::RequestComplete( iClientStatus, iStatus.Int() );
+        }
+    else
+        {
+        switch( iPhase )
+            {
+            case EListCertsFromWim: //get certificates from WIM.
+                {                  
+                if ( iArraySize ) //Delete previous preferences. 
+                    {           //User might added or removed a certificate. 
+                    DeallocWimCertInfo();
+                    DeallocReferences();
+                    }
+            
+                //Ok ready to begin. First get Cert count
+                iCertCount = CertCount( EWimEntryTypeAll ); 
+                _WIMTRACE2 ( _L( "CWimCertUtil::RunL() \
+                    certCount =%d" ),iCertCount );
+                if ( !iCertCount )  
+                    {
+                    User::RequestComplete( iClientStatus, KErrNotFound );
+                    }
+                else
+                    {
+                    __ASSERT_DEBUG( iCertRefLst == NULL, User::Invariant() );
+                    iCertRefLst = new( ELeave ) TCertificateAddress[iCertCount];
+
+                    //Creates new array according to certificate count
+                    __ASSERT_DEBUG( iCertInfoArr == NULL, User::Invariant() );
+                    iCertInfoArr  = new( ELeave ) TWimCertInfo[iCertCount];
+            
+                    AllocWimCertInfoL( iCertInfoArr, iCertCount );
+                    iStatus = KRequestPending;
+
+                    CertRefLstL( iCertRefLst, 
+                                 iCertInfoArr, 
+                                 EWimEntryTypeAll );
+
+                    iPhase = ECreateNewCertObjects;
+                    iIndex = 0;
+                    SetActive();
+
+                    TRequestStatus* status = &iStatus;
+                    User::RequestComplete( status, KErrNone );
+
+                    _WIMTRACE( _L( "CWimCertUtil::RunL() \
+                        GetCertRefLst" ) );
+                    }
+                break;
+                }
+            case ECreateNewCertObjects: //Certificates fetched, 
+                { 
+                CreateNewCertObjectsL();//create new cert-objects
+                break;
+                }
+            case EGetTrustedUsages:
+                {
+                GetTrustedUsagesL();
+                break;
+                }
+            case ETrustedUsagesDone:
+                {
+                TrustedUsagesDoneL();
+                break;
+                }
+            case ECertObjectsDone: 
+                {
+                User::RequestComplete( iClientStatus, KErrNone );    
+                _WIMTRACE ( _L( "CWimCertUtil::RunL() \
+                    ECertObjectsDone" ) );
+                break;
+                }
+            case ERetrieveCertificate: //Get Cert details from WIM
+                {
+                AllocMemoryForCertDetailsL();
+                CertDetailsL( iCertRefLst[iCertRetrieveIndex], 
+                              iWimCertDetails );
+                iPhase = ERetrievingCompleted;
+                SetActive();
+
+                TRequestStatus* status = &iStatus;
+                    User::RequestComplete( status, KErrNone );
+
+                _WIMTRACE ( _L( "CWimCertUtil::RunL() \
+                    ERetrieveCertificate" ) );
+                break;
+                }
+            case ERetrievingCompleted: //Cert details fetched, check errors &                         
+                {                      //cancellations & complete request                   
+                //copy cert details to iEncodedCert -buffer,
+                //which points to received aEncoded -cert buffer.
+                CopyRetrievedCertData();
+                DeallocCertHBufs();
+                User::RequestComplete( iClientStatus, KErrNone );
+                _WIMTRACE ( _L( "CWimCertUtil::RunL() \
+                    ERetrievingCompleted" ) );
+                break;
+                }
+           
+            default:
+                {
+                User::RequestComplete( iClientStatus, KErrNotSupported );
+                break;
+                }          
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::CreateNewCertObjectsL()
+// Creates new certificate objects which can be returned to the caller.
+// -----------------------------------------------------------------------------
+void CWimCertUtil::CreateNewCertObjectsL()
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::CreateNewCertObjectsL() | Begin" ) );
+
+    HBufC16* label16 = NULL;
+    HBufC8* hash8 = NULL;
+
+    if ( iIndex < iCertCount )
+        {
+        TCertificateOwnerType certificateType;
+        if ( iCertInfoArr[iIndex].iUsage == 0 )
+            {
+            certificateType = EUserCertificate; // 0 == User
+            }
+        else
+            {
+            certificateType = ECACertificate;   // 1 == CA
+            }
+                        
+        label16 = HBufC16::NewLC( iCertInfoArr[iIndex].iLabel.Length() );
+        label16->Des().Copy( iCertInfoArr[iIndex].iLabel );
+            
+        hash8 = HBufC8::NewLC( iCertInfoArr[iIndex].iIssuerHash.Length() );
+        hash8->Des().Copy( iCertInfoArr[iIndex].iIssuerHash );
+        // Convert type 
+        TCertificateFormat format;
+        format = GetCertFormatByIndex( iIndex );
+        //Create key indentifiers
+        TKeyIdentifier subjectKeyId;
+        TKeyIdentifier issuerKeyId;
+        //needs these for CCTCertInfo object -creation
+        subjectKeyId = iCertInfoArr[iIndex].iKeyId;
+        issuerKeyId  = iCertInfoArr[iIndex].iCAId;
+        //Create CCTCertInfo object. 
+        if ( iCertInfoArr[iIndex].iIssuerHash.Length() > 0 )
+            {
+            iCert = CCTCertInfo::NewL( label16->Des(), 
+                                      format, 
+                                      certificateType,
+                                      iCertInfoArr[iIndex].iCertlen, 
+                                      &subjectKeyId, 
+                                      &issuerKeyId, 
+                                      iToken, 
+                                      iIndex,
+                                      iCertInfoArr[iIndex].iModifiable,
+                                      hash8 );
+            }
+        else
+            {
+            iCert = CCTCertInfo::NewL( label16->Des(), 
+                                      format, 
+                                      certificateType,
+                                      iCertInfoArr[iIndex].iCertlen, 
+                                      &subjectKeyId, 
+                                      &issuerKeyId, 
+                                      iToken, 
+                                      iIndex,
+                                      iCertInfoArr[iIndex].iModifiable );
+            }
+
+        CleanupStack::PopAndDestroy( hash8 ); 
+        CleanupStack::PopAndDestroy( label16 );
+
+        iOids = new( ELeave ) RArray<HBufC*>();
+        //Check whether certificate has extra data. Certificate type must be
+        // X509
+        if ( iCertInfoArr[iIndex].iCDFRefs &&
+             iCertInfoArr[iIndex].iType == WIMI_CT_X509 )
+            {  
+            iPhase = EGetTrustedUsages;
+            }
+        else
+            {
+            CreateNewWimCertObjectL();
+            }
+        }
+    else
+        {
+        DeallocWimCertInfo(); 
+        iPhase = ECertObjectsDone;
+        }
+    SignalOwnStatusAndComplete();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::CreateNewWimCertObjectL()
+// 
+// -----------------------------------------------------------------------------
+void CWimCertUtil::CreateNewWimCertObjectL()
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::CreateNewWimCertObjectL()" ) );
+
+    iCertInfo = CWimCertInfo::NewL( iCert, //CCTCertInfo object
+                                    iCert->SubjectKeyId(), //key hash
+                                    *iOids, 
+                                    iCertInfoArr[iIndex].iCDFRefs );
+    
+    delete iOids;
+    iOids = NULL;
+
+    //Append WimCertInfo -object to array. Ownership to iArray here.
+    User::LeaveIfError( iArray->Append( iCertInfo ) );
+
+    iPhase = ECreateNewCertObjects;
+    iIndex++;
+    }
+        
+// -----------------------------------------------------------------------------
+// CWimCertUtil::GetTrustedUsagesL
+// Get trusted usages (OIDs) of a current certificate, which is pointed out 
+// by a index
+// -----------------------------------------------------------------------------
+void CWimCertUtil::GetTrustedUsagesL()
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::GetTrustedUsagesL() | Begin" ) );
+
+    delete iTrustedUsages;
+    iTrustedUsages = NULL;
+    delete iTrustedUsagesPtr;
+    iTrustedUsagesPtr = NULL;
+    //Allocate variables for trusted usage fetching
+    iTrustedUsages = HBufC::NewL( iCertInfoArr[iIndex].iTrustedUsageLength );
+    iTrustedUsagesPtr = new( ELeave ) TPtr( iTrustedUsages->Des() );
+
+    iCertExtrasInfo.iTrustedUsage = iTrustedUsagesPtr;
+    iPhase = ETrustedUsagesDone;
+
+    delete iKeyIdBuf;
+    iKeyIdBuf = NULL;
+    delete iKeyIdPointer;
+    iKeyIdPointer = NULL;
+    // Take a copy of key identifier
+    iKeyIdBuf = iCertInfoArr[iIndex].iKeyId.AllocL();
+    iKeyIdPointer = new( ELeave ) TPtr8( iKeyIdBuf->Des() );
+
+    GetCertExtrasL( iKeyIdPointer,
+                    iCertExtrasInfo,
+                    iCertInfoArr[iIndex].iUsage,
+                    iStatus );
+    SetActive();
+    _WIMTRACE ( _L( "CWimCertUtil::GetTrustedUsagesL() | End" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::TrustedUsagesDoneL()
+// -----------------------------------------------------------------------------
+void CWimCertUtil::TrustedUsagesDoneL()
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::TrustedUsagesDoneL()" ) );
+    if ( iStatus.Int() == KErrNone )
+        {
+        //Parse oids and put them to an array
+        TLex16 lex( *iTrustedUsages );
+        TPtrC16 lexToken;
+        for ( TBool extrasDone = EFalse; extrasDone == EFalse; )
+            {
+            lexToken.Set( lex.NextToken() );
+            if ( lexToken.Length() )
+                {
+                HBufC* oid = lexToken.AllocLC();
+                User::LeaveIfError( iOids->Append( oid ) );
+                CleanupStack::Pop( oid ); //oid
+                }
+            else
+                {
+                extrasDone = ETrue;
+                }
+            }
+        CreateNewWimCertObjectL();
+        SignalOwnStatusAndComplete();
+        }
+    else
+        {
+        User::RequestComplete( iClientStatus, iStatus.Int() );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::GetCertFormatByIndex()
+// Returns certificate format according to received index
+// -----------------------------------------------------------------------------
+TCertificateFormat CWimCertUtil::GetCertFormatByIndex( TInt aIndex )
+    {
+    _WIMTRACE ( _L( "WimServer|CWimCertUtil::GetCertFormatByIndex()" ) );
+
+    // Convert type 
+    TCertificateFormat format;
+    switch ( iCertInfoArr[aIndex].iType )
+        {
+        case WIMI_CT_WTLS: 
+            {
+            format = EWTLSCertificate;
+            break;
+            }
+        case WIMI_CT_X509: 
+            {
+            format = EX509Certificate;
+            break;
+            }
+        case WIMI_CT_X968: 
+            {
+            format = EX968Certificate;
+            break;
+            }
+        case WIMI_CT_URL: 
+            {
+            format = EX509CertificateUrl;
+            break;
+            }
+        default:
+            {
+            format = EUnknownCertificate;
+            break;
+            }         
+        }
+    return format;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::DoCancel()
+// Deallocates member variables and completes client status with
+// KErrCancel error code.
+// -----------------------------------------------------------------------------
+void CWimCertUtil::DoCancel()
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::DoCancel()" ) );
+
+    if ( iPhase == EGetTrustedUsages || iPhase == ETrustedUsagesDone )
+        {
+        iCert->Release();
+        }
+
+    DeallocWimCertInfo();
+    DeallocCertHBufs();
+    DeallocReferences();
+    User::RequestComplete( iClientStatus, KErrCancel );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::RunError() 
+//                                       
+// The active scheduler calls this function if this active object's RunL() 
+// function leaves. This gives this active object the opportunity to perform 
+// any necessary cleanup.
+// After array's cleanup, complete request with received error code.
+// -----------------------------------------------------------------------------
+TInt CWimCertUtil::RunError( TInt aError )
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::RunError Error = %d" ) );
+    DeallocWimCertInfo();
+    DeallocCertHBufs();
+    delete iTrustedUsages;
+    iTrustedUsages = NULL;
+    delete iTrustedUsagesPtr;
+    iTrustedUsagesPtr = NULL;
+    delete iKeyIdBuf;
+    iKeyIdBuf = NULL;
+    delete iKeyIdPointer;
+    iKeyIdPointer = NULL;
+
+    User::RequestComplete( iClientStatus, aError );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::AllocWimCertInfoL()
+// Allocates memory for the array which is filled by server.
+// -----------------------------------------------------------------------------
+void CWimCertUtil::AllocWimCertInfoL( 
+    TWimCertInfo* aWimCertInfoArr, 
+    TInt aCount )
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::AllocWimCertInfoL()" ) );
+
+    TUint8 index;    
+    //These are arrays
+    iLabel = new( ELeave ) PHBufC8[aCount];
+    iKeyId = new( ELeave ) PHBufC8[aCount];
+    iCAId  = new( ELeave ) PHBufC8[aCount];
+    iIssuerHash = new( ELeave ) PHBufC8[aCount];
+
+    iLabelPtr = new( ELeave ) PTPtr8[aCount];
+    iKeyIdPtr = new( ELeave ) PTPtr8[aCount];
+    iCAIdPtr  = new( ELeave ) PTPtr8[aCount];
+    iIssuerHashPtr = new( ELeave ) PTPtr8[aCount];
+
+    for ( index = 0; index < aCount ; index++ )
+        {
+        iLabel[index] = HBufC8::NewL( KLabelLen );
+        iKeyId[index] = HBufC8::NewL( KKeyIdLen );
+        iCAId[index]  = HBufC8::NewL( KPkcs15IdLen );
+        iIssuerHash[index] = HBufC8::NewL( KIssuerHash );
+        
+        iLabelPtr[index]  = new( ELeave ) TPtr8( iLabel[index]->Des() );
+        iKeyIdPtr[index]  = new( ELeave ) TPtr8( iKeyId[index]->Des() );
+        iCAIdPtr[index]   = new( ELeave ) TPtr8( iCAId[index]->Des() );
+        iIssuerHashPtr[index] = new( ELeave ) 
+                                TPtr8( iIssuerHash[index]->Des() );
+
+        aWimCertInfoArr[index].iLabel.Copy( iLabelPtr[index]->Ptr(),
+                                            iLabelPtr[index]->Length() );
+        aWimCertInfoArr[index].iKeyId.Copy( iKeyIdPtr[index]->Ptr(),
+                                            iKeyIdPtr[index]->Length() );
+        aWimCertInfoArr[index].iCAId.Copy( iCAIdPtr[index]->Ptr(),
+                                           iCAIdPtr[index]->Length() );
+        aWimCertInfoArr[index].iIssuerHash.Copy(
+            iIssuerHashPtr[index]->Ptr(), iIssuerHashPtr[index]->Length() );
+        }
+    iArraySize = aCount;   
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::AllocMemoryForCertDetailsL()
+// Allocates memory for a struct which is filled by server.
+// -----------------------------------------------------------------------------     
+void CWimCertUtil::AllocMemoryForCertDetailsL()
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::AllocMemoryForCertDetailsL()" ) );
+    iCertHBufOne = HBufC8::NewL( iEncodedCert->MaxLength() ); //whole cert
+    iCertHBufOnePtr = new( ELeave ) TPtr8( iCertHBufOne->Des() ); 
+    iWimCertDetails.iCert = iCertHBufOnePtr;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::CopyRetrievedCertData()
+// Writes data to caller's buffer by using pointer.
+// -----------------------------------------------------------------------------
+void CWimCertUtil::CopyRetrievedCertData()
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::CopyRetrievedCertData()" ) );
+    TPtr8 ptr = iCertHBufOne->Des();
+    iEncodedCert->Copy( ptr );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::DeallocCertHBufs()
+// DeAllocates memory from member variables, which are used
+// when communicating with WIM.
+// -----------------------------------------------------------------------------
+void CWimCertUtil::DeallocCertHBufs()
+    {
+    _WIMTRACE ( _L( "WimServer|CWimCertUtil::DeallocCertHBufs()" ) ); 
+    if ( iCertHBufOne )
+        {
+        delete iCertHBufOne;
+        delete iCertHBufOnePtr;
+        iCertHBufOne = NULL;
+        iCertHBufOnePtr = NULL;
+        }
+    if ( iCertHBufTwo )
+        {
+        delete iCertHBufTwo;
+        delete iCertHBufTwoPtr;
+        iCertHBufTwo = NULL;
+        iCertHBufTwoPtr = NULL;
+        }
+    if ( iCertHBufThree )
+        {
+        delete iCertHBufThree;
+        delete iCertHBufThreePtr;
+        iCertHBufThree = NULL;
+        iCertHBufThreePtr = NULL;
+        }
+    if ( iCertHBufFour )
+        {
+        delete iCertHBufFour;
+        delete iCertHBufFourPtr;
+        iCertHBufFour = NULL;
+        iCertHBufFourPtr = NULL;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::DeallocReferences()
+// Deallocates memory. If user has cancelled initialization process, we need
+// to dealloc our references to loaded certs. 
+// -----------------------------------------------------------------------------
+void CWimCertUtil::DeallocReferences()
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::DeallocReferences()" ) ); 
+    if ( iCertRefLst )
+        {
+        for( TInt index = 0; index < iCertCount; ++index )
+            {
+            WIMI_Ref_t* ref = reinterpret_cast< WIMI_Ref_t* >( iCertRefLst[ index ] );
+            _WIMTRACE2( _L( "WimServer|CWimCertUtil::DeallocReferences(), -ref 0x%08x" ), ref );
+            free_WIMI_Ref_t( ref );
+            iCertRefLst[ index ] = 0;
+            }
+        delete[] iCertRefLst;
+        iCertRefLst = NULL;
+        }
+    if ( iCertInfoArr )
+        {
+        delete iCertInfoArr;
+        iCertInfoArr = NULL;
+        }  
+    iArraySize = 0;
+    iArray = NULL;
+    iCertCount = 0;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::DeallocWimCertInfo()
+// Deallocates memory. If something has leaved during asynchronous request, we 
+// will deallocate all member data. 
+// -----------------------------------------------------------------------------
+void CWimCertUtil::DeallocWimCertInfo()
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::DeallocWimCertInfo()" ) ); 
+    TUint8 index;
+    for ( index = 0; index < iArraySize; index ++ )
+        {
+        if ( iLabel )
+            {
+            delete iLabel[index];
+            }
+        if ( iKeyId )
+            {
+            delete iKeyId[index];
+            }
+        if ( iCAId )
+            {
+            delete iCAId[index];
+            }
+        if ( iIssuerHash )
+            {
+            delete iIssuerHash[index];
+            }
+        if ( iLabelPtr )
+            {
+            delete iLabelPtr[index];
+            }
+        if ( iKeyIdPtr )
+            {
+            delete iKeyIdPtr[index];
+            }
+        if ( iCAIdPtr )
+            {
+            delete iCAIdPtr[index];
+            }
+        if ( iIssuerHashPtr )
+            {
+            delete iIssuerHashPtr[index];
+            }
+        }
+    
+    delete iLabel;   
+    delete iKeyId;                
+    delete iCAId;
+    delete iIssuerHash; 
+    delete iLabelPtr;        
+    delete iKeyIdPtr;        
+    delete iCAIdPtr;        
+    delete iIssuerHashPtr;  
+    iLabel = NULL;
+    iKeyId  = NULL;
+    iCAId = NULL;
+    iIssuerHash = NULL;
+    iLabelPtr = NULL;
+    iKeyIdPtr = NULL;
+    iCAIdPtr = NULL;
+    iIssuerHashPtr = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::CertCount
+// Get count of certificate in WIM
+// -----------------------------------------------------------------------------
+//
+TUint8 CWimCertUtil::CertCount( TWimEntryType aType )
+    {
+    _WIMTRACE( _L( "WimServer|CWimCertUtil::DeallocWimCertInfo()" ) ); 
+    WIMI_STAT callStatus = WIMI_Ok;
+    
+    WIMI_Ref_t* wimRef = NULL;
+    TUint8 certCount = 0;
+
+    wimRef = WIMI_GetWIMRef( 0 );
+
+    if ( wimRef )
+        {
+        if ( aType == EWimEntryTypeAll || aType == EWimEntryTypeCA )
+            {
+            callStatus = GetCertificateCountByWIM( wimRef, 
+                                                   certCount, 
+                                                   WIMI_CU_CA );            
+            }
+
+        if ( callStatus == WIMI_Ok && ( aType == EWimEntryTypeAll || 
+                                        aType == EWimEntryTypePersonal ) )
+            {
+            callStatus = GetCertificateCountByWIM( wimRef, 
+                                                   certCount, 
+                                                   WIMI_CU_Client );
+            }
+
+        free_WIMI_Ref_t( wimRef );
+        }
+    else
+        {
+        certCount = 0;
+        }
+
+    return certCount;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::CertRefLstL
+// 
+// -----------------------------------------------------------------------------
+//
+void CWimCertUtil::CertRefLstL(
+    TCertificateAddressList aCertAddrLst, 
+    TWimCertInfo* aCertInfoArr, 
+    TWimEntryType aCertEntryType )
+    {
+    
+    WIMI_STAT callStatus = WIMI_Ok;
+    TUint8 certNum = 0;
+    WIMI_Ref_t* wimRef = NULL;
+
+    wimRef = WIMI_GetWIMRef( 0 );
+
+    if ( wimRef )
+        {
+        CleanupPushWimRefL( wimRef );
+
+        if ( aCertEntryType == EWimEntryTypeAll || 
+             aCertEntryType == EWimEntryTypeCA )
+            {
+            callStatus = GetCertificateFromWimRefL( wimRef, 
+                                                    WIMI_CU_CA,
+                                                    certNum,
+                                                    aCertAddrLst,
+                                                    aCertInfoArr );
+            }
+        if ( callStatus == WIMI_Ok && 
+            ( aCertEntryType == EWimEntryTypeAll || 
+              aCertEntryType == EWimEntryTypePersonal ) )
+            {
+            callStatus = GetCertificateFromWimRefL( wimRef,
+                                                    WIMI_CU_Client,
+                                                    certNum,
+                                                    aCertAddrLst,
+                                                    aCertInfoArr );
+            }
+
+        CleanupStack::PopAndDestroy( wimRef );
+        }
+    else
+        {
+        callStatus = WIMI_ERR_OutOfMemory;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::GetCertExtrasL
+// 
+// -----------------------------------------------------------------------------
+//
+void CWimCertUtil::GetCertExtrasL(
+    const TPtr8* aKeyId, 
+    TCertExtrasInfo& aCertExtrasInfo,
+    TUint aUsage,
+    TRequestStatus& aStatus )
+    {
+    WIMI_STAT callStatus = WIMI_Ok;
+    TInt8 certUsage = 0;
+
+    TPtrC8 keyID( aKeyId->Ptr(), aKeyId->Length() );
+
+    WIMI_Ref_t* wimTempRef = WIMI_GetWIMRef( 0 );
+
+    if ( wimTempRef )
+        {
+        CleanupPushWimRefL( wimTempRef );
+
+        switch ( aUsage )
+            {
+            case EWimEntryTypeCA:
+                {
+                certUsage = WIMI_CU_CA;
+                break;
+                }
+            case EWimEntryTypeAll: //Flow through
+            case EWimEntryTypePersonal:
+                {
+                certUsage = WIMI_CU_Client;
+                break;
+                }
+            default:
+                {
+                callStatus = WIMI_ERR_BadParameters;
+                break;
+                }
+            }
+
+        if ( callStatus == WIMI_Ok )
+            {
+            callStatus = GetExtrasFromWimRefL( wimTempRef,
+                                               certUsage,
+                                               keyID,
+                                               aCertExtrasInfo );
+            }
+
+        CleanupStack::PopAndDestroy( wimTempRef );
+        }
+    else
+        {
+        callStatus = WIMI_ERR_BadReference;
+        }
+
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete( status, iWimUtilFuncs->MapWIMError( callStatus ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::CertDetailsL
+// 
+// -----------------------------------------------------------------------------
+//
+void CWimCertUtil::CertDetailsL(
+    const TCertificateAddress aCertAddr, 
+    TWimCertDetails& aWimCertDetails )
+    {
+    WIMI_STAT callStatus = WIMI_Ok;
+    WIMI_TransactId_t trId = ( void* )EInitializationCertListHashing;
+
+    WIMI_BinData_t ptCertData;
+    ptCertData.pb_buf = NULL;
+    ptCertData.ui_buf_length = 0;
+
+    callStatus = WIMI_CertificateReqT( trId, ( void* )aCertAddr, &ptCertData );
+
+    if ( callStatus == WIMI_Ok )
+        {
+        // Now we have certificate data, copy it to allocated buffer
+        if( aWimCertDetails.iCert->MaxLength() < ptCertData.ui_buf_length )
+            {
+            WSL_OS_Free( ptCertData.pb_buf );
+            User::Leave( KErrOverflow );
+        	}
+        aWimCertDetails.iCert->Copy( ptCertData.pb_buf,
+                                     ptCertData.ui_buf_length );
+        WSL_OS_Free( ptCertData.pb_buf );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertUtil::GetCertificateCountByWIM
+// Fetches count of certicates in certain WIM card.
+// -----------------------------------------------------------------------------
+//
+WIMI_STAT CWimCertUtil::GetCertificateCountByWIM(
+    WIMI_Ref_t* aRef, 
+    TUint8& aCertCount, 
+    TUint8 aUsage ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertUtil::GetCertificateCountByWIM | Begin"));
+    TUint8 certNum = 0;
+    WIMI_RefList_t refList ;
+    WIMI_STAT callStatus = WIMI_GetCertificateListByWIM( aRef, 
+                                                         aUsage,
+                                                         &certNum, 
+                                                         &refList );
+    if ( callStatus == WIMI_Ok )
+        {
+        aCertCount = ( TUint8 )( aCertCount + certNum );
+        }
+    free_WIMI_RefList_t( refList );
+    return callStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::GetExtrasFromWimRefL
+// Fetches extra information (e.g. certs trusted usage) from the WIM card.
+// -----------------------------------------------------------------------------
+//
+WIMI_STAT CWimCertUtil::GetExtrasFromWimRefL(
+    WIMI_Ref_t* aTmpWimRef,
+    TInt8 aUsage,
+    TDesC8& aKeyHash,
+    TCertExtrasInfo& aCertExtrasInfo ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::GetExtrasFromWimRefL | Begin"));
+  
+    TUint8 tempCertCount = 0;
+    WIMI_RefList_t certRefList = NULL;
+    WIMI_STAT callStatus = WIMI_Ok;
+    TInt certIndex = 0;
+    TPtrC8 keyHash;
+
+    if ( aTmpWimRef )
+        {
+        // List all certificates (by WIM and usage)
+        callStatus = WIMI_GetCertificateListByWIM( aTmpWimRef, 
+                                                   aUsage, 
+                                                   &tempCertCount, 
+                                                   &certRefList );
+        }
+    else
+        {
+        callStatus = WIMI_ERR_BadReference;
+        }
+    
+    if ( callStatus == WIMI_Ok )
+        {
+        CleanupPushWimRefListL( certRefList );
+
+        WIMI_Ref_t* tempRef = NULL;
+        WIMI_BinData_t ptLabel;
+        WIMI_BinData_t ptKeyID;
+        WIMI_BinData_t ptCAID;
+        WIMI_BinData_t ptIssuerHash;
+        WIMI_BinData_t ptTrustedUsage;
+        TUint8 uiCDFRefs;
+        TUint8 usage;
+        TUint8 certType;
+        TUint16 certLen;
+        TUint8 modifiable = 0;
+
+        for ( TInt i = 0; i < tempCertCount; i++ )
+            {
+            // Get info for each certificate until we find valid cert
+            callStatus = WIMI_GetCertificateInfo( certRefList[i],
+                                                  &tempRef,
+                                                  &ptLabel,
+                                                  &ptKeyID,
+                                                  &ptCAID,
+                                                  &ptIssuerHash,
+                                                  &ptTrustedUsage,
+                                                  &uiCDFRefs,
+                                                  &usage,
+                                                  &certType,   
+                                                  &certLen,
+                                                  &modifiable );
+            if ( callStatus == WIMI_Ok )
+                {
+                WSL_OS_Free( ptLabel.pb_buf );
+                WSL_OS_Free( ptCAID.pb_buf );
+                WSL_OS_Free( ptIssuerHash.pb_buf );
+                WSL_OS_Free( ptTrustedUsage.pb_buf );
+                free_WIMI_Ref_t( tempRef );
+
+                keyHash.Set( ptKeyID.pb_buf, ptKeyID.ui_buf_length );
+
+                // Compare given and fetched key hash
+                if ( keyHash.Compare( aKeyHash ) == 0 &&
+                     certType == WIMI_CT_X509 ) //Match
+                    {
+                    certIndex = i; // Found one
+                    i = tempCertCount; // Stop looping
+                    callStatus = WIMI_Ok;
+                    }
+                else // Cert not supported
+                    {
+                    callStatus = WIMI_ERR_UnsupportedCertificate;
+                    }
+
+                WSL_OS_Free( ptKeyID.pb_buf );
+                }
+            }
+
+        if ( callStatus == WIMI_Ok )
+            {
+            CopyCertExtrasInfoL( certRefList[certIndex], aCertExtrasInfo );
+            }
+        CleanupStack::PopAndDestroy( certRefList );
+        }
+
+    return callStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::CopyCertExtrasInfoL
+// Copies certs extra information to client's allocated structure.
+// -----------------------------------------------------------------------------
+//
+void CWimCertUtil::CopyCertExtrasInfoL(
+    WIMI_Ref_t* aCert,
+    TCertExtrasInfo& aCertExtrasInfo ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::CopyCertExtrasInfoL | Begin"));
+    WIMI_Ref_t* tempref = NULL;
+    WIMI_BinData_t ptLabel;
+    WIMI_BinData_t ptKeyID;
+    WIMI_BinData_t ptCAID;
+    WIMI_BinData_t ptIssuerHash;
+    WIMI_BinData_t ptTrustedUsage;
+    TUint8 uiCDFRefs;
+    TUint8 usage;
+    TUint8 type;
+    TUint16 certlen;
+    TUint8 modifiable = 0;
+    TBool found = ETrue;
+
+    WIMI_STAT callStatus = WIMI_GetCertificateInfo( 
+                                aCert,
+                                &tempref,
+                                &ptLabel,
+                                &ptKeyID, /* Key Id (hash)*/
+                                &ptCAID,
+                                &ptIssuerHash,
+                                &ptTrustedUsage,
+                                &uiCDFRefs,
+                                &usage,  /* 0 = client, 1 = CA */
+                                &type,   
+                                &certlen,   /* cert. content or URL length */
+                                &modifiable); 
+    if ( callStatus == WIMI_Ok )
+        {
+        free_WIMI_Ref_t( tempref );
+        WSL_OS_Free( ptLabel.pb_buf );
+        WSL_OS_Free( ptKeyID.pb_buf );
+        WSL_OS_Free( ptCAID.pb_buf );
+        WSL_OS_Free( ptIssuerHash.pb_buf );
+
+        CleanupPushWimBufL( ptTrustedUsage );
+
+        TPtrC8 undecodedUsage;
+        undecodedUsage.Set( ptTrustedUsage.pb_buf ); 
+
+        if ( ptTrustedUsage.ui_buf_length == 0 ) // No OIDs
+            {
+            found = EFalse;
+            }
+
+        // DECODE OIDs
+        TASN1DecObjectIdentifier decoder;
+        RPointerArray<HBufC> decodedOIDArray;
+        HBufC* decodedOIDs = NULL;
+        TInt oidsLength = 0;    // length of total OID buffer
+        TInt err;
+
+        for ( TInt position = 0; found; )   //Loop until no OIDs found anymore
+            {
+            if ( undecodedUsage.Length() > position ) //Don't go over buffer
+                {
+                TRAP( err, decodedOIDs = decoder.DecodeDERL( undecodedUsage, position ) );
+                if ( err == KErrNone ) //Found OID
+                    {
+                    CleanupStack::PushL( decodedOIDs );
+                    if ( decodedOIDs->Length() )
+                        {
+                        found = ETrue;
+                        decodedOIDArray.AppendL( decodedOIDs );
+                        oidsLength += decodedOIDs->Length();
+                        CleanupStack::Pop( decodedOIDs );
+                        }
+                    else    // Not found OID from buffer
+                        {
+                        found = EFalse;
+                        CleanupStack::PopAndDestroy( decodedOIDs );
+                        }
+                    decodedOIDs = NULL;
+                    }
+                else    // Error in OID parsing -> Not found OID
+                    {
+                    found = EFalse;
+                    }
+                }
+            else    // undecoded OID buffer seeked through
+                {
+                found = EFalse;
+                }
+            }
+
+        _LIT( KDelimeter16, " " ); //Delimeter between OIDs
+
+        if ( oidsLength > 0 ) // OID's found
+            {
+            // Add OID's to one buffer from separate buffers
+            for ( TInt i = 0; i < decodedOIDArray.Count(); i++ )
+                {
+                if ( i == 0 ) //First one
+                    {
+                    aCertExtrasInfo.iTrustedUsage->Copy( decodedOIDArray[i]->Des() );
+                    }
+                else // Append other OIDs, with delimeter
+                    {
+                    aCertExtrasInfo.iTrustedUsage->Append( KDelimeter16 );
+                    aCertExtrasInfo.iTrustedUsage->Append( decodedOIDArray[i]->Des() );
+                    }
+                }
+            }
+
+        aCertExtrasInfo.iCDFRefs = iWimUtilFuncs->MapCertLocation( uiCDFRefs );
+        
+        // Free the memory
+        decodedOIDArray.ResetAndDestroy();
+        CleanupStack::PopAndDestroy( ptTrustedUsage.pb_buf );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::GetCertificateFromWimRefL
+// Fetches certificate from the WIM card.
+// -----------------------------------------------------------------------------
+//
+WIMI_STAT CWimCertUtil::GetCertificateFromWimRefL(
+    WIMI_Ref_t* aTmpWimRef,
+    TInt8 aUsage,
+    TUint8& aCertNum,
+    TUint32* aCertRefLst,
+    TWimCertInfo* aCertInfoLst )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::GetCertificateFromWimRefL | Begin"));
+    TUint8 tempCrtCount;
+    WIMI_RefList_t refList ;
+    WIMI_STAT callStatus = WIMI_Ok;
+
+    if ( aTmpWimRef )
+        {
+        callStatus = WIMI_GetCertificateListByWIM( aTmpWimRef, 
+                                                   aUsage, 
+                                                   &tempCrtCount, 
+                                                   &refList );
+        if ( callStatus == WIMI_Ok )
+            {
+            for ( TUint8 certIndex = 0; certIndex < tempCrtCount; certIndex++ )
+                {
+                TInt current = aCertNum + certIndex;
+                _WIMTRACE2( _L( "CWimCertHandler::GetCertificateFromWimRefL, +ref 0x%08x" ),
+                        refList[certIndex] );
+                // transfers ownership of the refList item to aCertRefLst
+                aCertRefLst[current] = reinterpret_cast< TUint32 >( refList[certIndex] );
+                CopyCertificateInfo( aCertInfoLst[current], refList[certIndex] );
+                }
+            aCertNum = static_cast< TUint8 >( aCertNum + tempCrtCount );
+
+            // Because list items are moved to aCertRefLst, only refList array
+            // needs to be freed. Cannot use free_WIMI_RefList_t() as it would
+            // delete also items contained in refList.
+            WSL_OS_Free( refList );
+            }
+        }
+    return callStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertHandler::CopyCertificateInfo
+// Copies certificate information to client's allocated memory area.
+// -----------------------------------------------------------------------------
+//
+void CWimCertUtil::CopyCertificateInfo(
+    TWimCertInfo& aCertInfo,
+    WIMI_Ref_t* aCert )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimCertHandler::CopyCertificateInfoL | Begin"));
+
+    WIMI_Ref_t* tempRef = NULL;
+    WIMI_BinData_t ptLabel;
+    WIMI_BinData_t ptKeyID;
+    WIMI_BinData_t ptCAID;
+    WIMI_BinData_t ptIssuerHash;
+    WIMI_BinData_t ptTrustedUsage;
+    TUint8 uiCDFRefs;
+    TUint8 usage;
+    TUint8 type;
+    TUint16 certLen;
+    TUint8 modifiable = 0;
+    WIMI_STAT callStatus = WIMI_GetCertificateInfo( aCert,
+                                                    &tempRef,
+                                                    &ptLabel,
+                                                    &ptKeyID,
+                                                    &ptCAID,
+                                                    &ptIssuerHash,
+                                                    &ptTrustedUsage,
+                                                    &uiCDFRefs,
+                                                    &usage,
+                                                    &type,
+                                                    &certLen, 
+                                                    &modifiable );
+
+    if ( callStatus == WIMI_Ok )
+        {
+        free_WIMI_Ref_t( tempRef );
+
+        aCertInfo.iLabel.Copy( TPtr8( ptLabel.pb_buf,
+                ptLabel.ui_buf_length,
+                ptLabel.ui_buf_length ) );
+
+        aCertInfo.iKeyId.Copy( TPtr8( ptKeyID.pb_buf,
+                ptKeyID.ui_buf_length,
+                ptKeyID.ui_buf_length ) );
+        
+        aCertInfo.iCAId.Copy( TPtr8( ptCAID.pb_buf,
+                ptCAID.ui_buf_length,
+                ptCAID.ui_buf_length ) );
+        
+        aCertInfo.iIssuerHash.Copy( TPtr8( ptIssuerHash.pb_buf,
+                ptIssuerHash.ui_buf_length,
+                ptIssuerHash.ui_buf_length ) );
+
+        aCertInfo.iUsage = usage;
+        aCertInfo.iType = type;
+        aCertInfo.iCertlen = certLen;
+        aCertInfo.iModifiable = modifiable;
+        
+        // Certificate location
+        aCertInfo.iCDFRefs = iWimUtilFuncs->MapCertLocation( uiCDFRefs );
+
+        //Allocate enough memory for OID
+        aCertInfo.iTrustedUsageLength = ptTrustedUsage.ui_buf_length * 6;
+
+        WSL_OS_Free( ptLabel.pb_buf );
+        WSL_OS_Free( ptKeyID.pb_buf );
+        WSL_OS_Free( ptCAID.pb_buf );
+        WSL_OS_Free( ptIssuerHash.pb_buf );
+        WSL_OS_Free( ptTrustedUsage.pb_buf );
+        }
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimCleanup.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,24 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Cleanup functions
+*
+*/
+
+#include "WimCleanup.h"
+
+void FreeRefList( void* aRefList )
+    {
+    free_WIMI_RefList_t( static_cast< WIMI_RefList_t >( aRefList ) );
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimJavaProvisioning.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,484 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+
+// INCLUDE FILES
+#include    "WimJavaProvisioning.h"
+#include    "Wimi.h"                // WIMI
+#include    "WimClsv.h"
+#include    "WimUtilityFuncs.h"
+#include    "WimResponse.h"         // Callback response message
+#include    "WimTrace.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimJavaProvisioning::CWimJavaProvisioning
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimJavaProvisioning::CWimJavaProvisioning()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimJavaProvisioning::CWimJavaProvisioning | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaProvisioning::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimJavaProvisioning::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimJavaProvisioning::ConstructL | Begin"));
+    iWimUtilityFuncs = CWimUtilityFuncs::NewL();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaProvisioning::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimJavaProvisioning* CWimJavaProvisioning::NewL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimJavaProvisioning::NewL | Begin"));
+    CWimJavaProvisioning* self = new( ELeave ) CWimJavaProvisioning;
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+  
+// Destructor
+CWimJavaProvisioning::~CWimJavaProvisioning()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimJavaProvisioning::~CWimJavaProvisioning | Begin"));
+    delete iWimUtilityFuncs;
+    free_WIMI_Ref_t( iWimRef );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaProvisioning::ACIFFileSizeL
+// Get Java Provisioning file size
+// -----------------------------------------------------------------------------
+//
+void CWimJavaProvisioning::ACIFFileSizeL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimJavaProvisioning::ACIFFileSizeL | Begin"));
+
+    InitializePathsAndSizes();
+
+    TJavaProv javaProvisioning;
+    javaProvisioning.iSize = 0;
+    TPckgBuf<TJavaProv> javaFilePckg( javaProvisioning );
+
+    TInt ACIFfileSize = iACIFFileSize;
+    
+    
+    _WIMTRACE2(_L("WIM | WIMServer | CWimJavaProvisioning::ACIFFileSizeL | ACIFFileSize=%d"), ACIFfileSize);
+
+    javaFilePckg().iSize = ( TInt )ACIFfileSize;
+    aMessage.WriteL( 0, javaFilePckg );
+     
+    aMessage.Complete( KErrNone );
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CWimJavaProvisioning::ACFFileSizeL
+// Get ACF file size
+// -----------------------------------------------------------------------------
+//
+void CWimJavaProvisioning::ACFFileSizeL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimJavaProvisioning::ACFFileSizeL | Begin"));
+
+    //InitializePathsAndSizes();
+
+    TJavaProv javaProvisioning;
+    javaProvisioning.iSize = 0;
+    TPckgBuf<TJavaProv> javaFilePckg( javaProvisioning );
+
+    aMessage.ReadL( 2, iPathACF );
+    
+    InitializeSize(); //iACFFileSize is updated;
+    
+    
+    _WIMTRACE2(_L("WIM | WIMServer | CWimJavaProvisioning::ACFFileSizeL | iACFFileSize=%d"), iACFFileSize);
+
+    javaFilePckg().iSize = ( TInt )iACFFileSize;
+    aMessage.WriteL( 0, javaFilePckg );
+     
+    aMessage.Complete( KErrNone );
+    }
+    
+// -----------------------------------------------------------------------------
+// CWimJavaProvisioning::ACIFFileContentL
+// Write content of ACIF file to client memory
+// -----------------------------------------------------------------------------
+//
+void CWimJavaProvisioning::ACIFFileContentL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimJavaProvisioning::ACIFFileContentL | Begin"));
+
+    TUint16 callStatus = KErrNone;
+    WIMI_BinData_t pt_path;
+    //TPtrC8 ACIFpathPtr;
+    WIMI_BinData_t fileContent;
+    
+    // Do initialization
+    InitializePathsAndSizes();
+
+    if ( !iWimRef || ( iPathACIF.Length() == 0 ) )
+        {
+        callStatus = WIMI_ERR_KeyNotFound; // Mapped to KErrNotFound
+        }
+
+    _WIMTRACE2(_L("WIM | WIMServer | CWimJavaProvisioning::ACIFFileContentL | iACFFileSize=%d"), iACFFileSize);
+
+    if ( callStatus == KErrNone )
+        {
+        pt_path.ui_buf_length = ( TUint16 )iPathACIF.Length();
+        pt_path.pb_buf = ( TUint8* )iPathACIF.Ptr();
+
+        
+        fileContent.pb_buf = NULL;
+        fileContent.ui_buf_length = 0;
+    
+       
+        //Get ACIF file
+        WIMI_STAT callStatus = WIMI_GetJAVAFile(iWimRef,
+                                                &pt_path,
+                                                &fileContent );
+        }
+
+    if ( callStatus == KErrNone )
+        {
+        TJavaProv javaProvisioning;
+        javaProvisioning.iSize = fileContent.ui_buf_length;
+        javaProvisioning.iJavaData = NULL; //The value will be reset in Client side
+        TPckgBuf<TJavaProv> javaFilePckg( javaProvisioning );
+       
+        TPtrC8 ACIFFileContentPtr( fileContent.pb_buf, fileContent.ui_buf_length );
+        TInt err = aMessage.Write( 1, ACIFFileContentPtr );
+        if( err )
+            {
+            WSL_OS_Free( fileContent.pb_buf );
+            User::Leave( err );
+            }
+        aMessage.Complete( KErrNone );
+        }
+    else
+        {
+        aMessage.Complete( CWimUtilityFuncs::MapWIMError( callStatus ) );	
+        }    
+        
+     WSL_OS_Free( fileContent.pb_buf ); // Deallocate file content buffer    
+    _WIMTRACE(_L("WIM | WIMServer | CWimJavaProvisioning::ACIFFileContentL | End"));
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimJavaProvisioning::ACFFileContentL
+// Write content of ACIF file to client memory
+// -----------------------------------------------------------------------------
+//
+void CWimJavaProvisioning::ACFFileContentL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimJavaProvisioning::ACFFileContentL | Begin"));
+
+    TUint16 callStatus = KErrNone;
+    WIMI_BinData_t pt_path;
+    WIMI_BinData_t fileContent;
+    
+    aMessage.ReadL( 2, iPathACF );
+    
+    if ( !iWimRef || ( iPathACF.Length() == 0 ) )
+        {
+        callStatus = WIMI_ERR_KeyNotFound; // Mapped to KErrNotFound
+        }
+
+    if ( callStatus == KErrNone )
+        {
+        pt_path.ui_buf_length = ( TUint16 )iPathACF.Length();
+        pt_path.pb_buf = ( TUint8* )iPathACF.Ptr();
+
+        fileContent.pb_buf = NULL;
+        fileContent.ui_buf_length = 0;
+    
+        //Get ACIF file
+        WIMI_STAT callStatus = WIMI_GetJAVAFile(iWimRef,
+                                                &pt_path,
+                                                &fileContent );
+        }
+
+    if ( callStatus == KErrNone )
+        {
+        TJavaProv javaProvisioning;
+        javaProvisioning.iSize = fileContent.ui_buf_length;
+        javaProvisioning.iJavaData = NULL; //The value will be reset in Client side
+        TPckgBuf<TJavaProv> javaFilePckg( javaProvisioning );
+       
+        TPtrC8 ACFFileContentPtr( fileContent.pb_buf, fileContent.ui_buf_length );
+        TInt err = aMessage.Write( 1, ACFFileContentPtr );
+        if( err )
+            {
+            WSL_OS_Free( fileContent.pb_buf );
+            User::Leave( err );
+            }
+        aMessage.Complete( KErrNone );
+        }
+    else
+        {
+        aMessage.Complete( CWimUtilityFuncs::MapWIMError( callStatus ) );	
+        }    
+        
+    WSL_OS_Free( fileContent.pb_buf ); // Deallocate file content buffer
+    _WIMTRACE(_L("WIM | WIMServer | CWimJavaProvisioning::ACFFileContentL | End"));
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimJavaProvisioning::LabelAndPath
+// -----------------------------------------------------------------------------
+//
+void CWimJavaProvisioning::LabelAndPath( const RMessage2& aMessage )
+   {
+   _WIMTRACE(_L("WIM | WIMServer | CWimJavaProvisioning::LabelAndPath | Begin"));
+
+    TUint16 callStatus = KErrNone;
+    
+    WIMI_BinData_t path;
+    WIMI_BinData_t label;
+    
+    if( iWimRef )
+        {
+        free_WIMI_Ref_t( iWimRef );
+        iWimRef = NULL;
+        }
+    iWimRef = WIMI_GetWIMRef( 0 );
+
+    if ( !iWimRef )
+        {
+        callStatus = WIMI_ERR_KeyNotFound; // Mapped to KErrNotFound
+        }
+
+    if ( callStatus == KErrNone )
+        {
+        path.pb_buf = NULL;
+        label.pb_buf = NULL;
+        
+        path.ui_buf_length = 0;
+        label.ui_buf_length = 0;
+    
+        //Get Path and label
+        callStatus = WIMI_GetLabelAndPath(iWimRef,
+                                          &path,
+                                          &label );
+        }
+
+    if ( callStatus == KErrNone )
+        {
+        TPtrC8 PathPtr( path.pb_buf, path.ui_buf_length );
+        TPtrC8 LabelPtr( label.pb_buf, label.ui_buf_length );
+        
+        TInt err = KErrNone; 
+        err = aMessage.Write( 0, LabelPtr );
+        if ( err != KErrNone )
+            {
+            aMessage.Complete( err );
+            return;	
+            }
+        	  
+        err = aMessage.Write( 1, PathPtr );
+        if ( err != KErrNone )
+            {
+            aMessage.Complete( err );
+            return;	
+            }
+
+        aMessage.Complete( KErrNone );
+        }
+    else
+        {
+        aMessage.Complete( CWimUtilityFuncs::MapWIMError( callStatus ) );	
+        }    
+          
+    _WIMTRACE(_L("WIM | WIMServer | CWimJavaProvisioning::OmaFileContentL | End"));	
+   }
+    
+    
+// -----------------------------------------------------------------------------
+// CWimJavaProvisioning::InitializePathsAndSizes
+// Initializes the path and size data members
+// -----------------------------------------------------------------------------
+//
+void CWimJavaProvisioning::InitializePathsAndSizes()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimJavaProvisioning::InitializePathsAndSizesL | Begin"));
+
+    // Do initialization only if initialization is not done
+    if ( !iFileInfosInitialized )
+        {
+        TUint16 callStatus = KErrNone;
+
+        TBuf8<KWimProvACIFFileOidLength> ACIFOid;
+        
+        ACIFOid.Copy( KWimProvACIFFileOID, KWimProvACIFFileOidLength );
+
+        TBuf8<KWimProvACIFFileOidLengthTaged> ACIFOidTaged;
+
+        ACIFOidTaged.Copy( KWimProvACIFFileOIDTaged,
+                                KWimProvACIFFileOidLengthTaged );
+        
+        WIMI_BinData_t path;
+        path.pb_buf = NULL;
+        path.ui_buf_length = 0;
+
+        WIMI_File_Info* fileInfos = NULL;
+
+        TUint16 fileCount = 0;
+
+        WIMI_BinData_t fileOid;
+        fileOid.pb_buf = NULL;
+        fileOid.ui_buf_length = 0;
+
+        // Get WIM reference, reader is always 0
+        if ( iWimRef )
+            {
+            free_WIMI_Ref_t( iWimRef );
+            iWimRef = NULL;
+            }
+        iWimRef = WIMI_GetWIMRef( 0 );
+
+        if ( !iWimRef )
+            {
+            callStatus = WIMI_ERR_BadReference;
+            }
+    
+        if ( callStatus == KErrNone )
+            {
+
+            // Get Java file info from Wimlib
+            callStatus = WIMI_JAVAFileInfo( iWimRef,
+                                           &fileInfos,
+                                           &fileCount );
+            }
+
+        if ( callStatus == KErrNone )
+            {
+            TBuf8<KWimJavaOidLengthTaged> oidBuf; // Buffer for OID
+
+            // Loop all file infos and safe path to each file
+            for ( TInt i = 0; i < fileCount; i++ )
+                {
+                // Get file OID from infos
+                fileOid.pb_buf = fileInfos[i].t_oid.pb_buf;
+                fileOid.ui_buf_length = fileInfos[i].t_oid.ui_buf_length;
+                oidBuf.FillZ();
+                oidBuf.Copy( fileOid.pb_buf, fileOid.ui_buf_length );
+
+                // File path
+                path.pb_buf = fileInfos[i].b_path.pb_buf;
+                path.ui_buf_length = fileInfos[i].b_path.ui_buf_length;
+
+                // Compare OIDs
+                if ( !oidBuf.Compare( ACIFOid ) 
+                    || !oidBuf.Compare( ACIFOidTaged ) ) // ACIF File
+                    {
+                    // Copy file path to member
+                    iPathACIF.Copy( path.pb_buf, path.ui_buf_length );
+                    
+                    // Set file size
+                    iACIFFileSize = fileInfos[i].ui_file_size;
+
+                    // Check if path is given but size not. If path exists and
+                    // size == 0 then parse size from fetched file
+                    if ( iPathACIF.Length() > 0 &&
+                         iACIFFileSize == 0 )
+                        {
+                        WIMI_BinData_t pt_path;
+
+                        WIMI_BinData_t fileContent;
+                        
+                        pt_path.ui_buf_length = ( TUint16 )iPathACIF.Length();
+                        pt_path.pb_buf = ( TUint8* )iPathACIF.Ptr();
+        
+                        fileContent.pb_buf = NULL;
+                        fileContent.ui_buf_length = 0;
+    
+                        //Get ACIF file
+                        WIMI_STAT callStatus = WIMI_GetJAVAFile(iWimRef,
+                                                                 &pt_path,      
+                                                                 &fileContent );
+                       iACIFFileSize = fileContent.ui_buf_length;
+                       }
+                    }
+                
+                }
+            }
+        iFileInfosInitialized = ETrue;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimJavaProvisioning::InitializeSizes
+// Initializes the path and size data members
+// -----------------------------------------------------------------------------
+//
+void CWimJavaProvisioning::InitializeSize()
+   {
+     _WIMTRACE(_L("WIM | WIMServer | CWimJavaProvisioning::InitializeSizesL | Begin"));
+
+    // Do initialization only if initialization is not done
+
+    if ( iPathACF.Length() > 0 )
+       {
+       WIMI_BinData_t pt_path;
+
+       WIMI_BinData_t fileContent;
+
+       // Get WIM reference, reader is always 0
+       if ( iWimRef )
+           {
+           free_WIMI_Ref_t( iWimRef );
+           iWimRef = NULL;
+           }
+       iWimRef = WIMI_GetWIMRef( 0 );
+                        
+       pt_path.ui_buf_length = ( TUint16 )iPathACF.Length();
+       pt_path.pb_buf = ( TUint8* )iPathACF.Ptr();
+        
+       fileContent.pb_buf = NULL;
+       fileContent.ui_buf_length = 0;
+    
+       //Get ACIF file
+       WIMI_STAT callStatus = WIMI_GetJAVAFile(iWimRef,
+                                               &pt_path,      
+                                               &fileContent );
+                                               
+       iACFFileSize = fileContent.ui_buf_length;                
+       }
+    else
+       {
+       iACFFileSize = 0;	
+       }         
+
+  }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimKeyMgmtHandler.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,201 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Key management services
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimKeyMgmtHandler.h"
+#include    "WimSession.h"
+#include    "WimConsts.h"
+#include    "WimMemMgmt.h"
+#include    "WimUtilityFuncs.h"
+#include    "WimTrace.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimKeyMgmtHandler::CWimKeyMgmtHandler
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimKeyMgmtHandler::CWimKeyMgmtHandler()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimKeyMgmtHandler::CWimKeyMgmtHandler | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyMgmtHandler::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyMgmtHandler::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimKeyMgmtHandler::ConstructL | Begin"));
+    iWimUtilFuncs = CWimUtilityFuncs::NewL();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyMgmtHandler::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimKeyMgmtHandler* CWimKeyMgmtHandler::NewL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimKeyMgmtHandler::NewL | Begin"));
+    CWimKeyMgmtHandler* self = new( ELeave ) CWimKeyMgmtHandler;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+    
+// Destructor
+CWimKeyMgmtHandler::~CWimKeyMgmtHandler()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimKeyMgmtHandler::~CWimKeyMgmtHandler | Begin"));
+    delete iWimUtilFuncs;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyMgmtHandler::DoesKeyExistL
+// Checks if the given key exists.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyMgmtHandler::DoesKeyExistL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimKeyMgmtHandler::DoesKeyExistL | Begin"));
+    HBufC8* buf = iWimUtilFuncs->DesLC( 0, aMessage );
+    TUint8* keyHash = const_cast<TUint8*>( buf->Des().Ptr() );
+    WIMI_Ref_t* tmpKeyRef = NULL;
+    WIMI_STAT status = WIMI_GetKeyByHash( keyHash, &tmpKeyRef );
+    if ( status == WIMI_Ok )
+        {
+        free_WIMI_Ref_t( tmpKeyRef );
+        }
+    CleanupStack::PopAndDestroy( buf );
+    aMessage.Complete( CWimUtilityFuncs::MapWIMError( status ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimKeyMgmtHandler::GetKeyDetailsL
+// Fetches the details of the given key.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyMgmtHandler::GetKeyDetailsL( const RMessage2& aMessage )
+    { 
+    _WIMTRACE(_L("WIM | WIMServer | CWimKeyMgmtHandler::GetKeyDetailsL | Begin"));
+    WIMI_Ref_t* pKeyRef = const_cast<WIMI_Ref_pt>( aMessage.Ptr0() );
+        
+    WIMI_Ref_t* pWimRef;    
+    TUint8 keyType;
+    TUint8 keyNumber;
+    TUint8 pinNumber;
+    TUint16 usage;
+    TUint16 key_length;
+    WIMI_BinData_t pt_label;
+    WIMI_BinData_t pt_keyid;
+
+    WIMI_STAT callStatus = WIMI_GetKeyInfo( pKeyRef,
+                                            &pWimRef,
+                                            NULL,
+                                            &keyType,
+                                            &keyNumber,
+                                            &pinNumber,
+                                            &usage,
+                                            &pt_keyid,
+                                            &pt_label,
+                                            &key_length );
+
+    if ( callStatus == WIMI_Ok )
+        {
+        // Code MAY NOT leave before pWimRef, pt_keyid.pb_buf, and
+        // pt_label.pb_buf are deallocated.
+
+        free_WIMI_Ref_t( pWimRef );
+
+        TPckgBuf<TKeyInfo> keyInfoPckg;
+        TInt readErr = aMessage.Read( 1, keyInfoPckg );
+        if( readErr )
+            {
+            WSL_OS_Free( pt_label.pb_buf );
+            WSL_OS_Free( pt_keyid.pb_buf );
+            // Code can leave after this point.
+            User::Leave( readErr );
+            }
+
+        keyInfoPckg().iLabel.Copy( TPtr8(
+                pt_label.pb_buf, pt_label.ui_buf_length,
+                pt_label.ui_buf_length ) );
+
+        keyInfoPckg().iKeyId.Copy( TPtr8(
+                pt_keyid.pb_buf, pt_keyid.ui_buf_length,
+                pt_keyid.ui_buf_length ) );
+
+        keyInfoPckg().iType = keyType;
+        keyInfoPckg().iUsage = usage;
+        keyInfoPckg().iLength = key_length;
+        keyInfoPckg().iKeyNumber = keyNumber;
+        keyInfoPckg().iPinNumber = pinNumber;
+
+        WSL_OS_Free( pt_label.pb_buf );
+        WSL_OS_Free( pt_keyid.pb_buf );
+        // Code can leave after this point.
+
+        aMessage.WriteL( 1, keyInfoPckg );
+        }
+    aMessage.Complete( CWimUtilityFuncs::MapWIMError( callStatus ) );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimKeyMgmtHandler::GetKeyListL
+// Fetches the list of keys in a Wim.
+// -----------------------------------------------------------------------------
+//
+void CWimKeyMgmtHandler::GetKeyListL(
+    const RMessage2& aMessage,
+    CWimMemMgmt* aWimMgmt ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimKeyMgmtHandler::GetKeyListL | Begin"));
+    HBufC8* keyInfo = HBufC8::NewLC( KLabelLen );
+    TPtr8 ptr = keyInfo->Des();
+
+    WIMI_STAT status;
+    WIMI_Ref_t* wimRef = aWimMgmt->WimRef();
+    TUint16 keyNum = 0;
+    WIMI_RefList_t refList;
+
+    status = WIMI_GetKeyListByWIM( wimRef, &keyNum, &refList );
+    if ( status == WIMI_Ok )
+        {
+        for ( TUint8 keyIndex = 0; keyIndex < keyNum; keyIndex++ )
+            {
+            ptr.AppendNum( ( TInt32 ) refList[keyIndex], EDecimal );
+            ptr.Append( _L8(" ") ); //Space character
+            }
+        aWimMgmt->AppendWIMRefLstL( refList );
+        }
+    aMessage.WriteL( 0, keyInfo->Des() );
+    TPckg<TInt> pckg( keyNum );
+    aMessage.WriteL( 1, pckg );
+    CleanupStack::PopAndDestroy( keyInfo );
+    aMessage.Complete( CWimUtilityFuncs::MapWIMError( status ) );
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimMemMgmt.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,252 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Memory management function for WimServer to handle WIMI memory
+*
+*/
+
+
+// INCLUDE FILES
+#include    "WimMemMgmt.h"
+#include    "Wimi.h"        // WIMI definitions
+#include    "WimConsts.h"
+#include    "WimTrace.h"
+#include    "WimCleanup.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimMemMgmt::CWimMemMgmt
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimMemMgmt::CWimMemMgmt()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimMemMgmt::CWimMemMgmt | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimMemMgmt::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimMemMgmt::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimMemMgmt::ConstructL | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimMemMgmt::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimMemMgmt* CWimMemMgmt::NewL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimMemMgmt::NewL | Begin"));
+    CWimMemMgmt* self = new( ELeave ) CWimMemMgmt;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+    
+// Destructor
+CWimMemMgmt::~CWimMemMgmt()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimMemMgmt::~CWimMemMgmt | Begin"));
+
+    TInt refsCount = iRefs.Count();
+    for( TInt index = 0; index < refsCount; ++index )
+        {
+        TWimiAllocRef* allocRef = iRefs[ index ];
+        if( allocRef )
+            {
+            if( allocRef->refType == EWimiRefpt )
+                {
+                _WIMTRACE2(_L("WIM | WIMServer | CWimMemMgmt::~CWimMemMgmt | -ref 0x%08x"), allocRef->ref);
+                free_WIMI_Ref_t( allocRef->ref );
+                }
+            else
+                {
+                _WIMTRACE2(_L("WIM | WIMServer | CWimMemMgmt::~CWimMemMgmt | -refLst 0x%08x"), allocRef->refLst);
+                free_WIMI_RefList_t( allocRef->refLst );
+                }
+            }
+        }
+    iRefs.ResetAndDestroy();
+
+    if( iWimRef )
+        {
+        _WIMTRACE2(_L("WIM | WIMServer | CWimMemMgmt::~CWimMemMgmt, -ref 0x%08x"), iWimRef);
+        free_WIMI_Ref_t( iWimRef );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimMemMgmt::SetWIMRef
+// Sets active memory reference to iWimRef member variable.
+// -----------------------------------------------------------------------------
+//
+void CWimMemMgmt::SetWIMRef( WIMI_Ref_pt aWimRef )
+    {
+    __ASSERT_DEBUG( iWimRef == NULL, User::Invariant() );
+    _WIMTRACE2(_L("WIM | WIMServer | CWimMemMgmt::SetWIMRef, +ref 0x%08x"), aWimRef);
+    iWimRef = aWimRef;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimMemMgmt::GetWIMRef
+// Fetches active reference.
+// -----------------------------------------------------------------------------
+//
+WIMI_Ref_pt CWimMemMgmt::WimRef()
+    {
+    _WIMTRACE2(_L("WIM | WIMServer | CWimMemMgmt::GetWIMRef, iWimRef 0x%08x"), iWimRef);
+    return iWimRef;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimMemMgmt::AppendWIMRefLstL
+// Creates and appends a new WIMI_Alloc_Ref item to iRefs array.
+// -----------------------------------------------------------------------------
+//
+void CWimMemMgmt::AppendWIMRefLstL( WIMI_RefList_t aRefLst )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimMemMgmt::AppendWIMRefLstL | Begin"));
+    CleanupPushWimRefListL( aRefLst ); // take ownership first
+    TWimiAllocRef* allocRef = new( ELeave ) TWimiAllocRef;
+    CleanupStack::PushL( allocRef );
+    allocRef->refLst = aRefLst;
+    allocRef->refType = EWimiRefListt;
+    iRefs.AppendL( allocRef );
+    _WIMTRACE2(_L("WIM | WIMServer | CWimMemMgmt::AppendWIMRefLstL, +refLst 0x%08x"), aRefLst);
+    CleanupStack::Pop( 2, aRefLst );    // allocRef, aRefLst
+    }
+
+// -----------------------------------------------------------------------------
+// CWimMemMgmt::AppendWIMRefL
+// Creates and appends a new WIMI_Alloc_Ref item to iRefs array.
+// -----------------------------------------------------------------------------
+//
+void CWimMemMgmt::AppendWIMRefL( WIMI_Ref_pt aRef )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimMemMgmt::AppendWIMRefL | Begin"));
+    CleanupPushWimRefL( aRef );    // take ownership first
+    TWimiAllocRef* allocRef = new( ELeave ) TWimiAllocRef;
+    CleanupStack::PushL( allocRef );
+    allocRef->ref = aRef;
+    allocRef->refType = EWimiRefpt;
+    iRefs.AppendL( allocRef );
+    _WIMTRACE2(_L("WIM | WIMServer | CWimMemMgmt::AppendWIMRefL, +ref 0x%08x"), aRef);
+    CleanupStack::Pop( 2, aRef );   // allocRef, aRef
+    }
+
+// -----------------------------------------------------------------------------
+// CWimMemMgmt::FreeRef
+// Removes reference from the list and releases allocated memory.
+// -----------------------------------------------------------------------------
+//
+void CWimMemMgmt::FreeRef( WIMI_Ref_pt aRef )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimMemMgmt::FreeRef | Begin"));
+    TInt count = iRefs.Count();
+    for( TInt index = 0; index < count; index++ )
+        {
+        TWimiAllocRef* allocRef = iRefs[ index ];
+        if ( allocRef && ( allocRef->ref == aRef ) && ( allocRef->refType == EWimiRefpt ) )
+            {
+			_WIMTRACE2(_L("WIM | WIMServer | CWimMemMgmt::FreeRef, -ref 0x%08x"), aRef);
+            iRefs.Remove( index );
+            iRefs.Compress();
+            free_WIMI_Ref_t( aRef );
+            delete allocRef;
+            break;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimMemMgmt::FreeWIMRefs
+// Frees the reference(s) pointed by a client.
+// -----------------------------------------------------------------------------
+//
+void CWimMemMgmt::FreeWIMRefs( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimMemMgmt::FreeWIMRefsL | Begin"));
+    TUint wimCount = aMessage.Int1(); 
+    WIMI_Ref_pt ref = reinterpret_cast< WIMI_Ref_pt >( aMessage.Int0() );
+    _WIMTRACE3(_L("WIM | WIMServer | CWimMemMgmt::FreeWIMRefsL | ref 0x%08x, wimCount %d"),
+            ref, wimCount);
+
+    for( TUint8 wimIndex = 0; wimIndex < wimCount; wimIndex++ )
+        {
+        _WIMTRACE2(_L("WIM | WIMServer | CWimMemMgmt::FreeWIMRefsL | index=%d"), wimIndex);
+        FreeRef( ref );     // TODO: fix, now deallocating the same ref in each loop?
+        }
+
+    _WIMTRACE(_L("WIM | WIMServer | CWimMemMgmt::FreeWIMRefsL | End"));
+    aMessage.Complete( KErrNone );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimMemMgmt::FreeRefLst
+// Frees the list of reference(s) pointed by a client.
+// -----------------------------------------------------------------------------
+//
+void CWimMemMgmt::FreeRefLst( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimMemMgmt::FreeRefLst | Begin"));
+    WIMI_Ref_pt* refList = ( WIMI_Ref_pt* )aMessage.Int0();
+    TInt count = iRefs.Count();
+    for( TUint8 index = 0; index < count; index++ )
+        {
+        TWimiAllocRef* allocRef = iRefs[ index ];
+        if ( allocRef && ( allocRef->refLst == refList ) && ( allocRef->refType == EWimiRefListt ))
+            {
+            _WIMTRACE2(_L("WIM | WIMServer | CWimMemMgmt::FreeRefLst, -refList 0x%08x"), refList);
+            iRefs.Remove( index );
+            iRefs.Compress();
+            free_WIMI_RefList_t( refList );
+            delete allocRef;
+            aMessage.Complete( KErrNone );
+            return;
+            }
+        }
+    _WIMTRACE(_L("WIM | WIMServer | CWimMemMgmt::FreeRefLst | not found") );
+    aMessage.Complete( KErrNotFound );              
+    }
+
+// -----------------------------------------------------------------------------
+// CWimMemMgmt::ValidateWIMRefL
+// -----------------------------------------------------------------------------
+//
+TBool CWimMemMgmt::ValidateWIMRefL( WIMI_Ref_pt aRef )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimMemMgmt::ValidateWIMRefL | Begin"));
+    TInt count = iRefs.Count();
+    for( TUint8 index = 0; index < count; index++ )
+        {
+        TWimiAllocRef* allocRef = iRefs[ index ];
+        if( allocRef->ref == aRef )
+            {
+            _WIMTRACE(_L("WIM | WIMServer | CWimMemMgmt::ValidateWIMRefL, valid"));
+            return ETrue;
+            }
+        }
+    _WIMTRACE(_L("WIM | WIMServer | CWimMemMgmt::ValidateWIMRefL, invalid"));
+    return EFalse;
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimOmaProvisioning.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,480 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  WIM OMA Provisioning functionality. Reads OMA Provisioning
+*               documents from Smart Card.
+*
+*/
+
+
+// INCLUDE FILES
+#include    "WimOmaProvisioning.h"
+#include    "Wimi.h"                // WIMI
+#include    "WimClsv.h"
+#include    "WimUtilityFuncs.h"
+#include    "WimResponse.h"         // Callback response message
+#include    "WimTrace.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimOmaProvisioning::CWimOmaProvisioning
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimOmaProvisioning::CWimOmaProvisioning()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimOmaProvisioning::CWimOmaProvisioning | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOmaProvisioning::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimOmaProvisioning::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimOmaProvisioning::ConstructL | Begin"));
+    iWimUtilityFuncs = CWimUtilityFuncs::NewL();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOmaProvisioning::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimOmaProvisioning* CWimOmaProvisioning::NewL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimOmaProvisioning::NewL | Begin"));
+    CWimOmaProvisioning* self = new( ELeave ) CWimOmaProvisioning;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+  
+// Destructor
+CWimOmaProvisioning::~CWimOmaProvisioning()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimOmaProvisioning::~CWimOmaProvisioning | Begin"));
+    delete iWimUtilityFuncs;
+    free_WIMI_Ref_t( iWimRef );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOmaProvisioning::OmaFileSizeL
+// Get OMA Provisioning file size
+// -----------------------------------------------------------------------------
+//
+void CWimOmaProvisioning::OmaFileSizeL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimOmaProvisioning::OmaFileSizeL | Begin"));
+
+    InitializePathsAndSizes();
+
+    TOmaProv omaProvisioning;
+    omaProvisioning.iSize = 0;
+    TPckgBuf<TOmaProv> omaFilePckg( omaProvisioning );
+    aMessage.ReadL( 0, omaFilePckg );
+
+    TInt fileSize = 0;
+    TInt err = KErrNone;
+
+    switch ( omaFilePckg().iOmaType )
+        {
+        case EBootStrap:
+            {
+            fileSize = iBootstrapFileSize;
+            break;
+            }
+        
+        case EConfig1:
+            {
+            fileSize = iConfig1FileSize;
+            break;
+            }
+        
+        case EConfig2:
+            {
+            fileSize = iConfig2FileSize;
+            break;
+            }
+        
+        default:
+            {
+            err = KErrArgument;
+            break;
+            }
+        }
+
+    _WIMTRACE3(_L("WIM | WIMServer | CWimOmaProvisioning::OmaFileSizeL | FileType=%d, FileSize=%d"), omaFilePckg().iOmaType, fileSize);
+
+    if ( err == KErrNone )
+        {
+        omaFilePckg().iSize = ( TInt )fileSize;
+        aMessage.WriteL( 0, omaFilePckg );
+        }
+    aMessage.Complete( err );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOmaProvisioning::OmaFileContentL
+// Write content of OMA provisioning file to client memory
+// -----------------------------------------------------------------------------
+//
+void CWimOmaProvisioning::OmaFileContentL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimOmaProvisioning::OmaFileContentL | Begin"));
+
+    TUint16 callStatus = KErrNone;
+    WIMI_BinData_t pt_path;
+    WIMI_BinData_t fileContent;
+    TUint16 fileSize = 0;
+    TPtrC8 path;
+
+    // Do initialization
+    InitializePathsAndSizes();
+
+    TOmaProv omaProvisioning;
+    omaProvisioning.iSize = 0;
+    TPckgBuf<TOmaProv> omaFilePckg( omaProvisioning );
+    aMessage.ReadL( 0, omaFilePckg );
+
+    if ( !iWimRef )
+        {
+        callStatus = WIMI_ERR_KeyNotFound; // Mapped to KErrNotFound
+        }
+
+    if ( callStatus == KErrNone )
+        {
+        switch ( omaFilePckg().iOmaType )
+            {
+            case EBootStrap:
+                {
+                path.Set( iPathBootstrap.Ptr() );
+                fileSize = ( TUint16 )iBootstrapFileSize;
+                break;
+                }
+        
+            case EConfig1:
+                {
+                path.Set( iPathConfig1.Ptr() );
+                fileSize = ( TUint16 )iConfig1FileSize;
+                break;
+                }
+        
+            case EConfig2:
+                {
+                path.Set( iPathConfig2.Ptr() );
+                fileSize = ( TUint16 )iConfig2FileSize;
+                break;
+                }
+        
+            default:
+                {
+                callStatus = WIMI_ERR_BadParameters;
+                break;
+                }
+            }
+        }
+
+    if ( callStatus == KErrNone )
+        {
+        if ( path.Length() == 0 )
+            {
+            callStatus = WIMI_ERR_KeyNotFound; // Mapped to KErrNotFound
+            }
+        }
+
+    _WIMTRACE3(_L("WIM | WIMServer | CWimOmaProvisioning::OmaFileContentL | FileType=%d, FileSize=%d"), omaFilePckg().iOmaType, fileSize);
+
+    if ( callStatus == KErrNone )
+        {
+        pt_path.ui_buf_length = ( TUint16 )path.Length();
+        pt_path.pb_buf = ( TUint8* )path.Ptr();
+
+        WIMI_TransactId_t trId = ( void* )EOMAProvContentSync;
+
+        fileContent.pb_buf = NULL;
+        fileContent.ui_buf_length = 0;
+        // Get OMA Provisioning file from card
+        callStatus = WIMI_GetOMAFileSync( trId,
+                                          iWimRef,
+                                          &pt_path,
+                                          0,
+                                          &fileContent );
+                                          
+        if ( callStatus == KErrNone )
+            {
+            //Use filesize here, should be equal or smaller than fileContent.ui_length
+            TPtrC8 omaFilePtr( fileContent.pb_buf, fileSize );
+            TInt err = aMessage.Write( 1, omaFilePtr );
+            if( err )
+                {
+                WSL_OS_Free( fileContent.pb_buf );
+                User::Leave( err );
+                }
+            aMessage.Complete( KErrNone );
+            }
+        else
+            {
+            aMessage.Complete( CWimUtilityFuncs::MapWIMError( callStatus ) );	
+            }    
+        
+        WSL_OS_Free( fileContent.pb_buf ); // Deallocate file content buffer                                     
+        }
+      
+    _WIMTRACE(_L("WIM | WIMServer | CWimOmaProvisioning::OmaFileContentL | End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOmaProvisioning::InitializePathsAndSizes
+// Initializes the path and size data members
+// -----------------------------------------------------------------------------
+//
+void CWimOmaProvisioning::InitializePathsAndSizes()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimOmaProvisioning::InitializePathsAndSizesL | Begin"));
+
+    // Do initialization only if initialization is not done
+    if ( !iFileInfosInitialized )
+        {
+        TUint16 callStatus = KErrNone;
+
+        TBuf8<KWimProvFileOidLength> bootstrapOid;
+        TBuf8<KWimProvFileOidLength> config1Oid;
+        TBuf8<KWimProvFileOidLength> config2Oid;
+
+        bootstrapOid.Copy( KWimProvBootstrapFileOID, KWimProvFileOidLength );
+        config1Oid.Copy( KWimProvConfig1FileOID, KWimProvFileOidLength );
+        config2Oid.Copy( KWimProvConfig2FileOID, KWimProvFileOidLength );
+
+        TBuf8<KWimProvFileOidLengthTaged> bootstrapOidTaged;
+        TBuf8<KWimProvFileOidLengthTaged> config1OidTaged;
+        TBuf8<KWimProvFileOidLengthTaged> config2OidTaged;
+
+        bootstrapOidTaged.Copy( KWimProvBootstrapFileOIDTaged,
+                                KWimProvFileOidLengthTaged );
+        config1OidTaged.Copy( KWimProvConfig1FileOIDTaged,
+                              KWimProvFileOidLengthTaged );
+        config2OidTaged.Copy( KWimProvConfig2FileOIDTaged,
+                              KWimProvFileOidLengthTaged );
+        
+        WIMI_BinData_t path;
+        path.pb_buf = NULL;
+        path.ui_buf_length = 0;
+
+        WIMI_File_Info* fileInfos = NULL;
+
+        TUint16 fileCount = 0;
+
+        WIMI_BinData_t fileOid;
+        fileOid.pb_buf = NULL;
+        fileOid.ui_buf_length = 0;
+
+        // Get WIM reference, reader is always 0
+        iWimRef = WIMI_GetWIMRef( 0 );
+
+        if ( !iWimRef )
+            {
+            callStatus = WIMI_ERR_BadReference;
+            }
+    
+        if ( callStatus == KErrNone )
+            {
+
+            // Get OMA file info from Wimlib
+            callStatus = WIMI_OMAFileInfo( iWimRef,
+                                           &fileInfos,
+                                           &fileCount );
+            }
+
+        if ( callStatus == KErrNone )
+            {
+            TBuf8<KWimOidLengthTaged> oidBuf; // Buffer for OID
+
+            // Loop all file infos and safe path to each file
+            for ( TInt i = 0; i < fileCount; i++ )
+                {
+                // Get file OID from infos
+                fileOid.pb_buf = fileInfos[i].t_oid.pb_buf;
+                fileOid.ui_buf_length = fileInfos[i].t_oid.ui_buf_length;
+                oidBuf.Copy( fileOid.pb_buf, fileOid.ui_buf_length );
+
+                // File path
+                path.pb_buf = fileInfos[i].b_path.pb_buf;
+                path.ui_buf_length = fileInfos[i].b_path.ui_buf_length;
+
+                // Compare OIDs
+                if ( !oidBuf.Compare( bootstrapOid ) 
+                    || !oidBuf.Compare( bootstrapOidTaged ) ) // Bootstrap File
+                    {
+                    // Copy file path to member
+                    iPathBootstrap.Copy( path.pb_buf, path.ui_buf_length );
+                    // Set file size
+                    iBootstrapFileSize = fileInfos[i].ui_file_size;
+
+                    // Check if path is given but size not. If path exists and
+                    // size == 0 then parse size from fetched file
+                    if ( iPathBootstrap.Length() > 0 &&
+                         iBootstrapFileSize == 0 )
+                        {
+                        ParseFileSize( EBootStrap );
+                        }
+                    }
+                else if ( !oidBuf.Compare( config1Oid ) 
+                    || !oidBuf.Compare( config1OidTaged ) ) // Config1 File
+                    {
+                    // Copy file path to member
+                    iPathConfig1.Copy( path.pb_buf, path.ui_buf_length );
+                    // Set file size
+                    iConfig1FileSize = fileInfos[i].ui_file_size;
+
+                    // Check if path is given but size not. If path exists and
+                    // size == 0 then parse size from fetched file
+                    if ( iPathConfig1.Length() > 0 && iConfig1FileSize == 0 )
+                        {
+                        ParseFileSize( EConfig1 );
+                        }
+                    }
+                else if ( !oidBuf.Compare( config2Oid )
+                    || !oidBuf.Compare( config2OidTaged ) ) // Config2 File
+                    {
+                    // Copy file path to member
+                    iPathConfig2.Copy( path.pb_buf, path.ui_buf_length );
+                    // Set file size
+                    iConfig2FileSize = fileInfos[i].ui_file_size;
+
+                    // Check if path is given but size not. If path exists and
+                    // size == 0 then parse size from fetched file
+                    if ( iPathConfig2.Length() > 0 && iConfig2FileSize == 0 )
+                        {
+                        ParseFileSize( EConfig2 );
+                        }
+                    }
+                }
+            }
+        iFileInfosInitialized = ETrue;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimOmaProvisioning::ParseFileSize
+// Get content of file and parse size of it. For WIM size is mandatory in 
+// DODF-PROV file but for SIM implementation it is not mandatory.
+// -----------------------------------------------------------------------------
+//
+void CWimOmaProvisioning::ParseFileSize( TOMAType aOmaType )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimOmaProvisioning::ParseFileSize | Begin"));
+    WIMI_BinData_t path;
+    WIMI_BinData_t fileContent;
+    TInt fileSize;
+    TPtrC8 pathPtr;
+
+    // Set path to file
+    switch ( aOmaType )
+        {
+        case EBootStrap:
+            {
+            pathPtr.Set( iPathBootstrap.Ptr() );
+            break;
+            }
+        
+        case EConfig1:
+            {
+            pathPtr.Set( iPathConfig1.Ptr() );
+            break;
+            }
+        
+        case EConfig2:
+            {
+            pathPtr.Set( iPathConfig2.Ptr() );
+            break;
+            }
+        
+        default:
+            {
+            return;
+            }
+        }
+
+    path.ui_buf_length = ( TUint16 )pathPtr.Length();
+    path.pb_buf = ( TUint8* )pathPtr.Ptr();
+
+    
+    WIMI_TransactId_t trId = ( void* )EOMAProvContentSync;
+
+    TPtr8 contentPtr = TPtr8( NULL, 0, 0 );
+
+    fileContent.pb_buf = NULL;
+    fileContent.ui_buf_length = 0;
+    // Get OMA Provisioning file from card
+    WIMI_STAT callStatus = WIMI_GetOMAFileSync( trId,
+                                                iWimRef,
+                                                &path,
+                                                0,
+                                                &fileContent );
+
+    if ( callStatus != KErrNone )
+        {
+        fileSize = 0;
+        }
+    else
+        {
+        contentPtr.Set( fileContent.pb_buf,
+                        fileContent.ui_buf_length, 
+                        fileContent.ui_buf_length );
+
+        fileSize = fileContent.ui_buf_length;
+        }
+
+    // Set file size
+    switch ( aOmaType )
+        {
+        case EBootStrap:
+            {
+            iBootstrapFileSize = fileSize;
+            _WIMTRACE2( _L("WIM | WIMServer | CWimOmaProvisioning::ParseFileSize | Bootstrap size=%d"),
+                        fileSize );
+            break;
+            }
+        
+        case EConfig1:
+            {
+            iConfig1FileSize = fileSize;
+            _WIMTRACE2( _L("WIM | WIMServer | CWimOmaProvisioning::ParseFileSize | Config1 size=%d"),
+                        fileSize );
+            break;
+            }
+        
+        case EConfig2:
+            {
+            iConfig2FileSize = fileSize;
+            _WIMTRACE2( _L("WIM | WIMServer | CWimOmaProvisioning::ParseFileSize | Config2 size=%d"),
+                        fileSize );
+            break;
+            }
+        
+        default:
+            {
+            break;
+            }
+        }
+
+    WSL_OS_Free( fileContent.pb_buf ); // Deallocate file content buffer
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimResponse.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,69 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  WIM Response functions. Complete messages from client.
+*
+*/
+
+
+// INCLUDE FILES
+#include    "WimResponse.h"
+#include    "WimUtilityFuncs.h"
+#include    "WimTrace.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimResponse::CWimResponse( RMessage2 aMessage )
+    : iMessage( aMessage ),
+      iStatus( WIMI_ERR_Internal ),
+      iError( 0 )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimResponse::CWimResponse | Begin"));
+    }
+
+// Destructor
+CWimResponse::~CWimResponse()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimResponse::~CWimResponse | Begin"));
+    if( !iMessage.IsNull() )
+        {
+        if( iError ) // Check if any intenal error
+            {
+            iMessage.Complete( iError );
+            }
+        else
+            {
+            // Set the status of the WIM Call
+            iMessage.Complete( CWimUtilityFuncs::MapWIMError( iStatus ) );
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimResponse::CompleteMsgAndDelete
+// Delete message. Message is completed in destructor so just delete response.
+// -----------------------------------------------------------------------------
+//
+void CWimResponse::CompleteMsgAndDelete()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimResponse::CompleteMsgAndDelete | Begin"));
+    delete this;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimSatRefreshObserver.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,192 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observes 'SIM file changed' events from SAT. If changed file
+*               is WIM related, WimiLib's cache is cleared and WimiLib closed.
+*               Prevents WIM from operating with out-dated cache.
+*
+*/
+
+
+// INCLUDE FILES
+#include "WimSatRefreshObserver.h"
+#include "WimServer.h"
+#include "WimSession.h"
+#include "WimTrace.h"
+#include <RSatRefresh.h>
+#include <RSatSession.h>
+#include <etelsat.h>
+#if defined SAT_REFRESH_TIMER_TRIGGER
+#include "SatRefreshTimerTrigger.h" // for simulated sat refresh
+#endif
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimSatRefreshObserver::CWimSatRefreshObserver
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimSatRefreshObserver::CWimSatRefreshObserver()
+    {
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver | C'tor"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSatRefreshObserver::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimSatRefreshObserver::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver::ConstructL | Begin"));
+
+    iWimSvr = CWimServer::Server();
+
+#if defined SAT_REFRESH_TIMER_TRIGGER
+    // simulate SAT file changed events
+    iTimerTrigger = CSatRefreshTimerTrigger::NewL( this );
+    iTimerTrigger->Start();
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver::ConstructL | Using timer triggered SAT refresh."));
+#else
+    // real implementation
+    iRefreshClient = new( ELeave ) RSatRefresh( *this );
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver::ConstructL | iRefreshClient"));
+    iSatSession = new( ELeave ) RSatSession;
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver::ConstructL | iSatSession"));
+    iSatSession->ConnectL();
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver::ConstructL | ConnectL"));
+    iRefreshClient->OpenL( *iSatSession );
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver::ConstructL | OpenL"));
+    iRefreshClient->NotifyFileChangeL(); // start receiving notifications
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver::ConstructL | NotifyFileChangeL"));
+#endif // SAT_REFRESH_TIMER_TRIGGER
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver::ConstructL | End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSatRefreshObserver::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimSatRefreshObserver* CWimSatRefreshObserver::NewL()
+    {
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver::NewL | Begin"));
+    CWimSatRefreshObserver* self = new( ELeave ) CWimSatRefreshObserver();
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver::NewL | End"));
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimSatRefreshObserver::~CWimSatRefreshObserver
+// Destructor.
+// -----------------------------------------------------------------------------
+//
+CWimSatRefreshObserver::~CWimSatRefreshObserver()
+    {
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver | D'tor"));
+    if ( iRefreshClient )
+        {
+        iRefreshClient->Close();
+        delete iRefreshClient;
+        }
+    if ( iSatSession )
+        {
+        iSatSession->Close();
+        delete iSatSession;
+        }
+#if defined SAT_REFRESH_TIMER_TRIGGER
+    if ( iTimerTrigger )
+        {
+        delete iTimerTrigger;
+        }
+#endif
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimSatRefreshObserver::AllowRefresh
+// Query from SAT: Is it OK to refresh files on SIM.
+// -----------------------------------------------------------------------------
+//
+TBool CWimSatRefreshObserver::AllowRefresh( TSatRefreshType /*aType*/,
+                                            const TSatRefreshFiles& /*aFiles*/ )
+    {
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver::AllowRefresh | Begin"));
+
+    TBool allowRefresh( ETrue ); // allow by default
+    
+    if ( iWimSvr->IsAccessingToken()) // check if we are accessing card
+        {
+        allowRefresh = EFalse; // deny if we are accessing card
+        }
+
+    _WIMTRACE2(_L("WIM | CWimSatRefreshObserver::AllowRefresh | End | allowRefresh=%d"), allowRefresh);
+    return allowRefresh;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSatRefreshObserver::Refresh
+// Notification of completed refresh event from SAT.
+//
+// -----------------------------------------------------------------------------
+//
+void CWimSatRefreshObserver::Refresh( TSatRefreshType /*aType*/,
+                                      const TSatRefreshFiles& /*aFiles*/ )
+    {
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver::Refresh | Begin"));
+
+    iRefreshClient->RefreshEFRead( EFalse );
+    // WIM is doing stg with the card -> postpone WIMI closing.
+    if ( iWimSvr->IsAccessingToken() )
+        {
+        // Tell server to re-initialize at earliest convenience.
+        iWimSvr->SetRefreshNotificationReceived( ETrue );
+        _WIMTRACE(_L("WIM | CWimSatRefreshObserver::Refresh | WIMI closing postponed."));
+        }
+    else if ( CWimServer::iWimInitialized )
+        {
+        // Wim initialized, can close WIMI immediately.
+        // NOTE: Is it ok to run lengthy operations here?
+        RArray<CWimSession*> sessions;
+        TRAPD( err, iWimSvr->GetSessionsL( sessions ) );
+
+        if ( !err )  // Got sessions correctly
+            {
+            // Loop through all sessions and notify all clients that are
+            // requesting the notification
+            for ( TInt i( 0 ); i < sessions.Count(); i++ )
+                {
+                sessions[i]->NotifyComplete();
+                }
+            sessions.Reset();
+            // Close WIMI
+            WIMI_CloseDownReq();
+            _WIMTRACE(_L("WIM | CWimSatRefreshObserver::Refresh | WIMI closed."));
+            }
+        }
+    else
+        {
+        _WIMTRACE(_L("WIM | CWimSatRefreshObserver::Refresh | WIMI already closed."));
+        }
+
+    _WIMTRACE(_L("WIM | CWimSatRefreshObserver::Refresh | End"));
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimScardListener.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,136 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Listens for smard card events
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "ScardBase.h"
+#include    "WimScardListener.h"
+#include    "WimServer.h"
+#include    "WimSession.h"
+#include    "WimTrace.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimScardListener::CWimScardListener( 
+    RScard* aScard,
+    TUint8 aUiReaderID,
+    const TScardReaderName& aName )
+    : CScardListener( aScard ),
+      iUiReaderID( aUiReaderID ),
+      iName( aName )
+      
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimScardListener::CWimScardListener | Begin"));
+    }
+
+// Destructor
+CWimScardListener::~CWimScardListener()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimScardListener::~CWimScardListener | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimScardListener::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimScardListener* CWimScardListener::NewL(
+    RScard* aScard,
+    TUint8 aUiReaderID,
+    const TScardReaderName& aName )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimScardListener::NewL | Begin"));
+    CWimScardListener* self = new( ELeave ) CWimScardListener( aScard,
+        aUiReaderID, aName );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimScardListener::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimScardListener::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimScardListener::ConstructL | Begin"));
+    User::LeaveIfError( ListenCardEvents( iName ) ); // Start listening events
+    iServer = CWimServer::Server();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimScardListener::ProcessEvent
+// Card has been inserted/removed. From this point you have to inform 
+// WIMI & client what has happened. 
+// -----------------------------------------------------------------------------
+//
+void CWimScardListener::ProcessEvent( const TScardServiceStatus aEvent )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimScardListener::ProcessEvent | Begin"));
+
+    switch ( aEvent )
+        {
+        case EScardInserted:
+            {
+             _WIMTRACE(_L("WIM | WIMServer | CWimScardListener::ProcessEvent Inserted"));
+            break;
+            }
+
+        case EScardRemoved:
+            {
+            _WIMTRACE(_L("WIM | WIMServer | CWimScardListener::ProcessEvent Removed"));
+            RArray<CWimSession*> sessions;
+            TRAPD( err, iServer->GetSessionsL( sessions ) );
+
+            if ( !err )  // Got sessions correctly
+                {
+                // Loop through all sessions and notify all clients that are
+                // requesting the notification
+                for ( TInt i( 0 ); i < sessions.Count(); i++ )
+                    {
+                    sessions[i]->NotifyComplete();
+                    }
+                sessions.Reset();
+                // Close WIMI
+                if( CWimServer::iWimInitialized )
+                    {
+                    WIMI_CloseDownReq();   
+                    }
+               CWimServer::SetWimInitialized( EFalse, KErrHardwareNotAvailable );
+                }
+            break;
+            }
+
+        default:
+            {
+            _WIMTRACE(_L("WIM | WIMServer | CWimScardListener::ProcessEvent Unexpected smart card event"));
+            break;
+            }
+        }
+    _WIMTRACE(_L("WIM | WIMServer | CWimScardListener::ProcessEvent | End"));
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimSecurityDlgHandler.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,351 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  WIM Security Dialog Handler. Calls WimSecDlgs to query PIN(s)
+*               from user.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimSecurityDlgHandler.h"
+#include    "WimTrace.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::CWimSecurityDlgHandler
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimSecurityDlgHandler::CWimSecurityDlgHandler()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::CWimSecurityDlgHandler | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimSecurityDlgHandler::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::ConstructL | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimSecurityDlgHandler* CWimSecurityDlgHandler::NewL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::NewL | Begin"));
+    CWimSecurityDlgHandler* self = new( ELeave ) CWimSecurityDlgHandler;
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CWimSecurityDlgHandler::~CWimSecurityDlgHandler()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::~CWimSecurityDlgHandler | Begin"));
+    if ( iSecurityDlg )
+        {
+        _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::~CWimSecurityDlgHandler | Release dialog"));
+        iSecurityDlg->Release();
+        _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::~CWimSecurityDlgHandler | Dialog released"));
+        }
+    /*if ( iPKIDlg )
+        {    
+        iPKIDlg->Release();
+        }*/
+    iLibrary.Close();
+    _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::~CWimSecurityDlgHandler | Library closed"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::EnablePIN
+// Shows a security dialog for fetching PIN value from the user for enabling or 
+// disabling PIN query.
+// -----------------------------------------------------------------------------
+//
+void CWimSecurityDlgHandler::EnablePIN(
+    TBool aEnable,
+    TBool aRetry, 
+    const TPINParams& aPINParams, 
+    TPINValue& aPINValue,
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::GetPINValue | Begin"));
+
+    // First try to load security dialog
+    TInt loadError = LoadSecurityDialog( aStatus );
+
+    if ( loadError == KErrNone ) // Dialog loaded succesfully
+        {
+        if ( aEnable )
+            {
+            iSecurityDlg->EnablePIN( aPINParams, aRetry, aPINValue, aStatus );
+            }
+        else
+            {
+            iSecurityDlg->DisablePIN( aPINParams, aRetry, aPINValue, aStatus );
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::ChangePINValue
+// Shows a security dialog for changing PIN value.
+// -----------------------------------------------------------------------------
+//
+void CWimSecurityDlgHandler::ChangePINValue(
+    TBool aRetry,
+    const TPINParams& aPINParams, 
+    TPINValue& aOldPINValue,
+    TPINValue& aNewPINValue,
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::ChangePINValue | Begin"));
+
+    // First try to load security dialog
+    TInt loadError = LoadSecurityDialog( aStatus );
+
+    if ( loadError == KErrNone ) // Dialog loaded succesfully
+        {
+        iSecurityDlg->ChangePIN( aPINParams, 
+                                 aRetry, 
+                                 aOldPINValue, 
+                                 aNewPINValue, 
+                                 aStatus );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::ShowPINBlocked
+// Shows the note about blocked PIN to the user.
+// -----------------------------------------------------------------------------
+//
+void CWimSecurityDlgHandler::ShowPINBlocked( 
+    const TPINParams& aPINParams, 
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::ShowPINBlocked | Begin"));
+    // First try to load security dialog
+    TInt loadError = LoadSecurityDialog( aStatus );
+
+    if ( loadError == KErrNone ) // Dialog loaded succesfully
+        {
+        iSecurityDlg->PINBlocked( aPINParams, aStatus );
+        }
+    }
+    
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::ShowPINTotalBlocked
+// Shows the note about total blocked PIN to the user.
+// -----------------------------------------------------------------------------
+//
+void CWimSecurityDlgHandler::ShowPINTotalBlocked( 
+    const TPINParams& aPINParams, 
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::ShowPINTotalBlocked | Begin"));
+    // First try to load security dialog
+    TInt loadError = LoadSecurityDialog( aStatus );
+
+    if ( loadError == KErrNone ) // Dialog loaded succesfully
+        {
+        iSecurityDlg->TotalBlocked( aPINParams, aStatus );
+        }
+    }    
+
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::ShowCardRemoved
+// Shows the note about card removed to the user.
+// -----------------------------------------------------------------------------
+//
+void CWimSecurityDlgHandler::ShowCardRemoved( 
+    TRequestStatus& /*aStatus*/ )
+    {
+    /*_WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::ShowCardRemoved | Begin"));
+    // First try to load security dialog
+    TInt loadError = LoadPKIDialog( aStatus );
+
+    if ( loadError == KErrNone ) // Dialog loaded succesfully
+        {
+        iPKIDlg->Note( MPKIDialog::ENoSecurityModule, aStatus );
+        }*/
+    return;
+    }
+
+
+
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::UnblockPIN
+// Shows a security dialog for fetching PIN and PUK values 
+// for unblocking blocked PIN.
+// -----------------------------------------------------------------------------
+//
+void CWimSecurityDlgHandler::UnblockPIN(
+    TBool aRetry,
+    const TPINParams& aBlockedPINParams,
+    const TPINParams& aUnblockingPINParams, 
+    TPINValue& aUnblockingPINValue, 
+    TPINValue& aNewPINValue,
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::UnblockPIN | Begin"));
+
+    // First try to load security dialog
+    TInt loadError = LoadSecurityDialog( aStatus );
+
+    if ( loadError == KErrNone ) // Dialog loaded succesfully
+        {
+        iSecurityDlg->UnblockPIN( aBlockedPINParams,
+                                  aUnblockingPINParams, 
+                                  aRetry,
+                                  aUnblockingPINValue, 
+                                  aNewPINValue,
+                                  aStatus );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::EnterPIN
+// Shows a security dialog for asking user to enter PIN code.
+// -----------------------------------------------------------------------------
+//
+void CWimSecurityDlgHandler::EnterPIN( 
+    TBool aRetry, 
+    const TPINParams& aPINParams, 
+    TPINValue& aPINValue,
+    TRequestStatus& aStatus )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::EnterPIN | Begin"));
+
+    // First try to load security dialog
+    TInt loadError = LoadSecurityDialog( aStatus );
+
+    if ( loadError == KErrNone ) // Dialog loaded succesfully
+        {
+        _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::EnterPIN | Call EnterPIN"));
+        iSecurityDlg->EnterPIN( aPINParams, aRetry, aPINValue, aStatus );
+        _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::EnterPIN | EnterPIN called"));
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::Close()
+// -----------------------------------------------------------------------------
+//
+void CWimSecurityDlgHandler::Cancel()
+    {
+	TRAPD( err, DoLoadSecurityDialogL() );
+	if ( err == KErrNone ) // Dialog loaded succesfully
+        {
+        _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::EnterPIN | Call EnterPIN"));
+        iSecurityDlg->Cancel();
+        _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::EnterPIN | EnterPIN called"));
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::LoadSecurityDialog
+// Load Security Dialog if not yet done. Completes message with error if load
+// fails.
+// -----------------------------------------------------------------------------
+//
+TInt CWimSecurityDlgHandler::LoadSecurityDialog( TRequestStatus& aStatus )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::LoadSecurityDialog | Begin"));
+
+    // Load CTSecDlgs.dll, trap if leave occurred
+    TRAPD( err, DoLoadSecurityDialogL() );
+    
+    if ( err ) // Dll load failed, complete message with error
+        {
+        _WIMTRACE2(_L("WIM | WIMServer | CWimSecurityDlgHandler::LoadSecurityDialog | DoLoadSecurityDialogL()=%d"), err);
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete( status, err );
+        }
+    return err;
+    }
+    
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::LoadPKIDialog
+// Load PKI Dialog if not yet done. Completes message with error if load
+// fails.
+// -----------------------------------------------------------------------------
+//
+TInt CWimSecurityDlgHandler::LoadPKIDialog( TRequestStatus& /*aStatus*/ )
+    {
+    //Keep it for future usage 
+    
+    /*_WIMTRACE(_L("WIM | WIMServer | CWimPKIDlgHandler::LoadPKIDialog | Begin"));
+
+    // Load CTSecDlgs.dll, trap if leave occurred
+    TRAPD( err, DoLoadPKIDialogL() );
+    
+    if ( err ) // Dll load failed, complete message with error
+        {
+        _WIMTRACE2(_L("WIM | WIMServer | CWimSecurityDlgHandler::LoadPKIDialog | DoLoadPKIDialogL()=%d"), err);
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete( status, err );
+        }
+    return err;*/
+    return 0;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::DoLoadSecurityDialogL
+// Load security dialog if not yet done
+// -----------------------------------------------------------------------------
+//
+void CWimSecurityDlgHandler::DoLoadSecurityDialogL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSecurityDlgHandler::DoLoadSecurityDialogL | Begin"));
+
+    if ( !iSecurityDlg ) // Dialog not loaded yet
+        {
+        // Load security dialog dll
+
+        iSecurityDlg = SecurityDialogFactory::CreateL();
+
+        _WIMTRACE2(_L("WIM | WIMServer | CWimSecurityDlgHandler::LoadSecurityDialog | iSecurityDlg=%d"), iSecurityDlg );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSecurityDlgHandler::DoLoadPKIDialogL
+// Load PKI dialog if not yet done
+// -----------------------------------------------------------------------------
+//
+void CWimSecurityDlgHandler::DoLoadPKIDialogL()
+    {
+    //iPKIDlg = PKIDialogFactory::CreateNoteL();
+    return;
+    }
+
+
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimServer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1036 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Server startup and initialization
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimServer.h"
+#include    "WimSession.h"
+#include    "WimSig.h"
+#include    "WimSessionRegistry.h"
+#include    "WimTrustSettingsStore.h"
+#include    "WimDefs.h"
+#include    "WimTrace.h"
+#include    "WimUtilityFuncs.h"
+#include    "WimCallbackImpl.h"
+#include    <s32file.h>         // UserSvr
+
+#include    "WimCertInfo.h"
+#include    "Wimi.h"            // WIMI definitions
+#include    "WimSatRefreshObserver.h"
+#include    "WimBTSapObserver.h"
+
+#include    <e32property.h>     // RProperty
+#include    <PSVariables.h>     // Property values
+
+#ifdef WIMSERVER_SHUTDOWN
+const TInt KServerShutdownDelay = 0x200000; 
+#endif
+// Initialize static variables. These variables are static because static
+// callback functions in CWimCallBack.
+CWimServer* CWimServer::iWimServer = NULL;
+TInt CWimServer::iWimStatus = KErrNone;
+TBool CWimServer::iWimInitialized = EFalse;
+
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// StartServer
+// Server startup method. Creates active scheduler for the server.
+// Returns: TInt: error code
+// -----------------------------------------------------------------------------
+//
+static void StartServerL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | StartServer | Enter"));
+    User::LeaveIfError( User::RenameThread( KWIMServerName ) );
+    _WIMTRACE(_L("WIM | WIMServer | StartServer | Create AS"));
+ 
+    CActiveScheduler* s = new(ELeave) CActiveScheduler;
+    CleanupStack::PushL( s );    
+
+    CActiveScheduler::Install( s );
+    
+    _WIMTRACE(_L("WIM | WIMServer | StartServer | Create server"));
+        
+    CWimServer::NewL();
+      
+    _WIMTRACE(_L("WIM | WIMServer | StartServer | Notify client"));
+    // Notify Client that server has starter
+    RProcess::Rendezvous( KErrNone );       
+
+    _WIMTRACE(_L("WIM | WIMServer | StartServer | Start ActiveScheduler"));
+    CActiveScheduler::Start();
+       
+    CleanupStack::PopAndDestroy( s );
+    }
+
+
+// -----------------------------------------------------------------------------
+// E32Main
+// Server entry point
+// Returns: TInt: error code
+// -----------------------------------------------------------------------------
+//
+GLDEF_C TInt E32Main()
+    {
+    __UHEAP_MARK;
+    _WIMTRACE(_L("WIM | WIMServer | E32Main | Begin"));
+  
+    CTrapCleanup* cleanup=CTrapCleanup::New();
+    TInt r=KErrNoMemory;
+    
+    if ( cleanup )
+        {
+        TRAP( r, StartServerL() );
+        delete cleanup;
+        }
+    _WIMTRACE(_L("WIM | WIMServer | E32Main Memory leak checking line"));    
+    __UHEAP_MARKEND;    
+    _WIMTRACE(_L("WIM | WIMServer | E32Main Memory checking passed"));
+    return r;
+    }
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimServer::CWimServer
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimServer::CWimServer( TInt aPriority )
+    : CPolicyServer( aPriority, wimPolicy, ESharableSessions )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::CWimServer | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimServer::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::ConstructL | Begin"));
+    StartL( KWIMServerName );
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::ConstructL | StartL"));
+
+    iWimServer = this;
+    InitializeCallbackFunctions();  // Initialize WIMI callback functions
+    iWimSessionRegistry = CWimSessionRegistry::NewL();
+    iWimTrustSettingsStore = CWimTrustSettingsStore::NewL();
+    iWimTimer = CWimTimer::NewL( this );
+#ifdef WIMSERVER_SHUTDOWN    
+    iShutdown.ConstructL();
+    iShutdown.Start();
+#endif    
+     _WIMTRACE(_L("WIM | WIMServer | CWimServer::ConstructL | End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimServer* CWimServer::NewL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::NewL | Begin"));
+    CWimServer* self = new( ELeave ) CWimServer( EPriorityHigh );
+    CleanupStack::PushL( self );
+    self->ConstructL() ;
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// Destructor
+CWimServer::~CWimServer()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::~CWimServer | Begin"));
+    if ( iRefreshObserver )
+        {
+        delete iRefreshObserver;
+        iRefreshObserver = NULL;
+        }
+    if ( iBTSapObserver )
+        {
+        delete iBTSapObserver;
+        iBTSapObserver = NULL;
+        }
+    // Call close down request only if WIM is initialized
+    if ( iWimInitialized )
+        {
+        WIMI_CloseDownReq();
+        _WIMTRACE(_L("WIM | WIMServer | CWimServer::~CWimServer | WIMI_CloseDownReq"));
+        }
+    //iWimTrustSettingsStore->CloseD();
+    delete iWimTrustSettingsStore;
+    delete iWimSessionRegistry;
+    delete iWimTimer;
+    CWimCallBack::DeletegApdu();
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::~CWimServer | delete iWimSessionRegistry"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::WimInitialize
+// Initialize WIMI API, fetches WIM data to WIMI.
+// -----------------------------------------------------------------------------
+//
+void CWimServer::WimInitialize( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::WimInitialize | Begin"));
+
+    // Create observer for bluetooth sap event.
+    // This is checked every time we enter here.
+    if ( !iBTSapObserver )
+        {
+        TRAPD( err, iBTSapObserver = CWimBTSapObserver::NewL());
+        if ( KErrNone != err )
+            {
+            // creation failed
+            iBTSapObserver = NULL; // to be sure
+            _WIMTRACE(_L("WIM|CWimServer::WimInitialize | BT Sap observer NOT created."));
+            }
+        }
+    // If BT SAP observer exists, start it
+    if ( iBTSapObserver )
+        {
+        iBTSapObserver->Start(); //If already started, this doesn't start again
+        }
+
+    // Get state of smart card
+    TInt simState = CWimUtilityFuncs::SimState();
+
+    // Check whether state of Smart Card is OK and whether BT SAP is connected
+    if ( simState != KErrNone ) // Card is not OK
+        {
+        SetWimInitialized( EFalse, simState );
+        iWimStatus = simState;
+        aMessage.Complete( iWimStatus );
+        }
+    else // Smart Card is ready
+        {
+        // Initialize WIMI if not yet done
+        // iWimInitialized is set in callback function InitOKResp()
+        if ( !iWimInitialized )
+            {
+            TInt initStatus = CWimUtilityFuncs::MapWIMError(
+                                      WIMI_InitializeReq( &iWimCallBack ) );
+
+            _WIMTRACE2(_L("WIM|WIMServer|CWimServer::WimInitialize|initStatus=%d"), initStatus );
+
+            // In case WIMI_InitializeReq returs error
+            // iWimStatus may not be set
+            if ( initStatus != KErrNone )
+                {
+                SetWimInitialized( EFalse, initStatus  );
+                iWimStatus = KErrNotReady;
+                }
+            }
+        else // WIMI already initialized
+            {
+            _WIMTRACE(_L("WIM|WIMServer|CWimServer::WimInitialize|Wim already initialized"));
+            iWimStatus = KErrNone;
+            }
+
+        // Create observer for SAT refresh event.
+        // This is checked every time we enter here. It may have failed before
+        // because SAT Server wasn't started.
+        if ( !iRefreshObserver )
+            {
+            TRAPD( err, iRefreshObserver = CWimSatRefreshObserver::NewL());
+            if ( KErrNone != err )
+                {
+                // creation failed
+                iRefreshObserver = NULL; // to be sure
+                _WIMTRACE(_L("WIM|CWimServer::WimInitialize | SAT Refresh observer NOT created."));
+                }
+            }
+
+        aMessage.Complete( iWimStatus );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::SetWimInitialized
+// Set iWimInitialized flag
+// -----------------------------------------------------------------------------
+//
+void CWimServer::SetWimInitialized( TBool aInitialized, TInt aStatus )
+    {
+    _WIMTRACE2(_L("WIM|WIMServer|CWimServer::SetWimInitialized|Value=%d"), aInitialized);
+    iWimInitialized = aInitialized;
+
+    if ( !aInitialized )
+        {
+        iWimStatus = aStatus;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::NewSessionL
+// Creates a new sharable session.
+// -----------------------------------------------------------------------------
+//
+CSession2* CWimServer::NewSessionL(
+    const TVersion& aVersion,
+    const RMessage2& /*aMessage*/ ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::NewSessionL | Begin"));
+    TVersion v( KWIMServMajorVersionNumber, KWIMServMinorVersionNumber,
+        KWIMServBuildVersionNumber );
+
+    if ( !User::QueryVersionSupported( v, aVersion ) )
+        {
+        User::Leave( KErrNotSupported );
+        }
+
+    CWimSession* wimSession;
+    wimSession = CWimSession::NewL( ( CWimServer* )this );
+    iWimSessionRegistry->AddSessionL( wimSession );
+
+    return wimSession;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::InitializeCallbackFunctions
+// WIMI API callback initialization.
+// -----------------------------------------------------------------------------
+//
+void CWimServer::InitializeCallbackFunctions()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSession::InitializeCallbackFunctions | Begin"));
+    _WIMTRACE2(_L("WIM | WIMServer | CWimSession::InitializeCallbackFunctions | iWimCallBack = %d"), iWimCallBack );
+
+    iWimCallBack.InitOkResp = CWimCallBack::InitOkResp;
+    iWimCallBack.CloseDownResp = CWimCallBack::CloseDownResp;
+    iWimCallBack.SignResp = CWimCallBack::SignResp;
+    iWimCallBack.CertificateResp = CWimCallBack::CertificateResp;
+    iWimCallBack.CertificateDeleteResp = CWimCallBack::CertificateDeleteResp;
+    iWimCallBack.CertificateStoreResp = CWimCallBack::CertificateStoreResp;
+    iWimCallBack.VerifyPINResp = CWimCallBack::VerifyPINResp;
+    iWimCallBack.ChangePINResp = CWimCallBack::ChangePINResp;
+    iWimCallBack.UnblockPINResp = CWimCallBack::UnblockPINResp;
+    iWimCallBack.EnablePINResp = CWimCallBack::EnablePINResp;
+    iWimCallBack.CardInsertedResp = CWimCallBack::CardInsertedResp;
+    iWimCallBack.Open = CWimCallBack::Open;
+    iWimCallBack.Close = CWimCallBack::Close;
+    iWimCallBack.APDUReq = CWimCallBack::APDUReq;
+    iWimCallBack.GetATRReq = CWimCallBack::GetATRReq;
+    iWimCallBack.GetReaderListReq = CWimCallBack::GetReaderListReq;
+    iWimCallBack.ReadSimFileReq = CWimCallBack::ReadSimFileReq;
+    iWimCallBack.ProvSCFileResp = CWimCallBack::OmaProvisioningResp;
+
+     _WIMTRACE(_L("WIM | WIMServer | CWimSession::InitializeCallbackFunctions | END"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::PanicServer
+// Panics the server.
+// -----------------------------------------------------------------------------
+//
+void CWimServer::PanicServer( TWimServerPanic aPanic )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::PanicServer | Begin"));
+    // Set server state to EWimServerNotRunning
+    TInt retVal = RProperty::Set( KUidSystemCategory,
+                                  KWimServerUid.iUid,
+                                  EWimServerNotRunning );
+    retVal = retVal; // To prevent warning
+
+    User::Panic( KWIMServerName, aPanic );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::Server
+// Return static iServer
+// -----------------------------------------------------------------------------
+//
+CWimServer* CWimServer::Server()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::Server | Begin"));
+    return CWimServer::iWimServer;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::WimSessionRegistry
+// Get pointer to WimSessionRegistry
+// -----------------------------------------------------------------------------
+//
+CWimSessionRegistry* CWimServer::WimSessionRegistry()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::WimSessionRegistry | Begin"));
+    return iWimSessionRegistry;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::GetSessions
+// Return all sessions of server
+// -----------------------------------------------------------------------------
+//
+void CWimServer::GetSessionsL( RArray<CWimSession*>& aSessions ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::GetSessionsL | Begin"));
+    iWimSessionRegistry->GetSessionsL( aSessions );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::WimTrustSettingsStore
+// Return TrustSettingsStore pointer
+// -----------------------------------------------------------------------------
+//
+CWimTrustSettingsStore* CWimServer::WimTrustSettingsStore()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::WimTrustSettingsStore | Begin"));
+    return iWimTrustSettingsStore;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::CustomSecurityCheckL
+// Custom policy check for requests of certain WimServer services.Called by
+// framework.
+// -----------------------------------------------------------------------------
+//
+    CPolicyServer::TCustomResult
+CWimServer::CustomSecurityCheckL( const RMessage2& aMsg,
+                                  TInt& /*aAction*/,
+                                  TSecurityInfo& /*aMissing*/ )
+    {
+    _WIMTRACE2(_L("CWimServer::CustomSecurityCheckL | Begin, heap=%d"),
+               User::CountAllocCells());
+
+    WIMI_STAT callStatus;
+    TUint8 usage( 255 ); // init stg unused
+    // Set initial return value to failed
+    CPolicyServer::TCustomResult test( EFail );
+    TInt function = aMsg.Function();
+
+    _WIMTRACE4(_L("CWimServer::CustomSecurityCheckL: SID=%d,VID=%d, Function=%d"),
+               aMsg.SecureId().iId, aMsg.VendorId().iId, function);
+
+    switch ( function )
+        {
+        case EGetWIMCertDetails:
+            {
+            //Leave the capability checking to Certificate Handler object
+            test = EPass;
+            break;
+            }
+
+        case EGetCertExtras:
+            {
+            // Int2 contains usage of required cert
+            TWimEntryType certEntryType = ( TWimEntryType ) aMsg.Int2();
+
+            switch ( certEntryType )
+                {
+                case EWimEntryTypeCA:
+                    {
+                    // CA cert reading does not require caps
+                    _WIMTRACE(_L("CWimServer::CustomSecurityCheckL: CA cert read req, OK"));
+                    test = EPass;
+                    break;
+                    }
+                case EWimEntryTypePersonal: //lint -fallthrough
+                case EWimEntryTypeAll:
+                    {
+                    // User cert reading requires caps
+                    test = CheckReadCapsForUsage( aMsg, WIMI_CU_Client );
+                    break;
+                    }
+                default:
+                    {
+                    test = EFail;
+                    break;
+                    }
+                }
+            break;
+            }
+
+        case EStoreCertificate:
+            {
+            ResolveStoreCertReqL( aMsg, usage );
+            test = CheckWriteCapsForUsage( aMsg, usage );
+            break;
+            }
+
+        case ERemoveCertificate:
+            {
+            callStatus = ResolveRemoveCertReqL( aMsg, usage );
+            if ( WIMI_Ok == callStatus )
+                {
+                test = CheckWriteCapsForUsage( aMsg, usage );
+                }
+            break;
+            }
+
+        case ESignTextReq:
+            {
+            test = CheckReadCapsForUsage( aMsg, WIMI_CU_Client );
+            break;
+            }
+
+        case ESetApplicability:         //lint -fallthrough
+        case ESetTrust:                 //lint -fallthrough
+        case ESetDefaultTrustSettings:  //lint -fallthrough
+        case ERemoveTrustSettings:
+            {
+            if ( ResolveTrustModficationReqL( aMsg, usage ))
+                {
+                test = CheckWriteCapsForUsage( aMsg, usage );
+                }
+            break;
+            }
+
+        case EExportPublicKey:
+            {
+            ResolveExportPublicReqL( aMsg, usage );
+            test = CheckReadCapsForUsage( aMsg, usage );
+            break;
+            }
+
+        default:
+            {
+            _WIMTRACE2(_L("CWimServer::CustomSecurityCheckL: UNKNOWN FUNCTION %d"),
+                        function);
+            // Inconsistent policy, should not be here. Panic.
+            PanicServer( EWimIncorrectPolicy );
+            break;
+            }
+        } // switch ( function )
+
+    _WIMTRACE2(_L("CWimServer::CustomSecurityCheckL: Result=%d"), test);
+    _WIMTRACE2(_L("CWimServer::CustomSecurityCheckL | End, heap=%d"),
+               User::CountAllocCells());
+
+    return test;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimServer::ResolveCertUsage
+// Resolves usage (CA/User) for a certificate.
+// -----------------------------------------------------------------------------
+//
+WIMI_STAT CWimServer::ResolveCertUsage( const RMessage2& aMsg,
+                                        TUint8& aUsage )
+    {
+    _WIMTRACE(_L("CWimServer::ResolveCertUsage | Begin"));
+
+    // aMsg.Ptr0 contains reference to certificate
+    WIMI_Ref_pt pCertRef = const_cast< WIMI_Ref_pt >( aMsg.Ptr0() );
+
+    WIMI_STAT callStatus = GetCertificateInfo( pCertRef, aUsage );
+
+    _WIMTRACE(_L("CWimServer::ResolveCertUsage | End"));
+    return callStatus;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimServer::GetCertificateInfo
+// Fetches certificate info. Wrapper for WIMI call.
+// -----------------------------------------------------------------------------
+//
+WIMI_STAT CWimServer::GetCertificateInfo( WIMI_Ref_pt aCertRef,
+                                          TUint8& aUsage )
+    {
+    _WIMTRACE(_L("CWimServer::GetCertificateInfo | Begin"));
+
+    WIMI_Ref_pt     pWimRef = NULL;
+    WIMI_BinData_t  ptLabel;
+    WIMI_BinData_t  ptKeyID;
+    WIMI_BinData_t  ptCAID;
+    WIMI_BinData_t  ptIssuerHash;
+    WIMI_BinData_t  ptTrustedUsage;
+    TUint8          uiCDFRefs;
+    TUint8          type;
+    TUint16         certLen;
+    TUint8          modifiable = 0;
+
+    WIMI_STAT callStatus = WIMI_GetCertificateInfo(
+                                aCertRef,
+                                &pWimRef,
+                                &ptLabel,
+                                &ptKeyID, // Key Id (hash)
+                                &ptCAID,
+                                &ptIssuerHash,
+                                &ptTrustedUsage,
+                                &uiCDFRefs,
+                                &aUsage,  // 0 = client, 1 = CA
+                                &type,    // WTLSCert(1),
+                                          // X509Cert(2),
+                                          // X968Cert(3),
+                                          // CertURL(4)
+                                &certLen, // cert. content or URL length
+                                &modifiable );
+
+    if ( callStatus == WIMI_Ok )
+        {
+        free_WIMI_Ref_t( pWimRef );
+        WSL_OS_Free( ptLabel.pb_buf );
+        WSL_OS_Free( ptKeyID.pb_buf );
+        WSL_OS_Free( ptCAID.pb_buf );
+        WSL_OS_Free( ptIssuerHash.pb_buf );
+        WSL_OS_Free( ptTrustedUsage.pb_buf );
+        }
+
+    _WIMTRACE(_L("CWimServer::GetCertificateInfo | End"));
+    return callStatus;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimServer::ResolveStoreCertReqL
+// Resolves which kind of certificate (CA/User) client is accessing.
+// -----------------------------------------------------------------------------
+//
+void CWimServer::ResolveStoreCertReqL( const RMessage2& aMsg,
+                                       TUint8& aUsage )
+    {
+    _WIMTRACE(_L("CWimServer::ResolveStoreCertReqL | Begin"));
+    TPckgBuf<TWimCertAddParameters> certInfoPckg;
+    aMsg.ReadL( 1, certInfoPckg );
+
+    // Convert from TWimCertType to TUint8
+    if ( certInfoPckg().iUsage == EWimCertTypeCA )
+        {
+        aUsage = WIMI_CU_CA;     // 1
+        _WIMTRACE(_L("CWimServer::ResolveStoreCertReqL | Usage=CA"));
+        }
+    else
+        {
+        aUsage = WIMI_CU_Client; // 0
+        _WIMTRACE(_L("CWimServer::ResolveStoreCertReqL | Usage=Client"));
+        }
+    _WIMTRACE(_L("CWimServer::ResolveStoreCertReqL | End"));
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimServer::ResolveRemoveCertReqL
+// Resolves which kind of certificate client is accessing.
+// -----------------------------------------------------------------------------
+//
+WIMI_STAT CWimServer::ResolveRemoveCertReqL( const RMessage2& aMsg,
+                                             TUint8& aUsage )
+    {
+    _WIMTRACE2(_L("CWimServer::ResolveRemoveCertReqL | Begin, heap=%d"),
+               User::CountAllocCells());
+
+    WIMI_STAT callStatus = WIMI_Ok;
+    TWimCertRemoveAddr dataStruct = {0};
+
+    TPckgBuf<TWimCertRemoveAddr> wimCertRemoveAddrPckg( dataStruct );
+    aMsg.ReadL( 0, wimCertRemoveAddrPckg );
+    WIMI_Ref_pt pCertRef = ( void* )wimCertRemoveAddrPckg().iCertAddr;
+
+    callStatus = GetCertificateInfo( pCertRef, aUsage );
+
+    _WIMTRACE2(_L("CWimServer::ResolveRemoveCertReqL | End, heap=%d"),
+               User::CountAllocCells());
+
+    return callStatus;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimServer::ResolveTrustModficationReqL
+// Resolves which kind of certificate client is accessing.
+// -----------------------------------------------------------------------------
+//
+TBool CWimServer::ResolveTrustModficationReqL( const RMessage2& aMsg,
+                                               TUint8& aUsage )
+    {
+    _WIMTRACE(_L("CWimServer::ResolveTrustModficationReqL | Begin"));
+    TBool rc( EFalse );
+    TPckgBuf<TWimCertInfoPckg> pckg;
+    aMsg.ReadL( 0, pckg );
+
+    TInt owner = pckg().iCertificateOwnerType;
+
+    switch ( owner )
+        {
+        case ECACertificate:
+            {
+            aUsage = WIMI_CU_CA;
+            rc = ETrue;
+            _WIMTRACE(_L("CWimServer::ResolveTrustModficationReqL | Usage=CA"));
+            break;
+            }
+        case EUserCertificate:     //lint -fallthrough
+        case EPeerCertificate:
+            {
+            aUsage = WIMI_CU_Client;
+            rc = ETrue;
+            _WIMTRACE(_L("CWimServer::ResolveTrustModficationReqL | Usage=Client"));
+            break;
+            }
+        default:
+            {
+            rc = EFalse;
+            _WIMTRACE(_L("CWimServer::ResolveTrustModficationReqL | FAIL"));
+            break;
+            }
+        }
+    return rc;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimServer::ResolveExportPublicReqL
+// Resolves which kind of key (CA/User) client requests.
+// -----------------------------------------------------------------------------
+//
+WIMI_STAT CWimServer::ResolveExportPublicReqL( const RMessage2& aMsg,
+                                               TUint8& aUsage )
+    {
+    _WIMTRACE2(_L("CWimServer::ResolveExportPublicReqL | Begin, heap=%d"),
+               User::CountAllocCells());
+
+    WIMI_STAT callStatus = WIMI_Ok;
+
+    TPckgBuf<TExportPublicKey> keyExportPckg;
+    aMsg.ReadL( 0, keyExportPckg );
+
+    TBuf8<KKeyIdLen> keyIdBuf = keyExportPckg().iKeyId;
+    TUint8 clicertCount = 0;
+    WIMI_RefList_t clicertRefList = NULL;
+    const TUint16 KInvalidUsage = 10;
+    TUint16 usage = KInvalidUsage;
+
+    callStatus = WIMI_GetCertificateListByKeyHash( ( TUint8* ) keyIdBuf.Ptr(),
+                                            WIMI_CU_Client,
+                                            &clicertCount,
+                                            &clicertRefList );
+    if( callStatus != WIMI_Ok )
+        {
+    	return callStatus;
+        }
+    free_WIMI_RefList_t( clicertRefList );
+    
+    if ( clicertCount > 0 )
+        {
+    	usage = WIMI_CU_Client;
+        }    
+    else
+        {
+    	TUint8 cacertCount = 0;
+        WIMI_RefList_t cacertRefList = NULL;
+    
+        callStatus = WIMI_GetCertificateListByKeyHash( ( TUint8* ) keyIdBuf.Ptr(),
+                                            WIMI_CU_CA,
+                                            &cacertCount,
+                                            &cacertRefList );
+        if ( callStatus != WIMI_Ok )
+            {
+            return callStatus;
+            }
+        free_WIMI_RefList_t( cacertRefList );
+
+        if ( cacertCount > 0 )
+            {
+    	    usage = WIMI_CU_CA;
+            }
+        else
+            {
+        	aMsg.Complete( KErrBadHandle );
+            }
+        }
+    
+    aUsage = static_cast< TUint8 >( usage );
+
+    _WIMTRACE2(_L("CWimServer::ResolveExportPublicReqL | End, heap=%d"),
+               User::CountAllocCells());
+
+    return callStatus;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimServer::CheckReadCapsForUsage
+// Check if client has sufficient read capability for service in question.
+// -----------------------------------------------------------------------------
+//
+    CPolicyServer::TCustomResult
+CWimServer::CheckReadCapsForUsage( const RMessage2& aMsg,
+                                   TUint8 aUsage )
+    {
+    _WIMTRACE2(_L("CWimServer::CheckReadCapsForUsage | Begin, usage=%d"), aUsage );
+
+    CPolicyServer::TCustomResult rc( EFail );
+
+    switch ( aUsage )
+        {
+        case WIMI_CU_CA:
+            {
+            // CA certificate reading doesn't require any capability.
+            _WIMTRACE(_L("CWimServer::CheckReadCapsForUsage: CA cert read req, OK."));
+            rc = EPass;
+            break;
+            }
+        case WIMI_CU_Client:
+            {
+            // User certificate reading requires ReadUserData capability.
+            if ( aMsg.HasCapability( ECapabilityReadUserData ))
+                {
+                rc = EPass;
+                _WIMTRACE(_L("CWimServer::CheckReadCapsForUsage: User cert read capa PASS"));
+                }
+            else
+                {
+                rc = EFail;
+                _WIMTRACE(_L("CWimServer::CheckReadCapsForUsage: User cert read capa FAIL"));
+                }
+            break;
+            }
+        default:
+            {
+            _WIMTRACE(_L("CWimServer::CheckReadCapsAccordingToUsage: FAIL:Unknown usage."));
+            rc = EFail;
+            break;
+            }
+        }
+    _WIMTRACE(_L("CWimServer::CheckReadCapsForUsage | End"));
+    return rc;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimServer::CheckWriteCapsForUsage
+// Check if client has sufficient write capability for service in question.
+// -----------------------------------------------------------------------------
+//
+    CPolicyServer::TCustomResult
+CWimServer::CheckWriteCapsForUsage( const RMessage2& aMsg,
+                                    TUint8 aUsage )
+    {
+    _WIMTRACE2(_L("CWimServer::CheckWriteCapsForUsage | Begin, usage=%d"), aUsage);
+
+    CPolicyServer::TCustomResult rc( EFail );
+
+    switch ( aUsage )
+        {
+        case WIMI_CU_CA:
+            {
+            // CA certificate writing/modifying requires WriteDeviceData
+            // capability.
+            if ( aMsg.HasCapability( ECapabilityWriteDeviceData ))
+                {
+                rc = EPass;
+                _WIMTRACE(_L("CWimServer::CheckWriteCapsForUsage: CA cert write capa PASS"));
+                }
+            else
+                {
+                rc = EFail;
+                _WIMTRACE(_L("CWimServer::CheckWriteCapsForUsage: CA cert write capa FAIL"));
+                }
+            break;
+            }
+        case WIMI_CU_Client:
+            {
+            // User certificate writing/modifying requires WriteUserData
+            // capability.
+            if ( aMsg.HasCapability( ECapabilityWriteUserData ))
+                {
+                rc = EPass;
+                _WIMTRACE(_L("CWimServer::CheckWriteCapsForUsage: User cert write capa PASS"));
+                }
+            else
+                {
+                rc = EFail;
+                _WIMTRACE(_L("CWimServer::CheckWriteCapsForUsage: User cert write capa FAIL"));
+                }
+            break;
+            }
+        default:
+            {
+            _WIMTRACE(_L("CWimServer::CheckWriteCapsForUsage: FAIL:Unknown usage."));
+            rc = EFail; // Unknown cert usage -> fail to be sure
+            break;
+            }
+        }
+    _WIMTRACE(_L("CWimServer::CheckWriteCapsForUsage | End"));
+    return rc;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimServer::IsAccessingToken
+// Tells if currently requested service is accessing physical token.
+// -----------------------------------------------------------------------------
+//
+TBool CWimServer::IsAccessingToken()
+    {
+    return iIsAccessingToken;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::SetIsAccessingToken
+// Tell that currently requested service is accessing physical token.
+// -----------------------------------------------------------------------------
+//
+void CWimServer::SetIsAccessingToken( TBool aValue )
+    {
+    iIsAccessingToken = aValue;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::RefreshNotificationReceived
+// Informs server about completed SIM Refresh operation. Returns true if SIM
+// Refresh notification is received in the middle of service request that
+// accesses physical token. See IsAccessingToken().
+// Server shall re-initialize itself at earliest convenience.
+// -----------------------------------------------------------------------------
+//
+TBool CWimServer::RefreshNotificationReceived()
+    {
+    return iRefreshNotificationReceived;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::SetRefreshNotificationReceived
+// Tell server about completed SIM Refresh operation. Is set if SIM
+// Refresh notification is received in the middle of service request
+// that accesses physical token. See IsAccessingToken().
+// Server shall re-initialize itself at earliest convenience.
+// -----------------------------------------------------------------------------
+//
+void CWimServer::SetRefreshNotificationReceived( TBool aValue )
+    {
+    iRefreshNotificationReceived = aValue;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::TimerExpired()
+// Interface derived from 
+// -----------------------------------------------------------------------------
+//
+void CWimServer::TimerExpired()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::TimerExpired | Begin"));
+    WIMI_Ref_pt pWimRefTemp = NULL;
+
+    pWimRefTemp = WIMI_GetWIMRef( 0 );
+ 
+    if ( pWimRefTemp )  // Close the WIM
+        {
+        WIMI_CloseWIM( pWimRefTemp );
+        free_WIMI_Ref_t( pWimRefTemp );
+        }
+    //SetWimInitialized( EFalse );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::WimTimer()
+// Return the pointer of Timer 
+// -----------------------------------------------------------------------------
+//
+CWimTimer* CWimServer::WimTimer()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimServer::WimTimer | Begin"));
+    return iWimTimer;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimServer::CancelWimInitialize()
+// Cancel Wim Initialize 
+// -----------------------------------------------------------------------------
+//
+void CWimServer::CancelWimInitialize( const RMessage2& aMessage )
+    {
+	 if ( !iWimInitialized )
+		 {
+		 CWimCallBack::CancelWimInitialize();	
+		 }
+	aMessage.Complete( KErrNone );	 
+    }
+
+
+#ifdef WIMSERVER_SHUTDOWN
+
+// CShutdown
+
+// ---------------------------------------------------------------------------
+// CShutdown::CShutdown()
+// ---------------------------------------------------------------------------
+//
+inline CShutdown::CShutdown() :
+  CTimer(-1)
+    {
+    CActiveScheduler::Add(this);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CShutdown::ConstructL()
+// ---------------------------------------------------------------------------
+//
+inline void CShutdown::ConstructL()
+    {
+    CTimer::ConstructL();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CShutdown::Start()
+// ---------------------------------------------------------------------------
+//
+inline void CShutdown::Start()
+    {
+    After(KServerShutdownDelay);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CShutdown::RunL()
+// Initiate server exit when the timer expires.
+// ---------------------------------------------------------------------------
+//
+void CShutdown::RunL()
+    {
+     _WIMTRACE(_L("WIM | WIMServer |  CShutdown::RunL"));
+    CActiveScheduler::Stop();
+    _WIMTRACE(_L("WIM | WIMServer |  CShutdown::End"));
+    }
+
+// ---------------------------------------------------------------------------
+// CWimServer::DropSession()
+// ---------------------------------------------------------------------------
+//
+void CWimServer::AddSession()
+    {
+    ++iSessionCount;
+    iShutdown.Cancel();
+    }
+
+
+// ---------------------------------------------------------------------------
+// CWimServer::DropSession()
+// ---------------------------------------------------------------------------
+//
+void CWimServer::DropSession()
+    {
+    if (--iSessionCount==0)
+        {
+        iShutdown.Start();
+        }
+    }
+
+#endif //WIMSERVER_SHUTDOWN
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimSession.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,634 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Session class for WimServer
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimSession.h"
+#include    "WimMemMgmt.h"
+#include    "WimCertHandler.h"
+#include    "WimAuthObjHandler.h"
+#include    "WimTokenHandler.h"
+#include    "WimKeyMgmtHandler.h"
+#include    "WimSignTextHandler.h"
+#include    "WimServer.h"
+#include    "WimResponse.h"
+#include    "WimCallbackImpl.h"
+#include    "WimUtilityFuncs.h"
+#include    "WimSessionRegistry.h"
+#include    "WimOmaProvisioning.h"
+#include    "WimJavaProvisioning.h"
+#include    "WimTrustSettingsHandler.h"
+#include    "WimTrace.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimSession::CWimSession
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimSession::CWimSession() : CSession2()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSession::CWimSession | Begin"));
+    __DECLARE_NAME( _S( "CWimSession" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSession::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimSession::ConstructL( CWimServer* aWimServer )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSession::ConstructL | Begin"));
+    iWimSvr = aWimServer;
+#ifdef WIMSERVER_SHUTDOWN    
+    iWimSvr->AddSession();
+#endif    
+    iWimMgmt = CWimMemMgmt::NewL();
+    iWimCertHandler = CWimCertHandler::NewL();
+    iWimAuthObjHandler = CWimAuthObjHandler::NewL();
+    iWimTokenHandler = CWimTokenHandler::NewL();
+    iWimKeyMgmtHandler = CWimKeyMgmtHandler::NewL();
+    iWimSignTextHandler = CWimSignTextHandler::NewL();
+    //iTimer = CWimTimer::NewL( this );
+    iWimUtilFuncs = CWimUtilityFuncs::NewL();
+    iWimOmaProvisioning = CWimOmaProvisioning::NewL();
+    iWimJavaProvisioning = CWimJavaProvisioning::NewL();
+    iWimTrustSettingsHandler = CWimTrustSettingsHandler::NewL( iWimSvr->WimTrustSettingsStore() );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSession::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimSession* CWimSession::NewL( CWimServer* aWimServer )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSession::NewL | Begin"));
+    CWimSession* self = new( ELeave ) CWimSession();
+    CleanupStack::PushL( self );
+    self->ConstructL( aWimServer );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// Destructor
+CWimSession::~CWimSession()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSession::~CWimSession | Begin"));
+    
+#ifdef WIMSERVER_SHUTDOWN   
+    if ( iWimSvr )
+        {
+        iWimSvr->DropSession();	
+    	  } 
+#endif    
+    //Check if message is not completed before session is desctructed
+    if ( iMessage )
+        {
+        iMessage->Complete( KErrCancel );
+        delete iMessage;
+        }
+
+    if ( iNotifyMessage )   // NotifyOnRemoval message pending
+        {
+        iNotifyMessage->Complete( KErrCancel );
+        delete iNotifyMessage;
+        }
+
+    // Delete sessions from session registry
+    if ( iWimSvr )
+        {
+        iWimSvr->WimSessionRegistry()->RemoveSession( this );
+    	}
+
+    delete iWimMgmt;
+    //delete iTimer;
+    delete iWimCertHandler;
+    delete iWimAuthObjHandler;
+    delete iWimTokenHandler;
+    delete iWimKeyMgmtHandler;
+    delete iWimSignTextHandler;
+    delete iWimUtilFuncs;
+    delete iWimOmaProvisioning;
+    delete iWimJavaProvisioning;
+    delete iWimTrustSettingsHandler;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSession::ServiceL
+// Handles the servicing of client requests to the server.
+// -----------------------------------------------------------------------------
+//
+void CWimSession::ServiceL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSession::ServiceL | Begin"));
+
+    iMessage = new( ELeave ) RMessage2( aMessage );
+
+    TRAPD( appErr, DispatchMessageL( aMessage ) );
+    // The error is an application error 
+    // If the appErr is '0' or if the appErr is WIM_Error 
+    // then it is completed by the called functions or by
+    // the callback functions
+    if ( appErr )
+        {
+        _WIMTRACE2(_L("WIM | WIMServer | CWimSession::ServiceL | Leaved with %d"), appErr);
+        aMessage.Complete( appErr );
+        }
+
+    // Message is completed so delete copy of message
+    delete iMessage;
+    iMessage = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSession::DispatchMessageL
+// Handles client requests and forwards them to appropriate handler class.
+// -----------------------------------------------------------------------------
+//
+void CWimSession::DispatchMessageL( const RMessage2& aMessage )
+    {
+    _WIMTRACE2(_L("WIM|WIMServer|CWimSession::DispatchMessageL|Begin, Function=%d"), aMessage.Function());
+    // Check if the WIM has been initialized properly. If not just complete
+    // message with WimServer status and return
+    if ( CWimServer::iWimStatus != KErrNone
+        && aMessage.Function() != EWimInitialize
+        && aMessage.Function() != ECancelNotifyOnRemoval )
+        {
+        aMessage.Complete( CWimServer::iWimStatus );
+        return;
+        }
+
+	// Are we going to card? (blocks sim refresh until done)
+	if ( RequestAccessesHW( aMessage.Function() ))
+	    {
+	    iWimSvr->SetIsAccessingToken( ETrue );
+	    }
+
+    _WIMTRACE2( _L( "WIM|WIMServer|CWimSession::DispatchMessageL|Begin, heap=%d" ),
+                User::CountAllocCells() ); 
+#ifdef __WIM_ENABLE_TRACES
+	TTime funcStart;
+	TTime funcEnd;
+	funcStart.UniversalTime();
+#endif // __WIM_ENABLE_TRACES
+
+    switch ( aMessage.Function() )
+        {
+//==================== WIM operations ==========================================
+        case EWimInitialize:
+            _WIMTRACE2(_L("WIM|WIMServer|CWimSession::DispatchMessageL|EWimInitialize, iWimInitialized=%d"), CWimServer::iWimInitialized);
+            iWimSvr->WimInitialize( aMessage );
+            break;
+        case ECancelWimInitialize:
+            iWimSvr->CancelWimInitialize( aMessage );  
+            break; 
+        case EGetWIMCount:
+            GetWimCountL();
+            break;
+        case EGetWIMRefs:
+            GetWimRefListL();
+            break;
+
+//==================== WIM card management =====================================
+        case EGetWIMInfo:
+            iWimSvr->WimTimer()->ResetTimer();
+            iWimTokenHandler->GetWIMInfoL( aMessage, iWimMgmt );
+            break;
+        case EIsWIMOpen:
+            iWimTokenHandler->IsWIMOpenL( aMessage, iWimSvr->WimTimer(), iWimMgmt );
+            break;
+        case ECloseWIMAfter:
+            iWimSvr->WimTimer()->SetCloseAfter( aMessage );
+            break;
+        case EGetCloseWIMAfter:
+            iWimSvr->WimTimer()->GetCloseAfterL( aMessage );
+            break;
+        case EWimTimeRemaining:
+            iWimSvr->WimTimer()->TimeRemainingL( aMessage );
+            break;
+        case EWIMClose:
+            iWimTokenHandler->CloseWIM( aMessage );
+            break;
+
+//==================== Notify on removal =======================================
+        case ENotifyOnRemoval:
+            NotifyOnRemovalL();
+            break;
+        case ECancelNotifyOnRemoval:
+            CancelNotifyOnRemoval();
+            break;
+
+//==================== WIM Reference handling ==================================
+        case EFreeMemory:
+            iWimMgmt->FreeRef( ( WIMI_Ref_pt* )aMessage.Ptr0() );  
+            aMessage.Complete( KErrNone );
+            break;
+        case EFreeWIMMemoryLst:
+            { 
+            TUint wimCount = aMessage.Int1(); 
+    
+            WIMI_Ref_t* temp = NULL;
+            TUint8 wimIndex = 0 ;
+            for ( ; wimIndex < KWimMaxCount && ( temp = WIMI_GetWIMRef( wimIndex ) ) != NULL; wimIndex++ )
+                {
+                free_WIMI_Ref_t( temp );
+                }
+
+            if ( wimCount != wimIndex )
+               {
+               User::LeaveIfError( KErrArgument );
+               }
+    
+            iWimMgmt->FreeWIMRefs( aMessage );  
+            break;
+            }
+        case EFreeMemoryLst:
+            iWimMgmt->FreeRefLst( aMessage );
+            break;
+
+//==================== PIN operations ==========================================
+        case EGetPINCount:
+            iWimSvr->WimTimer()->ResetTimer();
+            iWimAuthObjHandler->GetPINCountL( aMessage );
+            break;
+        case EGetPINRefs:
+            iWimSvr->WimTimer()->ResetTimer();
+            iWimAuthObjHandler->GetPINRefListL( aMessage, iWimMgmt );
+            break;
+        case EGetPINInfo:
+            iWimSvr->WimTimer()->ResetTimer();
+            iWimAuthObjHandler->GetPINInfoL( aMessage );
+            break;
+        case EGetPINsInfo:
+            iWimSvr->WimTimer()->ResetTimer();
+            iWimAuthObjHandler->GetPINsInfoL( aMessage ); 
+            break;
+        case EIsPinBlocked:
+            iWimAuthObjHandler->VerifyPINRequestL( aMessage, EFalse );
+            break;
+        case EIsDisabledPinBlocked:
+            iWimAuthObjHandler->VerifyDisabledPINRequestL( aMessage );
+            break;
+        case EChangePINReq:
+            iWimSvr->WimTimer()->ResetTimer();
+            iWimAuthObjHandler->ChangePINRequestL( aMessage );
+            break;
+        case ECancelChangePin:
+            iWimAuthObjHandler->CancelChangePin( aMessage );
+            break;
+        case EEnablePINReq:
+            iWimSvr->WimTimer()->ResetTimer();
+            iWimAuthObjHandler->EnablePINReqL( aMessage );
+            break;
+        case ECancelEnablePin:
+            iWimAuthObjHandler->CancelEnablePin( aMessage );
+            break;
+        case EUnblockPinReq:
+            iWimSvr->WimTimer()->ResetTimer();
+            iWimAuthObjHandler->UnblockPinReqL( aMessage );
+            break;
+        case ECancelUnblockPin:
+            iWimAuthObjHandler->CancelUnblockPin( aMessage );
+            break;
+        case EVerifyPinReq:
+            iWimSvr->WimTimer()->ResetTimer();
+            iWimAuthObjHandler->VerifyPINRequestL( aMessage, ETrue );
+            break;
+        case ECancelVerifyPin:
+            iWimAuthObjHandler->CancelVerifyPin( aMessage );
+            break;
+        case ERetrieveAuthObjsInfo:
+            iWimAuthObjHandler->RetrieveAuthObjectsInfo( aMessage ); 
+            break;
+
+//==================== Key operations ==========================================
+        case EGetKeyDetails:
+            iWimKeyMgmtHandler->GetKeyDetailsL( aMessage );
+            break;
+        case EGetKeyList:
+            iWimKeyMgmtHandler->GetKeyListL( aMessage, iWimMgmt );
+            break;
+        case EDoesPvKeyExist:
+            iWimKeyMgmtHandler->DoesKeyExistL( aMessage );
+            break; 
+
+//==================== Certificate Management ==================================
+        case EGetWIMCertLst:
+            iWimCertHandler->GetCertificatesFromWimL( aMessage, iWimMgmt );
+            break;
+        case EGetCertCount:
+            iWimCertHandler->GetCerticateCountL( aMessage, iWimMgmt );
+            break;
+        case EGetWIMCertDetails:
+            iWimCertHandler->GetCertificateDetailsL( EGetWIMCertDetails,
+                                                     aMessage );
+            break;
+        case EGetCertExtras:    // Get cert extra data (e.g. trusted usage)
+            iWimCertHandler->GetExtrasFromWimL( aMessage, iWimMgmt );
+            break;
+        case EStoreCertificate:
+            iWimCertHandler->StoreCertificateL( EStoreCertificate, aMessage );
+            break;
+        case ERemoveCertificate:
+            iWimCertHandler->RemoveCertificateL( aMessage, iWimMgmt );
+            break;
+        case EExportPublicKey:
+            iWimCertHandler->ExportPublicKeyL( aMessage );
+            break;
+
+//==================== Digital signature =======================================
+        case ESignTextReq:
+            iWimSignTextHandler->SignTextL( aMessage );
+            break;
+
+//==================== Java Provisioning ========================================
+        case EGetACIFFileSize:
+            iWimJavaProvisioning->ACIFFileSizeL( aMessage );
+            break;
+        case EGetACIFFile:
+            iWimJavaProvisioning->ACIFFileContentL( aMessage );
+            break;
+        case EGetACFFileSize:
+            iWimJavaProvisioning->ACFFileSizeL( aMessage );
+            break;
+        case EGetACFFile:
+            iWimJavaProvisioning->ACFFileContentL( aMessage );
+            break;    
+        case EGetLabelAndPath:
+            iWimJavaProvisioning->LabelAndPath( aMessage );
+            break;
+            
+//==================== OMA Provisioning ========================================
+        case EGetOMAFileSize:
+            iWimOmaProvisioning->OmaFileSizeL( aMessage );
+            break;
+        case EGetOMAFile:
+            iWimOmaProvisioning->OmaFileContentL( aMessage );
+            break;            
+
+//==================== Trust Settings  =========================================
+        case EGetTrustSettings:
+            iWimTrustSettingsHandler->GetTrustSettingsL( aMessage );
+            break;
+        case ESetApplicability: 
+            iWimTrustSettingsHandler->SetApplicabilityL( aMessage );
+            break;
+        case ESetTrust:
+            iWimTrustSettingsHandler->SetTrustL( aMessage );
+            break;
+        case ESetDefaultTrustSettings:
+            iWimTrustSettingsHandler->SetDefaultTrustSettingsL( aMessage );
+            break;
+        case ERemoveTrustSettings:
+            iWimTrustSettingsHandler->RemoveTrustSettingsL( aMessage );
+            break;
+        case ECancelTrustSettings:
+            iWimTrustSettingsHandler->CancelDoing();
+            break;
+
+//==================== Opcode not supported ====================================
+        default:
+            aMessage.Complete( KErrArgument );
+            break;
+        }
+#ifdef __WIM_ENABLE_TRACES
+    funcEnd.UniversalTime();
+    TTimeIntervalMicroSeconds funcTime = funcEnd.MicroSecondsFrom( funcStart );
+    _WIMTRACE3( _L("WIMServer function %d, time %Ld us"), aMessage.Function(), funcTime.Int64() );
+	
+    TInt allocSize = 0;
+    TInt allocCount = User::AllocSize( allocSize );
+    _WIMTRACE3( _L( "WIM|WIMServer|CWimSession::DispatchMessageL|End, heap=%d, heapsize=%d" ), allocCount, allocSize );
+#endif // __WIM_ENABLE_TRACES
+
+    // Assuming that WIMI calls are asynchronous
+    iWimSvr->SetIsAccessingToken( EFalse ); // HW access complete
+
+    // Has the card data been modified during service? -> re-init
+    if ( iWimSvr->RefreshNotificationReceived() )
+        {
+        iWimSvr->SetRefreshNotificationReceived( EFalse );
+        RefreshWimi();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSession::GetWimRefListL
+// Fetches the list of the references of WIMs currently associated with readers.
+// -----------------------------------------------------------------------------
+//
+void CWimSession::GetWimRefListL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSession::GetWIMRefListL | Begin"));
+    WIMI_Ref_pt pWimRefTemp = NULL;
+
+    HBufC8* buf = iWimUtilFuncs->DesLC( 0, *iMessage );
+    TUint32* wimRef =  ( TUint32* )( buf->Des().Ptr() );
+    TUint8 wimIndex = 0;
+    for ( ; wimIndex < KWimMaxCount && 
+            ( pWimRefTemp = WIMI_GetWIMRef( wimIndex ) ) != NULL; wimIndex++ )
+        {
+        wimRef[wimIndex] = ( TUint32 )pWimRefTemp;
+        iWimMgmt->AppendWIMRefL( pWimRefTemp );     // takes ownership
+        }
+    iMessage->WriteL( 0, buf->Des() );
+    CleanupStack::PopAndDestroy( buf );
+
+    iMessage->Complete( KErrNone );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSession::GetWimCountL
+// Fetches the count of WIM cards in use.
+// -----------------------------------------------------------------------------
+//
+void CWimSession::GetWimCountL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSession::GetWimCountL | Begin"));
+    WIMI_Ref_t* temp = NULL;
+    TUint8 wimIndex = 0 ;
+    for ( ; wimIndex < KWimMaxCount &&
+        ( temp = WIMI_GetWIMRef( wimIndex ) ) != NULL; wimIndex++ )
+        {
+        free_WIMI_Ref_t( temp );
+        }
+
+    TPckgBuf<TUint> pckg( wimIndex );
+    iMessage->WriteL( 0, pckg );
+    iMessage->Complete( KErrNone );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSession::TimerExpired
+// Timer for closing WIM card. WIM is opened again with EVerifyPinReq after
+// new initialization.
+// -----------------------------------------------------------------------------
+//
+void CWimSession::TimerExpired()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSession::TimerExpired | Begin"));
+    WIMI_Ref_pt pWimRefTemp = NULL;
+
+    pWimRefTemp = WIMI_GetWIMRef( 0 );
+ 
+    if ( pWimRefTemp )  // Close the WIM
+        {
+        WIMI_CloseWIM( pWimRefTemp );
+        free_WIMI_Ref_t( pWimRefTemp );
+        }
+    CWimServer::SetWimInitialized( EFalse, KErrNone );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSession::NotifyOnRemoval
+// Notify on card removal. Store message for completing.
+// -----------------------------------------------------------------------------
+//
+void CWimSession::NotifyOnRemovalL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSession::NotifyOnRemoval | Begin"));
+    if ( iNotifyMessage ) // Message already pending
+        {
+        _WIMTRACE(_L("WIM|WIMServer|CWimSession::NotifyOnRemoval|KErrAlreadyExists"));
+        iMessage->Complete( KErrAlreadyExists );
+        return;
+        }
+    iNotifyMessage = new( ELeave ) RMessage2( *iMessage ); // Store message
+    _WIMTRACE(_L("WIM|WIMServer|CWimSession::NotifyOnRemoval|iNotifyMessage created"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSession::CancelNotifyOnRemoval
+// Cancels NotifyOnRemoval request if it is pending.
+// -----------------------------------------------------------------------------
+//
+void CWimSession::CancelNotifyOnRemoval()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSession::CancelNotifyOnRemoval | Begin"));
+    if ( iNotifyMessage )
+        {
+        _WIMTRACE(_L("WIM | WIMServer | CWimSession::CancelNotifyOnRemoval | iNotifyMessage completed with KErrCancel"));
+        iNotifyMessage->Complete( KErrCancel ); // Complete pending message
+        delete iNotifyMessage;
+        iNotifyMessage = NULL;
+        }
+    _WIMTRACE(_L("WIM | WIMServer | CWimSession::CancelNotifyOnRemoval | Message completed with KErrNone"));
+    iMessage->Complete( KErrNone ); // Complete Cancel message
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSession::NotifyComplete
+// Complete NotifyOnRemoval message
+// -----------------------------------------------------------------------------
+//
+void CWimSession::NotifyComplete()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSession::NotifyComplete | Begin"));
+    if ( iNotifyMessage )
+        {
+        iNotifyMessage->Complete( KErrNone );
+        delete iNotifyMessage;
+        iNotifyMessage = NULL;
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimSession::RequestAccessesHW
+// Check if current request accesses HW
+// -----------------------------------------------------------------------------
+//
+TBool CWimSession::RequestAccessesHW( TInt aFunction )
+	{
+	TBool rc( EFalse );
+
+	switch ( aFunction )
+		{
+        // Requests that access HW
+        case EWimInitialize:        //lint -fallthrough
+//==================== WIM card management =====================================
+        case EWIMClose:             //lint -fallthrough
+//==================== PIN operations ==========================================
+        case EIsPinBlocked:         //lint -fallthrough
+        case EChangePINReq:         //lint -fallthrough
+        case EEnablePINReq:         //lint -fallthrough
+        case EUnblockPinReq:        //lint -fallthrough
+        case EVerifyPinReq:         //lint -fallthrough
+//==================== Certificate Management ==================================
+        case EGetWIMCertDetails:    //lint -fallthrough
+        case EStoreCertificate:     //lint -fallthrough
+        case ERemoveCertificate:    //lint -fallthrough
+        case EExportPublicKey:      //lint -fallthrough
+//==================== Digital signature =======================================
+        case ESignTextReq:          //lint -fallthrough
+//==================== OMA Provisioning ========================================
+        case EGetOMAFileSize:       //lint -fallthrough
+        case EGetOMAFile:
+//==================== JAVA Proisioning ========================================
+		case EGetACIFFileSize:
+		case EGetACIFFile:
+		case EGetACFFileSize:
+		case EGetACFFile:
+	    case EGetLabelAndPath:        
+			rc = ETrue;
+            break;
+
+        // Request does not access HW
+        default:
+            break;
+		}
+	return rc;
+	}
+
+
+// -----------------------------------------------------------------------------
+// CWimSession::RefreshWimi
+// Data on card has changed, re-init Wimi.
+// -----------------------------------------------------------------------------
+//
+void CWimSession::RefreshWimi()
+    {
+    RArray<CWimSession*> sessions;
+    TRAPD( err, iWimSvr->GetSessionsL( sessions ));
+
+    if ( !err )  // Got sessions correctly
+        {
+        TInt count = sessions.Count();
+        // Loop through all sessions and notify all clients that are
+        // requesting the notification
+        for ( TInt i( 0 ); i < count; i++ )
+            {
+            sessions[i]->NotifyComplete();
+            }
+        sessions.Reset();
+        // Close WIMI
+        WIMI_CloseDownReq();
+        _WIMTRACE(_L("WIM | CWimSession::RefreshWimi | WIMI closed."));
+        }
+    else
+        {
+        _WIMTRACE(_L("WIM | CWimSession::RefreshWimi: FAILED to get sessions."));
+        }
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimSessionRegistry.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,115 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Registry of WimServer sessions
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimSessionRegistry.h"
+#include    "WimTrace.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimSessionRegistry::CWimSessionRegistry()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSessionRegistry::CWimSessionRegistry | Begin"));
+    }
+
+// Destructor
+CWimSessionRegistry::~CWimSessionRegistry()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSessionRegistry::~CWimSessionRegistry | Begin"));
+    iSessions.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSessionRegistry::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimSessionRegistry* CWimSessionRegistry::NewL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSessionRegistry::NewL | Begin"));
+    CWimSessionRegistry* self = new( ELeave ) CWimSessionRegistry();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSessionRegistry::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimSessionRegistry::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSessionRegistry::ConstructL | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSessionRegistry::AddSession
+// Add session to array
+// -----------------------------------------------------------------------------
+//
+void CWimSessionRegistry::AddSessionL( CWimSession* aSession )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSessionRegistry::AddSessionL | Begin"));
+    iSessions.AppendL( aSession );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSessionRegistry::GetSessionsL
+// Get array of sessions
+// -----------------------------------------------------------------------------
+//
+void CWimSessionRegistry::GetSessionsL( RArray<CWimSession*>& aSessions ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSessionRegistry::GetSessionsL | Begin"));
+    TInt count = iSessions.Count();
+    for( TInt i = 0; i < count; ++i )
+        {
+        aSessions.AppendL( iSessions[ i ] );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSessionRegistry::RemoveSession
+// Remove session from array
+// -----------------------------------------------------------------------------
+//
+void CWimSessionRegistry::RemoveSession( CWimSession* aSession )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSessionRegistry::RemoveSession | Begin"));
+	TInt sessionCount = iSessions.Count();
+    for( TInt i = 0; i < sessionCount; ++i )
+        {
+        if( iSessions[ i ] == aSession )
+            {
+            iSessions.Remove( i );
+            break;
+            }
+        }
+    iSessions.Compress();
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimSignTextHandler.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,581 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Services for Sign Text operation
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimServer.h"
+#include    "Wimi.h"            // WIMI definitions
+#include    "WimClsv.h"
+#include    "WimSignTextHandler.h"
+#include    "WimSecurityDlgHandler.h"
+#include    "WimCallbackImpl.h"
+#include    "WimTrace.h"
+#include    "WimCleanup.h"
+#include    <secdlg.h>
+
+#ifdef _DEBUG
+_LIT( KWimSignTextPanic, "WimSignText" );
+#endif
+
+//In secdlg.h Maxlength is defined as 32, which disobeies WIM standard.
+//According to WIM standard Pin length should be 4~8
+const TInt KWIMMaxPINLength = 8;
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimSignTextHandler::CWimSignTextHandler
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimSignTextHandler::CWimSignTextHandler() : CActive( EPriorityStandard )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSignTextHandler::CWimSignTextHandler | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSignTextHandler::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimSignTextHandler::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSignTextHandler::ConstructL | Begin"));
+    CActiveScheduler::Add( this );
+    iWimUtilFuncs = CWimUtilityFuncs::NewL();
+    iWimSecDlg = CWimSecurityDlgHandler::NewL();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimAuthObjHandler::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimSignTextHandler* CWimSignTextHandler::NewL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSignTextHandler::NewL | Begin"));
+    CWimSignTextHandler* self = new( ELeave ) CWimSignTextHandler;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// Destructor
+CWimSignTextHandler::~CWimSignTextHandler()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSignTextHandler::~CWimAuthObjHandler | Begin"));
+    Cancel();
+    CleanUp();      // frees iSigningDataBuf, iSigningDataPtr, and iKeyReference
+    delete iWimUtilFuncs;
+    delete iWimSecDlg;
+    // iResponseID and iTrId are deleted in callback functions
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSignTextHandler::SignTextL
+// Sign given text. Response is handled in CWimCallback if operation is given
+// to card. Otherwise message is completed here with error value.
+// -----------------------------------------------------------------------------
+//
+void CWimSignTextHandler::SignTextL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSignTextHandler::SignTextL | Begin"));
+
+    __ASSERT_DEBUG( iResponseID == NULL, User::Panic( KWimSignTextPanic, KErrGeneral ) );
+    iResponseID = new( ELeave ) CWimResponse( aMessage );
+    iResponseID->iOpcode = ESignTextReq;
+
+    __ASSERT_DEBUG( iTrId == NULL, User::Panic( KWimSignTextPanic, KErrGeneral ) );
+    iTrId = iWimUtilFuncs->TrIdLC( iResponseID, EWimMgmtReq );
+    CleanupStack::Pop( iTrId );
+
+    TPckgBuf<TKeySignParameters> signPckg;
+    aMessage.ReadL( 1, signPckg );
+
+    // Data to be signed
+    iSigningDataBuf = iWimUtilFuncs->DesLC( 2, aMessage );
+    CleanupStack::Pop( iSigningDataBuf );
+    
+    iSigningDataPtr = new( ELeave ) TPtr8( iSigningDataBuf->Des() );
+    
+    // Key ID
+    TBuf8<KKeyIdLen> keyIdBuf = signPckg().iKeyId;
+    TPtr8 keyIdHash( const_cast<TUint8*>( keyIdBuf.Ptr() ), keyIdBuf.Length() );
+    WIMI_Ref_t* keyRef;
+    WIMI_GetKeyByHash( ( TUint8* )keyIdHash.Ptr(), &keyRef );
+    iKeyReference = ( TAny* )keyRef; // Key reference
+
+    iRetry = EFalse;
+    GetPinParamsL( iPinParams ); // Get PIN parameters
+
+    AskPin(); // Ask PIN
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSignTextHandler::AskPin
+// Ask PIN from user
+// -----------------------------------------------------------------------------
+//
+void CWimSignTextHandler::AskPin()
+    {
+    TBool IsWIMOpen = EFalse;
+    iSigningState = EAskPin;
+    iStatus = KRequestPending;
+    SetActive();
+    
+   	_WIMTRACE(_L("WIM | WIMServer | CWimSignTextHandler::AskPin "));
+    WIMI_Ref_pt pWimRefTemp = NULL;
+    pWimRefTemp = WIMI_GetWIMRef( 0 );
+ 
+    if ( pWimRefTemp )  // Close the WIM
+       {
+       if ( WIMI_IsWIMOpened( pWimRefTemp ) )
+           {
+       	   IsWIMOpen = ETrue;
+           }
+       free_WIMI_Ref_t( pWimRefTemp );
+       }
+    
+    if( IsWIMOpen )
+    	{
+    	TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+    	}
+    else
+    	{
+    	iWimSecDlg->EnterPIN( iRetry,
+        	                  iPinParams,
+        	                  iSigningPin, 
+        	                  iStatus );	
+    	}
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSignTextHandler::GetPinParamsL
+// Get parameters for PIN. iKeyReferense has to be set before this function
+// is used.
+// -----------------------------------------------------------------------------
+//
+void CWimSignTextHandler::GetPinParamsL( TPINParams& aPinParams ) const
+    {
+    TInt pushed = 0;
+    TPINLabel pinLabel;    // The label that identifies the PIN
+	TPINLabel tokenLabel;  // The label of the token
+	TUint8 minLength = 0;  // The minimum length of the PIN
+
+    WIMI_STAT status = WIMI_Ok;
+
+    // WIMI_GetKeyInfo()
+    WIMI_Ref_t* pWimRef;    
+    TUint8 keyType;
+    TUint8 keyNumber;
+    TUint8 pinNumber;
+    TUint16 usage;
+    TUint16 keyLength;
+    WIMI_BinData_t ptKeyLabel;
+    WIMI_BinData_t ptKeyId;
+    // WIMI_GetPINList()
+    WIMI_Ref_pt pPinRef = NULL;
+    TUint16 pinNum;
+    WIMI_RefList_t pinRefLst;
+    // WIMI_GetPINStatus()
+    TUint8 flags;
+    WIMI_BinData_t ptPinLabel;
+    WIMI_Ref_t* cmeWimRef = NULL;
+    // WIMI_GetWIMInfo()
+    TUint16 wimFlags;
+    TUint8 seSet;
+    TUint8 version;
+    WIMI_BinData_t ptWimID;
+    WIMI_BinData_t ptManufacturerID;
+    WIMI_BinData_t ptWimLabel;
+    TUint8 reader = 0; 
+    TBool sim; 
+
+    // Get PIN number by Key reference
+    status = WIMI_GetKeyInfo( iKeyReference,
+                              &pWimRef,
+                              NULL,
+                              &keyType,
+                              &keyNumber,
+                              &pinNumber,
+                              &usage,
+                              &ptKeyId,
+                              &ptKeyLabel,
+                              &keyLength );
+    if ( status != WIMI_Ok )
+        {
+        User::Leave( CWimUtilityFuncs::MapWIMError( status ) );
+        }
+
+    // TODO: leaving PushL functions should not be used
+
+    CleanupPushWimRefL( pWimRef );
+    pushed++;
+    CleanupPushWimBufL( ptKeyId );
+    pushed++;
+    CleanupPushWimBufL( ptKeyLabel );
+    pushed++;
+    
+    // Get PIN references
+    status = WIMI_GetPINList( pWimRef, &pinNum, &pinRefLst );
+    if ( status == WIMI_Ok )
+        {
+        // Select right reference by PIN number
+        pPinRef = pinRefLst[pinNumber];
+        }
+    CleanupPushWimRefListL( pinRefLst );
+    pushed++;
+
+    if ( pPinRef )
+        {
+        // Get PIN info (label, min length etc.)
+        status = WIMI_GetPINStatus( pPinRef,
+                                    &cmeWimRef,
+                                    &flags,
+                                    &minLength,
+                                    &pinNumber,
+                                    &ptPinLabel );
+        if ( status != WIMI_Ok )
+            {
+            User::Leave( CWimUtilityFuncs::MapWIMError( status ) );
+            }
+        CleanupPushWimRefL( cmeWimRef );
+        pushed++;
+        CleanupPushWimBufL( ptPinLabel );
+        pushed++;
+
+        HBufC8* pinLabelBuf = HBufC8::NewLC( ptPinLabel.ui_buf_length );
+        pushed++;
+
+        TPtr8 pinPtr = pinLabelBuf->Des();
+        pinPtr.Copy( ptPinLabel.pb_buf, ptPinLabel.ui_buf_length );
+        pinLabel.Copy( pinPtr );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    // Get token label
+    status = WIMI_GetWIMInfo( cmeWimRef,
+                              &wimFlags,
+                              &seSet,
+                              &ptWimID,
+                              &ptManufacturerID,
+                              &ptWimLabel,
+                              &reader, 
+                              &pPinRef, 
+                              &sim, 
+                              &version );
+    if ( status != WIMI_Ok )
+        {
+        User::Leave( CWimUtilityFuncs::MapWIMError( status ) );
+        }
+    CleanupPushWimBufL( ptWimLabel );
+    pushed++;
+    CleanupPushWimBufL( ptWimID );
+    pushed++;
+    CleanupPushWimBufL( ptManufacturerID );
+    pushed++;
+
+    HBufC8* wimLabelBuf = HBufC8::NewLC( ptWimID.ui_buf_length );
+    pushed++;
+
+    TPtr8 wimLabelPtr( wimLabelBuf->Des() );
+    wimLabelPtr.Copy( ptWimLabel.pb_buf, ptWimLabel.ui_buf_length );
+
+    tokenLabel.Copy( wimLabelPtr ); // Copy token label
+    
+    aPinParams.iPINLabel = pinLabel;
+    aPinParams.iTokenLabel = tokenLabel;
+    aPinParams.iMinLength = minLength;
+    aPinParams.iMaxLength = KWIMMaxPINLength; // Use max value
+
+    CleanupStack::PopAndDestroy( pushed, pWimRef );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSignTextHandler::ContinueSigningL
+// Continues signing operation after signing PIN has asked from user.
+// Call WIMI and return error code in iStatus in case digital signature
+// can not be done e.g. wrong PIN has entered.
+// -----------------------------------------------------------------------------
+//
+void CWimSignTextHandler::ContinueSigningL()
+    {
+    _WIMTRACE(_L("WIM|WIMServer|CWimSignTextHandler::ContinueSigningL|Begin"));
+
+    WIMI_BinData_t pPin;
+
+    // Copy signing PIN to 8 bit buffer
+    HBufC8* signingPinBuf = HBufC8::NewLC( iSigningPin.Length() );
+    TPtr8 signingPin = signingPinBuf->Des();
+    signingPin.Copy( iSigningPin );
+    pPin.pb_buf = ( TUint8* )signingPin.Ptr();
+    pPin.ui_buf_length = ( TUint16 )signingPin.Length();
+
+    iStatus = KRequestPending;
+    TRequestStatus* status = &iStatus;
+    iSigningState = ECallbackResponse;
+    SetActive();
+
+    iResponseID->iStatus = WIMI_SignReq( iTrId,
+                                         ( TUint8* )iSigningDataPtr->Ptr(),
+                                         ( TUint8 )iSigningDataPtr->Length(),
+                                         iKeyReference,
+                                         &pPin );
+
+    CleanupStack::PopAndDestroy( signingPinBuf );
+    
+    // Some error in WIMI (no connection to card etc.) 
+    // Request not completed by callback function
+    if ( iResponseID->iStatus != WIMI_Ok )
+        {
+        iSigningState = EWimiError;
+        User::RequestComplete( status, iResponseID->iStatus );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSignTextHandler::CleanUp
+// Clean up member data
+// -----------------------------------------------------------------------------
+//
+void CWimSignTextHandler::CleanUp()
+    {
+    if( iSigningDataBuf )
+        {
+        delete iSigningDataBuf;
+        iSigningDataBuf = NULL;	
+        }
+    
+    if( iSigningDataPtr )
+        {
+        delete iSigningDataPtr;
+        iSigningDataPtr = NULL;	
+        }
+    
+    WIMI_Ref_t* keyRef = iKeyReference;
+    free_WIMI_Ref_t( keyRef );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSignTextHandler::RunL
+// Handle digital signature operation as state machine. Handle different
+// states here.
+// -----------------------------------------------------------------------------
+//
+void CWimSignTextHandler::RunL()
+    {
+    _WIMTRACE2(_L("WIM|WIMServer|CWimSignTextHandler::RunL|status=%d"), iStatus.Int());
+
+    switch ( iSigningState )
+        {
+        // PIN asked
+        case EAskPin:
+            {       
+            iRetry = ETrue; // Next is retry
+
+            if ( iStatus.Int() != KErrNone ) // Cancelled or other error
+                {
+                if( iResponseID )
+                    {
+                    if( iStatus.Int() == KErrCancel )
+	                	{
+	                	iResponseID->iStatus = WIMI_ERR_UserCancelled;
+	                	}
+                    else
+	                	{
+	                	iResponseID->iStatus = ( TUint16 )iStatus.Int();	
+	                	}
+                    iResponseID->CompleteMsgAndDelete();
+                    iResponseID = NULL;	
+                    }
+                
+                if( iTrId )
+                    {
+                    delete iTrId;
+                    iTrId = NULL;	
+                    }
+                
+                CleanUp();
+                }
+            else  // User entered PIN without errors
+                {
+                CWimCallBack::SetSignTextRequestStatus( &iStatus );
+                ContinueSigningL(); // Continue digital signature operation
+                }
+            break;
+            }
+        
+        // We come here from CWimCallBack::SignResp()
+        case ECallbackResponse:
+            {
+            CWimCallBack::SetSignTextRequestStatus( NULL );
+
+            if ( iStatus.Int() == WIMI_ERR_BadPIN ) // Wrong PIN, continue
+                {
+                AskPin(); // Ask PIN again and continue
+                }
+            // If PIN is blocked show note
+            else if ( iStatus.Int() == WIMI_ERR_PINBlocked )
+                {
+                iSigningState = EShowPinBlocked;
+                iWimSecDlg->ShowPINBlocked( iPinParams, iStatus );
+                SetActive();
+                }
+             else if ( iStatus.Int() == WIMI_ERR_CardIOError )
+                    {
+                    iSigningState = EShowCardIsRemoved;
+	                  iStatus = KRequestPending;
+                    TRequestStatus* status = &iStatus;
+                    SetActive();
+                    User::RequestComplete( status, KErrNone );
+                	  }
+            else // Response completed in callbacks, just finalize operation 
+                {
+                iStatus = KRequestPending;
+                iSigningState = ESigningDone;
+                TRequestStatus* status = &iStatus;
+                SetActive();
+                User::RequestComplete( status, KErrNone );
+                }
+            break;
+            }
+
+        // PIN Blocked note showed to user
+        case EShowPinBlocked:
+            {
+            // Complete message here with KErrLocked
+            if( iResponseID )
+                {
+                iResponseID->iStatus = WIMI_ERR_PINBlocked;
+                iResponseID->CompleteMsgAndDelete();
+                iResponseID = NULL;	
+                }
+            
+            if( iTrId )
+                {
+                delete iTrId;
+                iTrId = NULL;	
+                }
+            
+            iStatus = KRequestPending;
+            iSigningState = ESigningDone;
+            TRequestStatus* status = &iStatus;
+            SetActive();
+            User::RequestComplete( status, KErrNone );
+            break;
+            }
+        case EShowCardIsRemoved:
+               {
+               if( iResponseID )
+                        {
+                        iResponseID->iStatus = WIMI_ERR_CardIOError;
+                    	iResponseID->CompleteMsgAndDelete();
+                    	iResponseID = NULL;	
+                        }
+                	if( iTrId )
+                		{
+                		delete iTrId;
+                    	iTrId = NULL;	
+                		}
+               
+               iStatus = KRequestPending;
+               iSigningState = ESigningDone;
+               TRequestStatus* status = &iStatus;
+               SetActive();
+               User::RequestComplete( status, KErrNone );
+               break;
+               }            
+        // WIMI error. Message is not completed in callback function.
+        // So, complete it here
+        case EWimiError:
+            {
+            CWimCallBack::SetSignTextRequestStatus( NULL );
+            
+            if( iResponseID )
+                {
+                iResponseID->iStatus = ( TUint16 )iStatus.Int();
+                iResponseID->CompleteMsgAndDelete();
+                iResponseID = NULL;	
+                }
+            if ( iTrId )
+                {
+                delete iTrId;
+                iTrId = NULL;	
+                }
+           
+            CleanUp();
+            break;
+            }
+        
+        // Text is signed, handle response in callback functions
+        case ESigningDone:
+            {
+            CleanUp();
+            iResponseID = NULL;
+            iTrId = NULL;
+            break;
+            }    
+
+        default:
+            {
+            CleanUp();
+            break;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSignTextHandler::DoCancel
+// Asyncronous call cancelled.
+// -----------------------------------------------------------------------------
+//
+void CWimSignTextHandler::DoCancel()
+    {
+    _WIMTRACE(_L("WIM|WIMServer|CWimSignTextHandler::DoCancel|Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSignTextHandler::RunError
+// RunL leaved, handle error here.
+// -----------------------------------------------------------------------------
+//
+TInt CWimSignTextHandler::RunError( TInt aError )
+    {
+    CWimCallBack::SetSignTextRequestStatus( NULL );
+    if( iResponseID )
+        {
+        iResponseID->iStatus = ( TUint16 )aError;
+        iResponseID->CompleteMsgAndDelete();
+        iResponseID = NULL;	
+        }
+    if( iTrId )
+        {
+   	    delete iTrId;
+        iTrId = NULL;
+        }
+    
+    CleanUp();
+    return KErrNone;
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimSimFileHandler.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,306 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Handler for Wimlib request for SIM file reading. Calls 
+*               services from CustomAPI to read file and returns read file
+*               to WIMI (and Wimlib)
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimSimFileHandler.h"
+#include    "Wimi.h"                // WIMI
+#include    "WimTrace.h"
+#include    <mmtsy_names.h>         // TSY and Phone name
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimSimFileHandler::CWimSignTextHandler
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimSimFileHandler::CWimSimFileHandler() : CActive( EPriorityStandard )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::CWimSimFileHandler | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSimFileHandler::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimSimFileHandler::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::ConstructL | Begin"));
+    CActiveScheduler::Add( this );
+
+    //Create new CustomAPI instance
+    iCustomApi = new( ELeave ) RMmCustomAPI;
+    OpenCustomApiL(); // Open connection to CustomAPI
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSimFileHandler::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimSimFileHandler* CWimSimFileHandler::NewL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::NewL | Begin"));
+    CWimSimFileHandler* self = new( ELeave ) CWimSimFileHandler;
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::NewL | End"));
+    return self;
+    }
+  
+// Destructor
+CWimSimFileHandler::~CWimSimFileHandler()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::~CWimSimFileHandler | Begin"));
+    if ( iCustomApi )
+        {
+        iCustomApi->Close();
+        }
+    if ( iEtelServer )
+        {
+        iEtelServer->Close();
+        }
+    delete iCustomApi;
+    delete iEtelServer;
+    Cancel();
+    delete iResponseBytesBuf;
+    delete iResponseBytesPtr;
+    _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::~CWimSimFileHandler | End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSimFileHandler::OpenCustomApiL
+// Open CustomAPI for communication
+// -----------------------------------------------------------------------------
+//  
+void CWimSimFileHandler::OpenCustomApiL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::OpenCustomApiL | Begin"));
+    iEtelServer = new( ELeave ) RTelServer();
+    
+    RMobilePhone phone;
+
+    // Connect to the Etel server.
+    TInt ret = iEtelServer->Connect();
+    
+    if ( ret != KErrNone )
+        {
+        _WIMTRACE2(_L("WIM | WIMServer | CWimSimFileHandler::OpenCustomApiL | Connection to etel server failed: %d"), ret);
+        User::Leave( ret );
+        }
+
+    // Load phone module.
+    ret = iEtelServer->LoadPhoneModule( KMmTsyModuleName );
+    
+    if ( ret != KErrNone )
+        {
+        _WIMTRACE2(_L("WIM | WIMServer | CWimSimFileHandler::OpenCustomApiL | loading phone module failed: %d"), ret);
+        User::Leave( ret );
+        }
+    
+    // Open phone
+    ret = phone.Open( *iEtelServer, KMmTsyPhoneName );
+         
+    if ( ret != KErrNone )
+        {
+        _WIMTRACE2(_L("WIM | WIMServer | CWimSimFileHandler::OpenCustomApiL | phone.Open failed: %d"), ret);
+        User::Leave( ret );
+        }
+    
+    // Open new CustomAPI session for phone
+    ret = iCustomApi->Open( phone );
+
+    phone.Close(); // Close phone
+
+    if ( ret != KErrNone )
+        {
+        _WIMTRACE2(_L("WIM | WIMServer | CWimSimFileHandler::OpenCustomApiL | iCustomApi->Open failed: %d"), ret);
+        User::Leave( ret );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSimFileHandler::ReadSimFileL
+// Read SIM file using CustomAPI's ReadSimFile() method.
+// -----------------------------------------------------------------------------
+//
+void CWimSimFileHandler::ReadSimFileL(
+    TUint8 aReader,
+    const TDes8& aPath,
+    TUint16 aOffset,
+    TUint16 aSize )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::ReadSimFileL | Begin"));
+
+    iReaderNumber = aReader;
+
+    TInt size;
+    if ( aSize == 0 ) // Read whole file
+        {
+        size = KMaxSimFileSize;
+        }
+    else
+        {
+        // If size is bigger than maximum file size declared in header file use
+        // declared max size
+        if ( aSize > KMaxSimFileSize )
+            {
+            size = KMaxSimFileSize;
+            }
+        else
+            {
+            size = aSize;
+            }
+        }
+
+    iSimFileInfo.iPath = aPath;
+    iSimFileInfo.iOffSet = aOffset;
+    iSimFileInfo.iSize = ( TUint16 )size;
+
+    RMmCustomAPI::TSimFileInfoPckg simFileInfoPckg( iSimFileInfo );
+
+    iResponseBytesBuf = HBufC8::NewL( size );
+    iResponseBytesPtr = new( ELeave ) TPtr8( NULL, 0, size );
+    iResponseBytesPtr->Set( iResponseBytesBuf->Des() );
+
+    iStatus = KRequestPending;
+
+    _WIMTRACE9(_L("WIM | WIMServer | CWimSimFileHandler::ReadSimFileL | Path = %02x%02x %02x%02x %02x%02x %02x%02x "),
+        iSimFileInfo.iPath[0], iSimFileInfo.iPath[1], iSimFileInfo.iPath[2], iSimFileInfo.iPath[3],
+        iSimFileInfo.iPath[4], iSimFileInfo.iPath[5], iSimFileInfo.iPath[6], iSimFileInfo.iPath[7] );
+
+    _WIMTRACE2(_L("WIM | WIMServer | CWimSimFileHandler::ReadSimFileL | Offset = 0x%04x"), iSimFileInfo.iOffSet );
+
+    iCustomApi->ReadSimFile( iStatus, simFileInfoPckg, *iResponseBytesPtr );
+    
+    SetActiveAndWait(); // Wait request to be completed
+
+    _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::ReadSimFileL | End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSimFileHandler::FileReceivedL
+// Handle received file
+// -----------------------------------------------------------------------------
+//
+void CWimSimFileHandler::FileReceived()
+    {
+    _WIMTRACE2(_L("WIM | WIMServer | CWimSimFileHandler::FileReceived | Begin, error: %d"), iStatus.Int());
+    WIMI_BinData_t responseBytes;
+    
+    TInt error = iStatus.Int();
+    TUint8 status;
+
+    switch ( error )
+        {
+        case KErrPathNotFound:
+            {
+            _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::FileReceived | File not found"));
+            break;
+            }
+        case KErrNotFound:
+            {
+            _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::FileReceived | No data found from file"));
+            break;
+            }
+        case KErrUnknown:
+            {
+            _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::FileReceived | Unknown error"));
+            break;
+            }
+        default:
+            {
+            _WIMTRACE2(_L("WIM | WIMServer | CWimSimFileHandler::FileReceived | Error: %d"), error);
+            break;
+            }
+        }
+
+    if ( error != KErrNone ) // Error occurred in SIM file reading
+        {
+        responseBytes.pb_buf = NULL;
+        responseBytes.ui_buf_length = 0;
+        status = WIMI_Err;
+        }
+    else  // SIM file read succesfully
+        {
+        responseBytes.pb_buf = ( TUint8* )iResponseBytesPtr->Ptr();
+        responseBytes.ui_buf_length = ( TUint16 )iResponseBytesPtr->Length();
+        status = WIMI_Ok;
+        }
+
+    _WIMTRACE2(_L("WIM | WIMServer | CWimSimFileHandler::FileReceived | FileLength = %d"), responseBytes.ui_buf_length);
+    
+    // Pass data to WIMI
+    WIMI_SIM_ReadFileResp( iReaderNumber, status, &responseBytes );
+
+    delete iResponseBytesBuf;
+    iResponseBytesBuf = NULL;
+    delete iResponseBytesPtr;
+    iResponseBytesPtr = NULL;
+    
+    _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::FileReceived | End"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSimFileHandler::RunL
+// Handle CustomAPI response
+// -----------------------------------------------------------------------------
+//
+void CWimSimFileHandler::RunL()
+    {
+    _WIMTRACE2(_L("WIM | WIMServer | CWimSimFileHandler::RunL, status: %d"), iStatus.Int());
+    iWait.AsyncStop();
+    FileReceived();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSimFileHandler::DoCancel
+// Cancel asyncronous request
+// -----------------------------------------------------------------------------
+//
+void CWimSimFileHandler::DoCancel()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::DoCancel | Begin"));
+    delete iResponseBytesBuf;
+    iResponseBytesBuf = NULL;
+    delete iResponseBytesPtr;
+    iResponseBytesPtr = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimSimFileHandler::SetActiveAndWait
+// Wait until asynchronous call is completed
+// -----------------------------------------------------------------------------
+//
+void CWimSimFileHandler::SetActiveAndWait()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::SetActiveAndWait | Begin"));
+    SetActive();
+    iWait.Start();
+    _WIMTRACE(_L("WIM | WIMServer | CWimSimFileHandler::SetActiveAndWait | End"));
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimTimer.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,281 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Timer class
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimTimer.h"
+#include    "WimConsts.h"
+#include    "WimTrace.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimTimer::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimTimer* CWimTimer::NewL( MWimTimerListener* aTimerListener )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::NewL | Begin"));
+    CWimTimer *self = new( ELeave ) CWimTimer;
+    CleanupStack::PushL( self );
+    self->ConstructL( aTimerListener );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTimer::CWimTimer
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimTimer::CWimTimer() : CActive( EPriorityStandard ), iHeartBeatCount( 0 )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::CWimTimer | Begin"));
+    }
+
+// Destructor
+CWimTimer::~CWimTimer()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::~CWimTimer | Begin"));
+    Cancel();
+    iTimer.Close();
+    delete iHeartbeat;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTimer::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimTimer::ConstructL( MWimTimerListener* aTimerListener )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::ConstructL | Begin"));
+    User::LeaveIfError( iTimer.CreateLocal() );
+    iTimerListener = aTimerListener;
+    CActiveScheduler::Add( this );
+    iDelay = 0;
+    iHeartbeat = CHeartbeat::NewL( 0 ); // neutral priority
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTimer::SetCloseAfter
+// Set timeout of timer, delay given in seconds
+// -----------------------------------------------------------------------------
+//
+void CWimTimer::SetCloseAfter( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::SetCloseAfter | Begin"));
+    TInt closeAfter = aMessage.Int0();
+
+    // Check that given value is in limits
+    if ( closeAfter < KWimNoTimeout || closeAfter > KWimTimeoutMax )
+        {
+        aMessage.Complete( KErrArgument );
+        }
+    else // Value is OK, set timer
+        {
+        DoSetCloseAfter( closeAfter );
+        aMessage.Complete( KErrNone );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTimer::SetCloseAfter
+// Set timeout of timer, delay given in seconds
+// -----------------------------------------------------------------------------
+//
+void CWimTimer::DoSetCloseAfter( TInt aCloseAfter )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::DoSetCloseAfter | Begin"));
+    if ( IsActive() ) // Timeout already set, cancel
+        {
+        Cancel();
+        }
+    if ( aCloseAfter == KWimNoTimeout ) // No timeout, cancel timer
+        {
+        Cancel();
+        iDelay = KWimNoTimeout;
+        }
+    else
+        {
+        iDelay = aCloseAfter * 1000 * 1000; // Timer takes delay in microseconds
+        iTimer.After( iStatus, iDelay );
+        SetActive();
+        StartHeartBeat();
+        }
+    }
+// -----------------------------------------------------------------------------
+// CWimTimer::GetCloseAfterL
+// Return delay given in SetCloseAfter in seconds
+// If no timeout is set return -1 (KWimNoTimeout)
+// -----------------------------------------------------------------------------
+//
+void CWimTimer::GetCloseAfterL( const RMessage2& aMessage ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::Delay | Begin"));
+
+    TInt delay = 0;
+
+    if ( iDelay.Int() == KWimNoTimeout )
+        {
+        delay = KWimNoTimeout;
+        }
+    else
+        {
+        // Timer takes delay in microseconds
+        delay = iDelay.Int() / ( 1000 * 1000 );
+        }
+
+    TPckgBuf<TInt> closeAfterPckg( delay  );
+    aMessage.WriteL( 0, closeAfterPckg );
+    aMessage.Complete( KErrNone );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTimer::RunL()
+// Handles an active object’s request completion event
+// -----------------------------------------------------------------------------
+//
+void CWimTimer::RunL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::RunL | Begin"));
+    if ( iTimerListener )
+        {
+        iTimerListener->TimerExpired();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTimer::DoCancel
+// Cancellation of an outstanding request
+// -----------------------------------------------------------------------------
+//
+void CWimTimer::DoCancel()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::DoCancel | Begin"));
+    iTimer.Cancel();
+    iHeartbeat->Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTimer::ResetTimer
+// Resets active timer.
+// -----------------------------------------------------------------------------
+//
+void CWimTimer::ResetTimer()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::ResetTimer | Begin"));
+    if ( IsActive() )
+        {
+        Cancel();
+        iTimer.After( iStatus, iDelay );
+        SetActive();
+        iHeartbeat->Cancel();
+        StartHeartBeat();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTimer::TimeRemainingL
+// Returns remaining time of the timer in seconds. If timer has no timeout
+// then KWimNoTimeout (-1) is returned.
+// -----------------------------------------------------------------------------
+//
+void CWimTimer::TimeRemainingL( const RMessage2& aMessage  ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::TimeRemainingL | Begin"));
+
+    TInt timeRemaining;
+
+    if ( iDelay.Int() == KWimNoTimeout )
+        {
+        timeRemaining = KWimNoTimeout;
+        }
+    else
+        {
+        // Timer takes delay in microseconds
+        TInt delay = iDelay.Int() / ( 1000 * 1000 );
+        timeRemaining = delay - iHeartBeatCount;
+        }
+
+    TPckgBuf<TInt> timeRemainingPckg( timeRemaining  );
+    aMessage.WriteL( 0, timeRemainingPckg );
+    aMessage.Complete( KErrNone );
+    }
+    
+// -----------------------------------------------------------------------------
+// CWimTimer::TimeRemaining
+// Used inside wimserver
+// -----------------------------------------------------------------------------
+//
+TInt CWimTimer::TimeRemaining() const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::TimeRemaining | Begin"));
+
+    TInt timeRemaining;
+
+    if ( iDelay.Int() == KWimNoTimeout )
+        {
+        timeRemaining = KWimNoTimeout;
+        }
+    else
+        {
+        // Timer takes delay in microseconds
+        TInt delay = iDelay.Int() / ( 1000 * 1000 );
+        timeRemaining = delay - iHeartBeatCount;
+        }
+
+    return timeRemaining; 
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTimer::StartHeartBeat
+// Start heart beating
+// -----------------------------------------------------------------------------
+//
+void CWimTimer::StartHeartBeat()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::StartHeartBeat | Begin"));
+    iHeartbeat->Start( ETwelveOClock, this ); // 1 second intervals
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTimer::Beat
+// Beat has occurred, increase counter
+// -----------------------------------------------------------------------------
+//
+void CWimTimer::Beat()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::Beat | Begin"));
+    iHeartBeatCount++;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTimer::Synchronize
+// Synchronize the timer.
+// -----------------------------------------------------------------------------
+//
+void CWimTimer::Synchronize()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTimer::Synchronize | Begin"));
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimTokenHandler.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,231 @@
+/*
+* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Methods for token handling
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimTokenHandler.h"
+#include    "WimMemMgmt.h"
+#include    "WimClsv.h"
+#include    "WimSession.h"
+#include    "WimTimer.h"
+#include    "WimSession.h"
+#include    "WimUtilityFuncs.h"
+#include    "Wimi.h"            //WIMI definitions
+#include    "WimTrace.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimTokenHandler::CWimTokenHandler
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimTokenHandler::CWimTokenHandler()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTokenHandler::CWimTokenHandler | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenHandler::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimTokenHandler::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTokenHandler::ConstructL | Begin"));
+    iWimUtilFuncs = CWimUtilityFuncs::NewL();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenHandler::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimTokenHandler* CWimTokenHandler::NewL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTokenHandler::NewL | Begin"));
+    CWimTokenHandler* self = new( ELeave ) CWimTokenHandler;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// Destructor
+CWimTokenHandler::~CWimTokenHandler()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTokenHandler::~CWimTokenHandler | Begin"));
+    delete iWimUtilFuncs;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenHandler::GetWIMInfoL
+// Fetches WIM info from wimlib
+// -----------------------------------------------------------------------------
+//
+void CWimTokenHandler::GetWIMInfoL(
+    const RMessage2& aMessage,
+    CWimMemMgmt* const aWimMgmt ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTokenHandler::GetWIMInfoL | Begin"));
+    WIMI_Ref_pt pWimRef = const_cast<WIMI_Ref_pt>( aMessage.Ptr0() ); 
+    
+    __ASSERT_ALWAYS( pWimRef, User::Leave( KErrArgument ) );
+    __ASSERT_ALWAYS( aWimMgmt, User::Leave( KErrArgument ) );
+    if ( !aWimMgmt->ValidateWIMRefL( pWimRef ) )
+        {
+        _WIMTRACE(_L("WIM | WIMServer | CWimTokenHandler::GetWIMInfoL | KErrArgument"));
+        User::LeaveIfError( KErrArgument ); 
+        }
+    WIMI_STAT status = WIMI_Ok;
+    
+    WIMI_Ref_pt pinRef;
+    TUint16 flags;
+    TUint8 seSet;
+    TUint8 version;
+    WIMI_BinData_t ptWimID;
+    WIMI_BinData_t ptManufacturerID;
+    WIMI_BinData_t ptLabel;
+    TUint8 reader = 0; 
+    TBool sim; 
+    TPckgBuf<TWimSecModuleStruct> infoPckg;
+    aMessage.ReadL( 1, infoPckg );
+    
+    status = WIMI_GetWIMInfo( pWimRef,
+                              &flags,
+                              &seSet,
+                              &ptWimID,
+                              &ptManufacturerID,
+                              &ptLabel,
+                              &reader, 
+                              &pinRef, 
+                              &sim, 
+                              &version );
+    if ( status == WIMI_Ok )
+        {
+        // Code MAY NOT leave before ptLabel.pb_buf, ptManufacturerID.pb_buf,
+        // and ptWimID.pb_buf are deallocated. Next AppendWIMRefL() takes the
+        // ownership of pinRef struct.
+        TRAPD( err, aWimMgmt->AppendWIMRefL( pinRef ) );
+        if( err )
+            {
+            WSL_OS_Free( ptLabel.pb_buf );
+            WSL_OS_Free( ptManufacturerID.pb_buf );
+            WSL_OS_Free( ptWimID.pb_buf );
+            // Code can leave after this point.
+            User::Leave( err );
+            }
+        infoPckg().iRefPinG = reinterpret_cast< TUint32 >( pinRef );
+        
+        TBuf<KLabelLen> label;
+        label.Copy( TPtr8( 
+                ptLabel.pb_buf,
+                ptLabel.ui_buf_length,
+                ptLabel.ui_buf_length ) );
+        
+        TBuf<KManufacturerLen> manufacturer;
+        manufacturer.Copy( TPtr8(
+                ptManufacturerID.pb_buf,
+                ptManufacturerID.ui_buf_length,
+                ptManufacturerID.ui_buf_length ) );
+
+        TBuf<KSerialNumberLen> serialnumber;
+        serialnumber.Copy( TPtr8(
+                ptWimID.pb_buf,
+                ptWimID.ui_buf_length,
+                ptWimID.ui_buf_length ) );
+
+        infoPckg().iVersion = version;
+        infoPckg().iReader = reader;
+        infoPckg().iLabel = label;
+        infoPckg().iManufacturer = manufacturer;
+        infoPckg().iSerialNumber = serialnumber;
+
+        WSL_OS_Free( ptLabel.pb_buf );
+        WSL_OS_Free( ptManufacturerID.pb_buf );
+        WSL_OS_Free( ptWimID.pb_buf );
+        // Code can leave after this point.
+
+        aMessage.WriteL( 1, infoPckg );
+        }
+
+    aMessage.Complete( CWimUtilityFuncs::MapWIMError( status ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenHandler::IsWIMOpenL
+// Checks if the WIM is already opened.
+// -----------------------------------------------------------------------------
+//
+void CWimTokenHandler::IsWIMOpenL(
+    const RMessage2& aMessage,
+    CWimTimer* const aTimer,
+    CWimMemMgmt* const aWimMgmt ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTokenHandler::IsWIMOpenL | Begin"));
+    WIMI_Ref_pt pWimRef = const_cast<WIMI_Ref_pt>( aMessage.Ptr0() );
+    
+    __ASSERT_ALWAYS( pWimRef, User::Leave( KErrArgument ) );
+    __ASSERT_ALWAYS( aTimer, User::Leave( KErrArgument ) );
+    if ( !aWimMgmt->ValidateWIMRefL( pWimRef ) ) 
+        {
+        _WIMTRACE(_L("WIM | WIMServer | CWimTokenHandler::IsWIMOpenL | KErrArgument"));
+        User::LeaveIfError( KErrArgument ); 
+        }
+
+    TPckgBuf<TBool> pckg;
+    
+    if ( WIMI_IsWIMOpened( pWimRef ) )
+        {
+        pckg() = ETrue;
+        aTimer->ResetTimer();
+        }
+    else
+        {
+        pckg() = EFalse;
+        }
+
+    aMessage.WriteL( 1, pckg );
+    aMessage.Complete( KErrNone );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTokenHandler::CloseWIM
+// Closes connection to WIM card.
+// -----------------------------------------------------------------------------
+//
+void CWimTokenHandler::CloseWIM( const RMessage2& aMessage ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTokenHandler::CloseWIM | Begin"));
+    WIMI_STAT status = KErrNone;
+    WIMI_Ref_pt wimRef = const_cast<WIMI_Ref_pt>( aMessage.Ptr0() );
+
+    if ( wimRef )
+        {
+        status = WIMI_CloseWIM( wimRef );
+        }
+    else
+        {
+        status = WIMI_ERR_BadParameters;
+        }
+    aMessage.Complete( CWimUtilityFuncs::MapWIMError( status ) );
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimTrustSettingsHandler.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,338 @@
+/*
+* Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Handler class for Trust Settings Store calls from WimClient
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimTrustSettingsHandler.h"
+#include    "WimTrustSettingsStore.h"
+#include    "WimClsv.h"
+#include    "WimCertInfo.h"
+#include    "WimTrace.h"
+
+#ifdef _DEBUG
+_LIT( KWimTrustSettPanic, "WimTrustSett" );
+#endif
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsHandler::CWimTrustSettingsHandler
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimTrustSettingsHandler::CWimTrustSettingsHandler( 
+    CWimTrustSettingsStore* aWimTrustSettingsStore )
+    : CActive( EPriorityStandard ),
+      iWimTrustSettingsStore( aWimTrustSettingsStore )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTrustSettingsHandler::CWimTrustSettingsHandler | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsHandler::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsHandler::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTrustSettingsHandler::ConstructL | Begin"));
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsHandler::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimTrustSettingsHandler* CWimTrustSettingsHandler::NewL( 
+    CWimTrustSettingsStore* aWimTrustSettingsStore ) 
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTrustSettingsHandler::NewL | Begin"));
+    CWimTrustSettingsHandler* self = new( ELeave ) CWimTrustSettingsHandler( 
+    aWimTrustSettingsStore );
+ 
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CWimTrustSettingsHandler::~CWimTrustSettingsHandler()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTrustSettingsHandler::~CWimTrustSettingsHandler | Begin"));
+    iApplications.Close();
+    delete iCertInfo;
+    iWimTrustSettingsStore = NULL;  // not owned
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsHandler::GetTrustSettingsL
+// Fetches trust settings for given certificate. 
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsHandler::GetTrustSettingsL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTrustSettingsHandler::GetTrustSettingsL | Begin"));
+
+    TPckgBuf<TWimCertInfoPckg> pckg;
+
+    aMessage.ReadL( 0, pckg );
+
+    __ASSERT_DEBUG( iCertInfo == NULL, User::Panic( KWimTrustSettPanic, KErrGeneral ) );
+    iCertInfo = CWimCertInfo::InternalizeL( pckg() );
+
+    iStatus = KRequestPending;
+    iMessage = aMessage;
+    iPhase = EGetTrustSettings;
+    SetActive();
+    iWimTrustSettingsStore->GetTrustSettings( *iCertInfo,
+                                              iTrusted,
+                                              iApplications, 
+                                              iStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsHandler::SetApplicabilityL
+// Set applicability for given certificate. New certificate entry is set if
+// one not found from database (trust flag is set to EFalse).
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsHandler::SetApplicabilityL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTrustSettingsHandler::SetApplicabilityL | Begin"));
+
+    TPckgBuf<TWimCertInfoPckg> pckg;
+    aMessage.ReadL( 0, pckg );
+
+    __ASSERT_DEBUG( iCertInfo == NULL, User::Panic( KWimTrustSettPanic, KErrGeneral ) );
+    iCertInfo = CWimCertInfo::InternalizeL( pckg() );
+
+    RArray<TUid> applications;
+    CleanupClosePushL( applications );
+
+    TPckgBuf<TTrustSettings> trustSettingsPckg;
+
+    aMessage.ReadL( 1, trustSettingsPckg );
+
+    TInt applicationCount = trustSettingsPckg().iApplicationCount;
+
+    for ( TInt i = 0; i < applicationCount; i++ )
+        {
+        TUid uid;
+        uid.iUid = trustSettingsPckg().iUids[i];
+        applications.Append( uid );
+        }
+
+    iStatus = KRequestPending;
+    iMessage = aMessage;
+    iPhase = ESetApplicability;
+    SetActive();
+    iWimTrustSettingsStore->SetApplicability( *iCertInfo,
+                                              applications,
+                                              iStatus );
+
+    CleanupStack::PopAndDestroy( &applications );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsHandler::SetTrustL
+// Set trust flag for given certificate. New certificate entry is set if
+// one not found from database.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsHandler::SetTrustL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTrustSettingsHandler::SetTrustL | Begin"));
+
+    TPckgBuf<TWimCertInfoPckg> pckg;
+    aMessage.ReadL( 0, pckg );
+
+    __ASSERT_DEBUG( iCertInfo == NULL, User::Panic( KWimTrustSettPanic, KErrGeneral ) );
+    iCertInfo = CWimCertInfo::InternalizeL( pckg() );
+
+    TPckgBuf<TTrustSettings> trustSettingsPckg;
+
+    aMessage.ReadL( 1, trustSettingsPckg );
+
+    TBool trusted = trustSettingsPckg().iTrusted;
+
+    iStatus = KRequestPending;
+    iMessage = aMessage;
+    iPhase = ESetTrust;
+
+    SetActive();
+
+    iWimTrustSettingsStore->SetTrust( *iCertInfo,
+                                      trusted,
+                                      iStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsHandler::SetDefaultTrustSettingsL
+// Set default trust settings for given certificate. If certificate not
+// found from database new entry is inserted.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsHandler::SetDefaultTrustSettingsL( 
+    const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTrustSettingsHandler::SetDefaultTrustSettingsL | Begin"));
+
+    TPckgBuf<TWimCertInfoPckg> pckg;
+    aMessage.ReadL( 0, pckg );
+   
+    TBool addApps = aMessage.Int1();
+
+    __ASSERT_DEBUG( iCertInfo == NULL, User::Panic( KWimTrustSettPanic, KErrGeneral ) );
+    iCertInfo = CWimCertInfo::InternalizeL( pckg() );
+
+    iStatus = KRequestPending;
+    iMessage = aMessage;
+    iPhase = ESetDefaultTrustSettings;
+    SetActive();
+    iWimTrustSettingsStore->SetDefaultTrustSettings( *iCertInfo,
+                                                     addApps, 
+                                                     iStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsHandler::RemoveTrustSettingsL
+// Remove trust settings of given certificate. If certificate
+// is not found, return with status.Int() = KErrNotFound
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsHandler::RemoveTrustSettingsL( const RMessage2& aMessage )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTrustSettingsHandler::RemoveTrustSettingsL | Begin"));
+
+    TPckgBuf<TWimCertInfoPckg> pckg;
+    aMessage.ReadL( 0, pckg );
+
+    __ASSERT_DEBUG( iCertInfo == NULL, User::Panic( KWimTrustSettPanic, KErrGeneral ) );
+    iCertInfo = CWimCertInfo::InternalizeL( pckg() );
+
+    iStatus = KRequestPending;
+    iMessage = aMessage;
+    iPhase = ERemoveTrustSettings;
+    SetActive();
+    iWimTrustSettingsStore->RemoveTrustSettings( *iCertInfo,
+                                                 iStatus );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsHandler::CancelDoing
+// Cancel ongoing TrustSettingsStore operation
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsHandler::CancelDoing()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTrustSettingsHandler::CancelDoing | Begin"));
+
+    iWimTrustSettingsStore->CancelDoing();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsHandler::RunL
+// Complete asynchronous call
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsHandler::RunL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTrustSettingsHandler::RunL | Begin"));
+
+    delete iCertInfo;
+    iCertInfo = NULL;
+    
+    switch ( iPhase )
+        {
+        case EGetTrustSettings:
+            {
+            TInt applicationCount = iApplications.Count();
+
+            // Check that there is no more apps than allocated in array for
+            // If there is more applications than there is space in array
+            // complete message and return
+            if ( applicationCount > KMaxApplicationCount )
+                {
+                iMessage.Complete( KErrOverflow );
+                iApplications.Close();
+                return;
+                }
+
+            TPckgBuf<TTrustSettings> trustSettings;
+            iMessage.ReadL( 1, trustSettings );
+            trustSettings().iTrusted = iTrusted;
+            trustSettings().iApplicationCount = iApplications.Count();
+
+            for ( TInt i = 0; i < iApplications.Count(); i++ )
+                {
+                trustSettings().iUids[i] = iApplications[i].iUid;
+                }
+
+            iApplications.Close();
+            iMessage.WriteL( 1, trustSettings );
+            break;
+            }
+
+        case ESetDefaultTrustSettings:  // Flow through
+        case ESetApplicability:         // Flow through
+        case ESetTrust:                 // Flow through
+        case ERemoveTrustSettings:
+            {
+            break;
+            }
+
+        default:
+            {
+            break;
+            }
+        }
+
+    iMessage.Complete( iStatus.Int() );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsHandler::DoCancel
+// 
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsHandler::DoCancel()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTrustSettingsHandler::DoCancel | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsHandler::RunError
+// Handle trapped leave in RunL. Complete message with leave error code and
+// close open resources that need be freed.
+// -----------------------------------------------------------------------------
+//
+TInt CWimTrustSettingsHandler::RunError( TInt aError )
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimTrustSettingsHandler::RunError | Begin"));
+
+    iMessage.Complete( aError );
+    iApplications.Close();
+    return KErrNone;
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimTrustSettingsStore.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,1211 @@
+/*
+* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implements WIM TrustSettingsStore for WIM certificates
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "WimTrustSettingsStore.h"
+#include "WimCertInfo.h"
+#include "WimCertUtil.h"
+#include <x509cert.h>
+#include <x509certext.h>
+#include <hash.h>
+#include "WimTrace.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::CWimTrustSettingsStore()
+// Default constructor.
+// -----------------------------------------------------------------------------
+//
+CWimTrustSettingsStore::CWimTrustSettingsStore() 
+                      : CActive( EPriorityNormal ),
+                        iCompact ( EFalse )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::ConstructL()
+// Second phase constructor.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::ConstructL()
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::ConstructL()" ) );
+    // Connect to DB server
+    User::LeaveIfError( iDBSession.Connect() );
+
+    // combine trust settings DB path & name
+
+    HBufC* dbPathBuffer = HBufC::NewLC( KWimTrustSettingsStorePath().Length() +
+                                        KWimTrustSettingsDBFile().Length() );
+    TPtr wimTrustSettingsDB( dbPathBuffer->Des() );
+    wimTrustSettingsDB = KWimTrustSettingsStorePath;
+    wimTrustSettingsDB.Append( KWimTrustSettingsDBFile );
+
+    // Open database. Note: err used because of create is done if not found
+    TInt err = iDatabase.Open( iDBSession, wimTrustSettingsDB );
+
+    if ( err != KErrNone ) //Database could not open, create new
+        {
+        _WIMTRACE2( _L( "CWimTrustSettingsStore::ConstructL()|DB open error %d" ), err ); 
+        CreateDBL(); // Create DB
+        User::LeaveIfError( iDatabase.Open( iDBSession, wimTrustSettingsDB ) );
+        }
+
+    iPhase = EIdle;
+    CleanupStack::PopAndDestroy( dbPathBuffer );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::NewL()
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimTrustSettingsStore* CWimTrustSettingsStore::NewL()
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::NewL()" ) );
+    CWimTrustSettingsStore* self = new( ELeave ) CWimTrustSettingsStore;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::~CWimTrustSettingsStore()
+// Destructor. If updates has been done, compact databse.
+// -----------------------------------------------------------------------------
+
+CWimTrustSettingsStore::~CWimTrustSettingsStore()
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::~CWimTrustSettingsStore()" ) );
+    Cancel();
+
+    if ( iCompact ) // Is compact needed
+        {
+        iDatabase.Compact(); //Compact database
+        }
+
+    iDatabase.Close();  // Close database
+    iDBSession.Close(); // Close session to DB server
+
+    if ( iWimCertUtil )
+        {
+        delete iWimCertUtil;
+        }
+
+    delete iEncodedCertBuf;
+    delete iEncodedCertPtr;
+
+    iCertInfos.ResetAndDestroy();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::CloseD()
+// Closes all open resources and deletes this instance of the TrustSettingsStore
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::CloseD()
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::CloseD()" ) );
+    delete ( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::GetTrustSettings()
+// Return trust settings for given certificate.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::GetTrustSettings( const CWimCertInfo& aCert,
+                                               TBool& aTrusted,
+                                               RArray<TUid>& aApplications, 
+                                               TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::GetTrustSettings()" ) );
+    TRAPD( err, DoGetTrustSettingsL( aCert, aTrusted, aApplications ) );
+
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete( status, err );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::SetApplicability()
+// Set applicability for certificate.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::SetApplicability( const CWimCertInfo& aCert,
+                                              const RArray<TUid>& aApplications,
+                                              TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::SetApplicability()" ) );
+    TRAPD( err, DoSetApplicabilityL( aCert, aApplications ) );
+
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete( status, err );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::SetTrust()
+// Set trust flag for certificate.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::SetTrust( const CWimCertInfo& aCert,
+                                       TBool aTrusted,
+                                       TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::SetTrust()" ) );
+    TRAPD( err, DoSetTrustL( aCert, aTrusted ) );
+
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete( status, err );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::SetDefaultTrustSettings()
+// Set default trust settings for certificate.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::SetDefaultTrustSettings( const CWimCertInfo& aCert,
+                                                      TBool aAddApps,
+                                                      TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::SetDefaultTrustSettings()" ) );
+
+    iWimCert = &aCert;
+    iAddApps = aAddApps;
+    iOriginalRequestStatus = &aStatus;
+
+    iCert = aCert.CctCert();
+
+    //Certificate owner type
+    TCertificateOwnerType ownerType;
+    ownerType = iCert->CertificateOwnerType();
+
+    //Certificate format
+    TCertificateFormat certFormat;
+    certFormat = iCert->CertificateFormat();
+    
+    // If CA/X509 certificate locates in trusted certs area
+    // check if certificate extensions must be fetched
+    if ( ownerType == ECACertificate &&
+         certFormat == EX509Certificate &&
+         iWimCert->CDFRefs() == EWimTrustedCertsCDF )
+        {
+        // Check if Java Midlet OID is present
+        RArray<HBufC*> arr = iWimCert->TrustedUsage();
+        TInt oidCount = arr.Count();
+        TInt i = 0;
+
+        for ( ; i < oidCount; i++ )
+            {
+            if ( !arr[i]->Compare( KIpKpJavaMidlet ) )
+                {
+                i = oidCount + 1;
+                }
+            }
+        // If OID is not present, extensions must be fetched
+        if ( i == oidCount )
+            {
+            // Fetch extensions only for CA X509 certificates         
+            iPhase = ERetrieve;
+            TRequestStatus* status = &iStatus;
+            User::RequestComplete( status, KErrNone );
+            SetActive();
+            }
+        else
+            {
+            TRAPD( err, DoSetDefaultTrustSettingsL( aCert, aAddApps ) );
+            TRequestStatus* status = &aStatus;
+            User::RequestComplete( status, err );
+            }
+        }
+    else
+        {
+        TRAPD( err, DoSetDefaultTrustSettingsL( aCert, aAddApps ) );
+        TRequestStatus* status = &aStatus;
+        User::RequestComplete( status, err );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::RemoveTrustSettings()
+// Remove trust settings of given certificate
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::RemoveTrustSettings( const CWimCertInfo& aCert,
+                                                  TRequestStatus& aStatus )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::RemoveTrustSettings()" ) );
+    TRAPD( err, DoRemoveTrustSettingsL( aCert ) );
+    iCompact = ETrue;
+
+    TRequestStatus* status = &aStatus;
+    User::RequestComplete( status, err );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::DoGetTrustSettingsL ()
+// Get trust settings for given certificate.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::DoGetTrustSettingsL( const CWimCertInfo& aCert,
+                                                  TBool& aTrusted,
+                                                  RArray<TUid>& aApplications )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::DoGetTrustSettingsL()" ) );
+    TInt certID;
+    GetCertificateIDL( aCert, certID ); // Get certificate ID
+
+    if ( certID == KErrNotFound ) //Not found settings
+        {
+        User::Leave( KErrNotFound );
+        }
+    GetTrustedL( certID, aTrusted ); //Get trusted flag
+    GetApplicationsL( certID, aApplications ); //Get applications
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::DoSetApplicabilityL()
+// Set applicability for certificate.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::DoSetApplicabilityL( const CWimCertInfo& aCert,
+                                            const RArray<TUid>& aApplications )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::DoSetApplicabilityL()" ) );    
+    TInt certID;
+    GetCertificateIDL( aCert, certID ); // Get certificate ID
+
+    iDatabase.Begin(); // Begin transaction
+
+    TRAPD( err,
+    if ( certID == KErrNotFound ) //Certificate not found -> Insert new one
+        {
+        InsertCertificateL( aCert, EFalse ); //Insert + set flag (EFalse)
+        GetCertificateIDL( aCert, certID );    //Now get certificate ID
+        }
+    else // Certificate found
+        {
+        RemoveApplicationsL( certID );   //Remove old ones before inserting
+        }
+    InsertApplicationsL( certID, aApplications ); // Insert new apps
+    ); //TRAPD
+
+    if ( err != KErrNone ) //Some error occured
+        {
+        iDatabase.Rollback(); //Do rollback = restore changes
+        User::Leave ( err );
+        }
+    else // No errors -> commit changes
+        {
+        iDatabase.Commit(); // Commit changes
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::DoSetTrustL()
+// Set trust flag for certificate.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::DoSetTrustL( const CWimCertInfo& aCert,
+                                          TBool aTrusted )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::DoSetTrustL()" ) );    
+    TInt certID;
+    GetCertificateIDL( aCert, certID ); // Get certificate ID
+
+    if ( certID == KErrNotFound ) // Certificate not found -> Insert new
+       {
+       InsertCertificateL( aCert, aTrusted ); // Insert + set flag
+       }
+    else // Certificate found
+       {
+        SetTrustedL( certID, aTrusted ); // Set trusted flag
+       }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::DoSetDefaultTrustSettingsL()
+// Set default trust settings for certificate
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::DoSetDefaultTrustSettingsL( 
+                                                    const CWimCertInfo& aCert,
+                                                    TBool aAddApps )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::DoSetDefaultTrustSettingsL()" ) );    
+    TInt certID;
+    GetCertificateIDL( aCert, certID ); // Get certificate ID
+
+    iDatabase.Begin(); // Begin transaction
+
+    TRAPD( err,
+        if ( certID == KErrNotFound ) // Certificate not found -> Insert new one
+            {
+            InsertCertificateL( aCert, KDefaultTrustFlag ); // Set default
+            GetCertificateIDL( aCert, certID );
+            }
+        else // Certificate allready exists, set default trusted flag
+            {
+            SetTrustedL( certID, KDefaultTrustFlag );
+            }
+        //
+        // Applications
+        //
+        if ( aAddApps ) // Default applications required
+            {
+            RArray<TUid> applications;
+            CleanupClosePushL( applications );
+
+            DefaultApplicationsL( aCert, applications ); 
+            RemoveApplicationsL( certID ); // Remove previous applications
+            if ( applications.Count() > 0 ) // There is apps to insert
+                {
+                InsertApplicationsL( certID, applications );
+                }
+
+            CleanupStack::PopAndDestroy( &applications );
+            }
+    );
+
+    if ( err != KErrNone ) // Some error occured
+        {
+        iDatabase.Rollback(); // Do rollback = restore changes
+        User::Leave( err );
+        }
+    else // No errors
+        {
+        iDatabase.Commit(); // Commit changes
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::DoRemoveTrustSettingsL()
+// Remove trust settings of given certificate
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::DoRemoveTrustSettingsL( const CWimCertInfo& aCert )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::DoRemoveTrustSettingsL()" ) );    
+    TInt certID;
+    GetCertificateIDL( aCert, certID ); // Get certificate ID
+
+    if ( certID == KErrNotFound ) // Not found
+        {
+        User::Leave( KErrNotFound );
+        }
+
+    iDatabase.Begin(); // Begin transaction
+
+    TRAPD( err, 
+        RemoveApplicationsL( certID );  // Remove applications
+        RemoveCertificateL( certID );   // Remove certificate
+    );
+
+    if ( err ) // Some error occurred
+        {
+        iDatabase.Rollback(); // Rollback changes
+        User::Leave ( err );
+        }
+    else
+        {
+        iDatabase.Commit(); // Commit changes
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::GetCertificateIDL()
+// Get database ID for given certificate. Return KErrNotFound, if not found
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::GetCertificateIDL( const CWimCertInfo& aCert,
+                                                TInt& aCertificateID )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::GetCertificateIDL()" ) );    
+    _LIT( KSQLQuery, "SELECT CertificateID,\
+                             CertHash,\
+                             TokenSerial,\
+                             LabelHash,\
+                             IsTrusted\
+                      FROM Certificates" );
+
+    TBuf8<KSHA1HashLengthBytes> hash;
+    aCert.GetCertHash( hash );
+
+    HBufC8* buf8 = HBufC8::NewLC( aCert.CctCert()->Label().Length() );
+    TPtr8* ptr8 = new( ELeave ) TPtr8( buf8->Des() );
+    CleanupStack::PushL( ptr8 );
+
+    ptr8->Copy( aCert.CctCert()->Label() );
+
+    HBufC8* labelHash = GetHashL( *ptr8 );
+    CleanupStack::PushL( labelHash );
+
+    RDbView view;
+    User::LeaveIfError( view.Prepare( iDatabase, TDbQuery( KSQLQuery ) ) );
+    CleanupClosePushL( view );
+
+    TInt i = 0;
+    while ( i == 0 && view.NextL() ) // Should find only one ID
+        {
+        view.GetL();
+        // Compare given hash, token serial number, cert label hash
+        if ( !view.ColDes8( 2 ).Compare( hash ) &&
+             !view.ColDes( 3 ).Compare( aCert.CctCert()->
+                               Token().Information( MCTToken::ESerialNo ) ) &&
+             !view.ColDes8( 4 ).Compare( *labelHash ) )
+            {
+            aCertificateID = view.ColUint32( 1 );
+            i++;
+            }
+        }
+            
+    if ( i == 0 ) // Not found any matching rows
+        {
+        aCertificateID = KErrNotFound;
+        }
+
+    CleanupStack::PopAndDestroy( 4, buf8 ); // view, labelHash, ptr8, buf8
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::InsertCertificateL()
+// Insert certificate into the Certificates table
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::InsertCertificateL( const CWimCertInfo& aCert, 
+                                                 TBool aTrusted )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::InsertCertificateL()" ) );    
+    TBuf8<KSHA1HashLengthBytes> hash;
+    aCert.GetCertHash( hash );
+    
+    HBufC8* buf8 = HBufC8::NewLC( aCert.CctCert()->Label().Length() );
+    TPtr8* ptr8 = new(ELeave) TPtr8( buf8->Des() );
+    CleanupStack::PushL( ptr8 );
+
+    ptr8->Copy( aCert.CctCert()->Label() );
+
+    HBufC8* labelHash = GetHashL( *ptr8 );
+    CleanupStack::PushL( labelHash );
+
+    RDbView view;
+
+    _LIT( KSQLInsertCert, "SELECT CertHash,\
+                                  TokenSerial,\
+                                  LabelHash,\
+                                  IsTrusted\
+                           FROM Certificates" );
+
+    User::LeaveIfError( view.Prepare( iDatabase, TDbQuery( KSQLInsertCert ),
+        TDbWindow::EUnlimited, RDbView::EInsertOnly ) );
+
+    CleanupClosePushL( view );
+    
+    view.InsertL();
+    view.SetColL( 1, hash );
+    view.SetColL( 2, aCert.CctCert()->
+                           Token().Information( MCTToken::ESerialNo ) );
+    view.SetColL( 3, *labelHash );
+    view.SetColL( 4, aTrusted );
+    view.PutL();
+
+    CleanupStack::PopAndDestroy( 4, buf8 ); // view, labelHash, ptr8, buf8
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::GetHash()
+// Return hash of 8 bit string
+// -----------------------------------------------------------------------------
+//
+HBufC8* CWimTrustSettingsStore::GetHashL( TDesC8& aString )
+    {
+    CSHA1* sha = CSHA1::NewL();
+    CleanupStack::PushL( sha );
+    TPtrC8 shaFingerPrint = sha->Hash( aString );
+    HBufC8* fingerPrint = HBufC8::NewL( shaFingerPrint.Length() ); //make a copy
+    TPtr8 fingerPrintDes = fingerPrint->Des();
+    fingerPrintDes.Copy( shaFingerPrint );
+    CleanupStack::PopAndDestroy( sha );
+    return fingerPrint;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::GetTrustedL()
+// Get trusted flag of given certificate
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::GetTrustedL( TInt aCertificateID,  
+                                          TBool& aTrusted )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::GetTrustedL()" ) );    
+    _LIT( KSQLQuery, 
+         "SELECT IsTrusted FROM Certificates WHERE CertificateID = " );
+
+    TBuf<KMaxSQLLength> SQLStatement;
+    SQLStatement.Copy( KSQLQuery );
+
+    SQLStatement.AppendNum( aCertificateID );
+    TPtrC sqlStat( SQLStatement.PtrZ() );
+
+    RDbView view;
+    User::LeaveIfError( view.Prepare( iDatabase, TDbQuery( sqlStat ) ) );
+    CleanupClosePushL( view );
+
+    while ( view.NextL() ) // Should find only one certificate
+        {
+        view.GetL();
+        aTrusted = ( TBool )view.ColUint( 1 );
+        }
+    
+    CleanupStack::PopAndDestroy( &view );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::SetTrustedL()
+// Set trusted flag for given certificate
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::SetTrustedL( TInt aCertificateID,  
+                                          TBool aTrusted )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::SetTrustedL()" ) );    
+    _LIT( KSQLUpdate1, "UPDATE Certificates SET IsTrusted = " );
+    _LIT( KSQLUpdate2, " WHERE CertificateID = " );
+    TBuf<KMaxSQLLength> SQLStatement;
+    SQLStatement.Copy( KSQLUpdate1 );
+    SQLStatement.AppendNum( aTrusted );
+    SQLStatement.Append( KSQLUpdate2 );
+    SQLStatement.AppendNum( aCertificateID );
+
+    TPtrC sqlStat( SQLStatement.PtrZ() );
+
+    User::LeaveIfError( iDatabase.Execute( sqlStat ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::RemoveCertificateL()
+// Delete certificate from Certificates table
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::RemoveCertificateL( TInt aCertificateID )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::RemoveCertificateL()" ) );    
+    _LIT( KSQLDelete, "DELETE FROM Certificates WHERE CertificateID = " );
+
+    TBuf<60> SQLStatement;
+    SQLStatement.Copy( KSQLDelete );
+    SQLStatement.AppendNum( aCertificateID );
+    TPtrC sqlStat( SQLStatement.PtrZ() );
+    User::LeaveIfError( iDatabase.Execute( sqlStat ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::RemoveApplicationsL()
+// Delete all applications of given certificate
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::RemoveApplicationsL( TInt aCertificateID )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::RemoveApplicationsL()" ) );    
+    _LIT( KSQLDelete, 
+         "DELETE FROM CertificateApplications WHERE CertificateID = " );
+
+    TBuf<KMaxSQLLength> SQLStatement;
+    SQLStatement.Copy( KSQLDelete );
+    SQLStatement.AppendNum( aCertificateID );
+    TPtrC sqlStat( SQLStatement.PtrZ() );
+    User::LeaveIfError( iDatabase.Execute( sqlStat ) );
+    iCompact = ETrue;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::GetApplicationsL()
+// Get applications of given certificate
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::GetApplicationsL( TInt aCertificateID, 
+                                               RArray<TUid>& aApplications )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::GetApplicationsL()" ) );    
+    _LIT( KSQLQuery, "SELECT AppUid FROM CertificateApplications " );
+    _LIT( KSQLQuery2, "WHERE CertificateID = " );
+    
+    TBuf<KMaxSQLLength> SQLStatement;
+    SQLStatement.Copy( KSQLQuery );
+    SQLStatement.Append( KSQLQuery2 );
+    SQLStatement.AppendNum( aCertificateID );
+    TPtrC sqlStat( SQLStatement.PtrZ() );
+
+    RDbView view;
+    User::LeaveIfError( view.Prepare( iDatabase, TDbQuery( sqlStat ) ) );
+    CleanupClosePushL( view );
+
+    TUid uid;
+    while ( view.NextL() )
+        {
+        view.GetL();
+        uid.iUid = view.ColInt32( 1 );
+        aApplications.AppendL( uid );
+        }
+    
+    CleanupStack::PopAndDestroy( &view );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::InsertApplicationsL()
+// Insert applications to certificate
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::InsertApplicationsL( TInt aCertificateID, 
+                                            const RArray<TUid>& aApplications )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::InsertApplicationsL()" ) );    
+    RDbView view;
+
+    // Insert applications
+    _LIT( KSQLInsert, "SELECT CertificateID, AppUid FROM\
+        CertificateApplications" );
+
+    User::LeaveIfError( view.Prepare( iDatabase, TDbQuery( KSQLInsert ),
+                        TDbWindow::EUnlimited, RDbView::EInsertOnly ) );
+    CleanupClosePushL( view );
+    
+    // Loop application list and insert each to database
+    for ( TInt i = 0; i < aApplications.Count(); i++ )
+        {
+        view.InsertL();
+        view.SetColL( 1, aCertificateID );          // CertificateID
+        view.SetColL( 2, aApplications[i].iUid );   // AppUid
+        view.PutL();
+        }
+    
+    CleanupStack::PopAndDestroy( &view );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::DefaultApplicationsL()
+//
+// Decide default applications for certificate regarding certain rules
+// Format
+//    EX509Certificate    = 0x00,
+//    EWTLSCertificate    = 0x01,
+//    EX968Certificate    = 0x02,
+//    EUnknownCertificate = 0x0f,
+//    EX509CertificateUrl = 0x10,
+//    EWTLSCertificateUrl = 0x11,
+//    EX968CertificateUrl = 0x12
+//
+// Trusting applications
+//    KTrustUidWapBearer     
+//    KTrustUidAppController
+//    KTrustUidInternet
+//    KTrustUidJavaMidlet
+//
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::DefaultApplicationsL( const CWimCertInfo& aCert,
+                                                   RArray<TUid>& aApplications )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::DefaultApplicationsL()" ) );    
+    const CCTCertInfo* cctCert = aCert.CctCert();
+
+    //Certificate owner type
+    TCertificateOwnerType ownerType;
+    ownerType = cctCert->CertificateOwnerType();
+
+    //Certificate format
+    TCertificateFormat certFormat;
+    certFormat = cctCert->CertificateFormat();
+    TInt32 appUid;
+    
+    // Applications only for CA certificates
+    switch ( ownerType )
+        {
+        case ECACertificate:
+            {   
+            // Applications by certificate format
+            switch ( certFormat )    
+                {
+                case EX509Certificate: // For Url not the same handling
+                    {
+                    DefaultAppsByOIDsL( aCert, aApplications );
+                    break;
+                    }
+                case EWTLSCertificate: //All WTLSs has same apps, flow through!
+                case EWTLSCertificateUrl:
+                    {
+                    appUid = KTrustUidWapBearer; //WAP
+                    TUid uid = {appUid};
+                    User::LeaveIfError( aApplications.Append( uid ) );
+                    break;
+                    }             
+                default:
+                    {
+                    break;
+                    }
+                }
+            break;
+            }
+        case EUserCertificate: // User certificate: no defaults
+            {
+            break;
+            }
+        case EPeerCertificate: // Peer certificate: no defaults
+            {
+            break;
+            }
+        default:
+            {
+            break;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::DefaultAppsByOIDsL()
+// Get Default AppUid(s) from database regarding the OIDs from certificate
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::DefaultAppsByOIDsL( const CWimCertInfo& aCert,
+                                                 RArray<TUid>& aApplications )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::DefaultAppsByOIDsL()" ) );    
+    // Get trusted usage OID(s) of certificate
+    RArray<HBufC*> certTrustedUsage = aCert.TrustedUsage();
+    // Get extended key usage OID(s) of certificate
+    RArray<HBufC*> certExtendedKeyUsage = aCert.ExtendedKeyUsage();
+    // Get certificate location 
+    TUint8 certLocation = aCert.CDFRefs();
+
+    TInt certTrustedCount;
+    TInt certExtendedUsageCount;
+
+    certTrustedCount = certTrustedUsage.Count();
+    certExtendedUsageCount = certExtendedKeyUsage.Count();
+   
+    // Select all rows of table
+    _LIT( KSQLQuery1, 
+        "SELECT TrustedUsage, ExtendedKeyUsage, Location, AppUid " );
+    _LIT( KSQLQuery2, "FROM CertificateDefaultApps " );
+    TBuf<KMaxSQLLength> SQLStatement;
+    SQLStatement.Copy( KSQLQuery1 );
+    SQLStatement.Append( KSQLQuery2 );
+    
+    TPtrC sqlStat( SQLStatement.PtrZ() );
+    RDbView view;
+    User::LeaveIfError( view.Prepare( iDatabase, TDbQuery( sqlStat ) ) );
+    CleanupClosePushL( view );
+    
+    TInt32  appUid = 0;
+    TUid    uid;
+    TBool   found = EFalse;
+    TBool   canContinue = EFalse;
+    TPtrC   defaultTrustedUsage;
+    TPtrC   defaultExtendedKeyUsage;
+    TInt    defaultLocation;
+
+    // Check first if certificate's trusted usage field matches
+    // After that check extended key usage
+    while ( view.NextL() )
+        {
+        view.GetL();
+
+        defaultTrustedUsage.Set( view.ColDes( 1 ) );
+        defaultExtendedKeyUsage.Set( view.ColDes( 2 ) );
+        defaultLocation = view.ColInt( 3 ); // Not used yet
+        
+        if ( certTrustedCount == 0 ) // No trusted usages in the cert
+            {
+            if ( defaultTrustedUsage.Length() == 0 ) // Either in defaults
+                {
+                canContinue = ETrue; 
+                }
+            }
+        else
+            {
+            for ( TInt i = 0; i < certTrustedCount; i++ )
+                {
+                if ( !defaultTrustedUsage.
+                      Compare( certTrustedUsage[i]->Des() ) )
+                    {
+                    canContinue = ETrue;
+                    }
+                }
+            }
+
+        if ( canContinue )
+            {
+            canContinue = EFalse;
+
+            if ( certExtendedUsageCount == 0 ) // No ext.key usages in the cert
+                {
+                if ( defaultExtendedKeyUsage.Length() == 0 ) // Either in defs
+                    {
+                    canContinue = ETrue;
+                    }
+                }
+            else
+                {
+                for ( TInt i = 0; i < certExtendedUsageCount; i++ )
+                    {
+                    if ( !defaultExtendedKeyUsage.
+                          Compare( certExtendedKeyUsage[i]->Des() ) )
+                        {
+                        canContinue = ETrue;
+                        }
+                    }
+                }
+            }
+
+        if ( canContinue )
+            {
+            if ( defaultLocation == EWimUnknownCDF ) // No default location
+                {
+                appUid = view.ColInt32( 4 );
+                }
+            else
+                {
+                if ( defaultLocation == certLocation )
+                    {
+                    appUid = view.ColInt32( 4 );
+                    }
+                }
+            }
+
+        if ( appUid > 0 ) // Application found -> append it
+            {
+            //Check if app UID allready exists in array
+            for ( TInt i = 0; !found && i < aApplications.Count(); i++ )
+                {
+                if ( aApplications[i].iUid == appUid )
+                    {
+                    found = ETrue;
+                    }
+                }
+            if ( !found ) // AppUid not added to array yet
+                {
+                uid.iUid = appUid;
+                aApplications.AppendL( uid );
+                }
+            found = EFalse;
+            }
+        appUid = 0;
+        canContinue = EFalse;
+        }
+
+    CleanupStack::PopAndDestroy( &view );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::CreateDBL()
+// Create database for trust settings
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::CreateDBL() const
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::CreateDBL()" ) );    
+    RFs fsSession;
+    User::LeaveIfError( fsSession.Connect() );
+    CleanupClosePushL( fsSession );
+    
+    RDbNamedDatabase database;
+
+    // combine trust settings DB path & name
+
+    TInt pathError = fsSession.MkDirAll( KWimTrustSettingsStorePath );
+    if (( pathError != KErrNone ) && ( pathError != KErrAlreadyExists ))
+        {
+        User::Leave( pathError ); // Dir does not exist and can't be created
+        }
+    HBufC* dbPathBuffer = HBufC::NewLC( KWimTrustSettingsStorePath().Length() +
+                                        KWimTrustSettingsDBFile().Length() );
+    TPtr wimTrustSettingsDB( dbPathBuffer->Des() );
+    wimTrustSettingsDB = KWimTrustSettingsStorePath;
+    wimTrustSettingsDB.Append( KWimTrustSettingsDBFile );
+
+    User::LeaveIfError( database.Replace( fsSession, wimTrustSettingsDB ) );
+    CleanupClosePushL( database );
+
+    // Create tables
+
+    // Certificates
+    _LIT( KSQLCreateTable1, "CREATE TABLE Certificates (\
+                                          CertificateID COUNTER NOT NULL,\
+                                          CertHash CHAR(20) NOT NULL,\
+                                          TokenSerial CHAR(20) NOT NULL,\
+                                          LabelHash CHAR(20) NOT NULL,\
+                                          IsTrusted BIT NOT NULL)" );
+    // CertificateApplications
+    _LIT( KSQLCreateTable2, "CREATE TABLE CertificateApplications (\
+                                          CertificateID INTEGER NOT NULL,\
+                                          AppUid INTEGER NOT NULL )" );
+    // CertificateDefaultApps
+    _LIT( KSQLCreateTable3, "CREATE TABLE CertificateDefaultApps (\
+                                          TrustedUsage VARCHAR(200),\
+                                          ExtendedKeyUsage VARCHAR(200),\
+                                          Location INTEGER NOT NULL,\
+                                          AppUid INTEGER NOT NULL )" );
+
+    User::LeaveIfError( database.Execute( KSQLCreateTable1 ) );
+    User::LeaveIfError( database.Execute( KSQLCreateTable2 ) );
+    User::LeaveIfError( database.Execute( KSQLCreateTable3 ) );
+
+    // Create unique index for CertHash
+    _LIT( KSQLTableIndex, "CREATE UNIQUE INDEX hash_index ON\
+        Certificates (CertHash, TokenSerial, LabelHash)" );
+    User::LeaveIfError( database.Execute( KSQLTableIndex ) );
+   
+    CleanupStack::PopAndDestroy( 3, &fsSession ); // database, dbPathBuffer, fsSession
+
+    InsertDefaultAppRulesL();
+
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::CreateDBL()|End" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::InsertDefaultAppRulesL()
+// Insert default application UID selection rules to the database
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::InsertDefaultAppRulesL() const
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::InsertDefaultAppRulesL()" ) );
+    RDbView view;
+
+    RFs fsSession;
+    User::LeaveIfError( fsSession.Connect() );
+    CleanupClosePushL( fsSession );
+
+    RDbNamedDatabase database;
+
+    // combine trust settings DB path & name
+    HBufC* dbPathBuffer = HBufC::NewLC( KWimTrustSettingsStorePath().Length() +
+                                        KWimTrustSettingsDBFile().Length() );
+    TPtr wimTrustSettingsDB( dbPathBuffer->Des() );
+    wimTrustSettingsDB = KWimTrustSettingsStorePath;
+    wimTrustSettingsDB.Append( KWimTrustSettingsDBFile );
+
+    User::LeaveIfError( database.Open( fsSession, wimTrustSettingsDB ) );
+    CleanupClosePushL( database );
+
+    _LIT( KSQLInsertRules, "SELECT TrustedUsage, ExtendedKeyUsage,\
+        Location, AppUid FROM CertificateDefaultApps" );
+
+    User::LeaveIfError( view.Prepare( database, TDbQuery( KSQLInsertRules ),
+        TDbWindow::EUnlimited, RDbView::EInsertOnly ) );
+
+    CleanupClosePushL( view );
+
+    view.InsertL();
+    view.SetColL( 1, _L("") );                  // TrustedUsage OID
+    view.SetColL( 2, _L("") );                  // ExtendedUsage OID
+    view.SetColL( 3, TInt( EWimUnknownCDF ) );  // Location
+    view.SetColL( 4, KTrustUidInternet );       // Application Uid
+    view.PutL();
+
+    view.InsertL();
+    view.SetColL( 1, KIpKpServerAuth );         // TrustedUsage OID
+    view.SetColL( 2, KIpKpServerAuth );         // ExtendedUsage OID
+    view.SetColL( 3, TInt( EWimUnknownCDF ) );  // Location
+    view.SetColL( 4, KTrustUidInternet );       // Application Uid
+    view.PutL();
+
+    view.InsertL();
+    view.SetColL( 1, _L("") );                  // TrustedUsage OID
+    view.SetColL( 2, KIpKpServerAuth );         // ExtendedUsage OID
+    view.SetColL( 3, TInt( EWimUnknownCDF ) );  // Application Uid
+    view.SetColL( 4, KTrustUidInternet );       // Application Uid
+    view.PutL();
+
+    view.InsertL();
+    view.SetColL( 1, KIpKpServerAuth );         // TrustedUsage OID
+    view.SetColL( 2, _L("") );                  // ExtendedUsage OID
+    view.SetColL( 3, TInt( EWimUnknownCDF ) );  // Location
+    view.SetColL( 4, KTrustUidInternet );       // Application Uid
+    view.PutL();
+
+    view.InsertL();
+    view.SetColL( 1, KIpKpJavaMidlet );         // TrustedUsage OID
+    view.SetColL( 2, _L("") );                  // ExtendedUsage OID
+    view.SetColL( 3, TInt( EWimTrustedCertsCDF ) ); // Location
+    view.SetColL( 4, KTrustUidJavaMidlet );     // Application Uid
+    view.PutL();
+
+    view.InsertL();
+    view.SetColL( 1, _L("") );                  // TrustedUsage OID
+    view.SetColL( 2, KWimCodeSigningOID );      // ExtendedUsage OID
+    view.SetColL( 3, TInt( EWimTrustedCertsCDF ) );  // Location
+    view.SetColL( 4, KTrustUidJavaMidlet );     // Application Uid
+    view.PutL();
+
+    CleanupStack::PopAndDestroy( 4, &fsSession ); // view, database, dbPathBuffer, fsSession
+    }
+
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::RunL()
+// Not used.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::RunL()
+    {
+
+    switch ( iPhase )
+        {
+        case ERetrieve:
+            {
+            iPhase = ECheckRestore;
+
+            if ( !iWimCertUtil )
+                {
+                iWimCertUtil = CWimCertUtil::NewL( iCert->Token() );
+                iCertInfos.ResetAndDestroy();
+                iWimCertUtil->Restore( iCertInfos, iStatus );
+                }
+            else
+                {
+                TRequestStatus* status = &iStatus;
+                User::RequestComplete( status, KErrNone );
+                }
+            SetActive();
+            break;
+            }
+        case ECheckRestore:
+            {
+            if ( iStatus.Int() == KErrNone )
+                {
+                // Allocate space for certificate data
+                delete iEncodedCertBuf;
+                iEncodedCertBuf = 0;
+                delete iEncodedCertPtr;
+                iEncodedCertPtr = 0;
+                iEncodedCertBuf = HBufC8::NewL( iCert->Size() );
+                iEncodedCertPtr = new( ELeave ) TPtr8( iEncodedCertBuf->Des() );
+                iPhase = ECheckRetrieve;
+
+                iWimCertUtil->RetrieveCertByIndexL( iCert->Handle().iObjectId,
+                                                    *iEncodedCertPtr, 
+                                                    iStatus ); 
+                SetActive();
+                }
+            else
+                {
+                iPhase = EIdle;
+                User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+                }
+            break;
+            }
+        case ECheckRetrieve:
+            {
+            if ( iStatus.Int() == KErrNone )
+                {
+                ExtractExtensionL();
+                DoSetDefaultTrustSettingsL( *iWimCert, iAddApps );
+                User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+                }
+            else
+                {
+                iPhase = EIdle;
+                User::RequestComplete( iOriginalRequestStatus, iStatus.Int() );
+                }
+            break;
+            }
+        default:
+            {
+            // Here we should not be
+            User::RequestComplete( iOriginalRequestStatus, KErrCorrupt );
+            break;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::ExtractExtensionL()
+// If the certificate extension contains extended key usage and certificate 
+// locates in the trusted certificates area, add OID to extended key usages
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::ExtractExtensionL()
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::ExtractExtensionL()" ) );    
+    CX509Certificate* cert = CX509Certificate::NewLC( *iEncodedCertPtr );
+
+    const CX509CertExtension* ext = cert->Extension( KExtendedKeyUsage );
+
+    if ( ext )
+        {
+        TInt dummy = 0;
+        CX509ExtendedKeyUsageExt* extendedKeyUsage = 
+                CX509ExtendedKeyUsageExt::NewL( ext->Data(), dummy );
+        CleanupStack::PushL( extendedKeyUsage );
+        const CArrayPtrFlat<HBufC>& usages = extendedKeyUsage->KeyUsages();
+
+        TInt count = usages.Count();
+        for ( TInt i = 0; i < count; i++ )
+            {
+            HBufC* buf = usages[i]->AllocLC();
+            CWimCertInfo* tmp = const_cast<CWimCertInfo*>( iWimCert );
+            User::LeaveIfError( tmp->AddExtendedKeyUsage( buf ) ); 
+            CleanupStack::Pop( buf ); // Take the ownership
+            }
+
+        CleanupStack::PopAndDestroy( extendedKeyUsage );
+        }
+
+    CleanupStack::PopAndDestroy( cert );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::CancelDoing()
+// Not used.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::CancelDoing()
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::Cancel()" ) );
+    Cancel();
+    }
+// -----------------------------------------------------------------------------
+// CWimTrustSettingsStore::DoCancel()
+// Not used.
+// -----------------------------------------------------------------------------
+//
+void CWimTrustSettingsStore::DoCancel()
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::DoCancel()" ) );
+    iPhase = EIdle;
+    User::RequestComplete( iOriginalRequestStatus, KErrCancel );
+    }
+
+// -----------------------------------------------------------------------------
+// void CWimTrustSettingsStore::RunError()
+// Leave leads us here.
+// -----------------------------------------------------------------------------
+//
+TInt CWimTrustSettingsStore::RunError( TInt aError )
+    {
+    _WIMTRACE ( _L( "CWimTrustSettingsStore::RunError()" ) );
+    iPhase = EIdle;
+    User::RequestComplete( iOriginalRequestStatus, aError );
+    return KErrNone;
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimServer/src/WimUtilityFuncs.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,409 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of the CWimUtilityFuncs class.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimUtilityFuncs.h"
+#include    "Wimi.h"                // WIMI definitions
+#include    "WimDefs.h" 
+#include    "WimTrace.h"
+
+#include    <e32property.h>         // RProperty
+
+#ifdef RD_STARTUP_CHANGE
+#include    <startupdomainpskeys.h> // Property values
+#else
+#include    <PSVariables.h>         // Property values
+#endif // RD_STARTUP_CHANGE
+
+#ifdef BT_SAP_TEST_BY_CHARGER
+#include    <PSVariables.h>         // Property values
+#else
+//#include    <BTSapInternalPSKeys.h> // BT Sap property values
+#include    <BTSapDomainPSKeys.h>
+#endif // BT_SAP_TEST_BY_CHARGER
+
+//If want to use emulator hw, uncomment this line
+#define __EMULATOR_HW__ 
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimUtilityFuncs::CWimUtilityFuncs
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimUtilityFuncs::CWimUtilityFuncs()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimUtilityFuncs::CWimUtilityFuncs | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimUtilityFuncs::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimUtilityFuncs::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimUtilityFuncs::ConstructL | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimUtilityFuncs::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimUtilityFuncs* CWimUtilityFuncs::NewL()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimUtilityFuncs::NewL | Begin"));
+    CWimUtilityFuncs* self = new( ELeave ) CWimUtilityFuncs;
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+    }
+
+    
+// Destructor
+CWimUtilityFuncs::~CWimUtilityFuncs()
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimUtilityFuncs::~CWimUtilityFuncs | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimUtilityFuncs::::MapWIMError
+// Map WIMI errors to WIM errors
+// -----------------------------------------------------------------------------
+//
+TInt CWimUtilityFuncs::MapWIMError( WIMI_STAT aStatus )
+    {
+    _WIMTRACE2(_L("WIM | WIMServer | CWimUtilityFuncs::MapWIMError aStatus=%d"), aStatus);
+    TInt err = KErrUnknown; 
+    
+    switch ( aStatus ) 
+        {
+        case WIMI_Err:
+        case WIMI_ERR_Internal:
+             err = KErrCorrupt;
+            break;
+        case WIMI_ERR_OutOfMemory:
+            err = KErrNoMemory;
+            break;
+        case WIMI_Ok:
+            err = KErrNone;
+            break;
+        case WIMI_ERR_BadParameters:
+            err = KErrArgument;
+            break;
+        case WIMI_ERR_ServerCertRejected:
+            err = KErrCorrupt;
+            break;
+        case WIMI_ERR_CipherNotSupported:
+        case WIMI_ERR_MACANotSupported:
+            err = KErrNotSupported;
+            break;
+        case WIMI_ERR_UnsupportedCertificate:
+            err = KErrNotSupported;
+            break;
+        case WIMI_ERR_SessionNotSet:
+            err = KErrDisconnected;
+            break;
+        case WIMI_ERR_WrongKES:
+            err = KErrCorrupt;
+            break;
+        case WIMI_ERR_DecodeError:
+            err = KErrCorrupt;
+            break;
+        case WIMI_ERR_ExpiredReference:
+            err = KErrArgument;
+            break;
+        case WIMI_ERR_NoKey:
+            err = KErrNotFound;
+            break;
+        case WIMI_ERR_CertNotYetValid:
+            err = KErrCorrupt;
+            break;
+        case WIMI_ERR_CertExpired:
+            err = KErrTimedOut;
+            break;
+        case WIMI_ERR_UnknownCA:
+            err = KErrArgument;
+            break;
+        case WIMI_ERR_CertParseError:
+            err = KErrCorrupt;
+            break;
+        case WIMI_ERR_KeyStorageFull:
+            err = KErrDirFull;
+            break;
+        case WIMI_ERR_BadKey:
+            err = KErrArgument;
+            break;
+        case WIMI_ERR_CertStorageFull:
+            err = KErrDirFull;
+            break;
+        case WIMI_ERR_BadCert:
+            err = KErrArgument;
+            break;
+        case WIMI_ERR_PStorageError:
+            err = KErrDirFull;
+            break;
+        case WIMI_ERR_CertNotFound:
+            err = KErrNotFound;
+            break;
+        case WIMI_ERR_KeyNotFound:
+            err = KErrNotFound;
+            break;
+        case WIMI_ERR_BadReference:
+            err = KErrCorrupt;
+            break;
+        case WIMI_ERR_OperNotSupported:
+            err = KErrNotSupported;
+            break;
+        case WIMI_ERR_BadPIN:
+            err = KErrArgument;
+            break;
+        case WIMI_ERR_PINBlocked:
+            err = KErrLocked;
+            break;
+        case WIMI_ERR_CardDriverInitError:
+            err = KErrBadDriver;
+            break;
+        case WIMI_ERR_CardIOError:
+            err = KErrHardwareNotAvailable;
+            break;
+        case WIMI_ERR_AlgorithmNotYetImplemented:
+            err = KErrNotSupported;
+            break;
+        case WIMI_ERR_UserCancelled:
+            err = KErrCancel;
+            break;
+        default:
+            err = KErrUnknown;
+        }
+    return err;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimUtilityFuncs::TrIdLC
+// Creates a new TWimReqTrId item.
+// -----------------------------------------------------------------------------
+//
+TWimReqTrId* CWimUtilityFuncs::TrIdLC( TAny* aTrId, TWimReqType aReqType ) const 
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimUtilityFuncs::GetTrIdLC | Begin"));
+    TWimReqTrId* reqTrId = new( ELeave ) TWimReqTrId;
+    CleanupStack::PushL( reqTrId );
+    reqTrId->iReqType = aReqType;
+    reqTrId->iReqTrId = aTrId;
+    return reqTrId;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimUtilityFuncs::DesLC
+// Utility function that reads a descriptor from the clients address
+// space. The caller has to free the returned HBufC8.
+// -----------------------------------------------------------------------------
+//
+HBufC8* CWimUtilityFuncs::DesLC(
+    const TInt aIndex,
+    const RMessage2& aMessage ) const
+    {
+    _WIMTRACE(_L("WIM | WIMServer | CWimUtilityFuncs::GetDesLC | Begin"));
+
+    TInt len = aMessage.GetDesLength( aIndex );    
+
+    //User might cancelled operation, so we need to leave before
+    //HBufC panics. We do not want panic at this point. Leave is Trapped in 
+    //session
+    if ( len < 0 )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    HBufC8* buf = HBufC8::NewLC( len ); // free'd by caller
+    TPtr8 ptr = buf->Des();
+    aMessage.ReadL( aIndex, ptr );
+    
+    return buf;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimUtilityFuncs::SimState
+// Get state of SIM/SWIM card. Uses system wide repository to get state.
+// If card is OK return KErrNone, otherwise some other system wide state.
+// -----------------------------------------------------------------------------
+//
+TInt CWimUtilityFuncs::SimState()
+    {
+    TInt simState = KErrNotReady;
+    TInt stateError = 0;
+
+    // Get SIM state
+
+#ifdef RD_STARTUP_CHANGE
+    stateError = RProperty::Get( KPSUidStartup,
+                                 KPSSimStatus,
+                                 simState );
+#else
+    stateError = RProperty::Get( KUidSystemCategory,
+                                 KPSUidSIMStatusValue,
+                                 simState );
+#endif // RD_STARTUP_CHANGE
+ 
+    // In WINS may not return real SIM state -> ignore
+    #ifdef __WINS__
+    stateError = 0;
+    #endif
+
+    if ( stateError == KErrNone ) // Got SIM state succesfully
+        {
+        // In WINS may not return real SIM state -> ignore
+#ifdef __WINS__
+
+#ifdef __EMULATOR_HW__
+
+#ifdef RD_STARTUP_CHANGE
+        simState = ESimUsable;
+#else
+        simState = EPSSimOk;
+#endif // RD_STARTUP_CHANGE
+
+#else  //__EMULATOR_HW__
+
+#ifdef RD_STARTUP_CHANGE
+        simState = ESimNotPresent;
+#else
+        simState = EPSSimNotPresent;
+#endif // RD_STARTUP_CHANGE
+
+#endif //__EMULATOR_HW__
+
+#endif // __WINS__
+
+        _WIMTRACE2(_L("WIM | WIMServer | CWimUtilityFuncs::SimState|simState=%d"),simState);
+
+#ifdef RD_STARTUP_CHANGE
+        if ( simState == ESimUsable )
+#else
+        if ( simState == EPSSimOk )
+#endif // RD_STARTUP_CHANGE        
+            {
+            simState = KErrInUse;
+#ifdef BT_SAP_TEST_BY_CHARGER
+            // Test of BT Sap by charger. To emulate connected BT Sap, charger must be
+            // connected and charging.
+            stateError = RProperty::Get( KUidSystemCategory,
+                                         KPSUidChargerStatusValue,
+                                         simState );  
+#else
+            // Get state of BT Sap
+            stateError = RProperty::Get( KPSUidBluetoothSapConnectionState,
+                                         KBTSapConnectionState,
+                                         simState );
+#endif // BT_SAP_TEST_BY_CHARGER
+
+       // In WINS may not return real SIM state -> ignore
+#ifdef __WINS__
+            stateError = 0;
+#endif
+
+            if ( KErrNone == stateError ) // Got BT SAP state succesfully
+                {
+       // In WINS may not return real SIM state -> ignore 
+#ifdef __WINS__
+
+#ifdef BT_SAP_TEST_BY_CHARGER
+        simState = EPSChargerDisconnected;
+#else
+        simState = EBTSapNotConnected;
+#endif // BT_SAP_TEST_BY_CHARGER
+
+#endif // __WINS__            
+               
+                _WIMTRACE2(_L("WIM | WIMServer | CWimUtilityFuncs::SimState|simState=%d"),simState);
+               
+#ifdef BT_SAP_TEST_BY_CHARGER
+                if ( EPSChargerConnected != simState )
+#else
+                if ( EBTSapConnected != simState )
+#endif // BT_SAP_TEST_BY_CHARGER 
+                    {
+                    simState = KErrNone;
+                    }
+                else
+                    {
+                    simState = KErrInUse;
+                    }               
+                }
+            else if ( KErrNotFound == stateError )
+                {
+                _WIMTRACE(_L("WIM | WIMServer | CWimUtilityFuncs::SimState|BTSap not found, WIM initialization continued"));
+                simState = KErrNone;
+                }
+            else
+                {
+                _WIMTRACE2(_L("WIM | WIMServer | CWimUtilityFuncs::SimState|BTSap ERROR| stateError=%d"),stateError);    
+                }
+            }
+        else // simState != ESimUsable/EPSSimOk
+            {
+            simState = KErrNotReady;
+            }
+        }
+    _WIMTRACE2(_L("WIM | WIMServer | CWimUtilityFuncs::SimState|End|simState=%d"),simState); 
+    return simState;
+    }
+// -----------------------------------------------------------------------------
+// CWimCertHandler::MapCertLocation
+// Map Wimlib certificate CDF to our own type
+// -----------------------------------------------------------------------------
+//
+TUint8 CWimUtilityFuncs::MapCertLocation( const TUint8 aCertCDF ) const
+    {
+    TWimCertificateCDF certCDF;
+
+    switch ( aCertCDF )
+        {
+        case WIMLIB_CERTIFICATES_CDF:
+            {
+            certCDF = EWimCertificatesCDF;
+            break;
+            }
+        case WIMLIB_TRUSTEDCERTS_CDF:
+            {
+            certCDF = EWimTrustedCertsCDF;
+            break;
+            }
+        case WIMLIB_USEFULCERTS_CDF:
+            {
+            certCDF = EWimUsefulCertsCDF;
+            break;
+            }
+        default:
+            {
+            certCDF = EWimUnknownCDF;
+            break;
+            }
+        }
+    return ( TUint8 )certCDF;
+    }
+
+//  End of File  
Binary file wim/WimSoft/armv5/udeb/wimi.lib has changed
Binary file wim/WimSoft/armv5/urel/wimi.lib has changed
Binary file wim/WimSoft/winscw/udeb/WIMI.LIB has changed
Binary file wim/WimSoft/winscw/urel/WIMI.LIB has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimUtil/Bwins/WIMUTILU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,13 @@
+EXPORTS
+	?AddExtendedKeyUsage@CWimCertInfo@@QAEHPAVHBufC16@@@Z @ 1 NONAME ; int CWimCertInfo::AddExtendedKeyUsage(class HBufC16 *)
+	?AddTrustedUsage@CWimCertInfo@@QAEHPAVHBufC16@@@Z @ 2 NONAME ; int CWimCertInfo::AddTrustedUsage(class HBufC16 *)
+	?CDFRefs@CWimCertInfo@@QBEEXZ @ 3 NONAME ; unsigned char CWimCertInfo::CDFRefs(void) const
+	?CctCert@CWimCertInfo@@QBEPBVCCTCertInfo@@XZ @ 4 NONAME ; class CCTCertInfo const * CWimCertInfo::CctCert(void) const
+	?ExtendedKeyUsage@CWimCertInfo@@QBE?AV?$RArray@PAVHBufC16@@@@XZ @ 5 NONAME ; class RArray<class HBufC16 *> CWimCertInfo::ExtendedKeyUsage(void) const
+	?ExternalizeL@CWimCertInfo@@QBEPAVTWimCertInfoPckg@@XZ @ 6 NONAME ; class TWimCertInfoPckg * CWimCertInfo::ExternalizeL(void) const
+	?GetCertHash@CWimCertInfo@@QBEXAAV?$TBuf8@$0BE@@@@Z @ 7 NONAME ; void CWimCertInfo::GetCertHash(class TBuf8<20> &) const
+	?InternalizeL@CWimCertInfo@@SAPAV1@AAVTWimCertInfoPckg@@@Z @ 8 NONAME ; class CWimCertInfo * CWimCertInfo::InternalizeL(class TWimCertInfoPckg &)
+	?NewL@CWimCertInfo@@SAPAV1@PAVCCTCertInfo@@V?$TBuf8@$0BE@@@V?$RArray@PAVHBufC16@@@@E@Z @ 9 NONAME ; class CWimCertInfo * CWimCertInfo::NewL(class CCTCertInfo *, class TBuf8<20>, class RArray<class HBufC16 *>, unsigned char)
+	?SetCDFRefs@CWimCertInfo@@QAEXE@Z @ 10 NONAME ; void CWimCertInfo::SetCDFRefs(unsigned char)
+	?TrustedUsage@CWimCertInfo@@QBE?AV?$RArray@PAVHBufC16@@@@XZ @ 11 NONAME ; class RArray<class HBufC16 *> CWimCertInfo::TrustedUsage(void) const
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimUtil/EABI/WimUtilU.DEF	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,19 @@
+EXPORTS
+	_ZN12CWimCertInfo10SetCDFRefsEh @ 1 NONAME
+	_ZN12CWimCertInfo12InternalizeLER16TWimCertInfoPckg @ 2 NONAME
+	_ZN12CWimCertInfo15AddTrustedUsageEP7HBufC16 @ 3 NONAME
+	_ZN12CWimCertInfo19AddExtendedKeyUsageEP7HBufC16 @ 4 NONAME
+	_ZN12CWimCertInfo4NewLEP11CCTCertInfo5TBuf8ILi20EE6RArrayIP7HBufC16Eh @ 5 NONAME
+	_ZNK12CWimCertInfo11GetCertHashER5TBuf8ILi20EE @ 6 NONAME
+	_ZNK12CWimCertInfo12ExternalizeLEv @ 7 NONAME
+	_ZNK12CWimCertInfo12TrustedUsageEv @ 8 NONAME
+	_ZNK12CWimCertInfo16ExtendedKeyUsageEv @ 9 NONAME
+	_ZNK12CWimCertInfo7CDFRefsEv @ 10 NONAME
+	_ZNK12CWimCertInfo7CctCertEv @ 11 NONAME
+	_ZTI12CWimCertInfo @ 12 NONAME DATA 12 ; #<TI>#
+	_ZTI14CWimDummyToken @ 13 NONAME DATA 32 ; #<TI>#
+	_ZTI18CWimDummyTokenType @ 14 NONAME DATA 12 ; #<TI>#
+	_ZTV12CWimCertInfo @ 15 NONAME DATA 20 ; #<VT>#
+	_ZTV14CWimDummyToken @ 16 NONAME DATA 112 ; #<VT>#
+	_ZTV18CWimDummyTokenType @ 17 NONAME DATA 92 ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimUtil/group/WimUtil.mmp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Contains information for building Wim utilies dll
+*
+*/
+
+#include <platform_paths.hrh>
+//MACRO __WIM_ENABLE_TRACES
+//#define __WIM_ENABLE_TRACES
+
+TARGET          WimUtil.dll
+TARGETTYPE      DLL
+UID             0x1000008d 0x101F79D6
+
+CAPABILITY      CAP_GENERAL_DLL
+VENDORID        VID_DEFAULT
+
+
+SOURCE          ../src/WimCertInfo.cpp
+SOURCE          ../src/WimUtilEntry.cpp
+SOURCE          ../src/WimDummyToken.cpp
+
+USERINCLUDE     ../inc
+USERINCLUDE     ../../inc
+
+MW_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         ctframework.lib
+
+SMPSAFE
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimUtil/inc/WimDummyToken.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,261 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Dummy Token and TokenType for Client/Server
+*               information interchange
+*
+*/
+
+
+
+#ifndef CWIMDUMMYTOKEN_H
+#define CWIMDUMMYTOKEN_H
+
+//  INCLUDES
+#include <ct.h>
+
+// FORWARD DECLARATIONS
+class CWimDummyTokenType;
+
+
+// CLASS DECLARATION
+
+/**
+*  Class for token handling.
+*  Messaging between WimClient and WimServer requires a reference to token,
+*  which cannot be a null reference. Because the use of actual token is not
+*  required and because it would consume memory for no reason, dummy token is
+*  used.
+*
+*  @lib WimUtil.lib
+*  @since Series60 3.0
+*/
+class CWimDummyToken : public CBase, public MCTToken
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimDummyToken* NewL( MCTTokenType& aTokenType );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimDummyToken();
+
+    public: // New functions
+
+        /**
+        * Sets serial number to token
+        * @param  Serian number to be set
+        */
+        void SetSerialNumber( TDesC& aSerialNumber );
+
+    public: // Functions from base class MCTToken
+        
+        /**
+        * Returns a reference to this token's label.
+        * @return  A Reference to this token's label.
+        */
+        const TDesC& Label();
+        
+        /**
+        * Returns the associated token type.
+        * @return A reference to token's token type
+        */
+        MCTTokenType& TokenType();
+        
+        /**
+        * Returns the token's handle which is TCTTokenHandle class.
+        * @return tokens handle
+        */
+        TCTTokenHandle Handle();
+        
+        /** 
+        * Returns the specified information string about the token.
+        * @param aRequiredInformation (IN) Specifies the required information
+        *        needed from the token. See value from TTokenInformation.
+        * @return TDesC&  (OUT) Information string of the token, or KNullDesC,
+        *         if token information cannot be given
+        */
+        const TDesC& Information( TTokenInformation aRequiredInformation );
+
+        /**
+        * Notifies the client when the token has been removed. Notify is 
+        * given by changing the status code of given TRequestStatus.
+        * The caller should give listener's TRequestStatus in pending state 
+        * to this function.
+        * Note: this is not an asynchronous call, it only stores the
+        * address of given TRequestStatus for later notifications.
+        * @param  aStatus (IN/OUT) Async. request status.
+        *         KErrPending, token is on it's place
+        *         KErrCancel, caller has cancelled to notify token removal
+        *         KErrHardwareNotAvailable, token is removed
+        *         Any other system error code
+        * @return void
+        */
+        void NotifyOnRemoval( TRequestStatus& aStatus );
+
+        /**
+        * Cancels the NotifyOnRemoval request.
+        * @return void
+        */
+        void CancelNotify();
+
+                /**
+        * Returns a reference to a variable to be used as a reference counter
+        * @return  A reference to reference counter
+        */
+        TInt& ReferenceCount();
+
+    protected: // Functions from base class MCTToken
+
+        /**
+        * Returns a reference to pointer of an interface object.
+        * The caller owns all the parameters.
+        * @param  aRequiredInterface (IN) The UID of the interface that 
+        *         should be returned
+        * @param  aReturnedInterface (OUT). This will be set to a pointer to 
+        *         the returned interface on success and
+        *         to NULL if it isn't supported by this token
+        * @param  aStatus (IN/OUT) Async. request status.
+        *         KErrNone, if all ok and interface returned
+        *         KErrCancel, if call canceled
+        *         KErrNotSupported, if interface not supported
+        *         KErrHardwareNotAvailable, if Wim card suddenly removed
+        *         Any other system wide error code (e.g. KErrNoMemory)
+        * @return void
+        */
+        void DoGetInterface( TUid aRequiredInterface,
+                             MCTTokenInterface*& aReturnedInterface, 
+                             TRequestStatus& aStatus );
+        
+        /**
+        * Cancels DoGetInterface operation.
+        * @return Boolean value: true, if cancel is appropriate, false if
+        *         cancel is not appropriate
+        */
+        TBool DoCancelGetInterface();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CWimDummyToken( MCTTokenType& aTokenType );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+    private:    // Data
+
+        MCTTokenType& iTokenType;
+        // A variable needed for reference counting
+        TInt          iCount;
+        // Serial number of the token
+        HBufC*        iSerialNumber;
+         
+    };
+
+class CWimDummyTokenType : public CCTTokenType
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CWimDummyTokenType* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimDummyTokenType();
+
+    public: // Functions from base class MCTTokenType
+        
+        /**
+        * Lists all the tokens of this type. Caller owns all parameters and
+        * is responsible to destroy all objects in the received RCPointerArray.
+        * @param  aTokens (OUT) The returned tokens are added to this array.
+        * @param  aStatus (IN/OUT). Asyncronous return status: 
+        *         KErrNone, if no errors occurred
+        *         KErrNotFound, if Wim information not found
+        *         KErrCancel, if list operation cancelled
+        *         Any other system wide error code
+        * @return void
+        */
+        void List( RCPointerArray<HBufC>& aTokens, 
+                   TRequestStatus& aStatus );
+
+        /**
+        * Cancel a list operation.
+        * @return void
+        */
+        void CancelList();
+
+        /**
+        * Opens a specified token with token info.
+        * The caller owns all the parameters.
+        * @param  aTokenInfo (IN) The info of the required token (token label)
+        * @param  aToken (OUT) The returned token.
+        * @param  aStatus (IN/OUT) Asynchronous return status.  
+        *         KErrNone, if token opening succeeded
+        *         KErrNotFound, if token not found by aTokenInfo
+        *         Any other system wide error code
+        * @return void
+        */
+        void OpenToken( const TDesC& aTokenInfo, 
+                        MCTToken*& aToken,
+                        TRequestStatus& aStatus );
+    
+        /**
+        * Opens a specified token with handle
+        * The caller owns all the parameters.
+        * @param  aHandle (IN) The handle of the required token
+        * @param  aToken (OUT) The returned token.
+        * @param  aStatus (IN/OUT) Asynchronous return status.  
+        *         KErrNone, if token opening succeeded
+        *         KErrNotFound, if token not found by aHandle
+        *         Any other system wide error code
+        * @return void
+        */
+        void OpenToken( TCTTokenHandle aHandle, 
+                        MCTToken*& aToken,
+                        TRequestStatus& aStatus );
+    
+         /**
+        * Cancel an OpenToken operation.
+        * @return void
+        */
+        void CancelOpenToken();      
+
+    private: // Constructors
+
+        /**
+        * Second phase constructor
+        */
+        void ConstructL();
+
+        /**
+        * Default constructor
+        */
+        CWimDummyTokenType();
+
+    };
+
+#endif      // CWIMDUMMYTOKEN_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimUtil/src/WimCertInfo.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,276 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Certificate trust settings information
+*
+*/
+
+
+
+// INCLUDE FILES
+
+#include "WimCertInfo.h"
+#include "WimDummyToken.h"
+#include <securitydefs.h>
+#include "WimTrace.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimCertInfo::CWimCertInfo( CCTCertInfo* aCCTCertInfo, 
+//                            const TBuf8<KSHA1HashLengthBytes> aHash, 
+//                            RArray<HBufC*> aTrustedUsages, 
+//                            TUint8 aCDFRefs ) 
+//                          : iCCTCertInfo( aCCTCertInfo ),
+//                            iCertHash( aHash ),
+//                            iTrustedUsage( aTrustedUsages ),
+//                            iCDFRefs( aCDFRefs )
+// Default constructor
+// -----------------------------------------------------------------------------
+//
+CWimCertInfo::CWimCertInfo( CCTCertInfo* aCCTCertInfo, 
+                            const TBuf8<KSHA1HashLengthBytes> aHash, 
+                            RArray<HBufC*> aTrustedUsages, 
+                            TUint8 aCDFRefs ) 
+                          : iCCTCertInfo( aCCTCertInfo ),
+                            iCertHash( aHash ),
+                            iTrustedUsage( aTrustedUsages ),
+                            iCDFRefs( aCDFRefs )
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimCertInfo::CWimCertInfo | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertInfo::ConstructL()
+// Second phase constructor
+// -----------------------------------------------------------------------------
+//
+void CWimCertInfo::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimCertInfo::ConstructL | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertInfo::NewLNewL( CCTCertInfo* aCCTCertInfo,
+//                         const TBuf8<KSHA1HashLengthBytes> aHash,
+//                         RArray<HBufC*> aTrustedUsages,
+//                         TUint8 aCDFRefs )
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CWimCertInfo* CWimCertInfo::NewL( CCTCertInfo* aCCTCertInfo,
+                                     const TBuf8<KSHA1HashLengthBytes> aHash,
+                                     RArray<HBufC*> aTrustedUsages,
+                                     TUint8 aCDFRefs )
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimCertInfo::NewL | Begin"));
+    CWimCertInfo* self = new( ELeave ) CWimCertInfo( aCCTCertInfo, 
+                                                     aHash,
+                                                     aTrustedUsages,
+                                                     aCDFRefs );
+    CleanupStack::PushL( self );
+    self->ConstructL( );
+    CleanupStack::Pop( self );
+    return self;
+    }
+    
+// -----------------------------------------------------------------------------
+// CWimCertInfo::~CWimCertInfo()
+// Destructor
+// -----------------------------------------------------------------------------
+//
+CWimCertInfo::~CWimCertInfo()
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimCertInfo::~CWimCertInfo | Begin"));
+    if ( iCCTCertInfo )
+        {
+        iCCTCertInfo->Release();
+        iCCTCertInfo = NULL;
+        }
+
+    //Delete arrays of trusted usaga and extendedkeyusage
+    for ( TInt i = 0; i < iTrustedUsage.Count(); i++ )
+        {
+        delete iTrustedUsage[i]; //Delete buffers
+        }
+
+    iTrustedUsage.Close();
+    
+    for ( TInt j = 0; j < iExtendedKeyUsage.Count(); j++ )
+        {
+        delete iExtendedKeyUsage[j]; //Delete buffers
+        }
+
+    iExtendedKeyUsage.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertInfo::AddTrustedUsage( HBufC* aTrustedUsage )
+// Add TrustedUsage OID
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CWimCertInfo::AddTrustedUsage( HBufC* aTrustedUsage )
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimCertInfo::AddTrustedUsage | Begin"));
+    return ( iTrustedUsage.Append( aTrustedUsage ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertInfo::AddExtendedKeyUsage( HBufC* aExtendedKeyUsage )
+// Add ExtendedKeyUsage OID
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CWimCertInfo::AddExtendedKeyUsage( HBufC* aExtendedKeyUsage )
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimCertInfo::AddExtendedKeyUsage | Begin"));
+    return ( iExtendedKeyUsage.Append( aExtendedKeyUsage ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertInfo::GetCertHash( TBuf8<KSHA1HashLengthBytes>& aHash ) const
+// Get hash of certificate
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimCertInfo::GetCertHash( 
+                            TBuf8<KSHA1HashLengthBytes>& aHash ) const
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimCertInfo::GetCertHash | Begin"));
+    aHash = iCertHash;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertInfo::CctCert() const
+// Return pointer to CctCert (Symbian's certificate info )
+// -----------------------------------------------------------------------------
+//
+EXPORT_C const CCTCertInfo* CWimCertInfo::CctCert() const
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimCertInfo::CctCert | Begin"));
+    return iCCTCertInfo;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertInfo::TrustedUsage() const
+// Get pointer array of TrustedUsage OID's
+// -----------------------------------------------------------------------------
+//
+EXPORT_C RArray<HBufC*> CWimCertInfo::TrustedUsage() const
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimCertInfo::TrustedUsage | Begin"));
+    return iTrustedUsage;
+    }
+// -----------------------------------------------------------------------------
+// CWimCertInfo::ExtendedKeyUsage
+// Get pointer array of ExtendedKeyUsage OID's
+// -----------------------------------------------------------------------------
+//
+EXPORT_C RArray<HBufC*> CWimCertInfo::ExtendedKeyUsage() const
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimCertInfo::ExtendedKeyUsage | Begin"));
+    return iExtendedKeyUsage;
+    }
+// -----------------------------------------------------------------------------
+// CWimCertInfo::CDFRefs
+// Get location of certificate
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TUint8 CWimCertInfo::CDFRefs() const
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimCertInfo::CDFRefs | Begin"));
+    return iCDFRefs;
+    }
+// -----------------------------------------------------------------------------
+// CWimCertInfo::SetCDFRefs
+// Set location of certificate
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CWimCertInfo::SetCDFRefs( TUint8 aCDFRefs )
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimCertInfo::SetCDFRefs | Begin"));
+    iCDFRefs = aCDFRefs;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertInfo::Externalize
+// Externalize CWimCertInfo data to flat buffer
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TWimCertInfoPckg* CWimCertInfo::ExternalizeL() const
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimCertInfo::ExternalizeL | Begin"));
+    TWimCertInfoPckg* certPckg = new( ELeave ) TWimCertInfoPckg();
+    
+    GetCertHash( certPckg->iHash );
+    certPckg->iCertLabel.Copy( iCCTCertInfo->Label() );
+    certPckg->iCertificateOwnerType = iCCTCertInfo->CertificateOwnerType();
+    certPckg->iSize = iCCTCertInfo->Size();
+    certPckg->iFormat = iCCTCertInfo->CertificateFormat();
+    certPckg->iSubjectKeyId = iCCTCertInfo->SubjectKeyId();
+    certPckg->iIssuerKeyId = iCCTCertInfo->IssuerKeyId();
+    certPckg->iCDFRefs = iCDFRefs;
+    certPckg->iTokenSerialNbr = iCCTCertInfo->Token().Label();
+    certPckg->iIndex = iCCTCertInfo->Handle().iObjectId;
+    return certPckg;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimCertInfo::InternalizeL
+// Instantiates CWimCertInfo of externalized data
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CWimCertInfo* CWimCertInfo::InternalizeL( 
+    TWimCertInfoPckg& aExternalizedInfo )
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimCertInfo::InternalizeL | Begin"));
+    RArray<HBufC*> trustedUsages;
+      
+    CWimDummyTokenType* tokenType = CWimDummyTokenType::NewL();
+    CleanupReleasePushL( *tokenType );
+
+    CWimDummyToken* token = CWimDummyToken::NewL( *tokenType );
+	CleanupStack::Pop( tokenType );
+    CleanupReleasePushL( *token );
+
+    token->SetSerialNumber( aExternalizedInfo.iTokenSerialNbr );
+  
+    TInt certificateId = aExternalizedInfo.iIndex;
+    TBool deletable = EFalse;
+
+
+    CCTCertInfo* cctCertInfo = CCTCertInfo::NewL( 
+                                        aExternalizedInfo.iCertLabel,
+                                        aExternalizedInfo.iFormat,
+                                        aExternalizedInfo.iCertificateOwnerType,
+                                        aExternalizedInfo.iSize,
+                                        &(aExternalizedInfo.iSubjectKeyId),
+                                        &(aExternalizedInfo.iIssuerKeyId),
+                                        *token,
+                                        certificateId,
+                                        deletable );
+	CleanupStack::Pop( token );
+	CleanupReleasePushL( *cctCertInfo );    
+
+    CWimCertInfo* certInfo = CWimCertInfo::NewL( cctCertInfo,
+                                                 aExternalizedInfo.iHash,
+                                                 trustedUsages,
+                                                 0 );
+
+    CleanupStack::Pop( cctCertInfo );
+
+    certInfo->SetCDFRefs( aExternalizedInfo.iCDFRefs );
+
+    return certInfo;
+    }
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimUtil/src/WimDummyToken.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,322 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Token and TokenType implementation for TrustSettingsStore
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "WimDummyToken.h"
+#include    "WimTrace.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWimDummyToken::CWimDummyToken
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CWimDummyToken::CWimDummyToken( MCTTokenType& aTokenType )
+    : iTokenType( aTokenType )
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimDummyToken::CWimDummyToken | Begin"));
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyToken::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CWimDummyToken::ConstructL()
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimDummyToken::ConstructL | Begin"));
+    iCount = -1; // -1 instead of 0 because of different construction method
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyToken::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimDummyToken* CWimDummyToken::NewL( MCTTokenType& aTokenType )
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimDummyToken::NewL | Begin"));
+    CWimDummyToken* self = new( ELeave ) CWimDummyToken( aTokenType );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+// Destructor
+CWimDummyToken::~CWimDummyToken()
+    {
+    _WIMTRACE(_L("WIM | WIMUtil | CWimDummyToken::~CWimDummyToken | Begin"));
+    delete iSerialNumber;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyToken::Label()
+// Get the label from current token
+// -----------------------------------------------------------------------------
+//
+const TDesC& CWimDummyToken::Label()
+    {
+    _WIMTRACE ( _L( "CWimDummyToken::Label()" ) );
+    return KNullDesC;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyToken::Information()
+// Returns the specified information string about the token
+// -----------------------------------------------------------------------------
+//
+const TDesC& CWimDummyToken::Information( 
+    TTokenInformation aRequiredInformation )
+    {
+    _WIMTRACE ( _L( "CWimDummyToken::Information()" ) );
+
+    switch ( aRequiredInformation ) 
+        {
+        case ESerialNo: // Returns the Serialnumber from current token
+            {
+            return *iSerialNumber;
+            }
+        default:    // Returns empty string 
+            {
+            break;
+            }
+        }
+
+    return KNullDesC;
+    }
+
+// -----------------------------------------------------------------------------
+// MCTTokenType& CWimDummyToken::TokenType()
+// Returns the associated token type.
+// -----------------------------------------------------------------------------
+//
+MCTTokenType& CWimDummyToken::TokenType()
+    {
+    _WIMTRACE ( _L( "CWimDummyToken::TokenType()" ) );
+    return iTokenType;
+    }
+
+// -----------------------------------------------------------------------------
+// TCTTokenHandle CWimDummyToken::Handle()
+// Returns the token's handle. TCTTokenHandle defines a handle to a subclass 
+// of the MCTToken class
+// WimSecModule()->TokenNumber retrieves the token actually exists. 
+// Values 0..7 are for hardware tokens. Value 255 is for SoftId-token.
+// -----------------------------------------------------------------------------
+//
+TCTTokenHandle CWimDummyToken::Handle()
+    {
+    _WIMTRACE ( _L( "CWimDummyToken::Handle()" ) );
+    return TCTTokenHandle( TokenType().Type(), 0 );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyToken::DoGetInterface()
+// Returns a valid interface and KErrNone, or interface = NULL and 
+// KErrNotSupported if it isn't supported by this token
+// -----------------------------------------------------------------------------
+// 
+void CWimDummyToken::DoGetInterface(
+    TUid /*aRequiredInterface*/,
+    MCTTokenInterface*& /*aReturnedInterface*/,
+    TRequestStatus& /*aStatus*/ )
+    {
+    _WIMTRACE ( _L( "CWimDummyToken::DoGetInterface()" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyToken::DoCancelGetInterface()
+// Nothing to do
+// -----------------------------------------------------------------------------
+//
+TBool CWimDummyToken::DoCancelGetInterface()
+    {
+    _WIMTRACE ( _L( "CWimDummyToken::DoCancelGetInterface()" ) );
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyToken::ReferenceCount()
+// Returns a reference to reference counter.
+// -----------------------------------------------------------------------------
+//
+TInt& CWimDummyToken::ReferenceCount()
+    {
+    _WIMTRACE ( _L( "CWimDummyToken::ReferenceCount()" ) );
+    return iCount;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyToken::NotifyOnRemoval( TRequestStatus& aStatus )
+// Notifies the client when the token has been removed.
+// -----------------------------------------------------------------------------
+//
+void CWimDummyToken::NotifyOnRemoval( TRequestStatus& /*aStatus*/ )
+    {
+    _WIMTRACE ( _L( "CWimDummyToken::NotifyOnRemoval()" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyToken::CancelNotify()
+// Cancels the NotifyOnRemoval request.
+// -----------------------------------------------------------------------------
+//
+void CWimDummyToken::CancelNotify()
+    {
+    _WIMTRACE ( _L( "CWimDummyToken::CancelNotify()" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyToken::SetSerialNumber()
+// Sets serial number for token
+// -----------------------------------------------------------------------------
+//
+void CWimDummyToken::SetSerialNumber( TDesC& aSerialNumber )
+    {
+    _WIMTRACE ( _L( "CWimDummyToken::SetSerialNumber()" ) );
+    if ( iSerialNumber )
+        {
+        delete iSerialNumber;
+        iSerialNumber = NULL;
+        }
+
+    TRAPD( err, iSerialNumber = HBufC::NewL( aSerialNumber.Length() ) );
+    if ( err != KErrNone )
+        {
+        return;
+    	  }
+    TPtr serialNbr = iSerialNumber->Des();
+    serialNbr.Copy( aSerialNumber );
+    }
+
+
+// ============== TokenType ====================================================
+
+// -----------------------------------------------------------------------------
+// CWimDummyTokenType::CWimDummyTokenType()
+// Default constructor
+// -----------------------------------------------------------------------------
+//
+CWimDummyTokenType::CWimDummyTokenType()
+    {
+    _WIMTRACE ( _L( "CWimDummyToken::CWimDummyTokenType()" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyTokenType::ConstructL()
+// Second phase constructor
+// -----------------------------------------------------------------------------
+//
+void CWimDummyTokenType::ConstructL()
+    {
+    _WIMTRACE ( _L( "CWimDummyTokenType::ConstructL()" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyTokenType::NewL()
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CWimDummyTokenType* CWimDummyTokenType::NewL() 
+    {
+    _WIMTRACE ( _L( "CWimDummyToken::NewL()" ) );
+    CWimDummyTokenType* that = new( ELeave ) CWimDummyTokenType();
+    CleanupStack::PushL( that );
+    that->ConstructL();
+    CleanupStack::Pop();
+    return that;
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyTokenType::~CWimDummyTokenType()
+// Destructor.
+// -----------------------------------------------------------------------------
+//
+CWimDummyTokenType::~CWimDummyTokenType()
+    {
+    _WIMTRACE ( _L( "CWimDummyTokenType::~CWimDummyTokenType()" ) );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyTokenType::List()
+// List all the tokens of this type.
+// -----------------------------------------------------------------------------
+//
+void CWimDummyTokenType::List(
+    RCPointerArray<HBufC>& /*aTokens*/,
+    TRequestStatus& /*aStatus*/ )
+    {
+    _WIMTRACE ( _L( "CWimDummyToken::List()" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyTokenType::CancelList()
+// Cancel a list operation.
+// -----------------------------------------------------------------------------
+//
+void CWimDummyTokenType::CancelList()
+    {
+    _WIMTRACE ( _L( "CWimDummyTokenType::CancelList" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CTokenTypeImplementation::OpenToken() 
+// Opens new token, which name is specified in aTokenInfo
+// This is not true asynchronous function.
+// -----------------------------------------------------------------------------
+//
+void CWimDummyTokenType::OpenToken(
+    const TDesC& /*aTokenInfo*/,
+    MCTToken*& /*aToken*/,
+    TRequestStatus& /*aStatus*/ )
+    { 
+    _WIMTRACE ( _L( "CWimDummyTokenType::OpenToken with name" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CWimDummyTokenType::OpenToken()
+// Open new token, The handle of the required token is used to get needed 
+// information. Before opening new token we need to compare token numbers.
+// This is not true asynchronous function.
+// -----------------------------------------------------------------------------
+//
+void CWimDummyTokenType::OpenToken(
+    TCTTokenHandle /*aHandle*/,
+    MCTToken*& /*aToken*/,
+    TRequestStatus& /*aStatus*/ )
+    {
+    _WIMTRACE ( _L( "CWimDummyTokenType::OpenToken with handle" ) );
+    }
+// -----------------------------------------------------------------------------
+// CWimDummyTokenType::CancelOpenToken()
+// Cancel an OpenToken operation.
+// -----------------------------------------------------------------------------
+//
+void CWimDummyTokenType::CancelOpenToken()
+    {
+    _WIMTRACE ( _L( "CWimDummyTokenType::CancelOpenToken" ) );
+    }
+
+
+//  End of File  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/WimUtil/src/WimUtilEntry.cpp	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  DLL Entry point
+*
+*/
+ 
+
+#include "e32base.h"
+#include "WimTrace.h"
+
+#ifndef EKA2
+// -----------------------------------------------------------------------------
+// GLDEF_C TInt E32Dll( TDllReason aReason )
+// The E32Dll() entry point function
+// -----------------------------------------------------------------------------
+
+GLDEF_C TInt E32Dll( TDllReason /*aReason*/ )
+    {
+    _WIMTRACE ( _L( "WimUtilEntry | E32Dll" ) );
+    return( KErrNone );
+    }
+    
+#endif // EKA2
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/DigSigningNote.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,115 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface for Digital Signing Note
+*
+*/
+
+
+
+#ifndef MDIGSIGNINGNOTE_H
+#define MDIGSIGNINGNOTE_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <secdlg.h>
+
+// CLASS DECLARATION
+
+/**
+*  Digital Signing Note interface
+*  
+*  @since Series60 2.6
+*/
+class MDigSigningNote 
+    {
+    public:
+        
+        /**
+        * TNoteType defines different possible note types.
+        */
+        enum TNoteType
+            {
+            ESignatureRequested = 0xFF00,   // Digital signature requested
+            ESignatureDone,                 // Digital signature done.
+            ESigningCancelled,              // Digital signing cancelled   
+            ENoMatchCert,                   // No matchig certificate found
+            ENoSecurityModule,              // Security Module unvailable
+            EInternalError                  // Error note in any other case
+            };
+
+    public: // New functions
+        
+        /**
+        * Informs the user during digital signing.
+        * @param aNoteType Identifies the note type.
+        * @param aStatus KErrNone or KErrNotSupported
+        * @return void
+        */
+        virtual void ShowNote( MDigSigningNote::TNoteType aNoteType,
+                               TRequestStatus& aStatus ) = 0;
+        
+        /**
+        * Saves receipt to Notepad if receipt saving is on in .ini-file and
+        * informs user about this.
+        * @param aSignedText Signed text in readable form.
+        * @param aStatus KErrNone or KErrNotSupported
+        * @return void
+        */
+        virtual void SaveSignedText( const TDesC& aSignedText,
+                                     TRequestStatus& aStatus ) = 0;
+        
+        /**
+        * Shows instructions how to unblock PIN.
+        * @param aLabel Label of the PIN.
+        * @param aStatus KErrNone or KErrNotSupported
+        * @return void
+        */
+        virtual void ShowPINBlockedInfo( const TPINLabel& aLabel,
+                                         TRequestStatus& aStatus ) = 0;
+
+        /**
+        * Release is called to free resources of the MDigSigningNote class
+        */
+        virtual void Release() = 0;
+
+    protected: 
+        
+        // Destructor
+        inline virtual ~MDigSigningNote() = 0;
+
+    };
+
+inline MDigSigningNote::~MDigSigningNote(){}
+
+/**
+* Factory for creating the relevant concrete subclass
+* of the digital signing note.
+*/
+class DigSigningNoteFactory
+    {
+    public:
+    
+    /**
+     * Creates an instance of a subclass of MDigSigningNote. 
+     * Implement to create the appropriate security dialog.
+     * 
+     * @param returns an object that implements MDigSigningNote methods
+     */
+    IMPORT_C static MDigSigningNote* CreateNoteL(); 
+    
+    };
+
+#endif      // MDIGSIGNINGNOTE_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/Scard.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,81 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Main smard card object, acts as client for Scard Server
+*
+*/
+
+
+
+#ifndef RSCARD_H
+#define RSCARD_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// CLASS DECLARATION
+
+/**
+*  The basic client class.
+*  The basic client class representing a channel of communication 
+*  with the server. The connect function starts the server, if it 
+*  is not already running. An RSessionBase sends messages to the 
+*  server with the function RSessionBase::SendReceive(); specifying 
+*  an opcode (TScardServerRqst) and and array of argument pointers. 
+*  This class is a friend to the classes Comm and Listener.
+*  All four are classes that need to communicate 
+*  directly with the server.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class RScard : public RSessionBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static RScard* NewL();
+        
+        /**
+        * Destructor.
+        */
+        IMPORT_C virtual ~RScard();
+
+    private:
+        
+        /**
+        * C++ default constructor.
+        */
+        RScard();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Version of server
+        * @return Version number
+        */
+        TVersion Version() const;
+        
+    private:    // Friend classes
+        friend class CScardComm;
+        friend class CScardListener;
+    };
+
+#endif      // RSCARD_H
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/ScardBase.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,214 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions for smart card base
+*
+*/
+
+
+#ifndef CSCARDBASE_H
+#define CSCARDBASE_H
+
+//  INCLUDES
+#include <e32base.h>
+
+//  CONSTANTS  
+
+////////////////////////////////////////////////////////////////////////////////
+//  Scard Panic codes
+////////////////////////////////////////////////////////////////////////////////
+const TInt KScPanicNoMemory                 = -1;   // Not enough free memory
+const TInt KScPanicNullPointer              = -2;   // A NULL pointer was encountered
+const TInt KScPanicNullLength               = -3;   // A buffer or data member has null lenght
+const TInt KScPanicNotSupported             = -4;   // A given operation or resource is not supported
+const TInt KScPanicInvalidValue             = -5;   // A value was invalid in the given context
+const TInt KScPanicNoResourceConnection     = -6;   // Some external resource (eg. file server) 
+                                                    // could not be contacted
+//  7-9 rfu
+const TInt KScUtilPanicOverFlow             = -10; // A buffer overflow
+const TInt KScUtilPanicUnderFlow            = -11; // A buffer underflow
+//  12-14 rfu
+const TInt KScServerPanicInternalError      = -15; // Some internal error has occurred
+const TInt KScServerPanicBadRequest         = -16; // A service request had an unknown value
+const TInt KScServerPanicBadDescriptor      = -17; // A descriptor was too short or corrupted
+const TInt KScServerPanicDescrNonNumeric    = -18;  
+const TInt KScServerPanicMainSchedulerError = -19; // The active scheduler could not be activated
+const TInt KScServerPanicSvrCreateServer    = -20; // Server creatíon failed
+const TInt KScServerPanicCreateTrapCleanup  = -21; // CleanupStack creation failed
+const TInt KScServerPanicBadCounterRemove   = -22; 
+const TInt KScServerPanicBadSubsessionHandle= -23; // A subsession had an invalid handle
+//  24-29 rfu
+const TInt KScServicePanicAlreadyActive     = -30; // The service is still running the previous request
+const TInt KScServicePanicBadFormat         = -31; // A parameter did not conform to a spesified format
+const TInt KScServicePanicDataCorruption    = -32; // Some data (internal/external) has 
+                                                   // been terminally corrupted
+//  33-n proprietary panics
+
+////////////////////////////////////////////////////////////////////////////////
+//  Scard error codes
+////////////////////////////////////////////////////////////////////////////////
+const TInt KScErrUnknown                    = 1;  // An undefined internal error has occurred
+const TInt KScErrGeneral                    = 2;  // An internal error
+const TInt KScErrNotFound                   = 3;  // A search did not find the wanted resource
+const TInt KScErrCancelled                  = 4;  // Operation was cancelled
+const TInt KScErrTimeOut                    = 5;  // A command has timed out
+const TInt KScErrNotSupported               = 6;  // The operation or resource (reader etc.) 
+                                                  // is not supported
+const TInt KScErrUnknownGroup               = 7;  // The reader group could not be identified
+const TInt KScErrUnknownCard                = 8;  // The card could not be identified
+const TInt KScErrUnknownReader              = 9;  // The reader could not be identified
+const TInt KScErrBadArgument                = 10; // An argument has unacceptable value / does not
+                                                  // conform to a spesified format
+const TInt KScErrEmpty                      = 11; // A buffer or descriptor data area was empty, when it 
+                                                  // was expected to contain data
+const TInt KScErrFull                       = 12; // A buffer or descriptor is full
+const TInt KScErrNullPointer                = 13; // A null pointer was encountered
+const TInt KScErrNoMemory                   = 14; // There was not enough free memory to complete a task
+const TInt KScErrInsufficientBuffer         = 15; // A buffer had insufficient length
+const TInt KScErrFileFailure                = 16; // An operation could not complete due to file 
+                                                  // handling errors
+const TInt KScErrAlreadyExists              = 17; // A resource could not be installed because a resource
+                                                  // of same type by that name already exists
+const TInt KScErrInUse                      = 18; // A resource was in use
+
+
+// 18 - 29 rfu
+
+const TInt KScReaderErrNoCard               = 30; // The SC was removed from the reader
+const TInt KScReaderErrNoReader             = 31; // The reader could not be reached
+const TInt KScReaderErrUnpoweredCard        = 32; // The SC had no power on
+const TInt KScReaderErrUnsupportedCard      = 33; // The SC could not be supported
+const TInt KScReaderErrUnresponsiveCard     = 34; // The SC did not response
+const TInt KScReaderErrCardFailure          = 35; // A SC failure
+const TInt KScReaderErrReaderFailure        = 36; // A reader failure
+const TInt KScReaderErrCommunicationFailure = 37; // A communication failure other than the two previous ones
+const TInt KScReaderErrResponseTimeout      = 38; // A response time-out limit reached without a valid 
+                                                  // response from the SC or the reader
+const TInt KScReaderErrPowerFailure         = 39; // The reader has encountered a power failure
+const TInt KScReaderErrNotReady             = 40; // The reader or the SC was not ready
+const TInt KScReaderErrCannotConnect        = 41; // Reader handler is unable to connect to the reader
+                                                  // or the SC
+const TInt KScReaderErrUnsupportedTag       = 42; // In function GetCapabilities a unsupported 
+                                                  // capability tag was requested
+const TInt KScReaderErrUnsupportedProtocol  = 43; // In function NegotiateProtocol an unsupported
+                                                  // protocol was requested
+// 44 - 59 proprietary reader errors
+
+const TInt KScServerErrIllegalChannel       = 61; // The logical channel the client attempted to
+                                                  // use was not available for this client (no previous
+                                                  // ManageChannel command)
+const TInt KScServerErrIllegalOperation     = 62; // A client attempted to send a ManageChannel apdu via
+                                                  // TransmitToCard() instead of ManageChannel()
+// 62 - 79 rfu
+
+//  File services
+const TInt KScServiceErrDirNotFound         = 80; // The requested directory could not be found
+const TInt KScServiceErrFileNotFound        = 81; // The requested file could not be found
+const TInt KScServiceErrNoDir               = 82; // The request did not contain a valid directoryname
+const TInt KScServiceErrNoFile              = 83; // The request did not contain a valid filename
+const TInt KScServiceErrNoAccess            = 84; // The resource could not be accessed because of a 
+                                                  // sharing violation
+const TInt KScServiceErrCorruptedFile       = 85; // The requested file was corrupted
+const TInt KScServiceErrRecordNotFound      = 86; // A requested record was not found
+const TInt KScServiceErrRunning             = 87; // The service is already running a previous request
+const TInt KScServiceErrEOF                 = 88; // An end of file was encountered before a successful
+                                                  // completion of a task
+const TInt KScServiceErrInvalidOffset       = 89; // The offset could not be mapped inside the file/resource
+const TInt KScServiceErrWriteTooMany        = 90; // A write counter limit has been reached (?)
+const TInt KScServiceErrFPEmpty             = 91; // A file pointer was empty (?)
+
+// Application Management services
+const TInt KScServiceErrInvalidAID          = 92; // The given application identifier did not match any
+                                                  // applications on the SC
+const TInt KScServiceErrApplicationBlocked  = 93; // The requested application was blocked
+const TInt KScServiceErrNoSupportedApps     = 94; // The card contains no supportable applicatíons
+const TInt KScServiceErrSecurityViolation   = 95; // The task could not be completed because of a security
+                                                  // violation
+
+//These tags from PC/SC, shoud be moved to scard.h 
+////////////////////////////////////////////////////////////////////////////////
+//  Tags for reader capabilities           Length   Encoding
+////////////////////////////////////////////////////////////////////////////////
+const TInt32 KVendorName     = 0x0100; //  32       ASCII string
+const TInt32 KReaderType     = 0x0101; //  32       ASCII string
+const TInt32 KReaderVersion  = 0x0102; //  4        Dword 0xMMmmbbb
+                                       //               MM = major version
+                                       //               mm = minor version
+                                       //               bbbb = build number
+const TInt32 KReaderSerial   = 0x0103; //  32       ASCII string
+
+// Channel ID skipped
+
+const TInt32 KAsyncProtocols = 0x0120; //  4        Dword 0x0000PPPP
+                                       //        1 in a given position indicates
+                                       //        support for associated protocol
+                                       //        e.g 0x00000002 for T=1 support 
+//other protocol parameters skipped
+
+const TInt32 KPowerMgt       = 0x0131; //  1 (4)    0 = not supported
+const TInt32 KAuthFeatures   = 0x0140; //  4        See PC/SC part 3 page 7
+
+//Mechanical charasteristics skipped
+
+//Vendor defined tags from 0x0180 - 0x01F0
+
+////////////////////////////////////////////////////////////////////////////////
+//  Tags for Card state                    Length   Encoding
+////////////////////////////////////////////////////////////////////////////////
+const TInt32 KCardPrecence   = 0x0300; //  1        0 = not present, 1 = present
+const TInt32 KCardInterface  = 0x0301; //  1        0 = contact inactive, 
+                                       //           1 = contact active
+const TInt32 KCardType       = 0x0304; //  1        0 = unknown, 1 = 7816 async,
+const TInt32 KCardStatus     = 0x0310; //  1        bit 1: card powered
+                                       //           bit 2: card present
+                                       //           bit 3: card reader id1 size
+                                       //           bit 4: card reader present
+                                       //           bit 5: card reader removable
+
+////////////////////////////////////////////////////////////////////////////////
+//  Tags for Reader Protocol options       Length   Encoding
+////////////////////////////////////////////////////////////////////////////////
+const TInt32 KCurrentProtocol= 0x0201; //  4        As with AsyncProtocols
+const TInt32 KCurrentF       = 0x0203; //  4               
+const TInt32 KCurrentD       = 0x0204; //  4               
+const TInt32 KCurrentN       = 0x0205; //  4  
+
+////////////////////////////////////////////////////////////////////////////////
+//  Connection parameters
+////////////////////////////////////////////////////////////////////////////////
+const TInt KAnyReader               = 0x01;
+const TInt KExplicitReader          = 0x02;
+const TInt KExcludedReader          = 0x04;
+
+const TInt KAnyCard                 = 0x10;
+const TInt KATRSpesified            = 0x20;
+const TInt KApplicationSpesified    = 0x40;
+const TInt KServiceSpesified        = 0x80;
+
+const TInt KNewCardsOnly            = 0x100;
+const TInt KNewReadersOnly          = 0x200;
+
+////////////////////////////////////////////////////////////////////////////////
+//  Reader handler definitions
+////////////////////////////////////////////////////////////////////////////////
+_LIT( KReaderName, "SWIM Reader" );
+const TInt KReaderID = 1;
+
+_LIT( KGroupName, "SWIM Readers" );
+const TInt KGroupID  = 1;
+
+_LIT( KSwimReaderDLL, "SwimReader.dll" );
+
+#endif      // CSCARDBASE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/ScardComm.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,178 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Core class for all Smart Card aware applications to use when 
+*                communicating with the card.
+*
+*/
+
+
+
+#ifndef CSCARDCOMM_H
+#define CSCARDCOMM_H
+
+//  INCLUDES
+#include "ScardConnectionRequirement.h"
+
+
+// FORWARD DECLARATIONS
+class RScard;
+
+// CLASS DECLARATION
+
+/**
+*  Core class for card communication.
+*  This is the core class for all SC aware applications to use when 
+*  communicating with the card. All objects of this class are 
+*  connected to a reader, and the reader's name must be supplied as a 
+*  parameter when constructing objects of this class
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardComm : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        * @param aScard The connection to server. 
+        *        The RScard object must not have any other CScardComm objects
+        *        attached to it.
+        * @param aRequirement Parameters to the connection
+        * @param aReaderName This is set to contain the name of the 
+        *        reader that was contacted when a connection is established
+        * @param aStatus This status is signaled when connection has been made
+        * @param aTimeOut The timeout in microseconds
+        * @return Pointer to CScardComm object
+        */
+        IMPORT_C static CScardComm* NewL(
+            RScard* aScard, 
+            TScardConnectionRequirement& aRequirement,
+            TScardReaderName& aReaderName,
+            TRequestStatus& aStatus, 
+            const TInt32 aTimeOut = 0 );
+        
+        /**
+        * Destructor.
+        */
+        IMPORT_C virtual ~CScardComm();
+
+    public: // New functions
+        
+        /**
+        * Returns the RScard object contained within this object.
+        * @return Pointer to RScard object
+        */
+        IMPORT_C RScard* Scard() const;
+
+        /**
+        * This function fetches the answer-to-reset bytes of the SC 
+        * currently in the card reader. If an error occurs during the 
+        * operation, the  length of the atr bytes is set to zero. Currently
+        * leaves with KErrNotSupported
+        * @param aATR ATR-bytes
+        * @return void
+        */
+        IMPORT_C void GetATRL( TScardATR& aATR ) const;
+
+        /**
+        * Get proprietary parameters from the reader handler.
+        * @param aTag parameter wanted (see scardbase.h)
+        * @param aValue value of desired parameter
+        * @param aTimeOut timeout in microseconds
+        * @return void
+        */
+        IMPORT_C void GetCapabilitiesL( const TInt32 aTag,
+                                        TDes8& aValue, 
+                                        const TInt32 aTimeOut = 0 ) const;
+
+        /**
+        * This function is the basic transmission function. It takes a
+        * 8-bit command data of unspecified length and transmits it to 
+        * the reader handler. The reader handler will pass it on to the 
+        * card, and place the response in the supplied response buffer 
+        * (also of undefined length). The buffer must be sufficiently 
+        * big to accomodate the response, otherwise the calling thread 
+        * will be panicked.
+        * @param aCommand This descriptor holds the command sent to the 
+        *        card. The length of the descriptor must match the data length
+        *        of the command.
+        * @param aResponse The response from the SC is copied here.
+        * @param aStatus Signaled when the operation is finished.
+        * @param aTimeOut Timeout in microseconds.
+        * @param aChannel The logical channel this command will be executed in.
+        * @return void
+        */
+        IMPORT_C void TransmitToCard( const TDesC8& aCommand, 
+                                      TDes8& aResponse,
+                                      TRequestStatus& aStatus,
+                                      const TInt32 aTimeOut = 0, 
+                                      const TInt8 aChannel = 0) const;
+
+        /**
+        * This function will cancel any transmissions and other 
+        * operations this object has currently pending within the 
+        * server. If the object has an active transaction reservation, 
+        * this will also be cancelled. All operations sent before this 
+        * command will terminate with error code KScErrCancelled.
+        * @return void
+        */
+        IMPORT_C void CancelTransmit() const;
+
+        /**
+        * Channel management function.
+        * @param aCommand Channel operation.
+        * @param aArgument
+        * @param aResponseBuffer Buffer for response.
+        * @param aStatus Signaled when the operation is finished.
+        * @param aTimeOut Timeout in microseconds.
+        * @return void
+        */
+        IMPORT_C void ManageChannel( const TScChannelManagement aCommand, 
+                                     const TInt8 aArgument,
+                                     TDes8& aResponseBuffer,
+                                     TRequestStatus& aStatus,
+                                     const TInt32 aTimeOut ) const;
+
+    private:
+
+        /**
+        * C++ default constructor.
+        * @param aScard Pointer to RScard object
+        */
+        CScardComm( RScard* aScard );
+
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( TScardConnectionRequirement& aRequirement,
+                         TScardReaderName& aReaderName, 
+                         TRequestStatus& aStatus, 
+                         const TInt32 aTimeOut );
+
+        /**
+        * Disconnect from reader
+        * @return void
+        */
+        void DisconnectFromReader() const;
+    
+    private:    // Data
+        // Pointer to Scard object. Not owned. 
+        RScard* iScard;
+    };
+
+#endif      // CSCARDCOMM_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/ScardConnectionRequirement.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,147 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  For describing required smart card reader connections.
+*
+*/
+
+
+
+#ifndef CSCARDCONNECTIONREQUIREMENT_H
+#define CSCARDCONNECTIONREQUIREMENT_H
+
+//  INCLUDES
+#include "ScardDefs.h"
+
+
+// CLASS DECLARATION
+
+/**
+*  This class contains requirements for new connections.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class TScardConnectionRequirement // : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C TScardConnectionRequirement();
+
+    public: // New functions
+        
+        /**
+        * Set Explixit reader name
+        * @param aExplicitName Explicit reader name
+        * @return void
+        */
+        IMPORT_C void SetExplicitL( TScardReaderName& aExplicitName );
+        
+        /**
+        * Set excluded reader name
+        * @param aExcludedName Excluded Reader name
+        * @return void
+        */
+        IMPORT_C void SetExcludedL( TScardReaderName& aExcludedName );
+        
+        /**
+        * Set ATR bytes
+        * @param aATR ATR bytes
+        * @return void
+        */
+        IMPORT_C void SetATRL( TScardATR& aATR );
+        
+        /**
+        * Set AID bytes
+        * @param aAIDBytes AID bytes
+        * @return void
+        */
+        IMPORT_C void SetAIDBytesL( TDesC8& aAIDBytes );
+
+        /**
+        * Clear excplicit reader name
+        * @return void
+        */
+        IMPORT_C void ClearExplicitL();
+        
+        /**
+        * Clear Excluded reader name
+        * @return void
+        */
+        IMPORT_C void ClearExcludedL();
+        
+        /**
+        * Clear ATR bytes
+        * @return void
+        */
+        IMPORT_C void ClearATRL();
+        
+        /**
+        * Clear AID bytes
+        * @return void
+        */
+        IMPORT_C void ClearAIDBytesL();
+
+        /**
+        * Set new readers only flag
+        * @param aNewOnly Flag to tell if only new readers are supported
+        * @return void
+        */
+        IMPORT_C void NewReadersOnly( const TBool aNewOnly );
+        
+        /**
+        * Set new card only flag
+        * @param aNewOnly Flag to tell if only new cards are supported
+        * @return void
+        */
+        IMPORT_C void NewCardsOnly( const TBool aNewOnly );
+
+    private:
+        
+        /**
+        * Prohibit copy constructor if not deriving from CBase.
+        */
+        TScardConnectionRequirement( TScardConnectionRequirement& );
+        /**
+        * Prohibit assigment operator if not deriving from CBase.
+        */
+        TScardConnectionRequirement& operator=(
+            const TScardConnectionRequirement& aRequirement );
+
+    private:    // Data
+        // If we want only one singular reader. Owned.
+        TScardReaderName* iExplicitReader;
+        // This is the reader we do NOT want. Owned.
+        TScardReaderName* iExcludedReader;
+        // The reader should have a SC with these ATR bytes. Owned.
+        TScardATR*      iATRBytes;
+        // The reader should have a SC with an appl match these AID bytes.Owned.
+        TDesC8*         iAIDBytes;
+        // Count of parameters
+        TInt            iParameterCount;
+        // New card only
+        TBool           iNewCards;
+        // New readers only
+        TBool           iNewReaders;
+
+    public:     // Friend classes
+        friend class CScardComm;
+
+    };
+
+#endif      // CSCARDCONNECTIONREQUIREMENT_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/ScardDefs.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,95 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions for smart card
+*
+*/
+
+
+#ifndef SCARDDEFS_H
+#define SCARDDEFS_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// FORWARD DECLARATIONS (these has to be before data types)
+class CScardCommandTimer;
+
+const TInt KScardReaderMaxNameLength = 32; // Maximum data lengths
+
+//  DATA TYPES  
+
+// Database string aliases
+typedef TBuf<KScardReaderMaxNameLength> TScardReaderName;
+
+typedef TInt16 TReaderID;
+typedef TInt16 TGroupID;
+
+enum TScardServiceStatus
+    {
+    EScardReseted,
+    EScardInserted,
+    EScardRemoved,
+    EReaderRemoved,
+    ECommunicationError
+    };
+
+enum TPowerAction
+    {
+    EScardPowerUp,
+    EScardPowerDown,
+    EScardReset
+    };
+
+enum TScChannelManagement
+    {
+    EOpenAnyChannel = 1,
+    ECloseChannel,
+    EChannelStatus
+    };
+
+//  CScardAccessControl & CScardMessageRegistry
+struct TMessageHandle
+    {
+    RMessage2    iMessage;
+    TInt        iSessionID;
+    TReaderID   iReaderID;
+    TBool       iCancelled;
+    TInt8       iChannel;
+
+    CScardCommandTimer* iTimer;
+    TInt        iAdditionalParameter;
+
+    TMessageHandle( const RMessage2& aMessage,
+                    const TInt aSessionID,
+                    const TReaderID aReaderID,
+                    const TInt8 aChannel, 
+                    const TInt8 aAddition = 0 );
+    TMessageHandle();
+    };
+
+//  CScardConnector & CScardEventStack
+struct TQueueEvent
+    {
+    TReaderID   iReaderID;
+    TScardServiceStatus iEventType;
+    };
+
+// Answer To Reset
+const TInt KMaxATRBytes           = 33; 
+const TInt KMaxATRHistoricalBytes = 15;
+typedef TBuf8<KMaxATRBytes> TScardATR; // ATR bytes
+
+#endif      // SCARDDEFS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/ScardListener.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,122 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Listens for smard card events
+*
+*/
+
+
+
+#ifndef CSCARDLISTENER_H
+#define CSCARDLISTENER_H
+
+//  INCLUDES
+#include "ScardDefs.h"
+
+// FORWARD DECLARATIONS
+class RScard;
+
+// CLASS DECLARATION
+
+/**
+*  A base class for listening card events.
+*  This class is a virtual base class used to transmit card events from 
+*  a spesific reader to the terminal, and it intended for use in all 
+*  applications that need to use smart cards. When an event occurs, 
+*  it is reported to the listener, and the listener will launch the 
+*  ProcessEvent function. This function is pure virtual, so a user of 
+*  this class must derive a concrete class from CScardListener, 
+*  and give an implementation to the ProcessEvent function.
+*/
+class CScardListener : public CActive
+    { 
+    public: // New functions
+        
+        /**
+        * This function initiates the first request from this listener 
+        * to the server to be notified of card events from the spesified 
+        * reader. After this the listener will listen and report all 
+        * card events from the reader.
+        * @param aReaderName Name of the reader
+        * @return an error code (KErrNone if succesful)
+        */
+        IMPORT_C TInt ListenCardEvents( const TScardReaderName& aReaderName );
+
+    protected:  // New functions
+        
+        /**
+        * Construction.
+        * @param aScard pointer to scard class
+        * @return void
+        */
+        IMPORT_C CScardListener( RScard* aScard );
+
+        /**
+        * Destruction.
+        */
+        IMPORT_C virtual ~CScardListener();
+
+        /**
+        * This function is called from RunL() and it is pure virtual, 
+        * so an implementation must be provided by derived classes to 
+        * handle the received events.
+        * @param aEvent
+        */
+        virtual void ProcessEvent( const TScardServiceStatus aEvent) = 0;
+
+        
+    protected:  // Functions from base classes
+        
+        /**
+        * From CActive Cancel request
+        */
+        IMPORT_C void DoCancel();
+
+        /**
+        * From CActive Service completed request
+        */
+        IMPORT_C void RunL();
+
+    
+    private:
+
+        /**
+        * Tell the server to notify this object of card events.
+        * @param aStatus Request status
+        * @param aReaderName Name of the reader
+        * @return an error code (KErrNone if succesful)
+        */
+        TInt NotifyChange( TRequestStatus& aStatus, 
+                           const TScardReaderName& aReaderName );
+
+        /**
+        * Cancel notification.
+        * @param aStatus Request status
+        * @param aFriendlyName Name of the reader
+        */
+        /*void CancelNotifyChange( TRequestStatus& aStatus, 
+                                 const TScardReaderName& aFriendlyName );*/
+        TInt CancelNotifyChange( const TScardReaderName& aFriendlyName );
+        
+    private:    // Data
+        // Pointer to CScard class. Not owned.
+        RScard*          iScard;
+        // Reader name
+        TScardReaderName iReaderName;
+        //Transfer to server side
+        TPckgBuf<TRequestStatus*> iPckg;
+    };
+
+#endif      // CSCARDLISTENER_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/ScardNotifyObserver.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This file contains definition of abstract MScardNotifyObserver
+*               class
+*
+*/
+
+
+
+#ifndef MSCARDNOTIFYOBSERVER_H
+#define MSCARDNOTIFYOBSERVER_H
+
+//  INCLUDES
+#include "ScardDefs.h"
+
+//  CONSTANTS  
+
+// CLASS DECLARATION
+
+/**
+*  Defines a pure virtual function for notifying card events.
+*  Reader Launcher must send reference of object implementing this interface
+*  to specific Reader Handler in order to give Reader Handler a ability to 
+*  notify occured events.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class MScardNotifyObserver
+    {
+    public:
+
+        /**
+        * Notify on card event. Pure virtual.
+        * @param aEvent Scard Event
+        * @param aReaderID Reader ID
+        * @return void
+        */
+        virtual void NotifyCardEvent( TScardServiceStatus aEvent, 
+                                      TReaderID aReaderID ) = 0;
+    };
+
+#endif      // MSCARDNOTIFYOBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/ScardReader.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,111 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This file contains definition of abstract Card Reader interface
+*               class from which the final Reader classes in Reader Handler 
+*               level are derived.
+*
+*/
+
+
+
+#ifndef CSCARDREADER_H
+#define CSCARDREADER_H
+
+//  INCLUDES
+#include "ScardBase.h"
+#include "ScardDefs.h"
+
+//  CONSTANTS  
+
+// The UID for Card Reader DLLs.
+// The client imposes this on DLLs which are required
+// to satisfy the protocol 
+const TInt KReaderUidValue = 0x1000086E;
+const TUid KReaderUid      = {KReaderUidValue};
+
+// CLASS DECLARATION
+
+/**
+*  Smart card reader. 
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class MScardReader
+    {
+    public: 
+        
+        /**
+        * Initializes the Card Reader. Implementations of this method must carry
+        * out all steps required to set the concrete reader into a proper state.
+        * After invoking this method it should be possible to communicate with 
+        * the reader properly.
+        * @param aStatus Request status
+        * @return void
+        */
+        virtual void Open( TRequestStatus& aStatus ) = 0; 
+
+        /**
+        * Closes the Card Reader. Implementations of this method must carry out
+        * all steps required to close the concrete terminal and free resources 
+        * held by it.
+        * @return Symbian error code
+        */
+        virtual TInt Close() = 0;
+
+        /**
+        * Cancel any pending requests (if any)
+        * @return void
+        */
+        virtual void CancelTransmit() = 0;
+
+        /**
+        * Return the ATR bytes. 
+        * @param anATR ATR
+        * @return Symbian error code
+        */
+        virtual TInt GetATR( TScardATR& anATR ) = 0;
+        
+        /**
+        * Return the value corresponding to the specified TAG parameter
+        * @param aStatus Request status
+        * @param aTag Tag
+        * @param aValue Value for capabilities
+        * @param aTimeout Timeout
+        * @return ETrue/EFalse
+        */
+        virtual TBool GetCapabilities( TRequestStatus& aStatus, 
+                                       const TInt32 aTag,
+                                       TPtr8& aValue,
+                                       const TInt32 aTimeout ) = 0;
+
+        /**
+        * Send a Command(APDU) to the card and return Response(APDU)
+        * received from card.
+        * @param aStatus Request status
+        * @param aCommand Command APDU 
+        * @param aResponse Response APDU
+        * @param aTimeout Timeout
+        * @return void
+        */
+        virtual void TransmitToCard( TRequestStatus& aStatus, 
+                                     const TPtrC8& aCommand, 
+                                     TPtr8& aResponse,
+                                     const TInt32 aTimeout ) = 0;
+
+    };
+    
+#endif      // CSCARDREADER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/ScardReaderLauncher.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,100 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This file contains definition of abstract Card Reader Launcher
+*               interface class from which the final Reader Launcher classes 
+*               are derived.
+*
+*/
+
+
+
+#ifndef SCARDREADERLAUNCHER_H
+#define SCARDREADERLAUNCHER_H
+
+//  INCLUDES
+#include "ScardReader.h"
+#include "ScardNotifyObserver.h"
+
+//  CONSTANTS  
+
+// The UID for Card Reader DLLs.
+// The client imposes this on DLLs which are required
+// to satisfy the protocol 
+
+const TInt KReaderLauncherUidValue = 0x1000086E;
+const TUid KReaderLauncherUid      = {KReaderUidValue};
+
+// CLASS DECLARATION
+
+/**
+*  Defines pure virtual functions for getting notifyobservers.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class MScardReaderService 
+    {
+
+    public:
+        /**
+        * Return notify observer object
+        * @return Pointer to MScardNotifyObserver
+        */
+        virtual MScardNotifyObserver* NotifyObserver() = 0;
+
+    };
+
+// CLASS DECLARATION
+
+/**
+*  Defines pure virtual functions for load and unload service resources.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class MScardReaderLauncher
+    {
+
+    public:  // Constructors and destructor
+
+        /**
+        * Reader service object is the one that Launcher can query needed 
+        * information to connect reader for framework wide services.
+        * @param aReaderService ReaderService
+        * @return void
+        */
+        virtual void ConstructL( MScardReaderService* aReaderService ) = 0;
+
+    public: // New functions
+ 
+        /**
+        * Create specific reader object, just create not attach the physical
+        * reader device, Open() in Reader interface will do this.
+        * @param aReaderID Reader ID
+        * @return Pointer to MScardReader object
+        */
+        virtual MScardReader* CreateReaderL( TReaderID aReaderID ) = 0;
+
+        /**
+        * Delete the reader object, should be Closed() before this is called
+        * @param aReaderID Reader ID
+        * @return void
+        */
+        virtual void DeleteReader( TReaderID aReaderID ) = 0;
+
+    };
+    
+#endif      // SCARDREADERLAUNCHER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/ScardReaderQuery.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,93 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This class returns all supported readers and reader groups.
+*
+*/
+
+
+
+#ifndef CSCARDREADERQUERY_H
+#define CSCARDREADERQUERY_H
+
+//  INCLUDES
+#include "ScardDefs.h"
+
+
+// CLASS DECLARATION
+
+/**
+*  Utility class to make queries for readers and reader groups.
+*  This class is intended for use by all Smart card aware
+*  applications that need to query the resources available on
+*  the framework.
+*
+*  @lib Scard.lib
+*  @since Series60 2.1
+*/
+class CScardReaderQuery : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CScardReaderQuery* NewL();
+        
+        /**
+        * Destructor.
+        */
+        IMPORT_C virtual ~CScardReaderQuery();
+
+    public: // New functions
+        
+        /**
+        * Create a list of all the readers belonging to the group.
+        * @param aReaderList Dynamic array that will be filled with the 
+        * names of the readers that belong to the group. The array must 
+        * be already allocated and it must be empty. There is only one 
+        * reader in Series 60. If given group is not what expected, leaves
+        * with KScErrNotSupported
+        * @param aGroupName Name of the reader group to be queried.
+        */
+        IMPORT_C void ListReadersL(
+            CArrayFixFlat<TScardReaderName>* aReaderList,
+            const TScardReaderName& aGroupName );
+
+        /**
+        * List all groups currently installed to the framework.
+        * @param aGroupList dynamic array that will be filled with the 
+        *        names of the groups. The array must be already allocated and
+        *        it must be empty.
+        */
+        IMPORT_C void ListGroupsL(
+            CArrayFixFlat<TScardReaderName>* aGroupList );
+
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CScardReaderQuery();
+
+        /**
+        * Symbian 2nd phase constructor.
+        */
+        void ConstructL();
+    
+    };
+
+#endif      // CSCARDREADERQUERY_H   
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/WimBerConsts.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,101 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions for Ber objects
+*
+*/
+
+#ifndef WIMBERCONSTS_H
+#define WIMBERCONSTS_H
+
+#include <e32base.h>
+
+//  DATA TYPES
+typedef TUint8 TBerTag;
+
+// BER types.
+const TBerTag KBerEndOfContent  = 0x00;     // End of contents tag
+const TBerTag KBerBoolean       = 0x01;     // Boolean tag
+const TBerTag KBerInteger       = 0x02;     // Integer tag
+const TBerTag KBerBitString     = 0x03;     // Bit string tag
+const TBerTag KBerOctetString   = 0x04;     // Octet string tag
+const TBerTag KBerNull          = 0x05;     // NULL tag
+const TBerTag KBerOid           = 0x06;     // Object identifier tag
+const TBerTag KBerNumS          = 0x12;     // Numeric string       
+const TBerTag KBerPrS           = 0x13;     // Printable string tag
+const TBerTag KBerT61S          = 0x14;     // T61 string tag
+const TBerTag KBerVideoS        = 0x15;     // Video string tag              
+const TBerTag KBerIA5S          = 0x16;     // IA5 string tag
+const TBerTag KBerUtc           = 0x17;     // UTC time tag
+const TBerTag KBerGenTime       = 0x18;     // Generalized Time tag                 
+const TBerTag KBerGraphS        = 0x19;     // Graphics string tag          
+const TBerTag KBerVisibleS      = 0x1A;     // Visible string                   
+const TBerTag KBerGeneralS      = 0x1B;     // Generalised string   
+const TBerTag KBerBmpS          = 0x1E;     // Bmp string
+const TBerTag KBerSeq           = 0x30;     // Sequence tag
+const TBerTag KBerSet           = 0x31;     // Set tag
+
+const TBerTag KBerUnknown       = 0xff;     // Unknown tag
+
+const TBerTag KBerEncodedObject = 0xfe;     // Tag for ready-made
+                                            // BER encoded objects
+
+const TBerTag KBerLongLengthBit = 0x80;     // Long length bit
+const TBerTag KBerConstructedBit= 0x20;     // Constructed bit
+const TBerTag KBerConstructed   = 0x20;
+
+const TBerTag KBerImplicit = 0x80;   // Implicit tag
+const TBerTag KBerExplicit = 0x80;   // Explicit tag
+
+const TBerTag KBerImplicitConstructed = 0xA0;   // Implicit constructed tag
+const TBerTag KBerExplicitConstructed = 0xA0;   // Explicit constructed tag
+
+const TBerTag KBerBooleanTrue   = 0xFF;     // Boolean true value   (DER)
+const TBerTag KBerBooleanFalse  = 0x00;     // Boolean false value  (DER)
+const TBerTag KBerNullContent   = 0x00;     // Null objects content
+
+const TBerTag KBerBooleanLen    = 0x03;     // Boolean object length
+const TBerTag KBerNullLen       = 0x02;     // Null object length
+const TBerTag KBerShortLen      = 0x02;     // Tag + (short) length byte
+const TBerTag KBerIndefiniteLen = 0x04;     // Indefinite length (xx 80 00 00)
+
+const TInt KReadBufMax          = 256;      // Length of buffer used
+                                            // when reading from files.
+const TUint KOpenAllLevels      = 255;      // OpenL(....) function
+const TInt KOctetWidth          = 8;        
+const TInt KObjectIDDot         = 1;        // object id encoding
+const TInt KObjectIDFirstFactor = 4;        // object id encoding
+const TInt KObjectIDSecondFactor = 10;      // object id encoding
+
+const TInt KIntBufSize          = 6;        // Integer encoding buffer size 
+
+
+
+const TInt KMaxLenBytes   = 4;  // Max amount of length bytes in BER encoded
+                            // object.
+
+const TInt KFlushTargetMaxSize = 2048;
+const TInt KBerMask80 = 0x80;
+const TInt KBerMask81Negative = -0x81;
+const TInt KBerMask03 = 0x03;
+const TInt KBerMask8000 = 0x8000;
+const TInt KBerMask8001Negative = -0x8001;
+const TInt KBerMask04 = 0x04;
+const TInt KBerMask800000 = 0x800000;
+const TInt KBerMask800001Negative = -0x800001;
+const TInt KBerMask05 = 0x05;
+const TInt KBerMask06 = 0x06;
+const TInt KBerMask8 = 8;
+
+
+#endif 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/WimBerSet.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,274 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  An implementation of a CWimBerSet, which holds CWimBer objects
+*
+*/
+
+
+
+#ifndef WIMBERSET_H
+#define WIMBERSET_H
+
+
+//INCLUDES
+#include "WimBerConsts.h"
+#include <e32base.h>
+#include <bigint.h>
+
+
+
+//FORWARD DECLARATIONS
+class CWimBer;
+
+/*
+* Class CWimBerSet contains set of CWimBer objects
+* 
+*  @lib   WimBer
+*  @since Series60 2.6 
+*/
+
+class CWimBerSet: public CArrayPtrSeg<CWimBer>
+    {
+                 
+    public:
+
+        /*
+        * Two-phased constructor
+        * @param aGranularity -Initial size of the created set
+        * @return CWimBerSet* -initialized object which is inserted into 
+        * cleanupstack
+        */
+        IMPORT_C static CWimBerSet* NewLC( const TInt aGranularity );
+
+        /*
+        * Two-phased constructor
+        * @param aGranularity -Initial size of the created set
+        * @return CWimBerSet* -initialized object
+        */
+        IMPORT_C static CWimBerSet* NewL( const TInt aGranularity );
+        
+        /* 
+        * Destructor. Allocated memory is released
+        */
+        IMPORT_C  virtual ~CWimBerSet();
+
+        /*   
+        * Function creates CWimBer integer object.
+        * @param aValue. -Integer for object creation
+        * @return void
+        */
+        IMPORT_C void CreateIntL( const TInt aValue );
+        
+        /*
+        * Funtion creates long CWimBer integer object.
+        * @param aValue. -Integer for object creation.
+        * @return void
+        */
+        IMPORT_C void CreateLongIntL( RInteger& aValue );
+
+        /* 
+        * Function creates CWimBer octet string object. The octet string is an 
+        * arbitrarily long binary value.
+        * @param aString -String for octet creation
+        * @return void
+        */
+        IMPORT_C void CreateOctetL( TDesC8& aString );
+        
+        /* 
+        * Function creates CWimBer NULL object ( 0x05 0x00 ).
+        * @return void
+        */
+        IMPORT_C void CreateNullL();
+
+        /* 
+        * Function creates CWimBer object identifier object.
+        * @param aString -object identifier content
+        * @return void
+        */
+        IMPORT_C void CreateOidL( TDesC8& aString );
+
+
+        /* 
+        * Function creates CWimBer printable string object.
+        * The printable string is defined to only contain
+        * the characters A-Z, a-z, 0-9, space,
+        * and the punctuation characters ()-+=:',./?.
+        * @param aString -printable string
+        * @return void
+        */
+        IMPORT_C void CreatePrintableL( TDesC8& aString );
+
+        /* 
+        * Function creates CWimBer IA5 string object.
+        * IA5 ( International Alphabet 5 )
+        * is equivalent to US-ASCII.
+        * @param aString -IA5 string
+        * @return void
+        */
+        IMPORT_C void CreateIA5L( TDesC8& aString );
+
+        /*
+        * Function creates CWimBer universal time object.
+        * Note this value only represents years using two digits.
+        * @param aString -universal time
+        * @return void
+        */
+        IMPORT_C void CreateUTCL( TDesC8& aString );
+
+        /* 
+        * Append start of sequence ( 30 xx, xx = length )
+        * @param aDefinite. -ETrue for definite length sequence, EFalse for 
+        * indefinite length. 
+        * @return void
+        */
+        IMPORT_C void CreateSeqStartL( TBool aDefinite );
+
+        /*
+        * Append start of set ( 31 xx, xx = length )
+        * @param aDefinite. -ETrue for definite length sequence, EFalse for 
+        * indefinite length. 
+        * @return void
+        */
+        IMPORT_C void CreateSetStartL( TBool aDefinite );
+
+        /*  
+        * Append start of the constructed.
+        * @param aTag -object type ( tag )
+        * @param aDefinite -ETrue for definite length sequence, EFalse for 
+        * indefinite length. 
+        * @return void
+        */
+        IMPORT_C void CreateConstructedStartL( TBerTag aTag, TBool aDefinite );
+
+        /*
+        * Function closes last constructed object. 
+        * @return void
+        */
+        IMPORT_C void CreateEndL();
+
+        /*  
+        * Used to create a CWimBer object
+        * from buffer, which already contains a full CWimBer
+        * encoded object.
+        * @param aBuffer -contains full CWimBer encoded object.
+        * @return void
+        */
+        IMPORT_C void CreateBEREncodedObjectL( TDesC8& aBuffer );
+
+        /* 
+        * Function writes all created CWimBer objects (which are 
+        * Appended to set) to descriptor. Function also fixes all definite
+        * lengths. 
+        * @param aTarget -Descriptor where data is written. 
+        * @return TInt -Error code(negative) or the number of WimBer objects
+        *               (positive).
+        */
+        IMPORT_C TInt FlushL( HBufC8*& aTarget );
+
+    public:
+
+        /* 
+        * Encode and write object identifier.
+        * @param aString  -Object ID. e.g. _L8("1.2.3.4.5")
+        * @param aOnlyLen - ETrue if You don't want to write object to iTarget
+        * @return TInt    -Error code
+        */
+        TInt AppendObjectIdL( const TDesC8& aString, TBool aOnlyLen = EFalse );
+
+
+    private:
+
+        /* 
+        * Write constructed type start.
+        * @param aTag -type of constructed tag e.g. 04 for octetS.
+        * @param aLength -Length or 0 for indefinite length
+        * @return void
+        */
+        void AppendConstructedL( TBerTag aTag, TUint aLength = 0 );
+        
+        /* 
+        * Close indefinite length. (= add 0x00 0x00) 
+        * @return void
+        */
+        void CloseIndefinite(); 
+        
+        /* 
+        * Encode and write boolean object. 
+        * @param aBool -ETrue or EFalse
+        * @return void
+        */
+        void AppendBoolL( TBool aBool );   
+        
+        /* 
+        * Encode and write integer object.
+        * @param aData -Integer to be written to data. 
+        * @return void
+        */
+        void AppendIntL( TInt aData ); 
+
+        /* 
+        * Encode and write long integer object.
+        * @param aData -Integer to be written to data. 
+        * @return void
+        */ 
+        void AppendLongIntL( const RInteger* aData );
+        
+        /* 
+        * Encode and write null object. (0x05 0x00)
+        * @return void
+        */
+        void AppendNull();
+        
+        
+        /* 
+        * Encode and write string to iTarget
+        * @param aTag - Object type ( tag )
+        * @param aString - String to be written
+        * @void
+        */
+        void AppendStringL( TBerTag aTag, const TDesC8& aString );
+        
+        /* 
+        * Write CWimBer encoded object to iTarget.
+        * Note that this function doesn't add any tags
+        * etc. it trusts that the given object already
+        * is a whole CWimBer encoded object.
+        * @param aString -Buffer containing CWimBer encoded object
+        * @return void
+        */
+        void AppendBerEncodedObject( const TDesC8& aString );
+
+    private:
+
+        /* 
+        * Default constructor
+        * @param aGranularity -Granularity for this array 
+        */
+        CWimBerSet( const TInt aGranularity ); 
+        
+    private:  
+
+        // Descriptor for data. Not owned.
+        HBufC8* iTarget;
+        
+        // Nesting level of object. ( encoding ).
+        TInt iLevel;
+        
+        // Max level which is used in encoding.
+        TInt iMaxLevel;
+
+    };
+
+
+#endif //WIMBERSET_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/WimCertConverter.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,444 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface which handles certificate related operations
+*
+*/
+
+
+
+#ifndef WIMCERTCONVERTER_H
+#define WIMCERTCONVERTER_H
+
+
+//INCLUDES
+#include "WimClsv.h"        
+#include <e32base.h>
+#include <ct.h> 
+
+// FORWARD DECLARATIONS
+class RWimCertMgmt;
+class CWimCertInfo;
+class CCTCertInfo;
+
+// CONSTANTS
+typedef HBufC8* PHBufC8;
+typedef TPtr8* PTPtr8;
+
+
+
+//CLASS DECLARATION
+/**
+*  Interface which handles certificate related operations 
+*  with WimServer.
+*  Caller can add a certificate, remove a certificate,
+*  list a certificate and get certificate details.
+*
+*  @lib WimClient
+*  @since Series60 2.1
+*/
+class CWimCertConverter: public CActive
+    {
+
+    public:
+
+        /**
+        * Two-phased constructor.
+        * @param aToken -Reference to current token
+        */
+        IMPORT_C static CWimCertConverter* NewL( MCTToken& aToken );
+
+        
+        /**
+        * Restores certificates from WIM cache. If Restore cannot find
+        * any certificate, it will return KErrNotFound to caller.
+        * @param  aArray    -Array where new certificates are 
+        *                   inserted. Caller is responsible 
+        *                   to deallocate CWimCertInfo -objects
+        *                   by calling ResetAndDestroy.(IN/OUT)
+        * @param  aStatus   -Status from caller.         
+        * @return void
+        */
+        IMPORT_C void Restore( RPointerArray<CWimCertInfo>& aArray, 
+                               TRequestStatus& aStatus );
+
+        
+        /** 
+        * Cancels outgoing Restore operation. Sets an internal flag to true. 
+        * After necessary cleanup, caller is signalled with KErrCancel 
+        * -error code.
+        * @return void
+        */
+        IMPORT_C void CancelRestore();
+        
+        /**
+        * Retrieves the actual certificate. In case of other cert than
+        * Url cert the binary encoded certificate is written into the 
+        * aEncodedCert parameter. In case of Url cert the data is 
+        * the actual url.
+        * @param  aIndex. Used to point iCertRefLst and iCertInfoArr 
+        *         -arrays for correct certificate.
+        * @param  aEncodedCert. A buffer to put the certificate in. 
+        * @param  aStatus. A request status that is completed when the 
+        *         operation has finished.(IN/OUT)
+        * @return void
+        */
+        IMPORT_C void RetrieveCertByIndexL( const TInt aIndex,
+                                           TDes8& aEncodedCert, 
+                                           TRequestStatus& aStatus );
+
+        /**
+        * Cancels an ongoing Retrieve operation.
+        * If retrieve is cancelled, then operation is completed with 
+        * KErrCancel -error code.
+        * @return void
+        */
+        IMPORT_C void CancelRetrieve();
+
+        
+        /** 
+        * Adds a certificate to the cert store.
+        * The caller of this function owns all its parameters.
+        * @since Series 60 2.6
+        * @param  aLabel  -The label of the certificate to add 
+        * @param  aFormat  -The format of the certificate. Supported formats are
+                           EX509Certificate, EWTLSCertificate,
+                           EX509CertificateUrl and EWTLSCertificateUrl 
+        * @param  aCertificateOwnerType  -The owner type. Supported types are
+                                        ECACertificate and EUserCertificate.
+        * @param  aSubjectKeyId  -The Subject key ID
+        * @param  aIssuerKeyId  -The issuer key ID
+        * @param  aCert  -The certificate to add
+        * @param  aStatus  This is completed with the return result 
+        *         when the add has completed (IN/OUT)
+        * @return  void
+        */
+        IMPORT_C void AddCertificate( const TDesC& aLabel, 
+                              const TCertificateFormat aFormat,
+                              const TCertificateOwnerType aCertificateOwnerType, 
+                              const TKeyIdentifier& aSubjectKeyId,
+                              const TKeyIdentifier& aIssuerKeyId,
+                              const TDesC8& aCert, 
+                              TRequestStatus& aStatus );
+        
+        /**
+        * Cancels an ongoing add operation.
+        * @since Series 60 2.6
+        * @return void
+        */
+        IMPORT_C void CancelAddCertificate();
+
+        /** 
+        * Removes a certificate from WIM.
+        * @since Series 60 2.6
+        * @param aIndex     -Used to point iCertInfoArr 
+        *                   for the certificate to be removed.
+        * @param aStatus    -Status from caller 
+        * @return void      
+        */
+        IMPORT_C void RemoveL( const TInt aIndex, TRequestStatus& aStatus );
+
+        /** 
+        * Cancels ongoing remove operation.
+        * @since Series 60 2.6
+        * @return void
+        */
+        IMPORT_C void CancelRemove();
+
+        /**
+        * Destructor
+        */
+        IMPORT_C virtual ~CWimCertConverter();
+
+    private:
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * C++ default constructor.
+        * @param aToken -Reference to current token
+        */
+        CWimCertConverter( MCTToken& aToken );
+
+    private: //from CActive
+        
+        /**
+        * Different phases are handled here.
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * Cancellation function
+        * Deallocates member variables and completes client status with
+        * KErrCancel error code.
+        * @return void
+        */
+        void DoCancel();
+
+        /**
+        * The active scheduler calls this function if this active 
+        * object's RunL() function leaves. 
+        * Handles necessary cleanup and completes request with
+        * received error code.
+        * @param aError -The error code which caused this function call.
+        * @return TInt  -Error code to activescheduler, is always KErrNone.
+        */ 
+        TInt RunError( TInt aError );
+        
+    private:
+        
+        /**
+        * Allocates memory for the array which is filled by server.
+        * @param  aWimCertInfoArr    -Array to be initialized 
+        * @param  aCount             -Count of elements in the array         
+        * @return void
+        */
+        void AllocWimCertInfoL( TWimCertInfo* aWimCertInfoArr, TInt aCount );  
+        
+        /**
+        * Deallocates memory from the array.
+        * @return void
+        */
+        void DeallocWimCertInfo();   
+        
+        /**
+        * Allocates memory for a struct which is filled by server.
+        * @return void
+        */
+        void AllocMemoryForCertDetailsL();
+
+        /**
+        * Creates new certificate objects which can be returned to the caller.
+        * @return void
+        */
+        void CreateNewCertObjectsL();
+        
+        /**
+        * Creates new wim certificate objects.
+        * @return void
+        */
+        void CreateNewWimCertObjectL();
+
+        /**
+        * Gets trusted usages.
+        * @return void
+        */
+        void GetTrustedUsagesL();
+
+        /**
+        * Completion of trusted usages.
+        * @return void
+        */
+        void TrustedUsagesDoneL();
+
+        /**
+        * Sets own iStatus to KRequestPending, and signals it 
+        * with User::RequestComplete() -request. This gives chance 
+        * to activescheduler to run other active objects. After a quick
+        * visit in activescheduler, signal returns to RunL() and starts next
+        * phase of operation. 
+        * @return void
+        */
+        void SignalOwnStatusAndComplete();
+        
+        /**
+        * Allocates memory for member variables, which are needed when adding
+        * a certificate asynchronously to WIM.
+        * @param aLabel -certificate label (IN)
+        * @param aIssuerKeyId -Issuer KeyId of a certificate 
+        * @param aSubjectKeyId -Subject KeyId of a certificate
+        * @param aCert -certificate data
+        * @return void
+        */
+        void AllocMemoryForAddCertL( const TDesC& aLabel, 
+                            const TKeyIdentifier& aIssuerKeyId, 
+                            const TKeyIdentifier& aSubjectKeyId,
+                            const TDesC8& aCert );
+
+        /**
+        * Copies data to caller's buffer by using pointer.
+        * @return void
+        */
+        void CopyRetrievedCertData();
+
+
+        /**
+        * DeAllocates memory from member variables, which are used
+        * when communicating with WIM.
+        * @return void
+        */
+        void DeallocCertHBufs();
+
+        /**
+        * If user has cancelled initialization process, dealloc references 
+        * from loaded certs. 
+        * @return void
+        */
+        void DeallocReferences();
+
+        /**
+        * Returns certificate format according to received index.
+        * @param aIndex -index of the certificate to be returned.
+        * @return TCertificateFormat -format of the certificate
+        */
+        TCertificateFormat GetCertFormatByIndex( TInt aIndex );
+
+    private:
+
+        /**
+        * Ten different phases, which are used to 
+        * Read certificates from WIM cache, create new certificate objects,
+        * retrieve certificate, add certificate and remove certificate.
+        */
+        enum TPhase
+            {
+            EListCertsFromWim,
+            ECreateNewCertObjects,
+            EGetTrustedUsages,
+            ECertObjectsDone,
+            ETrustedUsagesDone,
+            ERetrieveCertificate,
+            ERetrievingCompleted,
+            EAddCertificate,
+            EAddCertificateCompleted,
+            ERemove,
+            ERemoveCompleted
+            };
+                   
+    private:
+              
+        //Client status is stored here while operation
+        //on the server side is done.
+        TRequestStatus*                 iClientStatus;
+        
+        //Array which is used to contain new certificate objects.
+        //Not owned. Caller is responsible to destroy array.
+        RPointerArray<CWimCertInfo>*    iArray;
+        
+        //Details of the certificate. Owned.
+        TWimCertDetails                 iWimCertDetails;
+        
+        //Struct which is used when adding a certificate
+        //to WIM.
+        TWimCertAddParameters           iParam;
+
+        //Struct which is used when removing a certificate for WIM.
+        TWimCertRemoveAddr              iWimCertRemoveAddr;    
+        
+        //Reference to current token. Needed in CCTCertInfo creation.
+        MCTToken&                       iToken;
+        
+        //Handle to connection with server. Owned.
+        RWimCertMgmt*                   iConnectionHandle;
+        
+        //Typedefs for the reference to certificate. Owned.
+        TCertificateAddressList         iCertRefLst; 
+        
+        // Certificate information structure. Owned.
+        TWimCertInfo*                    iCertInfoArr;
+        
+        //Used to handle different phases.
+        TPhase                          iPhase;
+                
+        //Index to point which certificate we want to be retrieved
+        TInt                            iCertRetrieveIndex;
+                 
+        //Used to inform the size of the array, needed in array construction/
+        //destruction.
+        TInt                            iArraySize;
+        
+        //The count of certificates
+        TUint8                          iCertCount;
+
+        //Pointer to HBufC8*. This is used as an array when listing every 
+        //certificate from WIM to an array during startup. Owned.
+        PHBufC8*                        iLabel;
+
+        //Pointer to HBufC8*. This is used as an array when listing every 
+        //certificate from WIM to an array during startup. Owned.
+        PHBufC8*                        iKeyId;
+
+        //Pointer to HBufC8*. This is used as an array when listing every 
+        //certificate from WIM to an array during startup. Owned.
+        PHBufC8*                        iCAId;
+
+        //Pointer to HBufC8*. This is used as an array when listing every 
+        //certificate from WIM to an array during startup. Owned.
+        PHBufC8*                        iIssuerHash;
+
+        //Pointer to iLabel. Also used as an array. Owned.        
+        PTPtr8*                         iLabelPtr;
+
+        //Pointer to iKeyId. Also used as an array. Owned.        
+        PTPtr8*                         iKeyIdPtr;
+
+        //Pointer to iCAId. Also used as an array. Owned.        
+        PTPtr8*                         iCAIdPtr;
+
+        //Pointer to iIssuerHash. Also used as an array. Owned.
+        PTPtr8*                         iIssuerHashPtr;
+            
+        //Modifiable 8-bit descriptor which points
+        //to caller's descriptor. We copy retrieved certificate
+        //data to this descriptor. Owned.
+        TDes8*                          iEncodedCert;
+
+        //Buffer which is used to contain certificate data. Owned.
+        HBufC8*                         iCertHBufOne;
+        //Pointer to iCertHBufOne. Owned.
+        TPtr8*                          iCertHBufOnePtr;
+
+        //Buffer which is used to contain certificate data. Owned.        
+        HBufC8*                         iCertHBufTwo;
+        //Pointer to iCertHBufTwo. Owned.
+        TPtr8*                          iCertHBufTwoPtr;
+
+        //Buffer which is used to contain certificate data. Owned.        
+        HBufC8*                         iCertHBufThree;
+        //Pointer to iCertHBufThree. Owned.
+        TPtr8*                          iCertHBufThreePtr;
+
+        //Buffer which is used to contain certificate data. Owned.        
+        HBufC8*                         iCertHBufFour;
+        //Pointer to iCertHBufFour. Owned.
+        TPtr8*                          iCertHBufFourPtr;
+        //ActiveSchedulerWaiter for certificate extra information
+        //fetching.
+        CActiveSchedulerWait            iActiveSchedulerWait;
+        //Pointer for trusted usage buffer
+        HBufC*                          iTrustedUsages;
+        //Pointer to trusted usage buffer pointer
+        TPtr*                           iTrustedUsagesPtr;
+        //Index pointing to certificate elements
+        TUint8                          iIndex;
+        //Pointer to one certificate info, owned
+        CCTCertInfo*                    iCert;
+        //Pointer to one WIM specific certificate info, owned
+        CWimCertInfo*                   iCertInfo;
+        //An array of trusted usage oids
+        RArray<HBufC*>*                 iOids;
+        //Package structure for certificate extra info
+        TCertExtrasInfo                 iCertExtrasInfo;
+        //Pointer for key identifier buffer
+        HBufC8*                         iKeyIdBuf;
+        //Used to point right keyId when retrieving extra data
+        TPtr8*                          iKeyIdPointer;
+
+    };
+
+
+#endif  //WIMCERTCONVERTER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/WimCertInfo.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,218 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  WIM specific trusted settings information
+*
+*/
+
+
+
+#ifndef CWIMCERTINFO_H
+#define CWIMCERTINFO_H
+
+//  INCLUDES
+
+#include <e32base.h>
+#include <cctcertinfo.h>
+#include <ct.h>
+
+// CLASS DECLARATION
+
+/**
+*  This class is for sending data between WimClient and WimServer.
+*  The data is packed into this form with ExternalizeL and read with
+*  InternalizeL methods.
+*
+*  @lib WimUtil.lib
+*  @since Series60 3.0
+*/
+
+class TWimCertInfoPckg
+    {
+    public:
+
+        /**
+        * Constructor.
+        */
+        TWimCertInfoPckg(){};
+
+        /**
+        * Destructor.
+        */
+        virtual ~TWimCertInfoPckg(){};
+          
+        TBuf<KMaxCertLabelLength>   iCertLabel;
+        TSHA1Hash                   iHash;
+        TBool                       iTrusted;
+        TCertificateFormat          iFormat;
+        TCertificateOwnerType       iCertificateOwnerType;
+        TInt                        iSize;
+        TUint8                      iCDFRefs;
+        TKeyIdentifier              iSubjectKeyId;
+        TKeyIdentifier              iIssuerKeyId;
+        TBuf<20>                    iTokenSerialNbr;
+        TInt                        iIndex;
+    };
+
+// CLASS DECLARATION
+
+/**
+*  This class contains data for trust settings of certificate.
+*  Class includes functions for creating DB, fetching, updating and 
+*  deleting trust settings.
+*
+*  @lib WimUtil.lib
+*  @since Series60 2.1
+*/
+class CWimCertInfo : public CBase
+    {
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        * @param  aCCTCertInfo  A pointer to CCTCertInfo object. This is owned
+        *         and released by CWimCertInfo  
+        * @param  aHash  A hash of certificate
+        * @param  aTrustedUsages  Array containing oids
+        * @param  aCDFRefs Location information of a certificate
+        * @return Pointer to CWimCertInfo object
+        */
+        IMPORT_C static CWimCertInfo* NewL( CCTCertInfo* aCCTCertInfo,
+                                      const TBuf8<KSHA1HashLengthBytes> aHash,
+                                      RArray<HBufC*> aTrustedUsages,
+                                      TUint8 aCDFRefs );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CWimCertInfo();
+
+    public: // New functions
+
+        /**
+        * Add ExtendedKeyUsage OID to list
+        * @param   aExtendedKeyUsage  A pointer to ExtendedKeyUsage OID
+        * @return  TInt -Error code
+        */
+        IMPORT_C TInt AddExtendedKeyUsage( HBufC* aExtendedKeyUsage );
+        
+        /**
+        * Add TrustedUsage OID to list
+        * @param   aTrustedUsage  Pointer to trusted usage info
+        * @return  TInt -Error code
+        */
+        IMPORT_C TInt AddTrustedUsage( HBufC* aTrustedUsage );
+
+        /**
+        * Get hash of certificate
+        * @param   aHash  Hash of certificate
+        * @return  void
+        */
+        IMPORT_C void GetCertHash( TBuf8<KSHA1HashLengthBytes>& aHash ) const;
+
+        /**
+        * Return pointer to CCTCertInfo
+        * @return Pointer to CCTCertInfo
+        */
+        IMPORT_C const CCTCertInfo* CctCert() const;
+
+        /**
+        * Return array of TrustedUsage pointers
+        * @return  TrustedUsage buffer
+        */
+        IMPORT_C RArray<HBufC*> TrustedUsage() const;
+
+        /*
+        * Return location information of this certificate
+        * @return TUint8 -location
+        */
+        IMPORT_C TUint8 CDFRefs() const;
+
+        /*
+        * Set location information of this certificate
+        * @param aCDFRefs -location to be set.
+        * @return void
+        */
+        IMPORT_C void SetCDFRefs( TUint8 aCDFRefs );
+
+        /**
+        * Return array of ExtendedKeyUsage pointers
+        * @return  ExtendedKeyUsage buffer
+        */
+        IMPORT_C RArray<HBufC*> ExtendedKeyUsage() const;
+
+        /**
+        * Externalize CWimCertInfo data to flat buffer
+        * @return pointer to buffer
+        */
+        IMPORT_C TWimCertInfoPckg* ExternalizeL() const;
+
+        /**
+        * Instantiates CWimCertInfo of externalized data
+        * @param flat buffer created with ExternalizeL
+        * @return pointer to CWimCertInfo
+        */
+        IMPORT_C static CWimCertInfo* InternalizeL(
+                               TWimCertInfoPckg& aExternalizedInfo );
+        
+    private: // Constructors
+
+        /**
+        * Default constructor.
+        * @param  aCCTCertInfo  A pointer to CCTCertInfo object. This is owned
+        *         and released by CWimCertInfo  
+        * @param  aHash  A hash of certificate
+        * @param  aTrustedUsages Oids of a certificate
+        * @parma  aCDFRefs Location of a certificate
+        */
+        CWimCertInfo( CCTCertInfo* aCCTCertInfo,
+                      const TBuf8<KSHA1HashLengthBytes> aHash,
+                      RArray<HBufC*> aTrustedUsages,
+                      TUint8  aCDFRefs );
+                    
+
+        /**
+        * 2nd phase constructor
+        */
+        void ConstructL();
+
+    private:    // Data
+
+        // Pointer to corresponding CCTCertInfo object
+        // This class owns pointed object
+        CCTCertInfo*                iCCTCertInfo;
+
+        //Certificate Hash
+        TBuf8<KSHA1HashLengthBytes> iCertHash;
+
+        // Array of pointers that point to trusted usage OIDs
+        // This class owns the pointed objects
+       // RArray<HBufC*> iTrustedUsage;
+
+        // Array of pointer that point to extended key usage OIDs
+        // This class owns the pointed objects
+        RArray<HBufC*>              iExtendedKeyUsage;
+
+        // Array of pointers that point to trusted usage OIDs
+        // This class owns the pointed objects
+        RArray<HBufC*>              iTrustedUsage;
+        
+        //Location information of a Certificate
+        TUint8                      iCDFRefs; 
+
+
+    };
+
+#endif      // CWIMCERTINFO_H
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/WimClsv.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,209 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  General definitions used in message passing between
+*                client and server
+*
+*/
+
+
+#ifndef __WIMCLSV_H__
+#define __WIMCLSV_H__
+
+//  INCLUDES
+#include <e32base.h>
+#include <securitydefs.h>
+#include "WimOpcode.h" 
+#include "WimConsts.h"
+#include "WimDefs.h"
+#include <secdlg.h>
+
+
+//  CONSTANTS
+_LIT( KWIMServerName, "WIMIServer" );
+
+// Number allocation for our certificates. Includes only WTLS CA
+// certificates.
+const TUid KUidWTLSTrustedCerts = {0x1000AA53}; 
+
+// Number allocation for our certificates. Includes only X509 client
+// certificates.
+const TUid KUidWTLSUserCerts = {0x1000AB5B}; 
+
+// A version must be specifyed when creating a session with the server
+const TUint KWIMServMajorVersionNumber = 1;
+const TUint KWIMServMinorVersionNumber = 0;
+const TUint KWIMServBuildVersionNumber = 1;
+
+// needed for creating server thread.
+const TUint KWIMDefaultHeapSize = 0x100000;
+
+// Maximum count of applications trusting to certificate
+const TInt KMaxApplicationCount = 50;
+
+// Mask for PIN status. Keeping MSBs and masking off LSBs.
+const TUint8 KPINStatusMask = 0xF0;
+const TUint8 KWimAuthObjectBlocked= 0x08;
+
+// Typedefs for the references to wim, pin and certificate 
+typedef TUint32                 TWimAddress;
+typedef TWimAddress*            TWimAddressList;
+typedef TWimAddress             TPinAddress; 
+typedef TWimAddress*            TPinAddressList;
+typedef TUint32                 TCertificateAddress;
+typedef TCertificateAddress*    TCertificateAddressList;
+
+// Server panic reasons
+enum TWimServerPanic
+    {
+    EWimMainSchedulerError,
+    EWimSvrCreateServer,
+    EWimCreateTrapCleanup,
+    EWimSubSessionRefCountInvalid,
+    EWimThreadOpenError,
+    EWimIncorrectPolicy
+    };
+
+// PIN status
+typedef TUint8 TWimPinStatus;
+
+//PIN Type
+enum TWimPin
+    {
+    EWimPinG,
+    EWimPinNR
+    };
+
+// WIM information structure
+struct TWimSecModuleStruct
+    {
+    TBuf<KLabelLen>        iLabel;
+    TBuf<KManufacturerLen> iManufacturer;
+    TBuf<KSerialNumberLen> iSerialNumber;
+    TUint8                 iVersion;
+    TUint8                 iReader;   
+    TPinAddress            iRefPinG;
+    };
+
+// PIN information structure
+struct TWimPinStruct 
+    {
+    TWimPin         iPinType;
+    TBuf<KLabelLen> iLabel;
+    TWimPinStatus   iStatus;
+    TUint8          iPinNumber;
+    };
+
+// Certificate info structure
+struct TWimCertAddParameters
+    {
+    TBuf8<KLabelLen> iLabel;
+    TBuf8<KKeyIdLen> iKeyId;
+    TBuf8<KCertHash> iCaId;
+    TWimCertType     iUsage;
+    TWimCertFormat   iFormat;
+    };
+
+// Certificate details
+struct TWimCertDetails
+    {
+    TPtr8* iCert; //The whole cert
+    };
+
+// Address of a certificate to be removed
+struct TWimCertRemoveAddr
+    {
+    TCertificateAddress iCertAddr;
+    TWimCertLocation    iLocation;
+    };
+
+// Certificate information structure
+struct TWimCertInfo
+    {
+    TBuf8<KLabelLen>   iLabel;
+    TBuf8<KKeyIdLen>   iKeyId;
+    TBuf8<KCertHash>   iCAId;
+    TBuf8<KIssuerHash> iIssuerHash;
+    TUint8             iCDFRefs;
+    TUint              iUsage;
+    TUint              iType;
+    TUint              iCertlen; 
+    TUint              iModifiable;
+    TUint              iTrustedUsageLength;
+    };
+
+// Certificate extra information structure
+struct TCertExtrasInfo
+    {
+    TPtr*  iTrustedUsage;
+    TUint8 iCDFRefs;
+    };
+
+// Key info struct
+struct TKeyInfo
+    {
+    TUint8           iKeyNumber;
+    TUint8           iType; //1 = rsa, 2 = ECC
+    TUint16          iUsage;
+    TBuf8<KLabelLen> iLabel;
+    TBuf8<KKeyIdLen> iKeyId;
+    TUint16          iLength;
+    TUint8           iPinNumber;
+    };
+
+// Digital signature struct
+struct TKeySignParameters
+    {
+    TPtr8*           iSigningData;
+    TBuf8<KKeyIdLen> iKeyId;
+    TPtr8*           iSignature;
+    };
+
+//Public key exportion struct
+struct TExportPublicKey
+    {
+    TPtr8*           iPublicKey;
+    TBuf8<KKeyIdLen> iKeyId;
+    };
+
+// struct for PIN state request
+struct TPINStateRequest
+    {
+    TBool iEnable;
+    TBool iRetry;
+    };
+
+struct TOmaProv
+    {
+    TInt   iSize;
+    TInt   iOmaType;
+    TPtr8* iOmaData;
+    };
+    
+struct TJavaProv
+    {
+    TBuf8<8>* iPath;
+    TInt   iSize;
+    TPtr8* iJavaData;	
+    };    
+
+struct TTrustSettings
+    {
+    TBool    iTrusted;
+    TInt32   iUids[KMaxApplicationCount];
+    TInt     iApplicationCount;
+    };
+
+#endif      // __WIMCLSV_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/WimConsts.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,86 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Consts for WimClient, WimPlugin and WimServer
+*
+*/
+
+
+#ifndef WIMCONSTS_H
+#define WIMCONSTS_H
+
+
+//  INCLUDES
+#include <e32base.h>
+#include <data_caging_path_literals.hrh>
+
+// Common error codes
+const TInt KWimSMInfoError         = -7;
+const TInt KWimCardDriverInitError = -37;
+
+
+// Extract of the constant values as specified in WIM spec and ISO/IEC 7812-1
+const TInt KLabelLen         = 255; 
+const TInt KManufacturerLen  = 32;
+const TInt KSerialNumberLen  = 20;
+const TInt KVersionNumberLen = 20; //Not sure of the length, may be less than 20
+const TInt KIssuerHash       = 20;
+const TInt KCertHash         = 20;
+// Hacking this. Some spec somewhere says it is 4, WIMI returns 20.
+const TInt KKeyIdLen         = 20;
+const TInt KPkcs15IdLen      = 20;
+const TInt KSoftId           = 255;
+const TInt KWimMaxCount      = 8;
+const TInt KMaxPinLen        = 8;
+const TInt KMinPinLen        = 4;
+
+// PKCS15KeyUsageFlags
+const TInt KPkcs15KeyUsageFlagsEncrypt        = 0x8000; 
+const TInt KPkcs15KeyUsageFlagsDecrypt        = 0x4000; 
+const TInt KPkcs15KeyUsageFlagsSign           = 0x2000; 
+const TInt KPkcs15KeyUsageFlagsSignRecover    = 0x1000; 
+const TInt KPkcs15KeyUsageFlagsWrap           = 0x0800; 
+const TInt KPkcs15KeyUsageFlagsUnwrap         = 0x0400; 
+const TInt KPkcs15KeyUsageFlagsVerify         = 0x0200; 
+const TInt KPkcs15KeyUsageFlagsVerifyRecover  = 0x0100; 
+const TInt KPkcs15KeyUsageFlagsDerive         = 0x0080; 
+const TInt KPkcs15KeyUsageFlagsNonRepudiation = 0x0040; 
+
+// WIMSTA_XX errors
+const TUint8 KWimStatusOK      = 0x00; // WIMSTA_OK
+const TUint8 KWimStatusIOError = 0xa2; // WIMSTA_IO_ERROR
+
+// Server startup specific
+_LIT( KWimServerFile, "WimServer.EXE" );
+
+const TUid KWimServerUid = {0x101F79DD};
+// path is \\private\\<WimServerUid>
+_LIT( KWimTrustSettingsStorePath, "\\private\\101F79DD\\" );
+
+const TInt KWimServerTerminatingMaxRetryCount = 10;
+const TInt KWimServerTerminatingRetryTimeout  = 200000; /* 200 msec */
+
+// Timeout limit values for WIM SetCloseAfter (in seconds)
+const TInt KWimNoTimeout  = -1;    // No timeout
+const TInt KWimTimeoutMax = 2146;  // Maximum when converted to microseconds
+
+// Public Key export
+const TInt KPublicKeyLength = 512;
+
+// Digital signature
+const TInt KMaxRSADigestSize   = 512;
+const TInt KMaxSignatureLength = 512;
+
+#endif      // WIMCONSTS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/WimDefs.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,115 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions for WimClient, WimServer and WimPlugin
+*
+*/
+
+
+#ifndef WIMDEFS_H
+#define WIMDEFS_H
+
+
+//  INCLUDES
+#include <e32std.h>
+
+//  CONSTANTS
+
+typedef TUint8  TWimKeyType;
+typedef TUint8  TWimApduStatus;
+
+// Key types.
+const TWimKeyType KWimDigitalSignature = 0x80;
+const TWimKeyType KWimNonRepudiation   = 0x40;
+
+// WimApdu errors
+// These errors are defined in WIM library design spec.
+const TWimApduStatus KWimApduOk                 = 0x00;
+const TWimApduStatus KWimApduTransmiossionError = 0x01;
+const TWimApduStatus KWimApduCardMute           = 0x02;
+const TWimApduStatus KWimApduCardDisconnected   = 0x03;
+const TWimApduStatus KWimApduNoCause            = 0x04;
+const TWimApduStatus KWimApduReaderNotValid     = 0x05;
+const TWimApduStatus KWimApduFormatError        = 0x06;
+const TWimApduStatus KWimApduTypeNotValid       = 0x07;
+const TWimApduStatus KWimApduReaderRemoved      = 0x08;
+const TWimApduStatus KWimApduCardRemoved        = 0x09;
+const TWimApduStatus KWimApduCardReaderBusy     = 0x0a;
+const TWimApduStatus KWimApduCardPoweredOff     = 0x0b;
+const TWimApduStatus KWimApduNoMemory           = 0xa0;
+
+//  DATA TYPES
+
+// State of WIM server
+enum TWimServerRunningState
+    {
+    EWimServerStateUnknown = 0,
+    EWimServerRunning      = 1,
+    EWimServerNotRunning   = 2
+    };
+
+// Data types Cert
+enum TWimCertLocation
+    {
+    EWimCertLocationCertMan,
+    EWimCertLocationPhoneMemory,
+    EWimCertLocationPhoneMemoryURL,
+    EWimCertLocationWIMCard,
+    EWimCertLocationWIMURL
+    };
+
+enum TWimCertType
+    {
+    EWimCertTypeCA,
+    EWimCertTypePersonal
+    };
+
+enum TWimCertFormat
+    {
+    EWimWTLSCertificate,
+    EWimX509Certificate,
+    EWimX968Certificate,
+    EWimCertificateURL
+    };
+
+enum TWimEntryType
+    {
+    EWimEntryTypeAll,
+    EWimEntryTypeCA,
+    EWimEntryTypePersonal
+    };
+
+enum TWimKeyLocation
+    {
+    EWimKeyLocationWIMCard,
+    EWimKeyLocationPhoneMemory,
+    EWimKeyLocationNoKey
+    };
+
+enum TWimCertStoringStatus
+    {
+    EWimCertNotStored
+    };
+
+// Enumerator for certificate location
+enum TWimCertificateCDF
+    {
+    EWimUnknownCDF      = 0,
+    EWimCertificatesCDF = 0x20,
+    EWimTrustedCertsCDF = 0x40,
+    EWimUsefulCertsCDF  = 0x80
+    };
+
+#endif  // WIMDEFS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/WimKeyDetails.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,353 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface which fetches all keyInfos from WIM -card.
+*
+*/
+
+
+
+#ifndef WIMKEYDETAILS_H
+#define WIMKEYDETAILS_H
+
+
+#include "WimClsv.h"
+#include <ct.h>
+#include <mctkeystore.h>
+#include <e32base.h>
+
+
+//FORWARD DECLARATION
+class RWimCertMgmt;
+
+
+//CLASS DECLARATION
+/**
+*  This class lists all keyInfos found from WIM -card.
+*  @lib WimClient
+*  @since Series60 2.1
+*/
+class CWimKeyDetails: public CActive
+    {
+    public:
+
+        /**
+        * Two-phased constructor.
+        * @param aToken -Reference to current token
+        */
+        IMPORT_C static CWimKeyDetails* NewL( MCTToken& aToken );
+        
+        /**
+        * Destructor
+        */
+        IMPORT_C virtual ~CWimKeyDetails();
+
+
+        /** 
+        * Lists all the keys in the WIM and creates CCTKeyInfo objects 
+        * from received information. CCTKeyInfo objects are inserted to array 
+        * aKeys.
+        * @param aKeys      -Array where keyInfos are 
+        *                   inserted. Caller is responsible 
+        *                   to deallocate Array.(OUT)
+        * @param aKeyNumbers -Array where keynumbers are inserted. Each key
+        *                   has its own number. This number helps to solve 
+        *                   which key is associated with which PIN.
+        *                    Caller is responsible to 
+        *                   deallocate Array. (OUT)
+        * @aStatus          -TRequestStatus from caller (IN/OUT)
+        * @return void
+        */
+        IMPORT_C void GetKeyList( RPointerArray<CCTKeyInfo>& aKeys,
+                                  CArrayFixFlat<TUint8>& aKeyNumbers,
+                                  TRequestStatus& aStatus );
+        
+        /* 
+        * Cancels outgoing listing operation
+        * @return void
+        */
+        IMPORT_C void CancelList();
+
+        /*  
+        * Sign some data. Authentication is handled by server.
+        * @since Series 60 2.6
+        * @param aData    The data to be signed - this should be some 
+        *                 form of hash of the actual message to be signed.  
+        *                 If the data is too long, this method will return 
+        *                 KErrOverflow through aStatus. (IN)
+        * @param aSignature Signature which is given back to caller. (OUT)
+        * @param aKeyId.  KeyId for signing operation.(IN)
+        * @param aStatus    Caller's status (IN/OUT)
+        * @return void
+        */
+        IMPORT_C void Sign( const TDesC8& aData,
+                            TDesC8& aKeyId,
+                            HBufC8*& aSignature,
+                            TRequestStatus& aStatus );
+
+        /** 
+        * Cancel signing operation
+        * @since Series 60 2.6
+        * @return void
+        */
+        IMPORT_C void CancelSign();
+
+        /** 
+        * Export public key
+        * @since Series 60 2.6
+        * @param aKeyId  -The KeyId of the key to be exported (IN)
+        * @param aPublicKey -DER Encoded public key. Must be allocated
+        *                    by caller(OUT)
+        * @param aStatus    -Caller's status (IN/OUT)
+        */
+        IMPORT_C void ExportPublicKeyL( TDesC8& aKeyId, 
+                                        HBufC8*& aPublicKey,
+                                        TRequestStatus& aStatus );
+
+        /** 
+        * Cancels ongoing export operation
+        * @since Series 60 2.6
+        * @return void
+        */
+        IMPORT_C void CancelExport();
+
+    private:
+        /** 
+        * Allocates memory for Array which is filled by server.
+        * @return void
+        */
+        void AllocMemoryForKeyListL();
+        
+        /** 
+        * Deallocates memory from the Array which was filled by server.
+        * @return void
+        */
+        void DeallocMemoryFromKeyList();
+
+        
+        /** 
+        * Allocates memory for Keyinfo structure.
+        * @param aKeyInfo   -Struct where allocated pointers are inserted.
+        * @return void
+        */
+        void AllocMemoryForKeyInfoL( TKeyInfo& aKeyInfo );   
+ 
+        /** 
+        * Deallocates memory from Keyinfo structure.
+        * @return void
+        */
+        void DeallocMemoryFromKeyInfo();
+
+        /** 
+        * Allocates memory for data to be signed
+        * @param aData -Data to be signed
+        * @param aKeyId -KeyId of the key to be used for sign
+        * @return void
+        */
+        void AllocMemoryForSignL( const TDesC8& aData, const TDesC8& aKeyId );
+
+        /** 
+        * Deallocates previously allocated data after signing operation.
+        * @return void
+        */
+        void DeallocMemoryFromSign();
+        
+        
+        /**
+        * Sets own iStatus to KRequestPending, and signals it 
+        * with User::RequestComplete() -request. This gives chance 
+        * to activescheduler to run other active objects. After a quick
+        * visit in activescheduler, signal returns to RunL() and starts next
+        * phase of operation. 
+        * @return void
+        */
+        void SignalOwnStatusAndComplete();
+
+        /** 
+        * Converts key list parameters. Extracts data out from key list 
+        * & key number. Extracted data is inserted to an RArray.
+        * @return void
+        */
+        void ConvertKeyListL();
+
+        /*  
+        * Converts key usage to match new key usage requirement
+        * @param aKeyUsage  -Value to be converted
+        * @return TKeyUsagePKCS15 -New form of key usage
+        */
+        TKeyUsagePKCS15 ConvertKeyUsage( TUint16 aKeyUsage );
+
+
+    private: //from CActive
+        
+        /**
+        * Different phases are handled here.
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * Cancellation function
+        * Deallocates member variables and completes client status with
+        * KErrCancel error code.
+        * @return void
+        */
+        void DoCancel();
+
+        /**
+        * The active scheduler calls this function if this active 
+        * object's RunL() function leaves. 
+        * Handles necessary cleanup and completes request with
+        * received error code.
+        * @param aError -Error which caused this event
+        * @return TInt  -Error code to activescheduler, is always KErrNone.
+        */ 
+        TInt RunError( TInt aError );
+
+    private:
+
+        /**
+        * Default constructor is private.
+        */
+        void ConstructL();
+        
+        /** 
+        * Default constructor
+        * @param aToken -Reference to current token
+        */
+        CWimKeyDetails( MCTToken& aToken );
+
+    private:
+
+        /** 
+        * Seven different phases which handles list, sign and export public
+        * key operations
+        */
+        enum TPhase
+            {
+            EGetKeyList,
+            EConvertParams,
+            EGetKeyInfo,
+            ESign,
+            ESignCompleted,
+            EExportPublicKey
+            };
+        
+    private:
+        //Reference to current token. Needed in CCTCertInfo creation.
+        MCTToken&                       iToken;
+
+        //Handle to connection with server. Owned.
+        RWimCertMgmt*                   iConnectionHandle;
+
+        //Client status is stored here while operation
+        //on the server side is done.        
+        TRequestStatus*                 iClientStatus;
+
+        //Used to handle different phases in RunL()
+        TPhase                          iPhase;
+
+        //Array which is used to contain key list.
+        //Not owned. Caller is responsible to destroy array.
+        RPointerArray<CCTKeyInfo>*      iKeys;
+
+        //Buffer which is used to contain keyreference information. Owned.
+        HBufC8*                         iKeyList;
+
+        //Pointer to iKeylist. Owned.
+        TPtr8*                          iKeyListPtr;
+
+        // The number of keys
+        TInt                            iKeyNumber;
+
+        //Buffer which is used for keys label when constructing new keyinfo
+        //-objects. Owned.
+        HBufC8*                         iLabel;
+     
+        //Pointer to iLabel. Owned.
+        TPtr8*                          iLabelPtr;
+
+        //Buffer which is used to contain unique modifier for a key. Used when
+        //constructing new keyinfo -objects. Owned.
+        HBufC8*                         iKeyId;
+     
+        //Pointer to iKeyId. Owned.
+        TPtr8*                          iKeyIdPtr;
+        
+        //Array which holds keyReferences. These references are needed when
+        //getting keyinfo for a single key.Owned.
+        RArray<TInt32>                  iKeyReferences;
+
+        //Array which hold keyNumber for each CCTKeyInfo -object, which are
+        //created and inserted to iKeys -array. Not owned.
+        CArrayFixFlat<TUint8>*          iKeyNumberArray;   
+        
+        //counter which informs how many keyinfos have been created.
+        TInt                            iFetchedKeyInfos;
+
+        //Struct which is used when signing data.
+        TKeySignParameters              iKeySignParameters;
+
+        //Struct which is used when exporting a key.
+        TExportPublicKey                iExportPublicKey;
+
+        //Buffer which holds data to be signed. Owned.
+        HBufC8*                         iSigningData;
+        
+        //Pointer to iSigningData. Owned.
+        TPtr8*                          iSigningDataPtr;
+
+        //Holds information which key is used for signing
+        TInt                            iSignKeyHandle;
+        
+        //Buffer which holds received signature from WIM, if signing was
+        //succesful. Not owned
+        HBufC8*                         iSignature;
+
+        //Pointer to iSignature. Owned.
+        TPtr8*                          iSignaturePtr;
+
+        //Buffer which holds DER encoded public key. Not owned.
+        HBufC8*                         iPublicKey;
+
+        //Pointer to iPublicKey.Owned
+        TPtr8*                          iPublicKeyPtr;
+        
+        //The pack to store key number
+        TPckg<TInt>                     iPckg;
+
+    };
+
+
+#endif  //WIMKEYDETAILS_H
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/WimOpcode.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,98 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Operation codes for WimClient and WimServer message passing
+*
+*/
+
+
+#ifndef WIMOPCODE_H
+#define WIMOPCODE_H
+
+// Opcodes used in message passing between client and server
+enum TWimServRqst
+    {
+    ENon,               // Opcode has not been assigned yet
+    /* -- WIM management ---------------------------------------------------- */
+    EWimInitialize,     // Initialize WIM
+    ECancelWimInitialize, //Cancel Initialize WIM
+    EGetWIMCount,       // WIM query operations code
+    EGetWIMRefs,        // Get the array of Wim structures
+    EGetWIMInfo,        // Get WIM info (manufacturer etc.)
+    EIsWIMOpen,         // WIM operations code
+    ECloseWIMAfter,     // Set closing time for WIM
+    EGetCloseWIMAfter,  // Get value for WIM closing timeout
+    EWimTimeRemaining,  // Time that WIM is still open   
+    EWIMClose,          // Closes the WIM
+    ENotifyOnRemoval,   // Notify client when the token has been removed
+    ECancelNotifyOnRemoval, // Cancel NotifyOnRemoval request  
+    EFreeMemory,        // Free the address list
+    EFreeWIMMemoryLst,  // Free the address list
+    EFreeMemoryLst,     // Free the address list
+    
+    /* -- PIN & Key management ---------------------------------------------- */
+    EGetPINCount,       // Get count of PINs in WIM
+    EGetPINRefs,        // Get the array of Pin structures
+    EGetPINInfo,        // Get PIN info
+    EGetPINsInfo,
+    EIsPinBlocked,      // Check if PIN is blocked or not
+    EIsDisabledPinBlocked,    
+    EChangePINReq,      // Change the PIN value
+    ECancelChangePin,   //Cancel change Pin value
+    EEnablePINReq,      // Enable PIN
+    ECancelEnablePin,   //Cancel enable pin
+    EUnblockPinReq,     // Unblock blocked PIN
+    ECancelUnblockPin,  //Cancel unblock pin
+    EVerifyPinReq,      // Verify PIN
+    ECancelVerifyPin,   //Cancel verify pin
+    EVerifyDisabledPinReq, //Verify Disabled PIN
+    ECancelDisabledPin, //Cancel disabled pin
+    EGetKeyDetails,     // Get Key details based on public key
+    EGetKeyList,        // Get list of keys in WIM
+    EDoesPvKeyExist,    // Check if private key exists
+    ERetrieveAuthObjsInfo,   // Get the auth Obj info
+    
+    /* -- Certificate management -------------------------------------------- */
+    EGetWIMCertLst,     // Get the certifcate list
+    EGetCertCount,      // Get the certificate count
+    EGetWIMCertDetails, // Get the certificate details
+    EGetCertExtras,     // Get certificate extra data
+    EStoreCertificate,  // Store certificate to card
+    ERemoveCertificate, // Remove certificate from card
+    EExportPublicKey,   // Export public key of certificate
+    
+    /* -- Digital signature ------------------------------------------------- */
+    ESignTextReq,       // Sign some text
+
+    /* -- OMA Provisioning -------------------------------------------------- */
+    EGetOMAFileSize,    // Get OMA Provisioning file size
+    EGetOMAFile,        // Get OMA Provisioning file
+   
+    /* -- Java Proisioning ---------------------------------------------------*/
+    EGetACIFFileSize,
+    EGetACIFFile,
+    EGetACFFileSize,
+    EGetACFFile,
+    EGetLabelAndPath,
+     
+    /* -- Trust Settings Store ---------------------------------------------- */
+    EGetTrustSettings,          // Get trust settings for given certificate
+    ESetApplicability,          // Set applicability for given certificate
+    ESetTrust,                  // Set trust flag for given certificate
+    ESetDefaultTrustSettings,   // Set default settings for given certificate
+    ERemoveTrustSettings,       // Remove trust settings of given certificate
+    ECancelTrustSettings        // Cancel any issued asynchronous call
+    };
+
+#endif      // WIMOPCODE_H
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/WimPin.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,318 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  API for managing PIN
+*
+*/
+
+
+#ifndef WIMPIN_H
+#define WIMPIN_H
+
+
+//  INCLUDES
+#include "WimClsv.h"
+#include <e32base.h>
+#include <secdlg.h> 
+
+
+class RWimMgmt;
+
+/**
+*  API for managing PIN.
+*  This API provides methods to manage PIN: check statuses and
+*  change settings.
+*
+*  @lib WimClient
+*  @since Series 60 2.6
+*/
+class CWimPin: public CActive
+    {
+    public:  
+        
+        /**
+        * Two-phased constructor.
+        * @param aPin       -the type of Pin
+        * @param aPinAddr   -Reference to Pin structure
+        * @param aTokenLabel -the name of the token
+        */
+        IMPORT_C static CWimPin* NewL( TWimPin aPin,  
+                                       const TPinAddress aPinAddr,
+                                       TDesC& aTokenLabel );  
+
+        /**
+        * Destructor.
+        */
+        IMPORT_C virtual ~CWimPin();
+
+        
+    public: // New functions
+
+        /**
+        * Enables Pin query of the Pin.
+        * The PinStatus() function should be called before 
+        * calling this function to make sure the status of
+        * pin
+        * @param aStatus -Caller's status.
+        * @return void
+        */        
+        IMPORT_C void EnablePinQuery( TRequestStatus& aStatus );
+        
+        /**
+        * Cancel enables Pin query of the Pin.
+        * @return void
+        */  
+        IMPORT_C void CancelEnablePinQuery();
+        
+        /**
+        * Disables Pin query of the Pin.
+        * The PinStatus() function should be called before 
+        * calling this function to make sure the status of
+        * pin
+        * @param aStatus -Caller's status.
+        * @return void
+        */                
+        IMPORT_C void DisablePinQuery( TRequestStatus& aStatus );
+        
+        /**
+        * Cancel disables Pin query of the Pin.
+        * @return void
+        */  
+        IMPORT_C void CancelDisablePinQuery();
+        
+        /**
+        * Changes Pin.
+        * The PinStatus() function should be called before 
+        * calling this function to make sure the status of
+        * pin
+        * @param aStatus -Caller's status
+        * @return void
+        */        
+        IMPORT_C void ChangePin( TRequestStatus& aStatus );
+        
+        /**
+        * Cancel changes Pin.
+        * @return void
+        */ 
+        IMPORT_C void CancelChangePin();
+        
+        /**
+        * Unblocks Pin
+        * The PinStatus() function should be called before 
+        * calling this function to make sure the status of
+        * pin
+        * @param aStatus -Caller's status
+        * @return void
+        */        
+        IMPORT_C void UnblockPin( TRequestStatus& aStatus );
+        
+        /**
+        * Cancel unblocks Pin
+        * @return void
+        */  
+        IMPORT_C void CancelUnblockPin();
+        
+        /**
+        * Verifies the enterd Pin -request.
+        * The PinStatus() function should be called before 
+        * calling this function to make sure the status of
+        * pin
+        * @param aStatus -Caller's status 
+        * @return void
+        */        
+        IMPORT_C void VerifyPin( TRequestStatus& aStatus );
+        
+        /**
+        * Cancel verifies the enterd Pin -request.
+        * @return void
+        */ 
+        IMPORT_C void CancelVerifyPin();
+        
+        /**
+        * Returns PIN's label.
+        * @return Pointer descriptor containing label.
+        */
+        IMPORT_C TPtrC Label();
+   
+        /**
+        * Returns the status of Pin.
+        * Variations are: WIMI_PF_Enabled           
+        *                 WIMI_PF_ChangeDisabled    
+        *                 WIMI_PF_UnblockDisabled   
+        *                 WIMI_PF_DisableAllowed
+        * @return iStatus -status of Pin
+        */        
+        IMPORT_C TWimPinStatus PinStatus();
+
+        /** 
+        * Returns the number of the pin. It is a number, which 
+        * identifies pin object in the Wim -card. Pin number
+        * can be eg. 0,1,2....
+        * @return TUint8    -PinNumber
+        */
+        IMPORT_C TUint8 PinNumber();
+
+    public:
+
+        /*
+        * Sets RWimMgmt* pointer to iClientSession
+        * @param aClientSession
+        * @return void
+        */
+        void SetClientSession( RWimMgmt* aClientSession );
+        
+        /*
+        * Sets Label 
+        * return void
+        */
+        void SetLabel( TBuf<KLabelLen>& aLabel );
+        
+        /*
+        * Sets PinStatus 
+        * return void
+        */
+    	  void SetPinStatus( TWimPinStatus& aStatus );
+    	  
+    	  /*
+        * Sets Pin Number 
+        * return void
+        */
+    	  void SetPinNumber( TUint8& aPinNumber );
+    
+    private:
+
+        /** 
+        * Constructs pinparams struct.
+        * @param aPinParams -params to be constructed.
+        * @return TPINParams
+        */
+        void PinParams( TPINParams& aPinParams );
+
+        /**
+        * Checks is Pin changeable.
+        * @return ETrue if PIN is changeable else returns EFalse.
+        */
+        TBool PinChangeable();
+
+        /**
+        * C++ constructor.
+        * @param aPin   -the type of the pin
+        * @param aPinAddr -Reference to Pin structure.
+        */
+        CWimPin( TWimPin aPin, TPinAddress aPinAddr );
+
+        /**
+        * Default constructor is private.
+        * @param aTokenLabel -Label of the token
+        * @return void
+        */
+        void ConstructL( const TDesC& aTokenLabel );
+
+        /*
+        * Get Pin Info. Initializes member variables.
+        * @return void
+        */
+        void PinInfo( TRequestStatus& aStatus );
+
+        /**
+        * Sets own iStatus to KRequestPending, and signals it 
+        * with User::RequestComplete() -request. This gives change 
+        * to activescheduler to run other active objects. After a quick
+        * visit in activescheduler, signal returns to RunL() and starts next
+        * phase of operation. 
+        * @return void
+        */
+        void SignalOwnStatusAndComplete();
+
+
+    private: //From CActive
+
+        /**
+        * Different phases are handled here.
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * Cancellation function
+        * Not allowed to cancel
+        * @return void
+        */       
+        void DoCancel();
+
+        /**
+        * The active scheduler calls this function if this active 
+        * object's RunL() function leaves. 
+        * Handles necessary cleanup and completes request with
+        * received error code.
+        * @param aError -The error code which caused this function call.
+        * @return TInt  -Error code to activescheduler, is always KErrNone.
+        */ 
+        TInt RunError( TInt aError );
+
+    private:
+        
+        //Ten different phases for PIN handling
+        enum TPinPhase
+            {
+            EEnablePinQueryStart,
+            EEnablePinQueryEnd,
+            EDisablePinQueryStart,
+            EDisablePinQueryEnd,
+            EChangePinStart,
+            EChangePinEnd,
+            EUnblockPinStart,
+            EUnblockPinEnd,
+            EVerifyPinStart,
+            EVerifyPinEnd,
+            EUpdatePinStatus,
+            EUpdatePinStatusDone
+            };
+
+        //Used to handle different phases in RunL()
+        TPinPhase iPhase;
+        
+        TPinPhase iCurrentPhase;
+        
+    private:    
+
+        //Client status is stored here while operation
+        //on the server side is done.        
+        TRequestStatus*             iClientStatus;
+        // Reference to PIN.
+        const TPinAddress           iReference; 
+        //Pin type: Pin-G or PinNR
+        TWimPin                     iPinType;
+        //Holds label. Owned
+        HBufC*                      iLabel;
+        //Holds tokenlabel.Owned.
+        HBufC*                      iTokenLabel;
+        //Holds Pin-status
+        TWimPinStatus               iPinStatus;
+        //pointer to clientSession. Owned by CWimSecModuleMgr.
+        RWimMgmt*                   iClientSession;
+        //Number that identifies Pin in the Wim. Its a running number 0,1,2..
+        TUint8                      iPinNumber;
+        //Struct for PIN parameters
+        TPINParams                  iPinParams;
+        //Struct for enable/disable information
+        TPINStateRequest            iPinStateRequest;
+        //To store the status value from wimserver
+        TInt                        iReceivedStatus;
+        
+        TWimPinStruct               iPinStruct;
+
+    };
+
+#endif       
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/WimSig.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,105 @@
+/*
+* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This is the header file for the TWIMSrvStartSignal class
+*
+*/
+
+
+
+#ifndef WIMSIG_H
+#define WIMSIG_H
+
+//  INCLUDES
+#include <e32std.h>
+
+
+// CLASS DECLARATION
+
+/**
+*  TWIMSrvStartSignal
+*  
+*  @since Series60 2.1
+*/
+class TWIMSrvStartSignal
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Constructor.
+        */
+        inline TWIMSrvStartSignal();
+        
+        /**
+        * Constructor.
+        */
+        inline TWIMSrvStartSignal( TRequestStatus& aStatus );
+
+    public: // New functions        
+
+        /**
+        * Setter that is used on server.cpp: InitProcess
+        * @param aCommand Command
+        * @return TInt
+        */
+        inline TInt Set( const TDesC& aCommand );
+
+        /**
+        * Returns TPtrC which is created by using this.
+        * @return TPtrC
+        */
+        inline TPtrC Command() const;
+
+        /** 
+        * Returns iStatus member variable
+        * @return TRequestStatus*
+        */
+        inline TRequestStatus* RequestStatus();
+
+        /** 
+        * Returns Threads ID
+        * @return TThreadId
+        */
+        inline TThreadId ThreadId();
+
+    private:
+
+        /** 
+        * Copy constructor
+        * @param aSource -Reference to class object.
+        */
+        TWIMSrvStartSignal( const TWIMSrvStartSignal& aSource );
+
+        /** 
+        * Assigment operator
+        * @param aParam -Reference to class object.
+        */
+        TWIMSrvStartSignal& operator = ( const TWIMSrvStartSignal& aParam );
+    
+    private: // Data
+        // //Status from caller
+        TRequestStatus* iStatus;
+        // Thread ID
+        const TThreadId iId;
+    };
+
+
+// FUNCTION PROTOTYPES
+//Imported function to start Wim server
+IMPORT_C TInt StartWimServer( TWIMSrvStartSignal& aSignal );
+
+#include "WimSig.inl" // Inline impelementations
+
+#endif      // WIMSIG_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/WimSig.inl	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,94 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Inline implementations for the TWIMSrvStartSignal class
+*
+*/
+
+
+
+// -----------------------------------------------------------------------------
+// TWIMSrvStartSignal::TWIMSrvStartSignal
+// Default constructor.
+// -----------------------------------------------------------------------------
+//
+inline TWIMSrvStartSignal::TWIMSrvStartSignal()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// TWIMSrvStartSignal::TWIMSrvStartSignal
+// Default constructor.
+// -----------------------------------------------------------------------------
+//
+inline TWIMSrvStartSignal::TWIMSrvStartSignal( TRequestStatus& aStatus )
+    : iStatus( &aStatus ),
+      iId( RThread().Id() )
+    {
+    aStatus = KRequestPending;
+    }
+
+// -----------------------------------------------------------------------------
+// TWIMSrvStartSignal::Command
+// Returns TPtrC which is created by using this.
+// -----------------------------------------------------------------------------
+//
+inline TPtrC TWIMSrvStartSignal::Command() const
+    {
+    return TPtrC( (const TText*)this, sizeof( *this ) / sizeof( TText ) );
+    }
+
+// -----------------------------------------------------------------------------
+// TWIMSrvStartSignal::Set
+// Setter function which is called from Wimserver.cpp.
+// -----------------------------------------------------------------------------
+//
+inline TInt TWIMSrvStartSignal::Set( const TDesC& aCommand )
+    {
+    TInt ret;
+
+    if ( aCommand.Size() != sizeof( *this ) )
+        {
+        ret = KErrGeneral;
+        }
+    else
+        {
+        Mem::Copy( this, aCommand.Ptr(), sizeof( *this ) );
+        ret = KErrNone;
+        }
+
+    return ret;
+    }
+
+// -----------------------------------------------------------------------------
+// TWIMSrvStartSignal::RequestStatus
+// Return RequestStatus set in construction
+// -----------------------------------------------------------------------------
+//
+inline TRequestStatus* TWIMSrvStartSignal::RequestStatus()
+    {
+    return iStatus;
+    }
+
+// -----------------------------------------------------------------------------
+// TWIMSrvStartSignal::ThreadId
+// Return thread ID set in construction
+// -----------------------------------------------------------------------------
+//
+inline TThreadId TWIMSrvStartSignal::ThreadId()
+    {
+    return iId;
+    }
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/WimTrace.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Defines for RDebug Traces
+*
+*/
+
+
+#ifndef WIMTRACE_H
+#define WIMTRACE_H
+
+
+#ifdef __WIM_ENABLE_TRACES
+#include <e32svr.h>
+#define _WIMTRACE( a ) RDebug::Print( a )
+#define _WIMTRACE2( a , b ) RDebug::Print( a , b )
+#define _WIMTRACE3( a , b , c ) RDebug::Print( a , b , c )
+#define _WIMTRACE4( a , b , c , d ) RDebug::Print( a , b , c , d )
+#define _WIMTRACE5( a , b , c , d , e ) RDebug::Print( a , b , c , d , e )
+#define _WIMTRACE6( a , b , c , d , e , f ) RDebug::Print( a , b , c , d , e , f )
+#define _WIMTRACE7( a , b , c , d , e , f , g ) RDebug::Print( a , b , c , d , e , f , g )
+#define _WIMTRACE8( a , b , c , d , e , f , g , h ) RDebug::Print( a , b , c , d , e , f , g , h )
+#define _WIMTRACE9( a , b , c , d , e , f , g , h , i ) RDebug::Print( a , b , c , d , e , f , g , h , i )
+#define _WIMTRACE10( a , b , c , d , e , f , g , h , i , j ) RDebug::Print( a , b , c , d , e , f , g , h , i , j )
+#define _WIMTRACE11( a , b , c , d , e , f , g , h , i , j , k ) RDebug::Print( a , b , c , d , e , f , g , h , i , j , k )
+#else
+#define _WIMTRACE( a ) 
+#define _WIMTRACE2( a , b ) 
+#define _WIMTRACE3( a , b , c ) 
+#define _WIMTRACE4( a , b , c , d ) 
+#define _WIMTRACE5( a , b , c , d , e ) 
+#define _WIMTRACE6( a , b , c , d , e , f ) 
+#define _WIMTRACE7( a , b , c , d , e , f , g ) 
+#define _WIMTRACE8( a , b , c , d , e , f , g , h ) 
+#define _WIMTRACE9( a , b , c , d , e , f , g , h , i ) 
+#define _WIMTRACE10( a , b , c , d , e , f , g , h , i , j ) 
+#define _WIMTRACE11( a , b , c , d , e , f , g , h , i , j , k ) 
+#endif
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/WimTrustSettingsAPI.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,207 @@
+/*
+* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface for WIM Trust Settings Store
+*
+*/
+
+
+
+#ifndef WIMTRUSTSETTINGSAPI_H
+#define WIMTRUSTSETTINGSAPI_H
+
+
+//INCLUDES
+#include <e32base.h>
+
+
+// FORWARD DECLARATIONS
+class RWimTrustSettingsMgmt;
+class CWimCertInfo;
+
+
+//CLASS DECLARATION
+/**
+*  Interface which handles Trust Settings Store related operations 
+*  with WimServer.
+*
+*  @lib WimClient.lib
+*  @since Series60 3.0
+*/
+class CWimTrustSettingsAPI : public CActive
+    {
+    public:  // Constructor and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CWimTrustSettingsAPI* NewL();
+        
+        /**
+        * Destructor.
+        */
+        IMPORT_C virtual ~CWimTrustSettingsAPI();
+
+    public: // New functions
+        
+        /**
+        * Fetches trust settings for given certificate. 
+        * Acts like an asynchronous for caller but not activates itself.
+        * @param  aCert (IN) Certificate
+        * @param  aTrusted  (OUT) Is certificate trusted
+        * @param  aApplications  (OUT) Array of applications supported 
+        *         by certificate
+        * @param  aStatus (IN/OUT) Request Status of asynchronous call
+        * @return void
+        */
+        IMPORT_C void GetTrustSettings( const CWimCertInfo& aCert,
+                                        TBool& aTrusted,
+                                        RArray<TUid>& aApplications, 
+                                        TRequestStatus& aStatus );
+
+        /**
+        * Set applicability for given certificate. Calls DoSetApplicabilityL,
+        * which handles actual operation. New certificate entry is set if
+        * one not found from database (trust flag is set to EFalse).
+        * Acts like an asynchronous for caller but not activates itself.
+        * @param aCert (IN) Certificate
+        * @param aApplications (IN) Array of applications supported by 
+        *        certificate
+        * @param aStatus Request (IN/OUT) Status of asynchronous call.
+        * @return void
+        */
+        IMPORT_C void SetApplicability( const CWimCertInfo& aCert,
+                                        const RArray<TUid>& aApplications,
+                                        TRequestStatus& aStatus );
+
+        /**
+        * Set trust flag for given certificate. Calls DoSetTrustL,
+        * which handles actual operation. New certificate entry is set if
+        * one not found from database.
+        * Acts like an asynchronous for caller but not activates itself.
+        * @param aCert (IN) Certificate
+        * @param aTrusted (IN) Is certificate trusted
+        * @param aStatus (IN/OUT) Request Status of asynchronous call.
+        * @return void
+        */
+        IMPORT_C void SetTrust( const CWimCertInfo& aCert,
+                                TBool aTrusted,
+                                TRequestStatus& aStatus );
+
+        /**
+        * Set default trust settings for given certificate. If certificate not
+        * found from database new entry is inserted.
+        * Acts like an asynchronous for caller but not activate itself.
+        * @param aCert (IN) Certificate
+        * @param aAddApps (IN) Are default applications inserted 
+        *        (ETrue means yes)
+        * @param aStatus (IN/OUT) Request Status of asynchronous call
+        * @return void
+        */
+        IMPORT_C void SetDefaultTrustSettings( const CWimCertInfo& aCert,
+                                               TBool aAddApps,
+                                               TRequestStatus& aStatus );
+
+        /**
+        * Remove trust settings of given certificate. If certificate
+        * is not found, return with status.Int() = KErrNotFound
+        * Acts like an asynchronous for caller but not activates itself.
+        * @param aCert (IN) Certificate
+        * @param aStatus (IN/OUT) Request Status of asynchronous call
+        * @return void
+        */
+        IMPORT_C void RemoveTrustSettings( const CWimCertInfo& aCert,
+                                           TRequestStatus& aStatus );
+
+        /**
+        * Delete TrustSettingsStore instance and release all resources
+        * @return void
+        */
+        IMPORT_C void Close();
+
+        /**
+        * Cancel any issued asynchronous call
+        * @return void
+        */
+        IMPORT_C void CancelDoing();
+
+    private:
+
+        /**
+        * Default constructor.
+        */
+        CWimTrustSettingsAPI();
+
+        /**
+        * 2nd phase constructor
+        */
+        void ConstructL();
+
+        /**
+        * Handle trapped leave. Completes client request in case leave
+        * has occurred.
+        * @return void
+        */
+        void HandleLeaveError( TInt aError ); 
+
+
+    private: // From base class CActive 
+
+        /**
+        * Handle asyncronous response
+        * @return void
+        */
+        void RunL();
+
+        /**
+        * Handle asyncronous call cancel
+        * @return void
+        */
+        void DoCancel();
+
+    private:
+              
+        //Client status is stored here while operation
+        //on the server side is done.
+        TRequestStatus*                 iClientStatus;
+        
+        // Used for saving caller status. Not owned
+        TRequestStatus*                 iOriginalRequestStatus;
+
+        //Handle to connection with server. Owned.
+        RWimTrustSettingsMgmt*          iConnectionHandle;
+
+        // Pointer to client array for applications. Not owned.
+        RArray<TUid>*                   iApplications;
+
+        // Pointer to flag telling if certificate is trusted or not. Not owned.
+        TBool*                          iTrusted;
+
+        // Different phases of Trust Settings Store operation
+        enum TPhase
+            {
+            EGetTrustSettings,
+            ESetDefaultTrustSettings,
+            ESetApplicability,
+            ESetTrust,
+            ERemoveTrustSettings
+            };
+
+        // Current phase of Trust Settings Store operation
+        TPhase                          iPhase;
+ 
+    };
+
+#endif  //WIMTRUSTSETTINGSAPI_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/inc/Wimi.h	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,963 @@
+/*
+* Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  WIMI definitions used by WimServer and WimClient. 
+*               All WIMI.lib API functions are described in this file.
+*
+*/
+
+
+#ifndef WIMI_H
+#define WIMI_H
+
+#include <e32base.h>
+#include <libc/stddef.h>     // For size_t
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+// CONSTANTS
+
+/* CDF of certificate */
+const TUint WIMLIB_CERTIFICATES_CDF  = 0x20;
+const TUint WIMLIB_TRUSTEDCERTS_CDF  = 0x40;
+const TUint WIMLIB_USEFULCERTS_CDF   = 0x80;
+
+/* PIN flags */
+const TUint8 WIMI_PF_DisableAllowed  = 0x10;
+const TUint8 WIMI_PF_UnblockDisabled = 0x20;
+const TUint8 WIMI_PF_ChangeDisabled  = 0x40;
+const TUint8 WIMI_PF_Enabled         = 0x80;
+
+
+/* Certificate usage */
+const TUint WIMI_CU_Client  = 0;
+const TUint WIMI_CU_CA      = 1;
+
+/* Certificate type */
+const TUint WIMI_CT_WTLS    = 1;
+const TUint WIMI_CT_X509    = 2;
+const TUint WIMI_CT_X968    = 3;
+const TUint WIMI_CT_URL     = 4;
+const TUint WIMI_CT_UNKNOWN = 255;
+
+/* APDU driver status codes */
+const TUint8 WIMI_APDU_OK                 = 0;
+const TUint8 WIMI_APDU_TRANSMISSION_ERROR = 1;
+
+
+// DATA TYPES 
+
+/* Return type for status codes */
+typedef TUint16 WIMI_STAT;
+
+/* Reference types */
+typedef void WIMI_Ref_t;
+typedef WIMI_Ref_t* WIMI_Ref_pt;
+
+/* Reference list */
+typedef WIMI_Ref_pt* WIMI_RefList_t;
+
+/* Binary data */
+typedef struct
+    {
+    TUint8* pb_buf;
+    TUint16 ui_buf_length;
+    TUint8  filler_byte[2];     /* filler byte to ensure alignment*/
+    } WIM_BIN_DATA;
+
+typedef WIM_BIN_DATA WIMI_BinData_t;
+
+/* Label list */
+typedef WIMI_BinData_t* WIMI_labelptr_t;
+typedef WIMI_labelptr_t* WIMI_labellist_t;
+
+/* Hash context type */
+typedef void WIMI_Hash_t;
+
+/* Transaction ID */
+typedef void *WIMI_TransactId_t;
+
+/* WTLS Certificate info structure */
+typedef struct 
+    { 
+    TUint16 ParsedLen;
+    TUint8  SignAlg;
+    TUint8* Issuer;
+    TUint16 IssuerLen;
+    TUint32 ValidNotBefore;
+    TUint32 ValidNotAfter;
+    TUint8* Subject;
+    TUint16 SubjectLen;
+    TUint8  PublicKeyType;
+    TUint16 exponentlen;
+    TUint8* exponent;
+    TUint16 moduluslen;
+    TUint8* modulus;
+    TUint16 signaturelen;
+    TUint8* signature;
+    } WIMI_WTLS_CertInfo_t;
+
+/* File info structure for Provisioning files */
+typedef struct
+    {
+    WIM_BIN_DATA  t_label;
+    WIM_BIN_DATA  t_oid;
+    WIM_BIN_DATA  b_path;
+    TUint16       ui_flags; /* bitmask */
+    TUint16       ui_file_size;
+    TUint8        ui_pin_ref;
+    TUint8        filler_byte[3];     /* filler byte to ensure alignment*/
+    } WIMI_File_Info;
+
+/* Status codes */
+enum __WIMI_STATUS_CODES
+    { 
+    WIMI_Ok = 0,
+    WIMI_Err,
+    WIMI_ERR_Internal,
+    WIMI_ERR_OutOfMemory,
+    WIMI_ERR_BadParameters,
+    WIMI_ERR_ServerCertRejected,
+    WIMI_ERR_WrongReference,
+    WIMI_ERR_CipherNotSupported,
+    WIMI_ERR_MACANotSupported,
+    WIMI_ERR_SessionNotSet,
+    WIMI_ERR_WrongKES,
+    WIMI_ERR_DecodeError,
+    WIMI_ERR_ExpiredReference,
+    WIMI_ERR_NoKey,
+    WIMI_ERR_CertNotYetValid,
+    WIMI_ERR_CertExpired,
+    WIMI_ERR_UnknownCA,
+    WIMI_ERR_CertParseError,
+    WIMI_ERR_UnsupportedCertificate,
+    WIMI_ERR_SignCheckFailed,
+    WIMI_ERR_NoWIM,
+    WIMI_ERR_NoKES,
+    WIMI_ERR_HashInitFailed,
+    WIMI_ERR_HashUpdateFailed,
+    WIMI_ERR_HashCopyFailed,
+    WIMI_ERR_HashFinalFailed,
+    WIMI_ERR_HashInvalidAlgorithm,
+    WIMI_ERR_UnknownKeyId,
+    WIMI_ERR_KeyStorageFull,
+    WIMI_ERR_BadKey,
+    WIMI_ERR_CertStorageFull,
+    WIMI_ERR_BadCert,
+    WIMI_ERR_PStorageError,
+    WIMI_ERR_CertNotFound,
+    WIMI_ERR_KeyNotFound,
+    WIMI_ERR_BadReference,
+    WIMI_ERR_OperNotSupported,
+    WIMI_ERR_BadPIN,
+    WIMI_ERR_CardDriverInitError,
+    WIMI_ERR_CardIOError,
+    WIMI_ERR_AlgorithmNotYetImplemented,
+    WIMI_ERR_PINBlocked,
+    WIMI_ERR_OperNotAllowed,
+    WIMI_ERR_NoCert,
+    WIMI_ERR_CAcertNotYetValid,
+    WIMI_ERR_CAcertExpired,
+    WIMI_ERR_BadCAcert,
+    WIMI_ERR_UserCancelled = 0x8F
+    };
+
+/* Operation codes for some WIMI calls */
+enum TWimiOpcodes
+    {
+    ENoOperation,                   // No operation
+    EInitializationCertListHashing, // Cert hash
+    EOMAProvContentSync             // Synchronous OMA Provisioning file fetch
+    };
+
+
+// =============================================================================
+// Callback functions. User of WIMI (WimServer) has to implement these
+// functions.
+// =============================================================================
+
+/* ------------ WIMI initialization and closing --------------------------- */
+/**
+   WIMI init respond callback.
+   aStatus - operation status 
+**/
+typedef void ( *WIMI_InitResp_t )( WIMI_STAT aStatus );
+
+/**
+   WIMI close respond callback 
+   aStatus - operation status 
+**/
+typedef void ( *WIMI_CloseDownResp_t )( WIMI_STAT aStatus );
+
+/* ------------ Digital signature ----------------------------------------- */
+/**
+   Respond to the digital signature operation 
+   aTrId    - transaction id
+   aStatus  - operation status 
+   aSignLen - signature length
+   aSign    - signature 
+**/
+typedef void ( *WIMI_SignResp_t )( WIMI_TransactId_t aTrId,
+                                   WIMI_STAT aStatus,
+                                   TUint8 aSignLen,
+                                   TUint8* aSign );
+
+/* ------------ Certificate management ------------------------------------ */
+/**
+   Respond to the certificate fetch operation
+   aTrId    - transaction id
+   aStatus  - operation status 
+   aCertRef - the reference to certificate that was fetched
+   aCertLen - certificate content length
+   aCert    - certificate content 
+**/
+typedef void ( *WIMI_CertificateResp_t )( WIMI_TransactId_t aTrId,
+                                          WIMI_STAT aStatus,
+                                          WIMI_Ref_t* aCertRef,
+                                          TUint16 aCertLen,
+                                          TUint8* aCert );
+
+/**
+   Respond to the certificate delete operation
+   aTrId - transaction id
+   aStatus - operation status 
+**/
+typedef void ( *WIMI_CertificateDeleteResp_t )( WIMI_TransactId_t aTrId,
+                                                WIMI_STAT aStatus );
+
+/**
+   Respond to the certificate store operation
+   aTrId - transaction id
+   aStatus - operation status 
+   aCertRef - the reference to certificate that was stored 
+**/
+typedef void ( *WIMI_CertificateStoreResp_t )( WIMI_TransactId_t aTrId,
+                                               WIMI_STAT aStatus,
+                                               WIMI_Ref_t* aCertRef );
+
+
+/* ------------ PIN management -------------------------------------------- */
+/**
+   Respond to the Verify PIN operation
+   aTrId - transaction id
+   aStatus - operation status 
+**/
+typedef void ( *WIMI_VerifyPINResp_t )( WIMI_TransactId_t aTrId,
+                                        WIMI_STAT aStatus );
+
+/**
+   Respond to the Change PIN operation
+   aTrId - transaction id
+   aStatus - operation status 
+**/
+typedef void ( *WIMI_ChangePINResp_t )( WIMI_TransactId_t aTrId,
+                                        WIMI_STAT aStatus );
+
+/**
+   Respond to the Unblock PIN operation
+   aTrId - transaction id
+   aStatus - operation status 
+**/
+typedef void ( *WIMI_UnblockPINResp_t )( WIMI_TransactId_t aTrId,
+                                         WIMI_STAT aStatus );
+
+/**
+   Respond to the Enable PIN operation
+   aTrId - transaction id
+   aStatus - operation status 
+**/
+typedef void ( *WIMI_EnablePINResp_t )( WIMI_TransactId_t aTrId,
+                                        WIMI_STAT aStatus );
+
+/* ------------ Hardware driver support ----------------------------------- */
+/**
+   Card inserted response
+   aReader - reader ID
+   aStatus - operation status 
+   aWimReg - WIM reference
+**/
+typedef void ( *WIMI_CardInsertedResp_t )( TUint8 aReader,
+                                           WIMI_STAT aStatus,
+                                           WIMI_Ref_t* aWimRef );
+
+/**
+   Open WIM request (connection request)
+   aReader  - reader ID
+**/
+typedef TUint8 ( *WIMI_Open_t )( TUint8 aReader );
+
+/**
+   Close WIM request (close connection)
+   aReader  - reader ID
+**/
+typedef TUint8 ( *WIMI_Close_t )( TUint8 aReader );
+
+/**
+   APDU request
+   aReader  - reader ID
+   aApdu    - APDU
+   aApduLen - length of APDU
+**/
+typedef void ( *WIMI_APDUReq_t )( TUint8 aReader,
+                                  TUint8* aApdu,
+                                  TUint16 aApduLen );
+
+/**
+   Get ATR request
+   aReader - reader ID
+**/
+typedef void ( *WIMI_GetATRReq_t )( TUint8 aReader );
+
+/**
+   Get reader list request
+**/
+typedef void ( *WIMI_GetReaderListReq_t )( void );
+
+/**
+   Read SIM file request
+   aReader - reader ID
+   aPath   - path to read from
+   aOffset - offset
+   aSize   - size to be read
+**/
+typedef void ( *WIMI_ReadSimFileReq_t )( TUint8 aReader,
+                                         TUint8* aPath,
+                                         TUint16 aOffset,
+                                         TUint16 aSize );
+
+/**
+   Provisioning file response
+   aTrId    - transaction ID
+   aStatus  - operation status
+   aFileLen - lenght of file
+   aFile    - file content
+**/
+typedef void (*WIMI_ProvSCFileResp_t)( WIMI_TransactId_t aTrId,
+                                       WIMI_STAT aStatus,
+                                       TUint16 aFileLen,
+                                       TUint8* aFile );
+
+/* WIMI Callbacks */
+typedef struct __WIMI_CALLBACKS
+    {
+    WIMI_InitResp_t                InitOkResp;
+    WIMI_CloseDownResp_t           CloseDownResp;
+    WIMI_SignResp_t                SignResp;
+    WIMI_CertificateResp_t         CertificateResp;
+    WIMI_CertificateDeleteResp_t   CertificateDeleteResp;
+    WIMI_CertificateStoreResp_t    CertificateStoreResp;
+    WIMI_VerifyPINResp_t           VerifyPINResp;
+    WIMI_ChangePINResp_t           ChangePINResp;
+    WIMI_UnblockPINResp_t          UnblockPINResp;
+    WIMI_EnablePINResp_t           EnablePINResp;
+    WIMI_CardInsertedResp_t        CardInsertedResp;
+    WIMI_Open_t                    Open;
+    WIMI_Close_t                   Close;
+    WIMI_APDUReq_t                 APDUReq;
+    WIMI_GetATRReq_t               GetATRReq;
+    WIMI_GetReaderListReq_t        GetReaderListReq;
+    WIMI_ReadSimFileReq_t          ReadSimFileReq;
+    WIMI_ProvSCFileResp_t          ProvSCFileResp;
+    } WIMI_Callbacks_t;
+
+/* ------------ Memory allocation/deallocation functions ------------------ */
+
+/**
+   Allocate memory block
+   aMemorySize - size of memory block to be allocated
+**/
+void* WSL_OS_Malloc( size_t aMemorySize );
+
+/**
+   Deallocate memory block
+   aBuffer - Pointer to memory to be freed
+**/
+void WSL_OS_Free( void* aBuffer );
+
+/* ------------ WIMI initialization and closing --------------------------- */
+
+/**
+   WIMI initialization request. 
+   WIMI should be initialized before WIM operations.
+   aCb parameter should point to the temporary structure 
+   which can be deallocated after function call
+**/
+WIMI_STAT WIMI_InitializeReq( WIMI_Callbacks_t* aCb );
+
+/**
+   WIMI close request.
+**/
+WIMI_STAT WIMI_CloseDownReq( void );
+
+/* ------------ Referencies ----------------------------------------------- */
+/**
+   Copy and dealloc references 
+   Creates a copy of reference. Function doesn't check reference validity.
+   Returns NULL in case of memory allocation failure.
+   aRef - reference to be copied
+**/
+WIMI_Ref_t* copy_WIMI_Ref_t( WIMI_Ref_t* aRef );
+
+/* Deallocates memory occupied by reference.
+   aRef - reference to be freed
+**/
+void free_WIMI_Ref_t( WIMI_Ref_t* aRef );
+
+/**
+   Creates a copy of reference list. Function doesn't check references
+   validity. Returns NULL in case of memory allocation failure.
+   aList - reference list to be copied
+**/
+WIMI_RefList_t copy_WIMI_RefList_t( WIMI_RefList_t aList );
+
+/**
+   Deallocates memory occupied by reference list.
+   aList - reference list to be freed
+**/
+void free_WIMI_RefList_t( WIMI_RefList_t aList );
+
+/* ------------ Digital signature ----------------------------------------- */
+/**
+   Digital signature request. Signed data is returned in callback.
+   aTrId    - transaction id. 
+              User application data that will be provided in respond callback
+              to match request/response.
+   aHash    - SHA1 hash of data to be signed.
+   aHashLen - length of hash
+   aKeyRef  - key reference which should be used for sign operaition.
+   aPin     - PIN code for the referenced key.
+**/
+WIMI_STAT WIMI_SignReq( WIMI_TransactId_t aTrId,
+                        TUint8* aHash,
+                        TUint8 aHashLen,
+                        WIMI_Ref_t* aKeyRef,
+                        WIMI_BinData_t* aPin );
+
+/* ------------ Label list ------------------------------------------------ */
+/**
+   Returns label list for specified reference list. 
+   All references in a list should be of one type.
+   Possible reference types are: PIN, KEY or Certificate.
+   aElNum   - IN  - number of elements
+   aRefList - IN  - list of references
+   aLabelList - OUT - string list. Should be freed by caller. 
+**/
+WIMI_STAT WIMI_GetLabelList( TUint8 aElNum,
+                             WIMI_RefList_t aRefList,
+                             WIMI_labellist_t* aLabelList );
+
+/* ------------ Key management -------------------------------------------- */
+/**
+   Returns key list for one WIM.
+   aWimRef  - IN  - WIM reference
+   aKeyNum  - OUT - number of returned keys
+   aRefList - OUT - key list. Should be freed by caller.
+**/
+WIMI_STAT WIMI_GetKeyListByWIM( WIMI_Ref_t* aWimRef,
+                                TUint16* aKeyNum,
+                                WIMI_RefList_t* aRefList );
+
+/**
+Returns key reference by given key hash. 
+   aHash   - IN  - SHA1 hash of the public key.
+   aKeyRef - OUT - Allocated key reference. Should be freed by caller.
+**/
+WIMI_STAT WIMI_GetKeyByHash( TUint8* aHash,
+                             WIMI_Ref_t** aKeyRef );
+
+/** 
+   Returns info for referenced key.
+   aKeyRef    - IN  - key reference
+   aWimRef    - OUT - reference to WIM where certificate reside. Freed by caller
+   aPin       - OUT - PIN code that protects key
+   aKeyType   - OUT - key type (1 = RSA, 2 = ECC)
+   aKeyNumber - OUT - the number of current key
+   aPinNumber - OUT - PIN number
+   aUsage     - OUT - PKCS15 key usage flags. See #defines in wimi_types.h 
+   aKeyId     - OUT - hash of public key. Should be deallocated by caller.
+   aLabel     - OUT - key label. Should be deallocated by caller
+   aKeyLength - OUT - key length in bits
+**/
+WIMI_STAT WIMI_GetKeyInfo( WIMI_Ref_t* aKeyRef,
+                           WIMI_Ref_t** aWimRef,
+                           WIMI_Ref_t** aPin,
+                           TUint8* aKeyType,
+                           TUint8* aKeyNumber,
+                           TUint8* aPinNumber,
+                           TUint16* aUsage,
+                           WIMI_BinData_t* aKeyId,
+                           WIMI_BinData_t* aLabel,
+                           TUint16* aKeyLength ); /* in bits */
+
+
+/* ------------ Certificate management ------------------------------------ */
+/**
+   Returns list of referencies to client certificates on all WIMs with
+   the same client key reference.
+   aKeyRef    - IN  - key reference
+   aCertCount - OUT - certificate number
+   aRefList   - OUT - allocated reference list. Should be freed by caller
+**/
+WIMI_STAT WIMI_GetClCertificateListByKey( WIMI_Ref_t* aKeyRef,
+                                          TUint8* aCertCount,
+                                          WIMI_RefList_t* aRefList );
+
+/**
+   Returns list of referencies to certificates on all WIMs with the same
+   public key (hash).
+   aHash      - IN  - key hash
+   aUsage     - IN  - certificate purpose (0 = client, 1 = CA)
+   aCertCount - OUT - certificate count
+   aRefList   - OUT - allocated reference list. Should be freed by caller
+**/
+WIMI_STAT WIMI_GetCertificateListByKeyHash( TUint8* aHash,
+                                            TUint8 aUsage,
+                                            TUint8* aCertCount,
+                                            WIMI_RefList_t* aRefList );
+
+/**
+   Returns list of referencies to certificates on all WIMs with the same
+   public key (hash).
+   aCAHash  - IN  - key hash
+   aUsage   - IN  - certificate purpose
+   aCertNum - OUT - certificate number
+   aRefList - OUT - allocated reference list. Should be freed by caller
+**/
+WIMI_STAT WIMI_GetCertificateListByCAKeyHash( TUint8* aCAHash,
+                                              TUint8 aUsage,
+                                              TUint8* aCertNum,
+                                              WIMI_RefList_t* aRefList );
+
+/**
+   Returns list of referencies to certificates on a WIM.
+   aWimRef  - IN  - WIM reference
+   aUsage   - IN  - Certificate usage (0 = client, 1 = CA)
+   aCertNum - OUT - certificate number
+   aRefList - OUT - allocated reference list. Should be freed by caller
+**/
+WIMI_STAT WIMI_GetCertificateListByWIM( WIMI_Ref_t* aWimRef,
+                                        TUint8 aUsage,
+                                        TUint8* aCertNum,
+                                        WIMI_RefList_t* aRefList );
+
+/**
+   Returns information about certificate stored in WIM 
+   aCert     - IN  - cert. reference.
+   aWimRef   - OUT - reference to WIM where cert is stored. Freed by caller
+   aLabel    - OUT - certificate label. pb_buf pointer in structure
+                 points to allocated buffer that should be deallocated by caller
+   aKeyId    - OUT - hash of public key. pb_buf pointer in WIMI_BinData_t struct
+                points to allocated buffer that should be deallocated by caller
+   aCAId     - OUT - hash of issuer public key. pb_buf pointer in WIMI_BinData_t
+       structure points to allocated buffer that should be deallocated by caller
+   aTrustedUsage - OUT - trusted usage OID's for this certificate
+   aCDFRefs  - OUT - information about the CDF that the certificate was
+                     referenced. Possible values: WIMLIB_CERTIFICATES_CDF,
+                     WIMLIB_TRUSTEDCERTS_CDF, WIMLIB_USEFULCERTS_CDF
+   aUsage    - OUT - 0 = client, 1 = CA
+   aType     - OUT - WTLSCert(1), X509Cert(2), X968Cert(3), CertURL(4)
+   aCertlen  - OUT - length of certificate content
+**/
+WIMI_STAT WIMI_GetCertificateInfo( WIMI_Ref_t* aCert,
+                                   WIMI_Ref_t** aWimRef,
+                                   WIMI_BinData_t* aLabel,
+                                   WIMI_BinData_t* aKeyID,
+                                   WIMI_BinData_t* aCAId,
+                                   WIMI_BinData_t* aIssuerNameHash,
+                                   WIMI_BinData_t* aTrustedUsage,
+                                   TUint8* aCDFRefs,
+                                   TUint8* aUsage,
+                                   TUint8* aType,
+                                   TUint16* aCertLen,
+                                   TUint8* aModifiable );
+
+/**
+   Requests certificate contents from WIM.
+   aTrId    - transaction id. 
+              User application data that will be provided in respond callback
+              to match request/response.
+   aCertRef - certificate reference 
+   aCert    - retrieved certificate
+**/
+WIMI_STAT WIMI_CertificateReqT( WIMI_TransactId_t aTrId,
+                                WIMI_Ref_t* aCertRef, 
+                                WIMI_BinData_t* aCert );
+
+/**
+   Requests certificate contents from WIM.
+   aTrId - transaction id. 
+          User application data that will be provided in respond callback
+          to match request/response.
+   aCertRef - certificate reference
+**/
+WIMI_STAT WIMI_CertificateReq( WIMI_TransactId_t aTrId,
+                               WIMI_Ref_t* aCertRef );
+
+/**
+   Requests certificate to be deleted from WIM.
+   aTrId    - transaction id. 
+              User application data that will be provided in respond callback
+              to match request/response.
+   aCertRef - certificate reference
+**/
+WIMI_STAT WIMI_CertificateDeleteReq( WIMI_TransactId_t aTrId, 
+                                     WIMI_Ref_t* aCertRef );
+/**
+   Requests certificate to be stored to WIM.
+   aTrId   - transaction id. 
+             User application data that will be provided in respond callback
+             to match request/response.
+   aWimRef - WIM reference where to store the certificate
+   aLabel  - certificate label
+   aKeyId  - hash of public key.
+   aCAId   - hash of issuer public key.
+   aIssuerNameHash  - Issuer name hash
+   aSubjectNameHash - Subject name hash
+   aUsage   - 0 = client, 1 = CA 
+   aType    - WTLSCert(1), X509Cert(2), X968Cert(3), CertURL(4)
+   aCertLen - certificate contents len
+   aCert    - certificate contents
+**/
+WIMI_STAT WIMI_CertificateStoreReq( WIMI_TransactId_t aTrId, 
+                                    WIMI_Ref_t* aWimRef,
+                                    WIMI_BinData_t* aLabel,
+                                    WIMI_BinData_t* aKeyId,
+                                    WIMI_BinData_t* aCAId,
+                                    WIMI_BinData_t* aIssuerNameHash,
+                                    WIMI_BinData_t* aSubjectNameHash,
+                                    TUint8 aUsage,
+                                    TUint8 aType,
+                                    TUint16 aCertLen,
+                                    TUint8* aCert ); 
+
+/* ------------ PIN management -------------------------------------------- */
+/**
+   Returns status of PIN
+   aPinRef    - IN  - PIN reference
+   aWimRef    - OUT - WIM reference. Should be freed by caller.
+   aFlags     - OUT - bitmask WIMI_PF_Enabled, WIMI_PF_ChangeDisabled,
+                      WIMI_PF_UnblockDisabled and WIMI_PF_DisableAllowed
+   minlength  - OUT - minimal PIN length
+   aPinNumber - OUT - the number of the pin
+   aLabel     - OUT - PIN label - Should be deallocated by caller.
+**/
+WIMI_STAT WIMI_GetPINStatus( WIMI_Ref_t* aPinRef,
+                             WIMI_Ref_t** aWimRef,  
+                             TUint8* aFlags,
+                             TUint8* aMinlength,
+                             TUint8* aPinNumber,
+                             WIMI_BinData_t* aLabel );
+
+/**
+   Returns Info of Authobj
+   pWIMref    -IN  WIM reference
+   authId     -IN  Authobj Id
+   pt_lable   -OUT 
+   flags      -OUT 
+   pinnumber  -OUT
+   minlength  -OUT
+   maxlength  -OUT
+   pinType    -OUT
+   storedlength -OUT
+   pinReference -OUT
+   padChar      -OUT
+**/                             
+WIMI_STAT WIMI_GetAuthObjInfo( WIMI_Ref_t* pWIMref,
+                              TUint32* authId,
+                              WIMI_BinData_t* pt_label,  
+                              TUint16* flags,
+                              TUint8* pinnumber,
+                              TUint8* minLength,
+                              TUint8* maxLength,
+                              TUint8* pinType,
+                              TUint8* storedLength,
+                              TUint8* pinReference,
+                              TUint8* padChar );                             
+
+/**
+   Returns the PINs list for one WIM. 
+   If aWimRef is NULL, then returns the list for all WIMs.
+   aWimRef  - IN  - WIMI reference
+   aPinNum  - OUT - number of PIN in list
+   aRefList - OUT - allocated PIN list. Should be freed by caller.
+**/
+WIMI_STAT WIMI_GetPINList( WIMI_Ref_t* aWimRef,
+                           TUint16* aPinNum,
+                           WIMI_RefList_t* aRefList );
+
+/**
+   PIN verify request. If WIM general PIN is given then WIM becomes open after 
+   successful verify operation 
+   aTrId   - transaction id. 
+             User application data that will be provided in respond callback to
+             match request/response.
+   aPinRrf - PIN reference
+   aPinLen - entered PIN length
+   aPin    - entered PIN data
+**/
+WIMI_STAT WIMI_VerifyPINReq( WIMI_TransactId_t aTrId,
+                             WIMI_Ref_t* aPinRef,          
+                             TUint8 aPinLen,
+                             TUint8* aPin );                            
+
+/**
+   PIN change request. 
+   aTrId      - transaction id. 
+                User application data that will be provided in respond callback
+                to match request/response.
+   aPinRef    - PIN reference
+   aOldPinLen - old PIN length
+   aOldPin    - old PIN for granting operation permission
+   aNewPinLen - new PIN length
+   aNewPin    - new PIN that should replace old
+**/
+WIMI_STAT WIMI_ChangePINReq( WIMI_TransactId_t aTrId,
+                             WIMI_Ref_t* aPinRef,          
+                             TUint8 aOldPinLen,
+                             TUint8* aOldPin,
+                             TUint8 aNewPinLen,
+                             TUint8* aNewPin ); 
+
+/**
+   PIN unblock request.
+   aTrId          - transaction id. 
+                    User application data that will be provided in respond
+                    callback to match request/response.
+   aPinRef        - PIN reference
+   aUnblockPinLen - length of unblocking code
+   aUnblockPin    - unblocking code
+   aNewPinLen     - new PIN length
+   aNewPin        - new PIN that should replace old after unblocking
+**/
+WIMI_STAT WIMI_UnblockPINReq( WIMI_TransactId_t aTrId,
+                              WIMI_Ref_t* aPinRef,          
+                              TUint8 aUnblockPinLen,
+                              TUint8* aUnblockPin,
+                              TUint8 aNewPinLen,
+                              TUint8* aNewPin ); 
+
+/**
+   Enable or disable PIN request.
+   aTrId   - transaction id. 
+             User application data that will be provided in respond callback
+             to match request/response.
+   aPinRef - PIN reference
+   aPinLen - PIN length
+   aPin    - PIN for granting operation permission
+   aEnable - if TRUE then enable else disable
+**/
+WIMI_STAT WIMI_EnablePINReq( WIMI_TransactId_t aTrId,
+                             WIMI_Ref_t* aPinRef,          
+                             TUint8 aPinLen,
+                             TUint8* aPin,
+                             TBool aEnable );
+
+/* ------------ Hardware driver support ----------------------------------- */
+/**
+   Returns WIM information.
+   aWimRef  - IN  - WIM reference.
+   aFlags   - OUT - reserved for future use
+   aSESet   - OUT - security environments bitset. See WIMI_SE_ constants
+   aWimId   - OUT - WIM serial number - pb_buf pointer in WIMI_BinData_t
+                    should be deallocated by caller 
+   aManufacturerId - OUT - manufacturer info - Should be
+                     deallocated by caller
+   aLabel   - OUT - WIM label - pb_buf pointer in WIMI_BinData_t structure
+                    should be deallocated by caller
+   aReader  - OUT - reader ID
+   aPinG    - OUT - reference to PIN-G
+   aSim     - OUT - if TRUE then WIM is SIM only
+   aVersion - OUT - version
+**/
+WIMI_STAT WIMI_GetWIMInfo( WIMI_Ref_t* aWimRef,
+                           TUint16* aFlags,
+                           TUint8* aSESet,
+                           WIMI_BinData_t* aWimId,
+                           WIMI_BinData_t* aManufacturerId,
+                           WIMI_BinData_t* aLabel,
+                           TUint8* aReader, 
+                           WIMI_Ref_t** aPinG,
+                           TBool* aSim,
+                           TUint8* aVersion);
+
+/**
+   Returns TRUE if WIM is already opened by general PIN 
+   aWimRef - WIM reference
+**/
+TUint8 WIMI_IsWIMOpened( WIMI_Ref_t* aWimRef );
+
+/**
+   Closes the WIM. WIM can be reopened with VerifyPIN operation.
+   aWimRef - WIM reference
+**/
+WIMI_STAT WIMI_CloseWIM( WIMI_Ref_t* aWimRef );
+
+/**
+   Returns the reference of WIM currently associated with reader. 
+   Returns valid reference if WIM card is inserted and initialized,
+   other case NULL.
+   aReader - reader number - 0-7
+**/
+WIMI_Ref_t* WIMI_GetWIMRef( TUint8 aReader );
+
+/**
+   Starts the initialization of newly inserted card.
+   aReader - reader number - 0-7
+**/
+WIMI_STAT WIMI_CardInsertedReq( TUint8 aReader );
+
+/**
+   Informs WIMI that card was removed from reader.
+   aReader - reader number - 0-7
+**/
+WIMI_STAT WIMI_CardRemoved( TUint8 aReader );
+
+/**
+   APDU respond from smartcard driver processing.
+   aReader - reader number - 0-7 
+   aStatus - WIMI_APDU_ codes
+   aAPDU   - received APDU
+   aSw     - status word for APDU codec support
+**/
+void WIMI_APDUResp( TUint8 aReader,
+                    TUint8 aStatus,
+                    WIMI_BinData_t* aAPDU,
+                    TUint16 aSw );
+
+/**
+   ATR respond from smartcard driver processing.
+   aReader - reader number - 0-7 
+   aStatus - WIMI_APDU_ codes
+   aATR    - ATR
+**/
+void WIMI_GetATRResp( TUint8 aReader,
+                      TUint8 aStatus,
+                      WIMI_BinData_t* aATR );
+
+/**
+   Respond for a reader list request.
+   aStatus - WIMI_APDU_ codes
+   aList - list of card reader statuses
+       Status =   0 \
+                    1  )  CardReaderIdentity 0-7
+                      2 /
+                      3     Card reader is not removable
+                      4     Card reader is present 
+                      5     Card reader is ID-1 size 
+                      6     Card is present in reader
+                      7     Card in reader is powered on
+**/
+void WIMI_GetReaderListResp( TUint8 aStatus,
+                             WIMI_BinData_t* aList );
+
+/**
+   Free memory
+   aMem - Pointer to memory area to be freed
+**/
+void WIMI_Free( void* aMem );
+
+/**
+   Respond to ReadSimFileReq
+   aReader - reader number
+   aStatus - error code for file reading
+   aData   - content of read file
+**/
+void WIMI_SIM_ReadFileResp( TUint8 aReader,
+                            TUint8 aStatus,
+                            WIMI_BinData_t* aData );
+
+/**
+   Return information of OMA Provisioning file on card
+   aWimRef    - IN  - WIM reference
+   aFileInfos - OUT - File info structure
+   aFileCount - OUT - Count of provisioning files
+**/
+WIMI_STAT WIMI_OMAFileInfo( WIMI_Ref_t* aWimRef,
+                            WIMI_File_Info** aFileInfos,
+                            TUint16* aFileCount );
+
+/**
+   Return information of Java Provisioning file on card
+   aWimRef    - IN  - WIM reference
+   aFileInfos - OUT - File info structure
+   aFileCount - OUT - Count of provisioning files
+**/
+WIMI_STAT WIMI_JAVAFileInfo( WIMI_Ref_t* aWIMref,
+                            WIMI_File_Info** aFileInfos,
+                            TUint16* aFileCount );
+/**
+   Get WIM count
+   aWimRef   - IN  - WIM reference.
+   aWimCount - OUT - count of WIMs
+**/
+WIMI_STAT WIMI_GetWIMCount( WIMI_Ref_t* aWimRef, TUint8* aWimCount );
+
+/**
+   Get content of OMA Provisioning file. Content is returned by callback.
+   aTrId     - IN - Transaction ID
+   aWimRef   - IN - WIM reference
+   aFileSize - IN - File size
+   aPath     - IN - File path
+**/
+WIMI_STAT WIMI_GetOMAFile( WIMI_TransactId_t aTrId,
+                           WIMI_Ref_t* aWimRef,
+                           TUint16 aFileSize,
+                           WIM_BIN_DATA* aPath );
+
+/**
+   Get content of OMA Provisioning file. Synchronous version.
+   aTrId        - IN  - Transaction ID
+   aWimRef      - IN  - WIM reference
+   aPath        - IN  - File path
+   aFileMaxSize - IN  - Not used
+   aFileContent - OUT - File content. Buffer allocated by WIMI, must be freed
+                        by caller.
+**/
+WIMI_STAT WIMI_GetOMAFileSync( WIMI_TransactId_t aTrId,
+                               WIMI_Ref_t* aWimRef,
+                               WIM_BIN_DATA* aPath,
+                               TUint16 aFileMaxSize,
+                               WIM_BIN_DATA* aFileContent );
+
+
+/**
+   Return content of JAVA Provisioning file on card
+   pWimRef            - IN  - WIM reference
+   pt_path            - IN  - File path
+   pt_file_content    - OUT 
+**/
+WIMI_STAT WIMI_GetJAVAFile(  WIMI_Ref_t* pWIMref,
+                             WIM_BIN_DATA* pt_path,
+                             WIM_BIN_DATA* pt_file_content );  
+
+
+/**
+   Return content of WIM label and path
+   pWimRef            - IN   - WIM reference
+   path               - OUT  - File path
+   label              - OUT 
+**/                             
+WIMI_STAT WIMI_GetLabelAndPath(WIMI_Ref_t* pWIMref,
+                               WIM_BIN_DATA* path,
+                               WIM_BIN_DATA* label );                                                          
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif      // WIMI_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/wim/rom/wim.iby	Tue Jan 26 15:20:08 2010 +0200
@@ -0,0 +1,42 @@
+/*
+* Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+
+#ifndef __WIM_IBY__
+#define __WIM_IBY__
+
+#include <bldvariant.hrh>
+
+FILE=ABI_DIR\BUILD_DIR\WIMCLIENT.DLL	SHARED_LIB_DIR\WIMCLIENT.DLL
+
+//WIM
+#if defined( __SIM_CERTIFICATES ) || defined( __SMART_CARD_PROV ) || defined( __WIM )
+FILE=ABI_DIR\BUILD_DIR\SWIMREADER.DLL	SHARED_LIB_DIR\SWIMREADER.DLL
+FILE=ABI_DIR\BUILD_DIR\SCARD.DLL	SHARED_LIB_DIR\SCARD.DLL
+FILE=ABI_DIR\BUILD_DIR\WIMSERVER.EXE	PROGRAMS_DIR\WIMSERVER.EXE
+FILE=ABI_DIR\BUILD_DIR\WIMUTIL.DLL	SHARED_LIB_DIR\WIMUTIL.DLL
+
+#if defined( __SIM_CERTIFICATES ) || defined( __WIM )
+
+ECOM_PLUGIN( WIMPLUGIN.DLL, 101FB674.rsc )
+
+
+#endif
+
+#endif //defined( __SIM_CERTIFICATES ) || defined( __SMART_CARD_PROV ) || defined( __WIM )
+#endif //__WIM_IBY__
+