Revision: 200951
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Thu, 07 Jan 2010 13:26:15 +0200
changeset 1 c9c2ad51f972
parent 0 33413c0669b9
child 2 ef893827b4d1
Revision: 200951 Kit: 201001
vpnengine/ikev2lib/inc/ikev2message.h
vpnengine/ikev2lib/inc/ikev2payloads.h
vpnengine/ikev2lib/src/ikev2message.cpp
vpnengine/ikev2lib/src/ikev2negotiation.cpp
vpnengine/pkiservice/group/PKIService.mmp
vpnengine/pkiservice/inc/PKIMapper.h
vpnengine/pkiservice/inc/mapdescriptor.h
vpnengine/pkiservice/inc/pkisupport.h
vpnengine/pkiservice/inc/pkiwrapper.h
vpnengine/pkiservice/src/mapdescriptor.cpp
vpnengine/pkiservice/src/pkimapper.cpp
vpnengine/pkiservice/src/pkiservice.cpp
vpnengine/pkiservice/src/pkisession.cpp
vpnengine/pkiservice/src/pkisupport.cpp
vpnengine/pkiservice/src/pkiwrapper.cpp
--- a/vpnengine/ikev2lib/inc/ikev2message.h	Thu Dec 17 09:14:51 2009 +0200
+++ b/vpnengine/ikev2lib/inc/ikev2message.h	Thu Jan 07 13:26:15 2010 +0200
@@ -307,7 +307,8 @@
      * A special method for adding a cookie notify in the
      * beginning of an existing ike message. 
      */
-    void PrependCookieNotifyPayloadL(const TDesC8& aCookieData);    
+    void PrependCookieNotifyPayloadL(TUint8 aProtocolId,
+                                     const TDesC8& aCookieData);    
     
     void AppendConfigurationPayloadL(TUint8 aCfgType, 
                                     const TDesC8& aConfigurationData);
--- a/vpnengine/ikev2lib/inc/ikev2payloads.h	Thu Dec 17 09:14:51 2009 +0200
+++ b/vpnengine/ikev2lib/inc/ikev2payloads.h	Thu Jan 07 13:26:15 2010 +0200
@@ -479,7 +479,7 @@
 	public:
 		static inline TNotifPayloadIkev2 *Cast(const TAny* aPayload) { return (TNotifPayloadIkev2 *)aPayload;}		
 		static inline TInt Size() { return sizeof(TNotifPayloadIkev2); }
-		inline TUint8 GetProtocolId() { return u.iData8[4]; };
+		inline TUint8 GetProtocolId() const { return u.iData8[4]; };
 		inline void SetProtocolId(TUint8 aProtId) { u.iData8[4] = aProtId; };
 		inline TUint8 GetSPISize() const { return u.iData8[5]; }
 		inline void SetSPISize(TUint8 aSpiSize) { u.iData8[5] = aSpiSize; }
--- a/vpnengine/ikev2lib/src/ikev2message.cpp	Thu Dec 17 09:14:51 2009 +0200
+++ b/vpnengine/ikev2lib/src/ikev2message.cpp	Thu Jan 07 13:26:15 2010 +0200
@@ -1022,10 +1022,10 @@
     AppendPayloadL(notifyPayload);
     }
 
-void CIkeV2Message::PrependCookieNotifyPayloadL(const TDesC8& aCookieData)
+void CIkeV2Message::PrependCookieNotifyPayloadL(TUint8 aProtocolId, const TDesC8& aCookieData)
     {
     _LIT8(KZeroDesc, "");
-    CIkeV2NotifyPayload* notifyPayload = CIkeV2NotifyPayload::NewL(0, KZeroDesc,
+    CIkeV2NotifyPayload* notifyPayload = CIkeV2NotifyPayload::NewL(aProtocolId, KZeroDesc,
                                                                    COOKIE, aCookieData);
     
     delete iIkeV2Datagram;
--- a/vpnengine/ikev2lib/src/ikev2negotiation.cpp	Thu Dec 17 09:14:51 2009 +0200
+++ b/vpnengine/ikev2lib/src/ikev2negotiation.cpp	Thu Jan 07 13:26:15 2010 +0200
@@ -3055,12 +3055,12 @@
         // Local end COOKIE usage has not been implemented yet
         //
 
-          //
-          // Init a new IKE message buffer and copy received COOKIE
-          // Notify to the first payload. Concatenate then all
-          // payloads from original IKE_SA_INIT request to this new
-          // IKE message (and set next payload field in Notify)
-          //
+            //
+            // Init a new IKE message buffer and copy received COOKIE
+            // Notify to the first payload. Concatenate then all
+            // payloads from original IKE_SA_INIT request to this new
+            // IKE message (and set next payload field in Notify)
+            //
             DEBUG_LOG1(_L("Cookie received, IKE_SA_INIT repeated: %d"), iState);
             if ( iCookieReturned )
             {	
@@ -3071,9 +3071,16 @@
                DEBUG_LOG(_L("Cookie already returned once, IKE_SA_INIT exchange stopped"));				   
                return EFalse;
             }		
+            
             CIkeV2Message* originalIkeSaInitRequest = iHdr.iLastRequest;            
+            
             const TPtrC8 cookieData(NotifyPayload->NotifData(), NotifyPayload->NotifDataLength());
-            originalIkeSaInitRequest->PrependCookieNotifyPayloadL(cookieData);
+            
+            // Use protocol id sent by gateway. RFC says id should be zero, but some GWs
+            // work against the spec.
+            TUint8 protocolId = NotifyPayload->GetProtocolId();
+            
+            originalIkeSaInitRequest->PrependCookieNotifyPayloadL(protocolId, cookieData);
             iHdr.iLastRequest = NULL; //claims the ownership of the message    
             
             SendIkeMsgL(originalIkeSaInitRequest);
--- a/vpnengine/pkiservice/group/PKIService.mmp	Thu Dec 17 09:14:51 2009 +0200
+++ b/vpnengine/pkiservice/group/PKIService.mmp	Thu Jan 07 13:26:15 2010 +0200
@@ -40,6 +40,7 @@
 SOURCE      logonservices.cpp
 SOURCE      keymanager.cpp
 SOURCE      keyoperationqueue.cpp
+SOURCE      mapdescriptor.cpp
 
 SOURCEPATH  ../../vpncommon/src
 SOURCE      srvstatic.cpp
@@ -71,5 +72,6 @@
 LIBRARY     random.lib
 LIBRARY     pbe.lib
 LIBRARY     eventmedapi.lib
+LIBRARY     ecom.lib 
 
 DEBUGLIBRARY flogger.lib 
--- a/vpnengine/pkiservice/inc/PKIMapper.h	Thu Dec 17 09:14:51 2009 +0200
+++ b/vpnengine/pkiservice/inc/PKIMapper.h	Thu Jan 07 13:26:15 2010 +0200
@@ -22,131 +22,10 @@
 #define __PKIMAPPER_H__
 
 #include <e32base.h>
-#include <securitydefs.h>
-
+#include "pkiserviceclientservercommon.h"
 #include "pkidefs.h"
-#include "pkiserviceclientservercommon.h"
-
-class TSecurityObjectDescriptor;
-class CX500DistinguishedName;
-class CX520AttributeTypeAndValue;
-
-enum TValidity
-{
-    EValid,
-    EExpired,
-    ENotValidYet
-};
-
-
-/**
- *  CMapDescriptor
- *
- *  Maintains information of installed certificates and keys
- *
- *  @lib internal (pkiservice.exe)
- *  @since S60 v3.0
- */
-class CMapDescriptor : public CBase
-{
-    public:
-        CMapDescriptor()
-                {
-                iOwnerType = EPKICACertificate;
-                iKeySize = 0;
-                iKeyAlgorithm = EPKIInvalidAlgorithm;
-                };
 
-        ~CMapDescriptor()
-            {
-            delete iTrustedAuthority;
-            iTrustedAuthority = NULL;
-            delete iIdentitySubjectName;
-            iIdentitySubjectName = NULL;
-            delete iIdentityRfc822Name;
-            iIdentityRfc822Name = NULL;
-            delete iSerialNumber;
-            iSerialNumber = NULL;
-            iApplUids.Close();
-            };
-        CMapDescriptor(TSecurityObjectDescriptor& aDesc);
-        CMapDescriptor& operator=(CMapDescriptor& aMapDesc);
-        void SetMapObjectName(const TDesC& aFilename) {iObjectName.Copy(aFilename);};
-        TBool IsMatchingL(TSecurityObjectDescriptor &aDesc, 
-                          const TBool aInfoOnly, 
-                          TPkiServiceStoreType aCertStoreType) const;
-                          
-        TBool IsEqual(CMapDescriptor &aDesc);
-        void SetMapSubjectKeyId(const TPKIKeyIdentifier &aKeyId)
-            {
-            iSubjectKeyId.Copy(aKeyId);
-            };
-        void SetMapOwnerType(const TPKICertificateOwnerType aOwnerType) {iOwnerType = aOwnerType;};        
-        void SetMapKeyUsageDer(const TDesC8 &aKeyUsage)
-            {
-            iKeyUsageDer.Copy(aKeyUsage);
-            };                          // Optional if only certificate is needed
-        // Key usage is not defined in the filter, this will be checked separately
-        void SetMapKeySize(const TUint aKeySize) {iKeySize = aKeySize;};                // Optional if only certificate is needed
-        // Issuer and serial are not defined in the filter, these will be checked separately
-        void SetMapTrustedAuthorityL(const TDesC8 &aTrustedAuthority)
-            {
-            delete iTrustedAuthority;
-            iTrustedAuthority = NULL;
-            iTrustedAuthority = aTrustedAuthority.AllocL();
-            };
-        void SetMapIdentitySubjectNameL(const TDesC8 &aIdentitySubjectName)
-            {
-            delete iIdentitySubjectName;
-            iIdentitySubjectName = NULL;
-            iIdentitySubjectName = aIdentitySubjectName.AllocL();
-            };
-        void SetMapIdentityRfc822NameL(const TDesC8 &aIdentityRfc822Name)
-            {
-            delete iIdentityRfc822Name;
-            iIdentityRfc822Name = NULL;
-            iIdentityRfc822Name = aIdentityRfc822Name.AllocL();
-            };
-        void SetMapSerialNumberL(const TDesC8 &aSerialNumber)
-            {
-            delete iSerialNumber;
-            iSerialNumber = NULL;
-            iSerialNumber = aSerialNumber.AllocL();
-            };
-
-        void SetCertStoreType(TPkiServiceStoreType aCertStoreType);
-
-        void SetMapKeyAlgorithm(const TPKIKeyAlgorithm &aKeyAlgorithm) {iKeyAlgorithm = aKeyAlgorithm;};
-        void SetMapStartTime(const TTime &aTime) {iStartTime = aTime;};
-        void SetMapEndTime(const TTime &aTime) {iEndTime = aTime;};
-        void SetMapTrusted(const TBool &aTrusted) {iIsTrusted = aTrusted;};
-        void SetMapIsDeletable(const TBool &aIsDeletable) {iIsDeletable = aIsDeletable;};
-		void SetMapApplications(const RArray<TUid> &aApplications) {for(TInt i=0; i<aApplications.Count();i++){ iApplUids.Append(aApplications[i]);}};
-        
-        TBool IsMatchingCertStore(const TDesC& aCertStoreName);
-
-    public: // data
-        // No get methods introduced, values are used directly!     
-        
-        /// Key or certificate: used internally, depends on the operation              
-        /// Own: Cert TrustedAuthority
-        HBufC8*                     iTrustedAuthority;          
-        HBufC8*                     iIdentitySubjectName;       // Identity subject name
-        HBufC8*                     iIdentityRfc822Name;        // Identity subjectAltName rfc822 name
-        HBufC8*                     iSerialNumber;              // Serialnumber
-        TPKIKeyIdentifier           iSubjectKeyId;              // SHA1 hash of the corresponding private key
-        TPKICertificateOwnerType    iOwnerType;                 // User, CA or peer. If user certificate, at least key usage must be set
-        TBuf8<KMaxUsageDer>         iKeyUsageDer;               // Der format flags
-        TBuf<SHORT_FILENAME_LENGTH> iObjectName;
-        TUint                       iKeySize;                   // Key size
-        TPKIKeyAlgorithm            iKeyAlgorithm;              // RSA, DSA
-        TTime                       iStartTime;
-        TTime                       iEndTime;
-        TBool                       iIsDeletable;              
-        TBool                       iIsTrusted;
-        RArray<TUid>                iApplUids;
-        TPkiServiceStoreType        iCertStoreType;
-};
+class CMapDescriptor;
 
 /**
  *  CPKIMapper
@@ -161,29 +40,30 @@
     public:
         // Constructors, destructor
         // When constructing an invocation, check if some key/certificate has been manually removed.
-        static CPKIMapper* NewL();
-        static TValidity CertValidity(const TTime &aStartTime, const TTime &aEndTime);
+        static CPKIMapper* NewL();        
         ~CPKIMapper();
         
-        ////////////////////////////////////////////////////////////////////////////////////////////
-        // Mapping methods
-        ////////////////////////////////////////////////////////////////////////////////////////////
-        // These are new methods, which will be called from ipsecmanager when importing policy or deleting a certificate/key
-        // In acuagent, these will be called after user key has been generated and authorized by CA
-        TInt AddMapping(CMapDescriptor &aMap);
-        TInt DeleteMapping(CMapDescriptor &aDesc);        
+        TInt AddMapping(CMapDescriptor* aMap);       
+        void DeleteMapping(TInt aIndex);
         CMapDescriptor& GetMapDescriptorAtIndex(TInt aIndex);
         // One-to-one mapping functions        
-        void GetCertificateKeyIdL(TSecurityObjectDescriptor &aDescriptor, TPKIKeyIdentifier &aKeyId,
+        void GetCertificateKeyIdL(TSecurityObjectDescriptor& aDescriptor, TPKIKeyIdentifier& aKeyId,
                                   TPkiServiceStoreType aStoreType = EPkiStoreTypeUser) const;
                                  
-        TInt ResolveCertMappingL(TSecurityObjectDescriptor &aDescriptor, TDes16 &aFilename, 
-                                TInt &aIndex, const TBool aInfoOnly, 
+        TInt ResolveCertMappingL(TSecurityObjectDescriptor& aDescriptor, TDes16& aFilename, 
+                                TInt &aIndex, TBool aInfoOnly, 
                                 TPkiServiceStoreType aStoreType = EPkiStoreTypeUser) const;
         
-        TInt CertCount(void);
+        TInt CertCount(TBool aInfoOnly);
 		TInt ApplicableCertCount(const RArray<TUid>& aUidArray);		
-        TInt GetCertListL(const RMessage2& aMessage, TPkiServiceStoreType aStoreType, TBool aDescUsed = EFalse);
+        TInt GetCertListL(const RMessage2& aMessage, TBool aInfoOnly);
+        
+        TInt GetCertDetailsL(TSecurityObjectDescriptor& aSecDesc, 
+                             TPkiServiceStoreType aStoreType, 
+                             TBool aInfoOnly,
+                             TCertificateListEntry& aResultCertInfo);
+
+        
 		void GetApplicableCertListL(const RMessage2& aMessage, const RArray<TUid>& aUidArray);               
         		    
         // Function to check whether the given certificate is unique (doesn't exist in cert store)
@@ -196,8 +76,7 @@
         TBool CacheCreated();        
     
     private: // implementation
-        
-        void DeleteMapping(TInt aIndex);        
+                        
         TBool LabelIsUnique(const TDesC& aLabel) const;
         void LogMap(CMapDescriptor& aDescriptor) const;
         void LogSearchArguments(TSecurityObjectDescriptor& aDescriptor) const;        
@@ -217,16 +96,5 @@
     	TBuf<MAX_FILENAME_LENGTH>           iObjectName;
 };
 
-class PkiUtil
-{
-    public:
-        static TBool MatchL(const CX500DistinguishedName& aDn1,
-                            const CX500DistinguishedName& aDn2);
 
-    private:    
-        static TBool HasElementL(const CX500DistinguishedName& aDn,
-                                 const CX520AttributeTypeAndValue& aElement);
-};
-
-
-#endif
\ No newline at end of file
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vpnengine/pkiservice/inc/mapdescriptor.h	Thu Jan 07 13:26:15 2010 +0200
@@ -0,0 +1,117 @@
+/*
+* 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: 
+* A data object for CPKIMapper class thar holds the information 
+* required to map API set to use the storage model which is not 
+* native for that API.
+*
+*/
+
+#ifndef C_MAPDESCRIPTOR_H
+#define C_MAPDESCRIPTOR_H
+
+#include <e32base.h>
+#include "pkidefs.h"
+
+class TSecurityObjectDescriptor;
+class CX500DistinguishedName;
+class CX520AttributeTypeAndValue;
+
+/**
+ *  CMapDescriptor
+ *
+ *  Maintains information of installed certificates and keys
+ *
+ *  @lib internal (pkiservice.exe)
+ *  @since S60 v3.0
+ */
+class CMapDescriptor : public CBase
+{
+public:
+    enum TValidity
+    {
+        EValid,
+        EExpired,
+        ENotValidYet
+    };
+                
+    static CMapDescriptor* NewL(const TDesC& aLabel,
+                                const CX509Certificate& aCertificate,
+                                TPKICertificateOwnerType aOwnerType,
+                                TPkiServiceStoreType aCertStoreType);  
+    
+    ~CMapDescriptor();
+       
+    TBool IsMatchingL(TSecurityObjectDescriptor &aDesc, 
+                      const TBool aInfoOnly, 
+                      TPkiServiceStoreType aCertStoreType) const;                  
+    TBool IsEqual(CMapDescriptor &aDesc);       
+    void SetMapDeletable(TBool aDeletable);
+    void SetMapTrusted(const TBool &aTrusted);
+    void SetMapApplications(const RArray<TUid> &aApplications);
+    
+    TPtrC Label() const;
+    const TPKIKeyIdentifier& CertificateKeyId() const;
+    TPKICertificateOwnerType OwnerType() const;
+    TUint KeySize() const;
+    TPtrC8 TrustedAuthority() const;
+    TPtrC8 IdentitySubjectName() const;
+    TPtrC8 SerialNumber() const;
+    TPKIKeyAlgorithm KeyAlgorithm() const;
+    TBool Deletable() const;
+    
+    TTime EndTime() const;
+    
+    TBool IsMatchingCertStore(const TDesC& aCertStoreName);           
+    TValidity CertValidity() const;
+
+    TBool IsApplicable(TUid aApplUid) const;
+    
+private:            
+    void ConstructL(const TDesC& aLabel,
+                    const CX509Certificate& aCertificate,
+                    TPKICertificateOwnerType aOwnerType,
+                    TPkiServiceStoreType aCertStoreType);  
+    
+    TBool MatchL(const CX500DistinguishedName& aDn1,
+                 const CX500DistinguishedName& aDn2) const;
+    
+    
+    TBool HasElementL(const CX500DistinguishedName& aDn,
+                      const CX520AttributeTypeAndValue& aElement) const;
+               
+    
+    TBuf<SHORT_FILENAME_LENGTH> iLabel;
+    TPkiServiceStoreType        iCertStoreType;
+    TPKICertificateOwnerType    iOwnerType;             
+    
+    HBufC8*                     iIssuerName;          
+    HBufC8*                     iSubjectName;       
+    HBufC8*                     iRfc822Name;        
+    HBufC8*                     iSerialNumber;      
+    
+    TPKIKeyIdentifier           iKeyId; 
+        
+    TUint                       iKeySize;                   
+    TPKIKeyAlgorithm            iKeyAlgorithm;              
+    TTime                       iStartTime;
+    TTime                       iEndTime;
+   
+    TBool                       iIsDeletable;              
+    TBool                       iIsTrusted;
+    RArray<TUid>                iApplUids;
+};
+
+
+#endif //C_MAPDESCRIPTOR_H
--- a/vpnengine/pkiservice/inc/pkisupport.h	Thu Dec 17 09:14:51 2009 +0200
+++ b/vpnengine/pkiservice/inc/pkisupport.h	Thu Jan 07 13:26:15 2010 +0200
@@ -94,17 +94,19 @@
             const TBool& aIsDeletable, TRequestStatus& aStatus);
         
         void AttachCertificateL(const TDesC &aLabel, 
-            const TPKIKeyIdentifier &aKeyId, 
             const TDesC8 &aBufferPtr, TRequestStatus& aStatus);
         
         void RetrieveCertificateL(const TDesC &aLabel, 
+            const TPKIKeyIdentifier& aCertificateKeyId,
             TPtr8 &aBufferPtr, const TPKICertificateOwnerType& aType, 
             TRequestStatus& aStatus);
                     
         void RemoveCertificateL(const TDesC &aLabel, 
+            const TPKIKeyIdentifier& aCertificateKeyId,
             TRequestStatus& aStatus);
                         
         void SelectCertificateL(const TDesC &aLabel, 
+                                const TPKIKeyIdentifier& aCertificateKeyId,
                                 const TPKICertificateOwnerType& aType = EPKICACertificate);
         
         // Asynchronous sertificate store request
@@ -114,13 +116,16 @@
         TInt GetRequiredBufferSize();
         void SetCallerStatusPending(TRequestStatus& aStatus);
         void CompleteCallerStatus(TInt aError);
-        void SetTrustL(
-            const TDesC &aLabel, TBool aTrusted, TRequestStatus& aStatus);
-        void TrustedL(const TDesC &aLabel, TRequestStatus& aStatus);
-        void SetApplicabilityL(
-            const TDesC &aLabel, const RArray<TUid>& aApplUids, 
-            TRequestStatus& Status);
-        void ApplicationsL(const TDesC &aLabel, TRequestStatus& Status);
+        void SetTrustL(const TDesC &aLabel, const TPKIKeyIdentifier& aCertificateKeyId,
+                       TBool aTrusted, TRequestStatus& aStatus);
+        void TrustedL(const TDesC &aLabel, const TPKIKeyIdentifier& aCertificateKeyId,
+                      TRequestStatus& aStatus);
+        void SetApplicabilityL(const TDesC &aLabel, 
+                               const TPKIKeyIdentifier& aCertificateKeyId, 
+                               const RArray<TUid>& aApplUids, 
+                               TRequestStatus& Status);
+        void ApplicationsL(const TDesC &aLabel, const TPKIKeyIdentifier& aCertificateKeyId,
+                           TRequestStatus& Status);
                     
         inline void SetCertStoreType(TPkiServiceStoreType aStoreType) 
             {
@@ -203,7 +208,7 @@
         TInt                        iCurrentFunction;
         TInitPhaseState             iInitState;
         TSubState                   iSubState;        
-        RMPointerArray<CCTCertInfo> *iCerts;
+        RMPointerArray<CCTCertInfo> iCerts;
         CCertAttributeFilter        *iCertFilter;        
         RMessage2                   iMessage;
         TKeyIdentifier              iKeyId;
@@ -211,7 +216,6 @@
         TBool                       iTrusted;
         RArray<TUid>                iApplUids;
         TInt                        iImportCounter;
-        CMapDescriptor              *iImportCertMapping;
         HBufC8                      *iImportCertData;
 		TBool						iToggleSwitch;		
 		
@@ -221,6 +225,5 @@
                 
         REventMediator              iEventMediator; // for logging
         HBufC8*                     iCertInfoForLogging;
-
 };
-#endif
\ No newline at end of file
+#endif
--- a/vpnengine/pkiservice/inc/pkiwrapper.h	Thu Dec 17 09:14:51 2009 +0200
+++ b/vpnengine/pkiservice/inc/pkiwrapper.h	Thu Jan 07 13:26:15 2010 +0200
@@ -40,7 +40,7 @@
         ////////////////////////////////////////////////////////////////////////////////////////////
         // Interface
         ////////////////////////////////////////////////////////////////////////////////////////////
-        TInt InitOperation(const RMessage2& aMessage);
+        void InitOperation(const RMessage2& aMessage);
         void CancelPendingOperation();
         TInt GetRequiredBufferSizeL(const RMessage2& aMessage);
         void CompleteRequestAndCleanupL();
@@ -54,10 +54,8 @@
         TPkiServiceStoreType CertStoreType() const;               
         
         void SetInformational(const TBool aInfoOnly);
+        TBool Informational() const;
         
-        static void SaveIdentityL(CMapDescriptor &aCertMapping, 
-                           const TDesC8& aCertDataIn,
-                           TCertificateOwnerType aOwner);
     private: // From CActive    
         void RunL();
         void DoCancel();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vpnengine/pkiservice/src/mapdescriptor.cpp	Thu Jan 07 13:26:15 2010 +0200
@@ -0,0 +1,562 @@
+/*
+* 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: 
+* A data object for CPKIMapper class thar holds the information 
+* required to map API set to use the storage model which is not 
+* native for that API.
+*
+*/
+#include <x509cert.h>
+#include <asymmetric.h>
+
+#include "mapdescriptor.h"
+#include "pkiserviceclientservercommon.h"
+#include "pkiserviceassert.h"
+#include "pkcs10.h"
+
+_LIT8(KEmptyDescriptor, "");
+
+CMapDescriptor* CMapDescriptor::NewL(const TDesC& aLabel,
+                                     const CX509Certificate& aCertificate,
+                                     TPKICertificateOwnerType aOwnerType,
+                                     TPkiServiceStoreType aCertStoreType)
+    {
+    CMapDescriptor* self = new (ELeave) CMapDescriptor;
+    CleanupStack::PushL(self);
+    self->ConstructL(aLabel, aCertificate,
+                     aOwnerType, aCertStoreType);
+    CleanupStack::Pop(self);
+    
+    return self;
+    }
+
+
+void CMapDescriptor::ConstructL(const TDesC& aLabel,
+                                const CX509Certificate& aCertificate,
+                                TPKICertificateOwnerType aOwnerType,
+                                TPkiServiceStoreType aCertStoreType)
+    {
+    iLabel = aLabel;
+    iCertStoreType = aCertStoreType;
+    iOwnerType = aOwnerType;
+
+
+    iIssuerName = aCertificate.DataElementEncoding(CX509Certificate::EIssuerName)->AllocL();
+    iSubjectName = aCertificate.DataElementEncoding(CX509Certificate::ESubjectName)->AllocL();    
+
+    // Copy rfc822 name from subjectAlt name    
+    const CX509CertExtension* subjAltName = aCertificate.Extension(KSubjectAltName);
+    if(subjAltName != NULL)
+        {
+        CX509AltNameExt* subjectAlt = CX509AltNameExt::NewLC(subjAltName->Data());
+        if(subjectAlt != NULL)
+            {
+            const CArrayPtrFlat<CX509GeneralName> *nameArray; 
+            nameArray = &subjectAlt->AltName();
+            // Search rfc822
+            for(TInt i = 0; i < nameArray->Count(); i++)
+                {
+                if(nameArray->At(i)->Tag() == EX509RFC822Name)
+                    {
+                    TPtrC8 data = nameArray->At(i)->Data();
+                    iRfc822Name = data.Right(data.Length() - 2).AllocL();
+                    break;
+                    }
+                }                            
+            }
+        CleanupStack::PopAndDestroy(subjectAlt);
+        }
+    
+    
+    
+    
+    // Serial number
+    const TPtrC8* serial = aCertificate.DataElementEncoding(CX509Certificate::ESerialNumber);
+    if(serial != NULL)
+        {
+        iSerialNumber = serial->AllocL();               
+        }
+    else
+        {
+        iSerialNumber = KEmptyDescriptor().AllocL();
+        }        
+    
+    // Validity period
+    iStartTime = aCertificate.ValidityPeriod().Start();
+    iEndTime = aCertificate.ValidityPeriod().Finish();    
+        
+    if (EPKICACertificate == iOwnerType)
+        {
+        iKeyId = aCertificate.SubjectKeyIdentifierL();
+        }
+    else
+        {
+        iKeyId = aCertificate.KeyIdentifierL();
+        }                
+    
+    const CSubjectPublicKeyInfo& publicKeyInfo = aCertificate.PublicKey();            
+    const TPtrC8 keyData = publicKeyInfo.KeyData();
+
+    TX509KeyFactory keyFactory;
+    switch(publicKeyInfo.AlgorithmId())
+        {
+        case ERSA:
+            {                        
+            iKeyAlgorithm = EPKIRSA;
+            const CRSAPublicKey* keyRSA = keyFactory.RSAPublicKeyL( keyData );
+            const TInteger&  n = keyRSA->N();
+            iKeySize = n.BitCount();
+            delete keyRSA;                    
+            }
+            break;          
+        case EDSA:
+            {                        
+            iKeyAlgorithm = EPKIDSA;
+            TPtrC8 params = publicKeyInfo.EncodedParams();
+            const CDSAPublicKey* keyDSA = keyFactory.DSAPublicKeyL( params, keyData );
+            const TInteger& y = keyDSA->Y();
+            iKeySize = y.BitCount();
+            delete keyDSA;
+            }
+            break;
+        default:
+            User::Leave(KErrNotSupported);
+            break;                    
+        }                    
+    
+    
+    }
+
+
+CMapDescriptor::~CMapDescriptor()
+    {
+    delete iIssuerName;
+    delete iSubjectName;
+    delete iRfc822Name;
+    delete iSerialNumber;
+    iApplUids.Close();
+    }
+
+TBool CMapDescriptor::IsMatchingL(TSecurityObjectDescriptor &aDesc, 
+                                  const TBool aInfoOnly, 
+                                  TPkiServiceStoreType aCertStoreType) const
+    {
+    TBool match(EFalse);
+
+    LOG(Log::Printf(_L("Matching")));
+    LOG_1(" Pure informational: %d", aInfoOnly);
+
+    LOG(Log::Printf(_L("Matching: certificate %S"), &iLabel));
+    for(;;)
+        {
+        if (aDesc.iOwnerType != EPKICACertificate &&
+            aCertStoreType != EPkiStoreTypeAny) 
+            {            
+            if (iCertStoreType != aCertStoreType)
+                {
+                LOG(Log::Printf(_L("    Store doesn't match, aborting")));
+                match = EFalse;
+                break;                
+                }
+            }
+        else 
+            {
+            LOG(Log::Printf(_L("Skipping store check, not relevant")));
+            }
+                    
+            
+        if (aDesc.iSubjectKeyIdUsed)
+            {            
+            if(iKeyId == aDesc.iSubjectKeyId)
+                {
+                match = ETrue;
+                }
+            else
+                {
+                match = EFalse;
+                break;
+                }
+            }
+            
+        if(aDesc.iTrustedAuthorityUsed)
+            {
+            if(iIssuerName == NULL)
+                {
+                match = EFalse;
+                break;
+                }
+            else
+                {
+                CX500DistinguishedName* dnSuffix1 = CX500DistinguishedName::NewLC(*iIssuerName);
+                CX500DistinguishedName* dnSuffix2;
+                TInt popCount = 3;
+
+                // ASN1 or plain text
+                if((aDesc.iTrustedAuthority[0] != 0x30)
+                   || ((aDesc.iTrustedAuthority[1] != 0x81)
+                   && (aDesc.iTrustedAuthority[1] != 0x82)
+                   && ((aDesc.iTrustedAuthority[1] + 2) != aDesc.iTrustedAuthority.Length())))
+                    {
+                    HBufC8* name2Der;
+                    CPkcs10Req::BuildDistinguishedNameDerFromTextL(name2Der,
+                                                                   aDesc.iTrustedAuthority,
+                                                                   EFalse, KNullDesC8);
+                    CleanupStack::PushL(name2Der);
+
+                    dnSuffix2 = CX500DistinguishedName::NewLC(*name2Der);
+                    }
+                else
+                    {
+                    dnSuffix2 = CX500DistinguishedName::NewLC(aDesc.iTrustedAuthority);
+                    popCount = 2;
+                    }
+
+
+                if(MatchL(*dnSuffix1, *dnSuffix2))
+                    {
+                    match = ETrue;
+                    CleanupStack::PopAndDestroy(popCount);
+                    }
+                else
+                    {
+                    match = EFalse;
+                    CleanupStack::PopAndDestroy(popCount);
+                    break;
+                    }
+                }
+            }
+        if(aDesc.iOwnerTypeUsed)
+            {
+            if(iOwnerType == aDesc.iOwnerType)
+                {
+                match = ETrue;
+                }
+            else
+                {
+                match = EFalse;
+                break;
+                }
+            }
+        if(aDesc.iSerialNumberUsed)
+            {
+            if ((iSerialNumber != NULL) && ((*iSerialNumber).Compare(aDesc.iSerialNumber) == 0))
+                {
+                match = ETrue;
+                }
+            else
+                {
+                match = EFalse;
+                break;
+                }
+            }
+
+        if(aDesc.iIdentitySubjectNameUsed)
+            {
+            if(iSubjectName == NULL)
+                {
+                match = EFalse;
+                break;
+                }
+            else
+                {
+                CX500DistinguishedName* dnSuffix1 = CX500DistinguishedName::NewLC(*iSubjectName);
+                CX500DistinguishedName* dnSuffix2;
+                TInt popCount = 3;
+                // ASN1 or plain text
+                if((aDesc.iIdentitySubjectName[0] != 0x30)
+                   || ((aDesc.iIdentitySubjectName[1] != 0x81)
+                   && (aDesc.iIdentitySubjectName[1] != 0x82)
+                   && ((aDesc.iIdentitySubjectName[1] + 2) != aDesc.iIdentitySubjectName.Length())))
+                    {
+                    HBufC8* name2Der;
+                    CPkcs10Req::BuildDistinguishedNameDerFromTextL(name2Der,
+                                                                   aDesc.iIdentitySubjectName,
+                                                                   EFalse, KNullDesC8);
+                    CleanupStack::PushL(name2Der);
+
+                    dnSuffix2 = CX500DistinguishedName::NewLC(*name2Der);
+                    }
+                else
+                    {
+                    dnSuffix2 = CX500DistinguishedName::NewLC(aDesc.iIdentitySubjectName);
+                    popCount = 2;
+                    }
+
+                if(MatchL(*dnSuffix1, *dnSuffix2))
+                    {
+                    CleanupStack::PopAndDestroy(popCount);
+                    match = ETrue;
+                    }
+                else
+                    {
+                    CleanupStack::PopAndDestroy(popCount);
+                    match = EFalse;
+                    break;
+                    }
+                }
+            }
+
+        if(aDesc.iIdentityRfc822NameUsed)
+            {
+            if(iRfc822Name == NULL)
+                {
+                match = EFalse;
+                break;
+                }
+            else
+                {
+                TInt bytes = aDesc.iIdentityRfc822Name.Length();
+                TPtrC8 tail = (*iRfc822Name).Right(bytes);
+                if (tail.CompareF(aDesc.iIdentityRfc822Name) == 0)
+                    {
+                    match = ETrue;
+                    }
+                else
+                    {
+                    match = EFalse;
+                    break;
+                    }
+                }
+            }
+            
+        if(aDesc.iKeySizeUsed)
+            {
+            if(iKeySize == aDesc.iKeySize)
+                {
+                match = ETrue;
+                }
+            else
+                {
+                match = EFalse;
+                break;
+                }
+            }
+            
+        if (match && !aInfoOnly)
+            {            
+            TValidity  val = CertValidity();
+            // Treat future certificates as valid
+            if((val == EValid) || (val == ENotValidYet))
+                {
+                match = ETrue;
+                }
+            else
+                {
+                LOG_("Matching: Expired, and not an informational request");
+                match = EFalse;
+                break;
+                }
+            }
+            
+        break;
+        }
+        
+    return match;
+    }
+
+TBool CMapDescriptor::IsEqual(CMapDescriptor &aDesc)
+    {
+    TBool match = EFalse;
+
+    for(;;)
+        {
+        if((iIssuerName != NULL) && 
+           (aDesc.iIssuerName != NULL) && 
+           (iIssuerName->Des().Compare(*aDesc.iIssuerName) == 0))
+            {
+            match = ETrue;
+            }
+        else
+            {
+            match = EFalse;
+            break;
+            }
+        
+        if((iSerialNumber != NULL) && (aDesc.iSerialNumber != NULL) && (iSerialNumber->Des().Compare(*aDesc.iSerialNumber) == 0))
+            {
+                match = ETrue;
+                }
+            else
+                {
+                match = EFalse;
+                break;
+                }
+            
+        break;
+        }
+
+    return match;
+    }
+    
+
+void CMapDescriptor::SetMapTrusted(const TBool &aTrusted) 
+    {
+    iIsTrusted = aTrusted;
+    }
+
+void CMapDescriptor::SetMapDeletable(TBool aDeletable)
+    {
+    iIsDeletable = aDeletable;
+    }
+
+void CMapDescriptor::SetMapApplications(const RArray<TUid> &aApplications) 
+    {
+    iApplUids.Close();
+    for(TInt i=0; i<aApplications.Count();i++)
+        { 
+        iApplUids.Append(aApplications[i]);
+        }
+    }
+
+TPtrC CMapDescriptor::Label() const
+    {
+    return iLabel;
+    }
+
+const TPKIKeyIdentifier& CMapDescriptor::CertificateKeyId() const
+    {    
+    return iKeyId;
+    }
+
+TUint CMapDescriptor::KeySize() const
+    {
+    return iKeySize;
+    }
+
+TPKICertificateOwnerType CMapDescriptor::OwnerType() const
+    {
+    return iOwnerType;
+    }
+
+TPtrC8 CMapDescriptor::TrustedAuthority() const
+    {
+    if (iIssuerName == NULL)
+        {
+        return KEmptyDescriptor();
+        }
+    else
+        {
+        return *iIssuerName;
+        }
+    }
+
+TPtrC8 CMapDescriptor::IdentitySubjectName() const
+    {
+    if (iSubjectName == NULL)
+        {
+        return KEmptyDescriptor();
+        }
+    else
+        {
+        return *iSubjectName;
+        }
+    }
+
+TPtrC8 CMapDescriptor::SerialNumber() const
+    {
+    if (iSerialNumber == NULL)
+        {
+        return KEmptyDescriptor();
+        }
+    else
+        {
+        return *iSerialNumber;
+        }
+    }
+
+TPKIKeyAlgorithm CMapDescriptor::KeyAlgorithm() const
+    {
+    return iKeyAlgorithm;
+    }
+
+TBool CMapDescriptor::Deletable() const
+    {
+    return iIsDeletable;
+    }
+
+TTime CMapDescriptor::EndTime() const
+    {
+    return iEndTime;
+    }
+
+CMapDescriptor::TValidity CMapDescriptor::CertValidity() const 
+    {
+    TTimeIntervalSeconds tolerance(120); 
+    TTime currentTime;
+    currentTime.UniversalTime();
+
+    if (iEndTime <= currentTime)
+        {
+        return EExpired;
+        }
+
+    if (iStartTime >= currentTime + tolerance)
+        {
+        return ENotValidYet;
+        }
+
+    return EValid;
+    }
+
+TBool CMapDescriptor::IsApplicable(TUid aApplUid) const
+    {
+    TBool isApplicable = EFalse;
+    for (TInt i = 0; i < iApplUids.Count(); ++i)
+        {
+        if (aApplUid == iApplUids[i])
+            {
+            isApplicable = ETrue;
+            break;
+            }
+        }
+    return isApplicable;
+    }
+
+TBool CMapDescriptor::MatchL(const CX500DistinguishedName& aDn1, const CX500DistinguishedName& aDn2) const
+{
+    if((aDn1.Count() == 0) || (aDn2.Count() == 0))
+        {
+        return EFalse;
+        }
+    
+    if (aDn1.Count() < aDn2.Count())
+        {
+        return EFalse;
+        }
+    else
+        {
+        // For each field in aDn2, aDn1 must contain a field with the same value
+        for (TInt i = 0; i < aDn2.Count(); i++)
+            {
+            if (!HasElementL(aDn1, aDn2.Element(i)))
+                {
+                return EFalse;
+                }
+            }
+        }
+
+    return ETrue;
+}
+
+TBool CMapDescriptor::HasElementL(const CX500DistinguishedName& aDn, const CX520AttributeTypeAndValue& aElement) const
+{
+    for (TInt i = 0; i < aDn.Count(); i++)
+        {
+        if (aElement.ExactMatchL(aDn.Element(i)))
+            {
+            return ETrue;
+            }
+        }
+    return EFalse;
+}
--- a/vpnengine/pkiservice/src/pkimapper.cpp	Thu Dec 17 09:14:51 2009 +0200
+++ b/vpnengine/pkiservice/src/pkimapper.cpp	Thu Jan 07 13:26:15 2010 +0200
@@ -17,347 +17,14 @@
 *
 */
 
-
-#include <x500dn.h>
 #include <x509cert.h>
 
 #include "PKIMapper.h"
-#include "pkcs10.h"
+#include "mapdescriptor.h"
 #include "log_r6.h"
 #include "pkiserviceassert.h"
 
 
-CMapDescriptor::CMapDescriptor(TSecurityObjectDescriptor &aDesc)
-    {
-    this->iSubjectKeyId = aDesc.iSubjectKeyId;
-    this->iOwnerType = aDesc.iOwnerType;
-    this->iKeySize = aDesc.iKeySize;            
-    this->iKeyAlgorithm = aDesc.iKeyAlgorithm;      
-    this->iIsDeletable = aDesc.iIsDeletable;      
-    }
-
-CMapDescriptor& CMapDescriptor::operator=(CMapDescriptor& aMapDesc)
-{
-    delete this->iTrustedAuthority;
-    this->iTrustedAuthority = NULL;
-    if(aMapDesc.iTrustedAuthority != NULL)
-        {
-        this->iTrustedAuthority     = aMapDesc.iTrustedAuthority->Des().AllocL();           // Cert TrustedAuthority
-        }
-    delete this->iIdentitySubjectName;
-    this->iIdentitySubjectName = NULL;
-    if(aMapDesc.iIdentitySubjectName != NULL)
-        {
-        this->iIdentitySubjectName  = aMapDesc.iIdentitySubjectName->Des().AllocL();        // Identity subject name
-        }
-    delete this->iIdentityRfc822Name;
-    this->iIdentityRfc822Name = NULL;
-    if(aMapDesc.iIdentityRfc822Name != NULL)
-        {
-        this->iIdentityRfc822Name   = aMapDesc.iIdentityRfc822Name->Des().AllocL();         // Identity subjectAltName rfc822 name
-        }
-    delete this->iSerialNumber;
-    this->iSerialNumber = NULL;
-    if(aMapDesc.iSerialNumber != NULL)
-        {
-        this->iSerialNumber         = aMapDesc.iSerialNumber->Des().AllocL();               // Serialnumber
-        }
-        
-    this->iSubjectKeyId         = aMapDesc.iSubjectKeyId;                               // SHA1 hash of the corresponding private key
-    this->iOwnerType            = aMapDesc.iOwnerType;                                  // User, CA or peer. If user certificate, at least key usage must be set
-    this->iKeyUsageDer          = aMapDesc.iKeyUsageDer;                                // Der format flags
-    this->iObjectName           = aMapDesc.iObjectName;
-    this->iKeySize              = aMapDesc.iKeySize;                                    // Key size
-    this->iKeyAlgorithm         = aMapDesc.iKeyAlgorithm;                               // RSA, DSA
-    this->iStartTime            = aMapDesc.iStartTime;
-    this->iEndTime              = aMapDesc.iEndTime;
-    this->iIsDeletable          = aMapDesc.iIsDeletable;
-    TInt i;
-    for(i=0;i<aMapDesc.iApplUids.Count();i++)
-        {
-        this->iApplUids.Append(aMapDesc.iApplUids[i]);
-        }
-        
-    this->iCertStoreType        = aMapDesc.iCertStoreType;
-    return *this;
-}
-
-
-TBool CMapDescriptor::IsMatchingL(TSecurityObjectDescriptor &aDesc, 
-                                  const TBool aInfoOnly, 
-                                  TPkiServiceStoreType aCertStoreType) const
-    {
-    TBool match(EFalse);
-
-    LOG(Log::Printf(_L("Matching")));
-    LOG_1(" Pure informational: %d", aInfoOnly);
-
-    LOG(Log::Printf(_L("Matching: certificate %S"), &iObjectName));
-    for(;;)
-        {
-        if (aDesc.iOwnerType != EPKICACertificate &&
-            aCertStoreType != EPkiStoreTypeAny) 
-            {            
-            if (iCertStoreType != aCertStoreType)
-                {
-                LOG(Log::Printf(_L("    Store doesn't match, aborting")));
-                match = EFalse;
-                break;                
-                }
-            }
-        else 
-            {
-            LOG(Log::Printf(_L("Skipping store check, not relevant")));
-            }
-                    
-			
-        if (aDesc.iSubjectKeyIdUsed)
-            {            
-			if(iSubjectKeyId == aDesc.iSubjectKeyId)
-				{
-				match = ETrue;
-				}
-			else
-				{
-				match = EFalse;
-				break;
-				}
-			}
-			
-        if(aDesc.iTrustedAuthorityUsed)
-            {
-            if(iTrustedAuthority == NULL)
-                {
-                match = EFalse;
-                break;
-                }
-            else
-                {
-                CX500DistinguishedName* dnSuffix1 = CX500DistinguishedName::NewLC(*iTrustedAuthority);
-                CX500DistinguishedName* dnSuffix2;
-                TInt popCount = 3;
-
-                // ASN1 or plain text
-                if((aDesc.iTrustedAuthority[0] != 0x30)
-                   || ((aDesc.iTrustedAuthority[1] != 0x81)
-                   && (aDesc.iTrustedAuthority[1] != 0x82)
-                   && ((aDesc.iTrustedAuthority[1] + 2) != aDesc.iTrustedAuthority.Length())))
-                    {
-                    HBufC8* name2Der;
-                    CPkcs10Req::BuildDistinguishedNameDerFromTextL(name2Der,
-                                                                   aDesc.iTrustedAuthority,
-                                                                   EFalse, KNullDesC8);
-                    CleanupStack::PushL(name2Der);
-
-                    dnSuffix2 = CX500DistinguishedName::NewLC(*name2Der);
-                    }
-                else
-                    {
-                    dnSuffix2 = CX500DistinguishedName::NewLC(aDesc.iTrustedAuthority);
-                    popCount = 2;
-                    }
-
-
-                if(PkiUtil::MatchL(*dnSuffix1, *dnSuffix2))
-                    {
-                    match = ETrue;
-                    CleanupStack::PopAndDestroy(popCount);
-                    }
-                else
-                    {
-                    match = EFalse;
-                    CleanupStack::PopAndDestroy(popCount);
-                    break;
-                    }
-                }
-            }
-        if(aDesc.iOwnerTypeUsed)
-            {
-            if(iOwnerType == aDesc.iOwnerType)
-                {
-                match = ETrue;
-                }
-            else
-                {
-                match = EFalse;
-                break;
-                }
-            }
-        if(aDesc.iSerialNumberUsed)
-            {
-            if ((iSerialNumber != NULL) && ((*iSerialNumber).Compare(aDesc.iSerialNumber) == 0))
-                {
-                match = ETrue;
-                }
-            else
-                {
-                match = EFalse;
-                break;
-                }
-            }
-
-        if(aDesc.iIdentitySubjectNameUsed)
-            {
-            if(iIdentitySubjectName == NULL)
-                {
-                match = EFalse;
-                break;
-                }
-            else
-                {
-                CX500DistinguishedName* dnSuffix1 = CX500DistinguishedName::NewLC(*iIdentitySubjectName);
-                CX500DistinguishedName* dnSuffix2;
-                TInt popCount = 3;
-                // ASN1 or plain text
-                if((aDesc.iIdentitySubjectName[0] != 0x30)
-                   || ((aDesc.iIdentitySubjectName[1] != 0x81)
-                   && (aDesc.iIdentitySubjectName[1] != 0x82)
-                   && ((aDesc.iIdentitySubjectName[1] + 2) != aDesc.iIdentitySubjectName.Length())))
-                    {
-                    HBufC8* name2Der;
-                    CPkcs10Req::BuildDistinguishedNameDerFromTextL(name2Der,
-                                                                   aDesc.iIdentitySubjectName,
-                                                                   EFalse, KNullDesC8);
-                    CleanupStack::PushL(name2Der);
-
-                    dnSuffix2 = CX500DistinguishedName::NewLC(*name2Der);
-                    }
-                else
-                    {
-                    dnSuffix2 = CX500DistinguishedName::NewLC(aDesc.iIdentitySubjectName);
-                    popCount = 2;
-                    }
-
-                if(PkiUtil::MatchL(*dnSuffix1, *dnSuffix2))
-                    {
-                    CleanupStack::PopAndDestroy(popCount);
-                    match = ETrue;
-                    }
-                else
-                    {
-                    CleanupStack::PopAndDestroy(popCount);
-                    match = EFalse;
-                    break;
-                    }
-                }
-            }
-
-        if(aDesc.iIdentityRfc822NameUsed)
-            {
-            if(iIdentityRfc822Name == NULL)
-                {
-                match = EFalse;
-                break;
-                }
-            else
-                {
-                TInt bytes = aDesc.iIdentityRfc822Name.Length();
-                TPtrC8 tail = (*iIdentityRfc822Name).Right(bytes);
-                if (tail.CompareF(aDesc.iIdentityRfc822Name) == 0)
-                    {
-                    match = ETrue;
-                    }
-                else
-                    {
-                    match = EFalse;
-                    break;
-                    }
-                }
-            }
-
-        if(aDesc.iKeyUsageUsed)
-            {
-            CX509KeyUsageExt* tempUsage = NULL;
-            if(iKeyUsageDer.Length() != 0)
-                {
-                tempUsage = CX509KeyUsageExt::NewL(iKeyUsageDer);
-                }
-            if((tempUsage == NULL) || tempUsage->IsSet(aDesc.iKeyUsage))       
-                {
-                delete tempUsage;
-                match = ETrue;
-                }
-            else
-                {
-                delete tempUsage;
-                match = EFalse;
-                break;
-                }
-            }
-            
-        if(aDesc.iKeySizeUsed)
-            {
-            if(iKeySize == aDesc.iKeySize)
-                {
-                match = ETrue;
-                }
-            else
-                {
-                match = EFalse;
-                break;
-                }
-            }
-            
-        if (match && !aInfoOnly)
-            {            
-            TValidity  val = CPKIMapper::CertValidity(iStartTime, iEndTime);
-            // Treat future certificates as valid
-            if((val == EValid) || (val == ENotValidYet))
-                {
-                match = ETrue;
-                }
-            else
-                {
-                LOG_("Matching: Expired, and not an informational request");
-                match = EFalse;
-                break;
-                }
-            }
-            
-        break;
-        }
-		
-    return match;
-    }
-
-TBool CMapDescriptor::IsEqual(CMapDescriptor &aDesc)
-    {
-    TBool match = EFalse;
-
-    for(;;)
-        {
-        if((iTrustedAuthority != NULL) && (aDesc.iTrustedAuthority != NULL) && (iTrustedAuthority->Des().Compare(*aDesc.iTrustedAuthority) == 0))
-            {
-            match = ETrue;
-            }
-        else
-            {
-            match = EFalse;
-            break;
-            }
-        
-        if((iSerialNumber != NULL) && (aDesc.iSerialNumber != NULL) && (iSerialNumber->Des().Compare(*aDesc.iSerialNumber) == 0))
-            {
-                match = ETrue;
-                }
-            else
-                {
-                match = EFalse;
-                break;
-                }
-            
-        break;
-        }
-
-    return match;
-    }
-    
-    
-void CMapDescriptor::SetCertStoreType(TPkiServiceStoreType aCertStoreType)
-    {
-    iCertStoreType = aCertStoreType;
-    }
-
 CPKIMapper* CPKIMapper::NewL()
     {
     CPKIMapper* self = new (ELeave) CPKIMapper();
@@ -397,19 +64,26 @@
     return iCacheCreated;
     }
     
-TInt CPKIMapper::AddMapping(CMapDescriptor& aMap)
+TInt CPKIMapper::AddMapping(CMapDescriptor* aMap)
     {
     // Insert as first element, so that newest object will be found first
-    return iMapping->Insert(&aMap, 0);
+    TInt err = iMapping->Insert(aMap, 0);
+    if (err != KErrNone)
+        {
+        delete aMap;
+        }
+    return err;
     }
 
 void CPKIMapper::LogMap(CMapDescriptor &aDescriptor) const 
     {
-    TInt len = aDescriptor.iSubjectKeyId.Length();
+    TPtrC objectName = aDescriptor.Label();
+    const TPKIKeyIdentifier& subjectKeyId = aDescriptor.CertificateKeyId();
+    
     LOG(Log::Printf(_L("====CertificateObject====\n")));
-    LOG(Log::Printf(_L("ObjectName: %S\n"), &(aDescriptor.iObjectName)));
+    LOG(Log::Printf(_L("ObjectName: %S\n"), &objectName));
     LOG(Log::Printf(_L("KeyId:")));
-    LOG(Log::HexDump(NULL, NULL, aDescriptor.iSubjectKeyId.Ptr(), len));
+    LOG(Log::HexDump(NULL, NULL, subjectKeyId.Ptr(), subjectKeyId.Length()));
     }
 
     
@@ -423,23 +97,7 @@
     iMapping->Compress();
     }
 
-TInt CPKIMapper::DeleteMapping(CMapDescriptor &aDesc)
-    {
-    TInt status(KErrNotFound);
-    
-    for(TInt i(0); i < iMapping->Count(); i++)
-        {
-        if((*iMapping)[i]->IsEqual(aDesc))
-            {
-            DeleteMapping(i);
-            status = KErrNone;
-            break;
-            }
-        }
-    return status;
-    }
-
-TInt CPKIMapper::CertCount()
+TInt CPKIMapper::CertCount(TBool aInfoOnly)
     {
     TInt count(0);    
     
@@ -447,7 +105,7 @@
         {
         CMapDescriptor* mapping = (*iMapping)[i];
         count++;
-        if (CertValidity(mapping->iStartTime, mapping->iEndTime) == EExpired)
+        if (!aInfoOnly && mapping->CertValidity() == CMapDescriptor::EExpired)
             {
             // do not count expider certificates
             count--;
@@ -459,65 +117,70 @@
 
 TInt CPKIMapper::ApplicableCertCount(const RArray<TUid>& aUidArray)
 {
-    TInt count(0);
-    TBool uidMatch(EFalse);
+    iCount = 0;
     
-    for(TInt i(0); i < iMapping->Count(); i++)
+    for(TInt i = 0; i < iMapping->Count(); i++)
         {
-        CMapDescriptor* mapping = (*iMapping)[i];
-        if(mapping->iOwnerType == EPKICACertificate)
+        const CMapDescriptor* mapping = (*iMapping)[i];
+        if(mapping->OwnerType() == EPKICACertificate)
             {
-            if(CertValidity(mapping->iStartTime, mapping->iEndTime) != EExpired)
+            if(mapping->CertValidity() != CMapDescriptor::EExpired)
                 {
-                uidMatch = EFalse;
-                for(TInt j = 0; j < mapping->iApplUids.Count(); j++)
+                for (TInt j = 0; j < aUidArray.Count(); ++j)
                     {
-                    for(TInt k = 0; k < aUidArray.Count(); k++)
+                    if (mapping->IsApplicable(aUidArray[j]))
                         {
-                        if(mapping->iApplUids[j].iUid == aUidArray[k].iUid)
-                            {
-                            uidMatch = ETrue;
-                            break;
-                            }
-                        }
-                    if(uidMatch)
-                        {
-                        count++;
+                        iCount++;
                         break;
                         }
                     }
                 }
             }
         }
-    iCount = count;
-    return count;
+                    
+    return iCount;
 }
 
+TInt CPKIMapper::GetCertDetailsL(TSecurityObjectDescriptor& aSecDesc, 
+                                 TPkiServiceStoreType aStoreType, 
+                                 TBool aInfoOnly,
+                                 TCertificateListEntry& aResultCertInfo)
+    {
+    TInt index;
+    TInt err;
+    
+    TRAPD(leave, err = ResolveCertMappingL(aSecDesc, iObjectName, 
+                                           index, aInfoOnly, 
+                                           aStoreType));
+    if (leave != KErrNone)
+        {
+        return leave; 
+        }
+    
+    if (err == KErrNone)
+        {        
+        const CMapDescriptor* mapping = (*iMapping)[index];        
+        aResultCertInfo.iObjectName = mapping->Label();
+        aResultCertInfo.iOwnerType = mapping->OwnerType();
+        aResultCertInfo.iTrustedAuthority = mapping->TrustedAuthority();
+        aResultCertInfo.iIdentitySubjectName = mapping->IdentitySubjectName();
+        aResultCertInfo.iSerialNumber = mapping->SerialNumber();
+        aResultCertInfo.iSubjectKeyId = mapping->CertificateKeyId();
+        aResultCertInfo.iKeySize = mapping->KeySize();                 
+        aResultCertInfo.iKeyAlgorithm = mapping->KeyAlgorithm();       
+        aResultCertInfo.iIsDeletable = mapping->Deletable();           
+        }
+    return err;    
+    }
 
-TInt CPKIMapper::GetCertListL(const RMessage2 &aMessage, TPkiServiceStoreType aStoreType, 
-                              TBool aDescUsed)
+
+TInt CPKIMapper::GetCertListL(const RMessage2 &aMessage, TBool aInfoOnly)
 {
     TInt pos = 0;
     TInt iLast = 0;
     TInt iFirst = 0;
-
-    if(aDescUsed)
-        {
-        aMessage.ReadL(1, iCurrentDescriptor);
-        TSecurityObjectDescriptor& secDesc = iCurrentDescriptor();
-        TInt status = ResolveCertMappingL(
-            iCurrentDescriptor(), iObjectName, iFirst, EFalse, aStoreType);
-        if(status == KErrNone)
-            {
-            iCount = 1;
-            iLast = iFirst + 1;
-            }
-        }
-    else
-        {
-        iLast = iMapping->Count();
-        }
     
+    iLast = iMapping->Count();
     CBufFlat* list = CBufFlat::NewL(sizeof(TCertificateListEntry));
     CleanupStack::PushL(list);
     list->ResizeL(iCount * sizeof(TCertificateListEntry));
@@ -526,26 +189,17 @@
     for(TInt i = iFirst; i < iLast; i++)
         {
         CMapDescriptor* mapping = (*iMapping)[i];
-        if(CertValidity(mapping->iStartTime, mapping->iEndTime) != EExpired)
+        if(aInfoOnly || mapping->CertValidity() != CMapDescriptor::EExpired)
             {
-            certInfo.iObjectName = mapping->iObjectName;
-            certInfo.iOwnerType = mapping->iOwnerType;
-            if(mapping->iTrustedAuthority != NULL)
-                {
-                certInfo.iTrustedAuthority = *(mapping->iTrustedAuthority);
-                }
-            if(mapping->iIdentitySubjectName != NULL)
-                {
-                certInfo.iIdentitySubjectName = *(mapping->iIdentitySubjectName);
-                }
-            if(mapping->iSerialNumber != NULL)
-                {
-                certInfo.iSerialNumber = *(mapping->iSerialNumber);
-                }
-            certInfo.iSubjectKeyId = mapping->iSubjectKeyId;
-            certInfo.iKeySize = mapping->iKeySize;                   // Key size
-            certInfo.iKeyAlgorithm = mapping->iKeyAlgorithm;         // RSA, DSA
-            certInfo.iIsDeletable = mapping->iIsDeletable;           // IsDeletable
+            certInfo.iObjectName = mapping->Label();
+            certInfo.iOwnerType = mapping->OwnerType();
+            certInfo.iTrustedAuthority = mapping->TrustedAuthority();
+            certInfo.iIdentitySubjectName = mapping->IdentitySubjectName();
+            certInfo.iSerialNumber = mapping->SerialNumber();
+            certInfo.iSubjectKeyId = mapping->CertificateKeyId();
+            certInfo.iKeySize = mapping->KeySize();                   // Key size
+            certInfo.iKeyAlgorithm = mapping->KeyAlgorithm();         // RSA, DSA
+            certInfo.iIsDeletable = mapping->Deletable();           // IsDeletable
 
             list->Write(pos * sizeof(TCertificateListEntry),
                         (TAny*)&certInfo,
@@ -567,8 +221,7 @@
 
 void CPKIMapper::GetApplicableCertListL(const RMessage2& aMessage, const RArray<TUid>& aUidArray)
 {
-    TBool uidMatch = EFalse;
-    TInt pos(0);
+    TInt pos = 0;
     
     CBufFlat* list = CBufFlat::NewL(sizeof(TCertificateListEntry));
     CleanupStack::PushL(list);
@@ -578,41 +231,23 @@
     for(TInt i = 0; (i < iMapping->Count()) && (pos < iCount); i++)
         {
         CMapDescriptor* mapping = (*iMapping)[i];
-        if(mapping->iOwnerType == EPKICACertificate)
+        if(mapping->OwnerType() == EPKICACertificate)
             {
-            if(CertValidity(mapping->iStartTime, mapping->iEndTime) != EExpired)
+            if(mapping->CertValidity() != CMapDescriptor::EExpired)
                 {
-                uidMatch = EFalse;
-                for(TInt j = 0; j < mapping->iApplUids.Count(); j++)
+                for(TInt j = 0; j < aUidArray.Count(); j++)
                     {
-                    for(TInt k = 0; k < aUidArray.Count(); k++)
-                        {
-                        if(mapping->iApplUids[j].iUid == aUidArray[k].iUid)
-                            {
-                            uidMatch = ETrue;
-                            break;
-                            }
-                        }
-                    if(uidMatch)
+                    if(mapping->IsApplicable(aUidArray[j]))
                         {
-                        certInfo.iObjectName = mapping->iObjectName;
-                        certInfo.iOwnerType = mapping->iOwnerType;
-                        if(mapping->iTrustedAuthority != NULL)
-                            {
-                            certInfo.iTrustedAuthority = *(mapping->iTrustedAuthority);
-                            }
-                        if(mapping->iIdentitySubjectName != NULL)
-                            {
-                            certInfo.iIdentitySubjectName = *(mapping->iIdentitySubjectName);
-                            }
-                        if(mapping->iSerialNumber != NULL)
-                            {
-                            certInfo.iSerialNumber = *(mapping->iSerialNumber);
-                            }
-                        certInfo.iSubjectKeyId = mapping->iSubjectKeyId;
-                        certInfo.iKeySize = mapping->iKeySize;                   // Key size
-                        certInfo.iKeyAlgorithm = mapping->iKeyAlgorithm;         // RSA, DSA
-                        certInfo.iIsDeletable = mapping->iIsDeletable;           // IsDeletable
+                        certInfo.iObjectName = mapping->Label();
+                        certInfo.iOwnerType = mapping->OwnerType();
+                        certInfo.iTrustedAuthority = mapping->TrustedAuthority();
+                        certInfo.iIdentitySubjectName = mapping->IdentitySubjectName();
+                        certInfo.iSerialNumber = mapping->SerialNumber();
+                        certInfo.iSubjectKeyId = mapping->CertificateKeyId();
+                        certInfo.iKeySize = mapping->KeySize();                   // Key size
+                        certInfo.iKeyAlgorithm = mapping->KeyAlgorithm();         // RSA, DSA
+                        certInfo.iIsDeletable = mapping->Deletable();           // IsDeletable
 
                         list->Write(pos * sizeof(TCertificateListEntry),
                                     (TAny*)&certInfo,
@@ -658,7 +293,7 @@
     
     if(status == KErrNone)
         {
-        aKeyId.Copy((*iMapping)[index]->iSubjectKeyId);
+        aKeyId.Copy((*iMapping)[index]->CertificateKeyId());
         }
     else
         {
@@ -676,7 +311,7 @@
     {
     for (TInt i(0); i < iMapping->Count(); i++) 
         {
-        if ((*iMapping)[i]->iObjectName.Compare(aLabel) == 0) 
+        if ((*iMapping)[i]->Label().Compare(aLabel) == 0) 
             {
             return EFalse;
             }
@@ -710,21 +345,21 @@
         CMapDescriptor* mapitem = (*iMapping)[i];
 
         //  Use subject name for uniqueness criterion
-        if (mapitem->iIdentitySubjectName)
+        if (mapitem->IdentitySubjectName().Length() > 0)
             {
-            if (subjectname->Compare(*(mapitem->iIdentitySubjectName)) == 0) 
+            if (subjectname->Compare(mapitem->IdentitySubjectName()) == 0) 
                 {
                 LOG(Log::Printf(_L("Found an existing cert that matches subject")));
-                if (issuername->Compare(*(mapitem->iTrustedAuthority)) == 0) 
+                if (issuername->Compare(mapitem->TrustedAuthority()) == 0) 
                     {
                     ret = EFalse;
                     break;
                     }
                 }
             }
-        else if (mapitem->iTrustedAuthority && (subjectname->Compare(*issuername) == 0))
+        else if (subjectname->Compare(*issuername) == 0)
             {
-            if (subjectname->Compare(*(mapitem->iTrustedAuthority)) == 0) 
+            if (subjectname->Compare(mapitem->TrustedAuthority()) == 0) 
                 {
                 LOG(Log::Printf(_L("Found an existing cert that matches subject (CA)")));
                 ret = EFalse;
@@ -814,11 +449,11 @@
             TBuf<12> buf;
             buf.Append(KMidp2Label);
             // Discard all MIDP2 certificates to avoid label-mapping problem
-            if (buf.Compare(mapping->iObjectName) != 0)
+            if (buf.Compare(mapping->Label()) != 0)
                 {
-                if(mapping->iEndTime > furthestEndTime)
+                if(mapping->EndTime() > furthestEndTime)
                     {
-                    furthestEndTime = mapping->iEndTime;
+                    furthestEndTime = mapping->EndTime();
                     foundIndex = i;
                     LOG(Log::Printf(_L("Resolve cert mapping: Tentatively found a suitable one")));
                     // Continue to search the longest lasting certificate
@@ -842,7 +477,7 @@
         status = KErrNone;
         if(status == KErrNone)
             {
-            aFilename.Append((*iMapping)[foundIndex]->iObjectName);
+            aFilename.Append((*iMapping)[foundIndex]->Label());
             status = KErrNone;
             aIndex = foundIndex;
             }
@@ -855,25 +490,6 @@
     }    
   
 
-TValidity CPKIMapper::CertValidity(const TTime &aStartTime,  const TTime &aEndTime) 
-    {
-    TTimeIntervalSeconds tolerance(120); 
-    TTime currentTime;
-    currentTime.UniversalTime();
-
-    if (aEndTime <= currentTime)
-        {
-        return EExpired;
-        }
-
-    if (aStartTime >= currentTime + tolerance)
-        {
-        return ENotValidYet;
-        }
-
-    return EValid;
-    }
-
 void CPKIMapper::LogSearchArguments(TSecurityObjectDescriptor &aDescriptor) const
     {
     TBuf<256> temp;
@@ -944,41 +560,3 @@
         }
     }   
 
-TBool PkiUtil::MatchL(const CX500DistinguishedName& aDn1, const CX500DistinguishedName& aDn2)
-{
-    if((aDn1.Count() == 0) || (aDn2.Count() == 0))
-        {
-        return EFalse;
-        }
-    
-    if (aDn1.Count() < aDn2.Count())
-        {
-        return EFalse;
-        }
-    else
-        {
-        // For each field in aDn2, aDn1 must contain a field with the same value
-        for (TInt i = 0; i < aDn2.Count(); i++)
-            {
-            if (!HasElementL(aDn1, aDn2.Element(i)))
-                {
-                return EFalse;
-                }
-            }
-        }
-
-    return ETrue;
-}
-
-TBool PkiUtil::HasElementL(const CX500DistinguishedName& aDn, const CX520AttributeTypeAndValue& aElement)
-{
-    for (TInt i = 0; i < aDn.Count(); i++)
-        {
-        if (aElement.ExactMatchL(aDn.Element(i)))
-            {
-            return ETrue;
-            }
-        }
-    return EFalse;
-}
-
--- a/vpnengine/pkiservice/src/pkiservice.cpp	Thu Dec 17 09:14:51 2009 +0200
+++ b/vpnengine/pkiservice/src/pkiservice.cpp	Thu Jan 07 13:26:15 2010 +0200
@@ -15,7 +15,7 @@
 *
 */
 
-
+#include <ecom/ecom.h>
 
 #include "pkiservice.h"
 #include "pkisession.h"
@@ -66,6 +66,8 @@
     delete iMapper;    
     delete iShutdown;
     delete iCertificateRequestStore;
+    
+    REComSession::FinalClose();
     }
 
 
@@ -123,7 +125,6 @@
     LOG_1("iSessionCount (%d)", iSessionCount);    
     PKISERVICE_ASSERT(iSessionCount >= 0);
     
-    
     if (iSessionCount == 0)
         {
         if (iStopImmediately)
--- a/vpnengine/pkiservice/src/pkisession.cpp	Thu Dec 17 09:14:51 2009 +0200
+++ b/vpnengine/pkiservice/src/pkisession.cpp	Thu Jan 07 13:26:15 2010 +0200
@@ -94,7 +94,7 @@
         {                            
         case PkiService::ECancelPendingOperation:
             iWrapper->CancelPendingOperation();
-            aMessage.Complete(Status);
+            aMessage.Complete(KErrNone);
             break;
         
         case PkiService::EGetRequiredBufferSize:
@@ -111,8 +111,8 @@
             break;
 
         case PkiService::ECertCount:        
-            count = iMapper.CertCount();
-            aMessage.Complete(count);          // Status <==> count
+            count = iMapper.CertCount(iWrapper->Informational());
+            aMessage.Complete(count);
             break;
             
         case PkiService::EApplicableCertCount:
@@ -141,15 +141,30 @@
     		CleanupStack::PopAndDestroy(1);     // list
     		
     		TInt matchCount = iMapper.ApplicableCertCount(iUidArray);
-    		aMessage.Complete(matchCount);          // Status <==> count
+    		aMessage.Complete(matchCount); 
     		}
     		break;
        case PkiService::EGetCertDetails:
-		    Status = iMapper.GetCertListL(aMessage, iWrapper->CertStoreType(), ETrue);
+            {
+            TPckgBuf<TSecurityObjectDescriptor> secDescPtr;
+            aMessage.ReadL(1, secDescPtr);
+            TCertificateListEntry* resultCertInfo = new (ELeave) TCertificateListEntry;
+            CleanupStack::PushL(resultCertInfo);            
+            Status = iMapper.GetCertDetailsL(secDescPtr(), 
+                                             iWrapper->CertStoreType(), 
+                                             iWrapper->Informational(),
+                                             *resultCertInfo);
+		    if (Status == KErrNone)
+		        {
+		        TPckg<TCertificateListEntry> certDetailsPtr(*resultCertInfo);
+	            aMessage.WriteL(0, certDetailsPtr);
+		        }
 		    aMessage.Complete(Status);
+		    CleanupStack::PopAndDestroy(resultCertInfo);            
+            }
 		    break;
         case PkiService::EGetCertList:
-		    iMapper.GetCertListL(aMessage, iWrapper->CertStoreType());
+		    iMapper.GetCertListL(aMessage, iWrapper->Informational());
 		    aMessage.Complete(KErrNone);
 		    break;
 
@@ -185,7 +200,7 @@
     		
         case PkiService::ECertReqCount:                    
             count = iServer.CertificateRequestStore().CertReqCountL();
-            aMessage.Complete(count);          // Status <==> count
+            aMessage.Complete(count); 
             break;    		
     		
         case PkiService::EGetCertReqList:
@@ -331,7 +346,7 @@
             }
             break;
             
-        case PkiService::EInitialize://falls through    		
+        case PkiService::EInitialize://falls through
         case PkiService::EKeyCount: //falls through    		                
         case PkiService::EGetKeyDetails: //falls through    		
         case PkiService::EDecrypt: //falls through    		
@@ -349,7 +364,7 @@
             break;  
         default:      
             iRequiredBufferSize = KBufferSizeNotDefined;
-            Status = iWrapper->InitOperation(aMessage);
+            iWrapper->InitOperation(aMessage);
             break;
         }
     }
--- a/vpnengine/pkiservice/src/pkisupport.cpp	Thu Dec 17 09:14:51 2009 +0200
+++ b/vpnengine/pkiservice/src/pkisupport.cpp	Thu Jan 07 13:26:15 2010 +0200
@@ -29,6 +29,7 @@
 
 #include "pkiwrapper.h"
 #include "PKIMapper.h"
+#include "mapdescriptor.h"
 #include "pkisupport.h"
 #include "pkisession.h"
 #include "log_r6.h"
@@ -62,16 +63,11 @@
     LOG_("CPKISupport::~CPKISupport");
     Cancel();    
 
-    if(iCerts != NULL)
-        {
-        iCerts->Close();
-        delete iCerts;
-        }
+    iCerts.Close();
     delete iCertFilter;
     delete iCertStore;
     iFSession.Close();
     iApplUids.Close();
-    delete iImportCertMapping;
     delete iImportCertData;
     iEventMediator.Close();
     delete iCertInfoForLogging; 
@@ -100,9 +96,7 @@
     {
     LOG_("-> CPKISupport::StartInitialize()");
     User::LeaveIfError(iFSession.Connect());
-    iCertStore = CUnifiedCertStore::NewL(iFSession, ETrue);
-    PKISERVICE_ASSERT(!iCerts);
-    iCerts = new (ELeave) RMPointerArray<CCTCertInfo>;
+    iCertStore = CUnifiedCertStore::NewL(iFSession, ETrue);    
     
     iMessage = aMessage;
     iCallerStatus = NULL;
@@ -215,41 +209,23 @@
 void  CPKISupport::ReadNextCertForImportL()
 {
     LOG_("-> CPKISupport::ImportNextCertL()");
-    PKISERVICE_ASSERT(iImportCounter < iCerts->Count());
+    PKISERVICE_ASSERT(iImportCounter < iCerts.Count());
     
     if(iImportCounter == 0)
         {
-        LOG_1("Import %d certificates\n", iCerts->Count());
+        LOG_1("Import %d certificates\n", iCerts.Count());
         }
         
     LOG_1("Import certificate:%d", iImportCounter);
-    LOG_1("Label: %S", &((*iCerts)[iImportCounter]->Label()));
-    
-    PKISERVICE_ASSERT((*iCerts)[iImportCounter]->CertificateFormat() == EX509Certificate);
-
-    TSecurityObjectDescriptor descriptor;    
-    descriptor.SetSubjectKeyId(
-        (*iCerts)[iImportCounter]->SubjectKeyId());
-    descriptor.SetOwnerType(
-        (TPKICertificateOwnerType)(*iCerts)[iImportCounter]->
-        CertificateOwnerType());
-	descriptor.SetIsDeletable(
-	    (*iCerts)[iImportCounter]->IsDeletable());
-      
-    delete iImportCertMapping;
-    iImportCertMapping = NULL;
-    iImportCertMapping = new (ELeave) CMapDescriptor(descriptor);
-            
-    iImportCertMapping->SetMapObjectName((*iCerts)[iImportCounter]->Label());
-    
+    LOG_1("Label: %S", &(iCerts[iImportCounter]->Label()));
+        
     delete iImportCertData;
     iImportCertData = NULL;
-    iImportCertData = HBufC8::NewL((*iCerts)[iImportCounter]->Size());        
+    iImportCertData = HBufC8::NewL(iCerts[iImportCounter]->Size());        
     iImportCertDataPtr.Set(iImportCertData->Des());
-    
-    LOG_(" Values set OK, retrieving");
+        
     iCertStore->Retrieve(
-        *(*iCerts)[iImportCounter], iImportCertDataPtr, iStatus);
+        *(iCerts[iImportCounter]), iImportCertDataPtr, iStatus);
     iPending = ECertRetrieve;
     SetActive();
     LOG_("<- CPKISupport::ImportCTFCertsL() SetActive() and ret: EFalse");
@@ -261,114 +237,76 @@
 //
 void CPKISupport::SaveCertInfoToCacheL()
     {
-    if((iImportCertMapping != NULL) && (iImportCertData != NULL))
+    LOG_("Saving cert info to cache");
+    PKISERVICE_ASSERT(iImportCertData != NULL);
+    
+    CX509Certificate* certificate = CX509Certificate::NewLC(iImportCertDataPtr);       
+    const CCTCertInfo* currentCertInfo = iCerts[iImportCounter]; 
+    TPkiServiceStoreType storeType = EPkiStoreTypeAny;
+    switch(currentCertInfo->Token().TokenType().Type().iUid)
         {
-        LOG_("Saving cert info to cache");
-       
-        CX509Certificate* certificate = CX509Certificate::NewLC(iImportCertDataPtr);            
-        const CSubjectPublicKeyInfo& publicKeyInfo = certificate->PublicKey();            
-        const TPtrC8 keyData = publicKeyInfo.KeyData();
-
-        TX509KeyFactory keyFactory;
-        switch(publicKeyInfo.AlgorithmId())
-            {
-            case ERSA:
-                {                        
-                iImportCertMapping->iKeyAlgorithm = EPKIRSA;
-                const CRSAPublicKey* keyRSA = keyFactory.RSAPublicKeyL( keyData );
-                const TInteger&  n = keyRSA->N();
-                iImportCertMapping->iKeySize = n.BitCount();
-                delete keyRSA;                    
-                }
-                break;        	
-            case EDSA:
-                {                        
-                iImportCertMapping->iKeyAlgorithm = EPKIDSA;
-                TPtrC8 params = publicKeyInfo.EncodedParams();
-                const CDSAPublicKey* keyDSA = keyFactory.DSAPublicKeyL( params, keyData );
-                const TInteger& y = keyDSA->Y();
-                iImportCertMapping->iKeySize = y.BitCount();
-                delete keyDSA;
-                }
-                break;
-            default:
-                iImportCertMapping->iKeyAlgorithm = EPKIInvalidAlgorithm;
-                break;                    
-            }                    
-        CleanupStack::PopAndDestroy(certificate);                        
-
-        iWrapper.SaveIdentityL(*iImportCertMapping,
-                               iImportCertDataPtr,
-                               ((*iCerts)[iImportCounter])->CertificateOwnerType());
-
-        TInt storeType = (*iCerts)[iImportCounter]->Token().TokenType().Type().iUid;
-        if ( storeType == STORETYPE_DEVICE_CERT_ID )
-            {
-            iImportCertMapping->SetCertStoreType(EPkiStoreTypeDevice);
-            }
-        else if ( storeType == STORETYPE_USER_CERT_ID )
-            {
-            iImportCertMapping->SetCertStoreType(EPkiStoreTypeUser);
-            }
-        else
-            {
-            iImportCertMapping->SetCertStoreType(EPkiStoreTypeAny);
-            }
+        case STORETYPE_DEVICE_CERT_ID:
+            storeType = EPkiStoreTypeDevice;
+            break;
+        case STORETYPE_USER_CERT_ID:
+            storeType = EPkiStoreTypeUser;
+            break;
+        default:
+            storeType = EPkiStoreTypeAny;
+            break;
+        }
+    
+    CMapDescriptor* newMapping = CMapDescriptor::NewL(currentCertInfo->Label(),
+                                                      *certificate,
+                                                      (TPKICertificateOwnerType)currentCertInfo->CertificateOwnerType(),
+                                                      storeType);  
+    CleanupStack::PushL(newMapping);
+    
+    newMapping->SetMapDeletable(currentCertInfo->IsDeletable());
+    newMapping->SetMapApplications(iApplUids);
+    iApplUids.Reset();
+    User::LeaveIfError(iMapper.AddMapping(newMapping));
             
-		for(TInt i=0;i<iApplUids.Count();i++)
-			{
-			iImportCertMapping->iApplUids.Append(iApplUids[i]);
-			}
-        User::LeaveIfError( 
-            iMapper.AddMapping(*iImportCertMapping) );
-
-        iApplUids.Close();            
-            
-        iImportCertMapping = NULL;    
-        iImportCounter++;
-        }    
+    CleanupStack::Pop(newMapping);
+    CleanupStack::PopAndDestroy(certificate);
+    iImportCounter++;    
     }
 
 // ---------------------------------------------------------------------------
 // GetApplicationsOfCTFCertL
 // ---------------------------------------------------------------------------
 //
-TBool  CPKISupport::GetApplicationsOfCTFCertL()
+TBool CPKISupport::GetApplicationsOfCTFCertL()
 {
     LOG_("-> CPKISupport::GetApplicationsOfCTFCertL()");
-	if((iImportCertMapping != NULL) && (iImportCertData != NULL))
-		{
-		if(iToggleSwitch == EFalse)
-			{
-			if((*iCerts)[iImportCounter]->CertificateOwnerType() == ECACertificate)
-				{
-				PKISERVICE_ASSERT(iApplUids.Count() == 0);
-				
-				iToggleSwitch = ETrue;
-				// Get applications				
-				iCertStore->Applications(*(*iCerts)[iImportCounter], iApplUids, iStatus);
-				iPending = EApplications;
-                LOG_("<- CPKISupport::GetApplicationsOfCTFCertL() SetActive(), ret: ETrue");
-				SetActive();
-				return ETrue;
-				}
-			else
-				{
-                LOG_("<- CPKISupport::GetApplicationsOfCTFCertL() Not a CA cert, ret: EFalse");
-				return EFalse;
-				}
-			}
-		else
-			{
-            LOG_("<- CPKISupport::GetApplicationsOfCTFCertL() iToggleSwitch == ETrue, ret: EFalse");
-			iToggleSwitch = EFalse;
-			return EFalse;
-			}
-		}
-	else
-		{
-		return EFalse;
-		}
+    PKISERVICE_ASSERT(iImportCertData != NULL);
+    
+    if(iToggleSwitch == EFalse)
+        {
+        if(iCerts[iImportCounter]->CertificateOwnerType() == ECACertificate)
+            {
+            PKISERVICE_ASSERT(iApplUids.Count() == 0);
+            
+            iToggleSwitch = ETrue;
+            // Get applications				
+            iCertStore->Applications(*(iCerts[iImportCounter]), iApplUids, iStatus);
+            iPending = EApplications;
+            LOG_("<- CPKISupport::GetApplicationsOfCTFCertL() SetActive(), ret: ETrue");
+            SetActive();
+            return ETrue;
+            }
+        else
+            {
+            LOG_("<- CPKISupport::GetApplicationsOfCTFCertL() Not a CA cert, ret: EFalse");
+            return EFalse;
+            }
+        }
+    else
+        {
+        LOG_("<- CPKISupport::GetApplicationsOfCTFCertL() iToggleSwitch == ETrue, ret: EFalse");
+        iToggleSwitch = EFalse;
+        return EFalse;
+        }
 }
 
 
@@ -635,7 +573,7 @@
     MCTWritableCertStore* certStore(NULL);
 
     CX509Certificate* tempCert = CX509Certificate::NewLC(aBufferPtr);
-    iKeyId = tempCert->KeyIdentifierL();
+    iKeyId = tempCert->SubjectKeyIdentifierL();
     CleanupStack::PopAndDestroy();
 
     if(aOwnerType == EUserCertificate)
@@ -720,7 +658,7 @@
 // ---------------------------------------------------------------------------
 //
 void CPKISupport::AttachCertificateL(const TDesC& aLabel, 
-    const TPKIKeyIdentifier &aKeyId, const TDesC8 &aBufferPtr, 
+    const TDesC8 &aBufferPtr, 
     TRequestStatus& aStatus)
 {
     TKeyIdentifier tempKeyId;
@@ -728,18 +666,10 @@
 
     LOG_("Attach certificate");
     
-    iSupportStatus = KErrNone;
-    iKeyId = aKeyId;
-    
-    ExtractCertInfoL(aLabel, EUserCertificate, aBufferPtr);
+    iSupportStatus = KErrNone;   
     
-    // fetch the keyId from the certificate
-    tempKeyId = certificate->KeyIdentifierL();
-    // If given keyId is empty, use the keyId from the certificate
-    if(iKeyId.Length() == 0)
-        {
-        iKeyId = tempKeyId;
-        }
+    ExtractCertInfoL(aLabel, EUserCertificate, aBufferPtr);    
+    iKeyId = certificate->SubjectKeyIdentifierL();
         
     SetCallerStatusPending( aStatus );
     CleanupStack::PopAndDestroy(certificate);    // certificate
@@ -781,7 +711,7 @@
     certStore->Add(aLabel, 
                    EX509Certificate, 
                    EUserCertificate, 
-                   &iKeyId, 
+                   NULL, 
                    NULL, 
                    aBufferPtr, 
                    iStatus);
@@ -795,16 +725,17 @@
 // ---------------------------------------------------------------------------
 //
 void CPKISupport::RetrieveCertificateL(const TDesC &aLabel, 
+    const TPKIKeyIdentifier& aCertificateKeyId,
     TPtr8 &aBufferPtr, const TPKICertificateOwnerType& aType, 
     TRequestStatus& aStatus)
 {
     LOG(Log::Printf(_L("Retrieve certificate\n")));
     iSupportStatus = KErrNone;
-    iCerts->Close();
+    iCerts.Close();
     iSubState = ESSContinue;
     iOutBufferPtr = &aBufferPtr;
     SetCallerStatusPending( aStatus );
-    SelectCertificateL(aLabel, aType);
+    SelectCertificateL(aLabel, aCertificateKeyId, aType);
 }
 
 // ---------------------------------------------------------------------------
@@ -816,11 +747,11 @@
     iSubState = ESSComplete;
     iPending = ECertRetrieve;
     
-    TUint certificateSize = (*iCerts)[0]->Size();
+    TUint certificateSize = iCerts[0]->Size();
     iRequiredBufferLength = certificateSize;
     if (certificateSize <= iOutBufferPtr->MaxLength())
         {        
-        iCertStore->Retrieve(*(*iCerts)[0], *iOutBufferPtr, iStatus);
+        iCertStore->Retrieve(*(iCerts[0]), *iOutBufferPtr, iStatus);
         SetActive();
         }
     else
@@ -846,33 +777,27 @@
 void CPKISupport::CleanupCertListL() 
     {
     LOG_("Removing invalid certs (MIDP2 certs)");
-    if (iCerts) 
+
+    TInt certcount = iCerts.Count();
+    _LIT(KMidp2Label, "MIDP2");
+    LOG_1("Total cert count, before cleanup: %d", iCerts.Count());
+    RMPointerArray<CCTCertInfo> removedInfos;
+    CleanupClosePushL(removedInfos);
+    for (TInt i = certcount - 1; i >= 0; i--) 
         {
-        TInt certcount = iCerts->Count();
-        _LIT(KMidp2Label, "MIDP2");
-        LOG_1("Total cert count, before cleanup: %d", iCerts->Count());
-        RMPointerArray<CCTCertInfo> removedInfos;
-        CleanupClosePushL(removedInfos);
-        for (TInt i = certcount - 1; i >= 0; i--) 
+        CCTCertInfo* info = iCerts[i];
+        if (info->Label().Compare(KMidp2Label) == 0 ||
+            info->CertificateFormat() != EX509Certificate) 
             {
-            CCTCertInfo* info = (*iCerts)[i];
-            if (info->Label().Compare(KMidp2Label) == 0 ||
-                info->CertificateFormat() != EX509Certificate) 
-                {
-                // CCTCertInfo has private destructor
-                removedInfos.AppendL( info );
-                iCerts->Remove(i);
-                continue;
-                }
+            // CCTCertInfo has private destructor
+            removedInfos.AppendL( info );
+            iCerts.Remove(i);
+            continue;
             }
-        CleanupStack::PopAndDestroy(); // removedInfos
-        iCerts->Compress();
-        LOG_1("Total cert count, after cleanup: %d", iCerts->Count());
         }
-    else 
-        {
-        LOG_("Certs list empty!");
-        }
+    CleanupStack::PopAndDestroy(); // removedInfos
+    iCerts.Compress();
+    LOG_1("Total cert count, after cleanup: %d", iCerts.Count());
     }
 
 // ---------------------------------------------------------------------------
@@ -913,8 +838,17 @@
             // if it hasn't been already done
             CleanupCertListL();
             iInitState = EInitCompleteImportCerts;
-            
-            //Falls through
+            if(iImportCounter < iCerts.Count())
+                {
+                ReadNextCertForImportL();
+                }
+            else
+                {
+                LOG_(" Cert store is empty");
+                iInitState = EInitDone;
+                iMessage.Complete(KErrNone);
+                }
+            break;
         case EInitCompleteImportCerts:
             LOG_("CPKISupport::DoRunOperationL() EInitCompleteImportCerts");            
 			if(GetApplicationsOfCTFCertL())
@@ -923,7 +857,7 @@
 				break;
 				}
             SaveCertInfoToCacheL();    // Handles one certificate, if found
-            if(iImportCounter < iCerts->Count())
+            if(iImportCounter < iCerts.Count())
                 {
                 ReadNextCertForImportL();
                 }
@@ -931,14 +865,10 @@
                 {
                 LOG_(" All certificates imported, doing clean ups");
                 // Cleanup
-
-                delete iImportCertMapping;
-                iImportCertMapping = NULL;
-
                 delete iImportCertData;
                 iImportCertData = NULL;
 
-                iCerts->Close();
+                iCerts.Close();
 
                 delete iCertFilter;
                 iCertFilter = NULL;
@@ -985,21 +915,21 @@
                 {
                 case ESSContinue:
                     {
-                    if(iCerts->Count() > 1)
+                    if(iCerts.Count() > 1)
                         {
                         LOG(Log::Printf(_L("Duplicate Certificate\n")));
                         iSubState = ESSCompleteRequest;
                         iSupportStatus = KErrNotFound;
                         }
-                    else if (iCerts->Count() < 1)
+                    else if (iCerts.Count() < 1)
                         {
                         LOG(Log::Printf(_L("No matching certificates found\n")));
                         iSubState = ESSCompleteRequest;
                         iSupportStatus = KErrNotFound;
                         }
-					else if ((((*iCerts)[0])->CertificateOwnerType() == EUserCertificate) &&
-							(((iCertStoreType == EPkiStoreTypeDevice) && (((*iCerts)[0])->Token().Label().Compare(KDeviceCertStore)!=0)) ||
-                    	  	((iCertStoreType == EPkiStoreTypeUser) && (((*iCerts)[0])->Token().Label().Compare(KUserCertStore)!=0))))
+					else if ((iCerts[0]->CertificateOwnerType() == EUserCertificate) &&
+							(((iCertStoreType == EPkiStoreTypeDevice) && (iCerts[0]->Token().Label().Compare(KDeviceCertStore)!=0)) ||
+                    	  	((iCertStoreType == EPkiStoreTypeUser) && (iCerts[0]->Token().Label().Compare(KUserCertStore)!=0))))
 						{
 						LOG_1("User certificate's certificate info does not match certificate store type. Store type is: %d", iCertStoreType);
 						iSubState = ESSCompleteRequest;
@@ -1027,7 +957,7 @@
                 {
                 case ESSContinue:
                     {
-                    if(iCerts->Count() != 1)
+                    if(iCerts.Count() != 1)
                         {
                         iSubState = ESSCompleteRequest;
                         iSupportStatus = KErrNotFound;
@@ -1065,7 +995,7 @@
                 {
                 case ESSContinue:
                     {
-                    if(iCerts->Count() != 1)
+                    if(iCerts.Count() != 1)
                         {
                         iSubState = ESSCompleteRequest;
                         iSupportStatus = KErrNotFound;
@@ -1106,7 +1036,7 @@
             switch(iSubState)
                 {
                 case ESSContinue:
-                    if(iCerts->Count() != 1)
+                    if(iCerts.Count() != 1)
                         {
                         iSupportStatus = KPKIErrNotFound;
                         iSubState = ESSCompleteRequest;
@@ -1141,14 +1071,15 @@
 // ---------------------------------------------------------------------------
 //
 void CPKISupport::RemoveCertificateL(const TDesC &aLabel, 
+    const TPKIKeyIdentifier& aCertificateKeyId,
     TRequestStatus& aStatus)
 {
     LOG(Log::Printf(_L("Remove certificate\n")));
     iSupportStatus = KErrNone;
-    iCerts->Close();
+    iCerts.Close();
     iSubState = ESSContinue;
     SetCallerStatusPending( aStatus );
-    SelectCertificateL(aLabel);
+    SelectCertificateL(aLabel, aCertificateKeyId);
 }
 
 // ---------------------------------------------------------------------------
@@ -1157,7 +1088,7 @@
 //
 void CPKISupport::ContinueRemoveCertificate()
 {
-    iCertStore->Remove(*(*iCerts)[0], iStatus);
+    iCertStore->Remove(*(iCerts[0]), iStatus);
     iPending = ECertRemove;
     iSubState = ESSComplete;
     SetActive();
@@ -1169,15 +1100,16 @@
 // ---------------------------------------------------------------------------
 //
 void CPKISupport::SetTrustL(const TDesC &aLabel, 
+    const TPKIKeyIdentifier& aCertificateKeyId,
     TBool aTrusted, TRequestStatus& aStatus)
 {
     LOG(Log::Printf(_L("SetTrust\n")));
     iSupportStatus = KErrNone;
-    iCerts->Close();
+    iCerts.Close();
     iSubState = ESSContinue;
     iTrusted = aTrusted;
     SetCallerStatusPending( aStatus );
-    SelectCertificateL(aLabel);
+    SelectCertificateL(aLabel, aCertificateKeyId);
 }
 
 // ---------------------------------------------------------------------------
@@ -1187,7 +1119,7 @@
 void CPKISupport::ContinueSetTrust()
 {
     iSubState = ESSComplete;    
-    iCertStore->SetTrust(*(*iCerts)[0], iTrusted, iStatus);
+    iCertStore->SetTrust(*(iCerts[0]), iTrusted, iStatus);
     iPending = ESetTrust;
     SetActive();
 }
@@ -1196,14 +1128,16 @@
 // ?description_if_needed
 // ---------------------------------------------------------------------------
 //
-void CPKISupport::TrustedL(const TDesC &aLabel, TRequestStatus& aStatus)
+void CPKISupport::TrustedL(const TDesC &aLabel, 
+                           const TPKIKeyIdentifier& aCertificateKeyId, 
+                           TRequestStatus& aStatus)
 {
     LOG(Log::Printf(_L("Trusted\n")));
     iSupportStatus = KErrNone;
-    iCerts->Close();
+    iCerts.Close();
     iSubState = ESSContinue;
     SetCallerStatusPending( aStatus );
-    SelectCertificateL(aLabel);
+    SelectCertificateL(aLabel, aCertificateKeyId);
 }
 
 // ---------------------------------------------------------------------------
@@ -1213,7 +1147,7 @@
 void CPKISupport::ContinueTrusted()
 {
     iSubState = ESSComplete;
-    iCertStore->Trusted(*(*iCerts)[0], iTrusted, iStatus);
+    iCertStore->Trusted(*(iCerts[0]), iTrusted, iStatus);
     iPending = ETrusted;
     SetActive();
 }
@@ -1222,11 +1156,13 @@
 // ?description_if_needed
 // ---------------------------------------------------------------------------
 //
-void CPKISupport::SetApplicabilityL(const TDesC &aLabel, const RArray<TUid>& aApplUids, TRequestStatus& aStatus)
+void CPKISupport::SetApplicabilityL(const TDesC &aLabel, 
+                                    const TPKIKeyIdentifier& aCertificateKeyId,
+                                    const RArray<TUid>& aApplUids, TRequestStatus& aStatus)
 {
     LOG(Log::Printf(_L("SetApplicability\n")));
     iSupportStatus = KErrNone;
-    iCerts->Close();
+    iCerts.Close();
     iSubState = ESSContinue;
 	iApplUids.Close();
 	for(TInt i = 0;i<aApplUids.Count();i++)
@@ -1234,7 +1170,7 @@
 		iApplUids.Append(aApplUids[i]);
 		}
     SetCallerStatusPending( aStatus );
-    SelectCertificateL(aLabel);
+    SelectCertificateL(aLabel, aCertificateKeyId);
 }
 
 // ---------------------------------------------------------------------------
@@ -1243,9 +1179,9 @@
 //
 void CPKISupport::ContinueSetApplicability()
     {
-    PKISERVICE_ASSERT(iCerts && iCerts->Count());
+    PKISERVICE_ASSERT(iCerts.Count());
     iSubState = ESSComplete;
-    iCertStore->SetApplicability(*(*iCerts)[0], iApplUids, iStatus);
+    iCertStore->SetApplicability(*(iCerts[0]), iApplUids, iStatus);
     iPending = ESetApplicability;
     SetActive();
     }
@@ -1254,14 +1190,15 @@
 // ?description_if_needed
 // ---------------------------------------------------------------------------
 //
-void CPKISupport::ApplicationsL(const TDesC &aLabel, TRequestStatus& aStatus)
+void CPKISupport::ApplicationsL(const TDesC &aLabel, const TPKIKeyIdentifier& aCertificateKeyId,
+                                TRequestStatus& aStatus)
 {
     LOG(Log::Printf(_L("Applications\n")));
     iSupportStatus = KErrNone;
-    iCerts->Close();
+    iCerts.Close();
     iSubState = ESSContinue;
     SetCallerStatusPending( aStatus );
-    SelectCertificateL(aLabel);
+    SelectCertificateL(aLabel, aCertificateKeyId);
 }
 
 // ---------------------------------------------------------------------------
@@ -1272,7 +1209,7 @@
 {
     iSubState = ESSComplete;
 	iApplUids.Close();
-    iCertStore->Applications(*(*iCerts)[0], iApplUids, iStatus);
+    iCertStore->Applications(*(iCerts[0]), iApplUids, iStatus);
     iPending = EApplications;
     SetActive();
 }
@@ -1283,6 +1220,7 @@
 // ---------------------------------------------------------------------------
 //
 void CPKISupport::SelectCertificateL(const TDesC &aLabel, 
+                                     const TPKIKeyIdentifier& aCertificateKeyId,
                                      const TPKICertificateOwnerType& aType )
 {
     delete iCertFilter;
@@ -1291,6 +1229,7 @@
 
     LOG(Log::Printf(_L(" Select by label: %S\n"), &aLabel));
     iCertFilter->SetLabel(aLabel);
+    iCertFilter->SetSubjectKeyId(aCertificateKeyId);
     if (aType != 0) 
         {
         LOG_1(" Select by owner type: %d", aType);
@@ -1310,12 +1249,12 @@
     LOG_1("-> CPKISupport::GetCertificateStoreListAsync() iSubState:%d",
             iSubState );
     // preconditions
-    PKISERVICE_ASSERT( iCerts && iCertFilter && iStatus != KRequestPending );
+    PKISERVICE_ASSERT( iCertFilter && iStatus != KRequestPending );
     LOG_1("CPKISupport::GetSertificateStoreListAsync iSubState:%d", 
         iSubState );
 
     // Get list of all known certificates
-    iCertStore->List(*iCerts, *iCertFilter, iStatus);
+    iCertStore->List(iCerts, *iCertFilter, iStatus);
     iPending = EListCerts;
     SetActive();
     LOG_("<- CPKISupport::GetCertificateStoreListAsync()");
--- a/vpnengine/pkiservice/src/pkiwrapper.cpp	Thu Dec 17 09:14:51 2009 +0200
+++ b/vpnengine/pkiservice/src/pkiwrapper.cpp	Thu Jan 07 13:26:15 2010 +0200
@@ -22,8 +22,10 @@
 
 #include "pkiwrapper.h"
 #include "PKIMapper.h"
+#include "mapdescriptor.h"
 #include "pkisession.h"
 #include "pkisupport.h"
+#include "pkiserviceassert.h"
 #include "log_r6.h"
 
 
@@ -41,7 +43,6 @@
     {
     LOG_("-> CPKIWrapper::~CPKIWrapper()");
     Cancel();
-    delete iCurrentMapping;
     delete iObjectName;
     delete iCertBuffer;
     iUidArray.Close();
@@ -87,28 +88,29 @@
 *   Initialization routine
 */
 //====================================================================================================================================    
-TInt CPKIWrapper::InitOperation(const RMessage2& aMessage)
+void CPKIWrapper::InitOperation(const RMessage2& aMessage)
 {
-    if (IsActive())
+    if (iMessage.Handle() != 0)
         {
         LOG(Log::Printf(_L("Pkiservice busy. Function %d\n"), aMessage.Function()));
-        return KPKIErrServiceBusy;
+        aMessage.Complete(KPKIErrServiceBusy);
+
         }
-    
-    LOG(Log::Printf(_L("InitOperation function %d\n"), aMessage.Function()));
-    iCurrentStatus = KErrNone;              // Clear status
-    iCurrentState = EExecute;               // Set state
-    iMessage = aMessage;                    // Save message
-    iPKISupport->SetCurrentFunction(iMessage.Function());
-    iIndex = KErrNotFound;
-    
-    // Trigger function
-    iStatus = KRequestPending;
-    SetActive();
-    TRequestStatus *status = &iStatus;
-    User::RequestComplete(status, KErrNone);
-    
-    return KErrNone;
+    else
+        {
+        LOG(Log::Printf(_L("InitOperation function %d\n"), aMessage.Function()));
+        iCurrentStatus = KErrNone;              // Clear status
+        iCurrentState = EExecute;               // Set state
+        iMessage = aMessage;                    // Save message
+        iPKISupport->SetCurrentFunction(iMessage.Function());
+        iIndex = KErrNotFound;
+        
+        // Trigger function
+        iStatus = KRequestPending;
+        SetActive();
+        TRequestStatus *status = &iStatus;
+        User::RequestComplete(status, KErrNone);
+        }
 }
     
 /**---------------------------------------------------------
@@ -301,13 +303,15 @@
 
     LOG(Log::Printf(_L("CPKIWrapper::ExecuteReadCertificateL()\n")));
     iCurrentStatus = iMapper.ResolveCertMappingL(iCurrentDescriptor(), *iObjectName, 
-                                                           index, iInfoOnly, 
-                                                           iPKISupport->CertStoreType());
+                                                 index, iInfoOnly, 
+                                                 iPKISupport->CertStoreType());
     if(iCurrentStatus == KErrNone)
         {
-        TSecurityObjectDescriptor sdesc = iCurrentDescriptor();
+        const CMapDescriptor& mapping = iMapper.GetMapDescriptorAtIndex(index);        
         iCurrentState = EComplete;
-        iPKISupport->RetrieveCertificateL(*iObjectName, iPtrCertBuffer, sdesc.iOwnerType, iStatus);
+        iPKISupport->RetrieveCertificateL(mapping.Label(),
+                                          mapping.CertificateKeyId(),
+                                          iPtrCertBuffer, mapping.OwnerType(), iStatus);
         SetActive();
         }
     LOG_1("CPKIWrapper::ExecuteReadCertificateL() exit:%d", iCurrentStatus);
@@ -332,33 +336,39 @@
         if (certIsNew)
             {
             LOG(Log::Printf(_L("Creating new certificate entry\n")));
-            delete iCurrentMapping;
-            iCurrentMapping = NULL;
-            iCurrentMapping = new (ELeave) CMapDescriptor(iCurrentDescriptor());
+            
             iMapper.GenerateUniqueNameL(iPtrCertBuffer, *iObjectName);
-            iCurrentMapping->SetMapObjectName(*iObjectName);
-            SaveIdentityL(*iCurrentMapping, iPtrCertBuffer, (TCertificateOwnerType)iCurrentDescriptor().iOwnerType);
-            
             TPkiServiceStoreType storeType = iPKISupport->CertStoreType();
             if (storeType == EPkiStoreTypeAny)
                 {
                 storeType = EPkiStoreTypeUser;
                 }
-            iCurrentMapping->SetCertStoreType(storeType);
+
+            CX509Certificate* certificate = CX509Certificate::NewLC(iPtrCertBuffer);  
 
-            if(iCurrentStatus == KErrNone)
-                {
-                LOG(Log::Printf(_L("Status OK, identity saved\n")));
-                iCurrentStatus = KErrNone;
-                iCurrentState = EComplete;
-                LOG(Log::Printf(_L("Storing CERT with LABEL:")));
-                LOG(Log::Printf(iCurrentMapping->iObjectName));
-                iPKISupport->StoreCertificateL(iCurrentMapping->iObjectName, 
-                    (TCertificateOwnerType)iCurrentDescriptor().iOwnerType, 
-                    iPtrCertBuffer, iCurrentDescriptor().iIsDeletable, iStatus);
-                LOG(Log::Printf(_L("CERT stored\n")));
-                SetActive();
-                }
+            PKISERVICE_ASSERT(iCurrentMapping == NULL);
+            CMapDescriptor* newMapping = CMapDescriptor::NewL(*iObjectName,
+                                                              *certificate,
+                                                              iCurrentDescriptor().iOwnerType,
+                                                              storeType);  
+            CleanupStack::PushL(newMapping);            
+            newMapping->SetMapDeletable(iCurrentDescriptor().iIsDeletable);            
+                                           
+            iCurrentStatus = KErrNone;
+            iCurrentState = EComplete;
+            LOG(Log::Printf(_L("Storing CERT with LABEL:")));
+            LOG(Log::Printf(*iObjectName));
+            iPKISupport->StoreCertificateL(*iObjectName, 
+                (TCertificateOwnerType)iCurrentDescriptor().iOwnerType, 
+                iPtrCertBuffer, iCurrentDescriptor().iIsDeletable, iStatus);
+            
+            iCurrentMapping = newMapping;
+            CleanupStack::Pop(newMapping);
+            CleanupStack::PopAndDestroy(certificate);
+            
+            LOG(Log::Printf(_L("CERT stored\n")));
+            SetActive();
+
             }
         else 
             {
@@ -387,29 +397,38 @@
     LOG(Log::Printf(_L("ExecuteAttachCertificateL")));
 
     iMapper.GenerateUniqueNameL(iPtrCertBuffer, *iObjectName, EUserCertificate);
-
-    delete iCurrentMapping;
-    iCurrentMapping = NULL;
-    iCurrentMapping = new (ELeave) CMapDescriptor(iCurrentDescriptor());
-    iCurrentMapping->SetMapObjectName(*iObjectName);
-    SaveIdentityL(*iCurrentMapping, iPtrCertBuffer, (TCertificateOwnerType)iCurrentDescriptor().iOwnerType);
-
+    
     TPkiServiceStoreType storeType = iPKISupport->CertStoreType();
     if (storeType == EPkiStoreTypeAny)
         {
         storeType = EPkiStoreTypeUser;
-        }
-    iCurrentMapping->SetCertStoreType(storeType);
-    if(iCurrentStatus == KErrNone)
-        {
-        iCurrentStatus = KErrNone;
-        iCurrentState = EComplete;
-        LOG(Log::Printf(_L("Attaching certificate")));
-        LOG(Log::Printf(iCurrentMapping->iObjectName));
-        iPKISupport->AttachCertificateL(iCurrentMapping->iObjectName, iCurrentDescriptor().iSubjectKeyId, iPtrCertBuffer, iStatus);
-        LOG(Log::Printf(_L("Certificate attached")));
-        SetActive();
-        }
+        }  
+    
+    PKISERVICE_ASSERT(iCurrentMapping == NULL);
+    
+    CX509Certificate* certificate = CX509Certificate::NewLC(iPtrCertBuffer);  
+    CMapDescriptor* newMapping = CMapDescriptor::NewL(*iObjectName,
+                                                      *certificate,
+                                                      iCurrentDescriptor().iOwnerType,
+                                                      storeType);  
+    CleanupStack::PushL(newMapping);            
+    newMapping->SetMapDeletable(iCurrentDescriptor().iIsDeletable);
+
+            
+    
+    iCurrentStatus = KErrNone;
+    iCurrentState = EComplete;
+    LOG(Log::Printf(_L("Attaching certificate")));
+    LOG(Log::Printf(*iObjectName));
+    iPKISupport->AttachCertificateL(*iObjectName, iPtrCertBuffer, iStatus);
+    LOG(Log::Printf(_L("Certificate attached")));
+
+    iCurrentMapping = newMapping;
+    CleanupStack::Pop(newMapping);                 
+    CleanupStack::PopAndDestroy(certificate);
+
+    
+    SetActive();
     }
 
 
@@ -427,12 +446,11 @@
                                         iPKISupport->CertStoreType());
     if(iCurrentStatus == KErrNone)
         {
-        delete iCurrentMapping;
-        iCurrentMapping = NULL;
-        iCurrentMapping = new (ELeave) CMapDescriptor(iCurrentDescriptor());
-        *iCurrentMapping = iMapper.GetMapDescriptorAtIndex(index);
+        const CMapDescriptor& mapping = iMapper.GetMapDescriptorAtIndex(index);
+        TPKIKeyIdentifier keyId = mapping.CertificateKeyId();
+        iMapper.DeleteMapping(index);
         iCurrentState = EComplete;
-        iPKISupport->RemoveCertificateL(*iObjectName, iStatus);
+        iPKISupport->RemoveCertificateL(*iObjectName, keyId, iStatus);
         SetActive();
         }
     }
@@ -452,10 +470,11 @@
     if(iCurrentStatus == KErrNone)
         {
         const CMapDescriptor& mapping = iMapper.GetMapDescriptorAtIndex(index);
-        if (mapping.iOwnerType == EPKICACertificate)
+        if (mapping.OwnerType() == EPKICACertificate)
             {            
             iCurrentState = EComplete;
-            iPKISupport->SetTrustL(*iObjectName, iTrusted, iStatus);
+            iPKISupport->SetTrustL(*iObjectName, mapping.CertificateKeyId(), 
+                                   iTrusted, iStatus);
             SetActive();
             }
         else
@@ -479,8 +498,9 @@
                                                             iPKISupport->CertStoreType());
     if(iCurrentStatus == KErrNone)
         {
+        const CMapDescriptor& mapping = iMapper.GetMapDescriptorAtIndex(index);
         iCurrentState = EComplete;
-        iPKISupport->TrustedL(*iObjectName, iStatus);
+        iPKISupport->TrustedL(*iObjectName, mapping.CertificateKeyId(), iStatus);
         SetActive();
         }
     }
@@ -493,18 +513,17 @@
 void CPKIWrapper::ExecuteSetApplicabilityL()
     {
     TInt index(KErrNotFound);
-    iCurrentStatus = iMapper.ResolveCertMappingL(
-        iCurrentDescriptor(), *iObjectName, 
-        index, iInfoOnly,
-        iPKISupport->CertStoreType());
-    
+    iCurrentStatus = iMapper.ResolveCertMappingL(iCurrentDescriptor(), *iObjectName, 
+                                                 index, iInfoOnly,
+                                                 iPKISupport->CertStoreType());    
 	// Save index
 	iIndex = index;
     if(iCurrentStatus == KErrNone)
         {
         LOG_1("ExecuteSetApplicabilityL:%d", iIndex);
+        const CMapDescriptor& mapping = iMapper.GetMapDescriptorAtIndex(index);
         iCurrentState = EComplete;
-        iPKISupport->SetApplicabilityL(*iObjectName, iUidArray, iStatus);
+        iPKISupport->SetApplicabilityL(*iObjectName, mapping.CertificateKeyId(), iUidArray, iStatus);
         SetActive();
         }
     }
@@ -524,8 +543,9 @@
     iUidArray.Close();
     if(iCurrentStatus == KErrNone)
         {
+        const CMapDescriptor& mapping = iMapper.GetMapDescriptorAtIndex(index);
         iCurrentState = EComplete;
-        iPKISupport->ApplicationsL(*iObjectName, iStatus);
+        iPKISupport->ApplicationsL(*iObjectName, mapping.CertificateKeyId(), iStatus);
         SetActive();
         }
 }
@@ -561,32 +581,26 @@
             if (iCurrentStatus == KErrNone)
                 {
                 User::LeaveIfError( 
-                    iMapper.AddMapping(*iCurrentMapping) );
-                iCurrentMapping = NULL;    
+                    iMapper.AddMapping(iCurrentMapping) );                                    
                 }
+            else
+                {
+                delete iCurrentMapping;
+                }
+            iCurrentMapping = NULL;
             if (iCurrentStatus == KErrBadName)
                 {
                 // Already exists
                 iCurrentStatus = KErrNone;
                 }
-            break;
-                        
+            break;                        
         case PkiService::ERemoveCertificate:
-            if (iCurrentStatus == KErrNone)
-                {
-                iMapper.DeleteMapping(*iCurrentMapping);
-                }
             break;
 
 		case PkiService::ESetApplicability:
 			if (iCurrentStatus == KErrNone)
 				{
-				iMapper.GetMapDescriptorAtIndex(iIndex).iApplUids.Close();
-				TUint i;
-				for(i=0;i<iCount;i++)
-					{
-					iMapper.GetMapDescriptorAtIndex(iIndex).iApplUids.Append(iUidArray[i]);
-					}
+				iMapper.GetMapDescriptorAtIndex(iIndex).SetMapApplications(iUidArray); 
 				}
 			break;
 
@@ -634,8 +648,6 @@
         iMessage.Function(), iCurrentStatus));
 
     delete iCertBuffer;
-    delete iCurrentMapping;
-    iCurrentMapping = NULL;
     iCertBuffer = NULL;
     iMessage.Complete(iCurrentStatus);
     }
@@ -737,9 +749,7 @@
 TInt CPKIWrapper::RunError(TInt aError)
     {
     LOG(Log::Printf(_L("CPKIWrapper::RunError, Complete function %d, status %d\n"), iMessage.Function(), aError));
-    delete iCertBuffer;
-    delete iCurrentMapping;
-    iCurrentMapping = NULL; 
+    delete iCertBuffer; 
     iCertBuffer = NULL;
     
     iMessage.Complete(aError);
@@ -754,93 +764,14 @@
         iPKISupport->Cancel();
         }
     iMessage.Complete(KErrCancel);
-    }
-      
-
-
-void CPKIWrapper::SaveIdentityL(CMapDescriptor &aCertDesc, 
-                                const TDesC8& aCertDataIn,
-                                TCertificateOwnerType aOwner)
-{
-    LOG(Log::Printf(_L("CPKIWrapper::SaveIdentityL()\n")));
-
-    CX509Certificate* certificate = CX509Certificate::NewLC(aCertDataIn);            
-
-    // Validity period
-    aCertDesc.SetMapStartTime(certificate->ValidityPeriod().Start());
-    aCertDesc.SetMapEndTime(certificate->ValidityPeriod().Finish());    
-    
-    
-    // Copy issuer
-    const TPtrC8* issuer = certificate->DataElementEncoding(CX509Certificate::EIssuerName);
-    aCertDesc.SetMapTrustedAuthorityL(*issuer);
-
-    // Copy subject name
-    const TPtrC8* subject = certificate->DataElementEncoding(CX509Certificate::ESubjectName);    
-    aCertDesc.SetMapIdentitySubjectNameL(*subject);
-
-    // Copy rfc822 name from subjectAlt name    
-    const CX509CertExtension* subjAltName = certificate->Extension(KSubjectAltName);
-    if(subjAltName != NULL)
-        {
-        CX509AltNameExt* subjectAlt = CX509AltNameExt::NewLC(subjAltName->Data());
-        if(subjectAlt != NULL)
-            {
-            const CArrayPtrFlat<CX509GeneralName> *nameArray; 
-            nameArray = &subjectAlt->AltName();
-            // Search rfc822
-            for(TInt i = 0; i < nameArray->Count(); i++)
-                {
-                if(nameArray->At(i)->Tag() == EX509RFC822Name)
-                    {
-                    TPtrC8 data = nameArray->At(i)->Data();
-                    aCertDesc.SetMapIdentityRfc822NameL(data.Right(data.Length() - 2));
-                    break;
-                    }
-                }                            
-            }
-        CleanupStack::PopAndDestroy(subjectAlt);
-        }
-
-    // Key usage
-    const CX509CertExtension* keyUsage = certificate->Extension(KKeyUsage);
-    if((keyUsage != NULL) && keyUsage->Critical())
-        {
-        aCertDesc.iKeyUsageDer.Copy(keyUsage->Data());        
-        }
-
-    // Serial number
-	const TPtrC8* serial = certificate->DataElementEncoding(CX509Certificate::ESerialNumber);
-	if(serial != NULL)
-		{
-		aCertDesc.SetMapSerialNumberL(*serial);               
-		}
-    
-	// Set Subject Key Identifier if we are handling CA
-	if(aOwner == ECACertificate)
-	{
-	    TPKIKeyIdentifier keyId = certificate->SubjectKeyIdentifierL();
-	    aCertDesc.SetMapSubjectKeyId(keyId);
-	}
-	
-    CleanupStack::PopAndDestroy(certificate); 
-    
-
-    if(CPKIMapper::CertValidity(aCertDesc.iStartTime, aCertDesc.iEndTime) == EExpired)
-    {
-        LOG(Log::Printf(_L("Certificate expired\n")));
-    }
-}
-
+    }      
 
 void CPKIWrapper::SetCertStoreType(TPkiServiceStoreType aStoreType)
     {
 	LOG(Log::Printf(_L("CPKIWrapper: SETTING CERT STORE TYPE: %d\n"), aStoreType));
     iPKISupport->SetCertStoreType(aStoreType);
     }
-
-    
-    
+        
 TPkiServiceStoreType CPKIWrapper::CertStoreType() const
     {
     return iPKISupport->CertStoreType();
@@ -851,3 +782,7 @@
     iInfoOnly = aInfoOnly;
     }
     
+TBool CPKIWrapper::Informational() const
+    {
+    return iInfoOnly;
+    }