Revision: 201033 RCL_3 PDK_3.0.3
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Tue, 14 Sep 2010 23:16:15 +0300
branchRCL_3
changeset 25 735de8341ce4
parent 24 e06095241a65
Revision: 201033 Kit: 201035
vpnengine/dmadipsecvpn/src/DmAdRtNodeData.cpp
vpnengine/eventmediator/group/eventmediator.mmp
vpnengine/eventmediator/inc/eventlogger.h
vpnengine/eventmediator/inc/eventmediator.h
vpnengine/eventmediator/inc/eventmediatorsession.h
vpnengine/eventmediator/src/eventlogger.cpp
vpnengine/eventmediator/src/eventmediator.cpp
vpnengine/eventmediator/src/eventmediatorsession.cpp
vpnengine/eventmediatorapi/inc/eventmediatorclientservercommon.h
vpnengine/eventmediatorapi/src/EventMediatorAPI.cpp
vpnengine/ikecert/src/ikev1pkiservice.cpp
vpnengine/ikepolparser/group/ikepolparser.mmp
vpnengine/ikepolparser/inc/ikepolparser.h
vpnengine/ikepolparser/src/ikepolparser.cpp
vpnengine/ikev1lib/src/ikev1negotiation.cpp
vpnengine/kmdserver/group/kmdserver.mmp
vpnengine/kmdserver/group/kmdservertest.mmp
vpnengine/pkiservice/inc/PKIMapper.h
vpnengine/pkiservice/inc/pkiserviceclientservercommon.h
vpnengine/pkiservice/src/pkimapper.cpp
vpnengine/pkiservice/src/pkisession.cpp
vpnengine/pkiserviceapi/inc/pkidefs.h
vpnengine/pkiserviceapi/src/pkiserviceapi.cpp
vpnengine/sit/inc/taskarrivalobserver.h
vpnengine/sit/src/sit.cpp
vpnengine/sit/src/taskarrivalobserver.cpp
vpnengine/vpnmanager/src/pkiutil.cpp
vpnengine/vpnmanager/src/policypatcher.cpp
--- a/vpnengine/dmadipsecvpn/src/DmAdRtNodeData.cpp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/dmadipsecvpn/src/DmAdRtNodeData.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -599,6 +599,23 @@
     if (aName.Length() > 0)
         {
         iName = CnvUtfConverter::ConvertToUnicodeFromUtf8L(aName);
+
+        if (iContent == NULL)
+            {
+            //If the content has not been set we also generate an empty
+            //dummy policy at this point. The dummy policy is needed in
+            //a case of a large policy. Large policies are delivered using
+            //two separate messages from the OMA DM server. First message 
+            //contains only the policy info details and the second one contains 
+            //the actual data. We have to have the dummy content to handle
+            //the completion of the first message correctly.
+            _LIT8(KEmptyPolicyContent, "SECURITY_FILE_VERSION: 1\n"\
+                                       "[INFO]\n"\
+                                       "%S\n");
+            iContent = HBufC8::NewL(iName->Length() + KEmptyPolicyContent().Length());
+            TPtr8 contentPtr = iContent->Des();
+            contentPtr.Format(KEmptyPolicyContent, iName);
+            }
         }
     }
 
--- a/vpnengine/eventmediator/group/eventmediator.mmp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/eventmediator/group/eventmediator.mmp	Tue Sep 14 23:16:15 2010 +0300
@@ -29,6 +29,7 @@
 
 SOURCEPATH  ../src
 SOURCE      eventmediator.cpp
+SOURCE      eventmediatorsession.cpp
 SOURCE      eventlogger.cpp
 SOURCE      eventmediatorstarter.cpp
 
--- a/vpnengine/eventmediator/inc/eventlogger.h	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/eventmediator/inc/eventlogger.h	Tue Sep 14 23:16:15 2010 +0300
@@ -98,12 +98,6 @@
         static CEventLogger* NewL(CEventMediatorServer* aServer);
 
         /**
-        * Constructor
-        * @param aFileMaxLength: maximum length of log file in kbytes
-        */
-        CEventLogger(TInt aFileMaxLength, CEventMediatorServer* aServer);
-
-        /**
         * Destructor
         */
         ~CEventLogger();
--- a/vpnengine/eventmediator/inc/eventmediator.h	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/eventmediator/inc/eventmediator.h	Tue Sep 14 23:16:15 2010 +0300
@@ -51,8 +51,6 @@
 */
 class CEventMediatorServer : public CPolicyServer, public MSitDeathListener
     {
-    friend class CEventMediatorSession; // Friend class
-
     public: //Methods
 
     // Constructors and destructor
@@ -77,6 +75,10 @@
         */
         CSession2* NewSessionL(const TVersion& aVersion, const RMessage2& aMessage) const;
 
+        /**
+         * Notifies the server that a session has been deleted.
+         */
+        void SessionDeleted(TBool aIsSitSession);
     // Other methods
         
         /**
@@ -98,7 +100,7 @@
          * Finds out whether the specified client thread is a SIT
          * thread or not
          */
-        TBool IsClientTheSitL(const RMessage2& aMessage);
+        TBool IsClientTheSitL(const RMessage2& aMessage) const;
 
         /**
          * Starts the SIT thread if it is not running
@@ -208,6 +210,14 @@
 
         TPtrC EventLogFileName(void);
         
+        /**
+         * Copies data describing an event to the client.
+         * @param aMessge: a message from client side sent by RConnection::FetchData
+         * @return error code, KErrNone if successfull
+         */
+        TInt CopyEventDataL(const RMessage2& aMessage);    
+        
+        
    public: // From MSitDeathListener
         void SitDied();
 
@@ -231,23 +241,11 @@
         /**
          * Perform the second phase construction of a CVpnManagerServer
          * object.
-         * @param aServer Pointer to the server itself.
          */
-        void ConstructL(CEventMediatorServer* aServer);
+        void ConstructL();
 
     // Other methods
 
-        /**
-         * Stops the server if the session count is zero.
-         */
-        void StopEventMediator(void);
-
-        /**
-         * Copies data describing an event to the client.
-         * @param aMessge: a message from client side sent by RConnection::FetchData
-         * @return error code, KErrNone if successfull
-         */
-        TInt CopyEventDataL(const RMessage2& aMessage);    
 
         /**
          * Reduces listener count of a stored event by one and destroys it if count becomes zero.
@@ -255,16 +253,11 @@
          */
         void MarkStoredEventListened(TInt aIndex);
 
-        /**
-         * Sets the iShuttingDown flag.
-         */
-        void SetShuttingDown(TBool aShuttingDown);
-
     private: //Data
         // List of Events that have been reported but not handled by all listeners.
         CArrayFixFlat<TEventContainer*> iStoredEvents;
         // Number of currently existing sessions.
-        TInt iSessionCount;
+        mutable TInt iSessionCount;
         // Log writer
         CEventLogger* iLogger;
         // The next event specification ID
@@ -290,231 +283,6 @@
 
     };
 
-// CLASS DECLARATION
-
-/**
-* Defines the session to the VPN manager server. 
-*/
-class CEventMediatorSession : public CSession2
-    {
-    public: //Message types
-        enum
-            {
-            KEventMediatorListen,
-            KEventMediatorListenWithSpec,
-            KEventMediatorCancel,
-            KEventMediatorCancelWithSpec,
-            KEventMediatorCancelAll,
-            KEventMediatorReportEvent,
-            KEventMediatorReportEventWithSpec,
-            KEventMediatorFetchData,
-            KEventMediatorReportLogEvent,
-            KEventMediatorNewEventSpecId,
-            KEventMediatorDeletePrivateFiles,
-            KEventMediatorGetEventLogSize,
-            KEventMediatorGetEventLogHeader,
-            KEventMediatorGetEventLogData,
-            KEventMediatorClearEventLog
-            };
-    
-    public: // Methods
-
-    // Constructors and destructor
-
-        /**
-        * Static constructor
-        */
-        static CEventMediatorSession* NewL(CEventMediatorServer* aServer, const RMessage2& aMessage);
-        
-        /**
-        * Default destructor
-        */
-        ~CEventMediatorSession(void);
-
-        /**
-        * Wrapper function which Dispatches and executes the client's service calls
-        * (See Message type definition).
-        */
-        void ServiceL(const RMessage2& aMessage);
-
-        /**
-         * Checks if client is listening events of the given type and completes message 
-         * sent by clients ListenToEvent function. The length of the event data and
-         * the pointer to that data are written to the message.
-         * @param aType: type of the event.
-         * @param aSpec: additional info on event.
-         * @param aData: event data.
-         * @return number of listeners for the event was listened.
-         */
-        TInt CheckEventL(const TEventType aType, const TDesC8* aSpec, const TDesC8* aData, TInt aStatus);
-
-        /**
-         * Tries to find a task request that is not being fulfilled
-         * already
-         */
-        CListenerContainer* FindWaitingTaskRequest();
-
-        /**
-         * Retrieves the event listener object, if any, that is using
-         * the SIT that is fulfilling the specified event.
-         */
-        CListenerContainer* FindListener(TEventType aEventType, TInt aEventSpecId);
-        
-        /**
-         * Retrieves the event listener object, if any, that is using
-         * the SIT that is fulfilling the specified event.
-         */
-        CListenerContainer* FindListener(TEventType aEventType, const TDesC8* aEventSpec);
-
-        /**
-         * Completes the specified listener if it is owned by the
-         * session. Returns ETrue is the listener was found and
-         * completed, EFalse otherwise.
-         */
-        void CompleteListener(TEventType aEventType, const TDesC8* aEventSpec, TInt aStatus);
-
-        void CompleteTaskRequests(TInt aStatus);
-
-        TBool IsASitSession();
-        
-    private: //Methods
-    // Constructors and destructor
-
-        /**
-        * Constructor
-        */
-        CEventMediatorSession(CEventMediatorServer* aServer);
-
-        /**
-         * Starts listening events of requesteed type by coping the message to iListenedEvents.
-         * @param aMessage: aMessage sent by clients ListenToEvent function.
-         * @return: error code, KErrNone if successfull.
-         */
-        TInt ListenToEventWithSpecL(const RMessage2& aMessage);
-
-        /**
-         * Starts listening events of requesteed type by coping the message to iListenedEvents.
-         * @param aMessage: aMessage sent by clients ListenToEvent function.
-         * @return: error code, KErrNone if successfull.
-         */
-        TInt ListenToEventL(const RMessage2& aMessage);
-
-        /**
-         * Reports the event contained in the message to the event mediator server.
-         * @param aMessage: aMessage sent by clients ReportEvent function.
-         * @return: error code, KErrNone if successfull.
-         */
-        void ReportEventL(const RMessage2& aMessage);
-
-        /**
-         * Reports a log event contained in the message to the event mediator server.
-         * @param aMessage: aMessage sent by clients ReportLogEvent function.
-         * @return: error code, KErrNone if successfull.
-         */
-        void ReportLogEventL(const RMessage2& aMessage);
-
-        /**
-         * Reports the event contained in the message to the event mediator server.
-         * @param aMessage: aMessage sent by clients ReportEvent function.
-         * @return: error code, KErrNone if successfull.
-         */
-        void ReportEventWithSpecL(const RMessage2& aMessage);
-
-        /**
-         * Cancels listning of one event type.
-         * @param aMessage: aMessage sent by clients CancelListenToEvent function.
-         */
-        void CancelListening(const RMessage2& aMessage);
-
-        /**
-         * Cancels listning of one event type.
-         * @param aMessage: aMessage sent by clients CancelListenToEvent function.
-         */
-        void CancelListeningWithSpecL(const RMessage2& aMessage);
-
-        /**
-         * Cancels all listening.
-         * @param aMessage: aMessage sent by clients CancelAllListening function.
-         */
-        void CancelAll();
-
-        /**
-         * Copies event data from the server to the client.
-         * @param aMessage: aMessage sent by clients FetchData function.
-         * @return: error code, KErrNone if successfull.
-         */
-        TInt FetchDataL(const RMessage2& aMessage);
-
-        /**
-         * Looks up a message from iListenedEvents.
-         * @param aType: type of the event the message is listening to.
-         * @param aIndex: the position of the message in iListenedEvents.
-         * @return ETrue if message exists, EFalse if not.
-         */
-        TBool FindListenerMsg(const TEventType aType,TInt& index);
-
-        /**
-         * Looks up a message from iListenedEvents.
-         * @param aType: type of the event the message is listening to.
-         * @param aIndex: the position of the message in iListenedEvents.
-         * @return ETrue if message exists, EFalse if not.
-         */
-        TBool FindListenerMsg(const TEventType aType,const TDesC8* aSpec,TInt& index);
-
-        /**
-         * Searches for a task request type event listening request
-         */
-        TBool FindTaskRequestListenerMsg(TInt& index);
-        
-        /**
-         * Reads data that was reported with the event from client. Allocates a buffer
-         * for data and gives ownership of that buffer to caller.
-         * @param aMessage: aMessage sent by clients ReportEvent function.
-         * @return pointer to the newly created buffer containig data.
-         */
-        HBufC8* ReadEventDataFromClientL(const RMessage2& aMessage);
-
-        /**
-         * Reads specification describing the event from client. Allocates a buffer
-         * for secification and gives ownership of that buffer to caller.
-         * @param aMessage: aMessage sent with event specification.
-         * @return pointer to the newly created buffer containig data.
-         */
-        HBufC8* ReadSpecificationFromClientL(const RMessage2& aMessage);
-
-        /**
-         * Completes the specified listener and deletes it from the
-         * listener list
-         */
-        void CompleteListener(TInt aIndex, TInt aStatus);
-
-        /**
-         * Returns to the client a new event specification ID
-         */
-        void NewEventSpecIdL(const RMessage2& aMessage);
-
-        TInt DeletePrivateFiles();
-        void DeletePrivateFilesL();
-        
-        TInt GetEventLogSize(const RMessage2& aMessage);
-        TInt GetEventLogHeader(const RMessage2& aMessage);
-        TInt GetEventLogData(const RMessage2& aMessage);
-        TInt ClearEventLog();
-        
-    private: //Data
-        // List of messages listening to events
-        CArrayFixFlat<CListenerContainer*> iListenedEvents;
-        // Event mediator server
-        CEventMediatorServer* iServer;
-
-        RFs     iFs;
-        RFile   iEventLogFile;
-        TBool   iEventLogFileOpen;
-        // Is this session from a SIT or not
-
-    public:        
-        TBool iIsSitSession;
-    };
 
 // CLASS DECLARATION
 
@@ -549,7 +317,7 @@
     public: //Methods
     // Constructors and destructor
         CListenerContainer(const RMessage2& aMessage, TDesC8* aSpec,
-                           CEventMediatorServer* aServer);
+                           CEventMediatorServer& aServer);
         ~CListenerContainer();
 
         inline TEventType Type() {return (TEventType) iMessage.Int0();}
@@ -570,7 +338,7 @@
         RMessage2   iMessage;
         TEventType  iEventType;
         // Pointer to the event mediator server
-        CEventMediatorServer* iServer;
+        CEventMediatorServer& iServer;
         // A flag that tells whether the request
         // is being fulfilled by the SIT or not
         TBool iBeingFulfilledBySit;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vpnengine/eventmediator/inc/eventmediatorsession.h	Tue Sep 14 23:16:15 2010 +0300
@@ -0,0 +1,233 @@
+/*
+* Copyright (c) 2003-2010 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This module defines event mediator server side session.
+*
+*/
+#ifndef EVENTMEDIATORSESSION_H_
+#define EVENTMEDIATORSESSION_H_
+
+#include <e32base.h>
+#include <f32file.h>
+#include "eventmediatorapi.h"
+
+/**
+* Defines the session to the VPN manager server. 
+*/
+class CEventMediatorServer;
+class CListenerContainer;
+
+class CEventMediatorSession : public CSession2
+    {    
+    public: // Methods
+
+    // Constructors and destructor
+
+        /**
+        * Static constructor
+        */
+        static CEventMediatorSession* NewL(CEventMediatorServer& aServer, 
+                                           TBool aIsSitSession);
+        
+        /**
+        * Default destructor
+        */
+        ~CEventMediatorSession(void);
+
+        /**
+        * Wrapper function which Dispatches and executes the client's service calls
+        * (See Message type definition).
+        */
+        void ServiceL(const RMessage2& aMessage);
+
+        /**
+         * Checks if client is listening events of the given type and completes message 
+         * sent by clients ListenToEvent function. The length of the event data and
+         * the pointer to that data are written to the message.
+         * @param aType: type of the event.
+         * @param aSpec: additional info on event.
+         * @param aData: event data.
+         * @return number of listeners for the event was listened.
+         */
+        TInt CheckEventL(const TEventType aType, const TDesC8* aSpec, const TDesC8* aData, TInt aStatus);
+
+        /**
+         * Tries to find a task request that is not being fulfilled
+         * already
+         */
+        CListenerContainer* FindWaitingTaskRequest();
+
+        /**
+         * Retrieves the event listener object, if any, that is using
+         * the SIT that is fulfilling the specified event.
+         */
+        CListenerContainer* FindListener(TEventType aEventType, TInt aEventSpecId);
+        
+        /**
+         * Retrieves the event listener object, if any, that is using
+         * the SIT that is fulfilling the specified event.
+         */
+        CListenerContainer* FindListener(TEventType aEventType, const TDesC8* aEventSpec);
+
+        /**
+         * Completes the specified listener if it is owned by the
+         * session. Returns ETrue is the listener was found and
+         * completed, EFalse otherwise.
+         */
+        void CompleteListener(TEventType aEventType, const TDesC8* aEventSpec, TInt aStatus);
+
+        void CompleteTaskRequests(TInt aStatus);
+
+        TBool IsASitSession();
+        
+    private: //Methods
+    // Constructors and destructor
+
+        /**
+        * Constructor
+        */
+        CEventMediatorSession(CEventMediatorServer& aServer, TBool aIsSitSession);
+        void ConstructL();
+
+        /**
+         * Starts listening events of requesteed type by coping the message to iListenedEvents.
+         * @param aMessage: aMessage sent by clients ListenToEvent function.
+         * @return: error code, KErrNone if successfull.
+         */
+        TInt ListenToEventWithSpecL(const RMessage2& aMessage);
+
+        /**
+         * Starts listening events of requesteed type by coping the message to iListenedEvents.
+         * @param aMessage: aMessage sent by clients ListenToEvent function.
+         * @return: error code, KErrNone if successfull.
+         */
+        TInt ListenToEventL(const RMessage2& aMessage);
+
+        /**
+         * Reports the event contained in the message to the event mediator server.
+         * @param aMessage: aMessage sent by clients ReportEvent function.
+         * @return: error code, KErrNone if successfull.
+         */
+        void ReportEventL(const RMessage2& aMessage);
+
+        /**
+         * Reports a log event contained in the message to the event mediator server.
+         * @param aMessage: aMessage sent by clients ReportLogEvent function.
+         * @return: error code, KErrNone if successfull.
+         */
+        void ReportLogEventL(const RMessage2& aMessage);
+
+        /**
+         * Reports the event contained in the message to the event mediator server.
+         * @param aMessage: aMessage sent by clients ReportEvent function.
+         * @return: error code, KErrNone if successfull.
+         */
+        void ReportEventWithSpecL(const RMessage2& aMessage);
+
+        /**
+         * Cancels listning of one event type.
+         * @param aMessage: aMessage sent by clients CancelListenToEvent function.
+         */
+        void CancelListening(const RMessage2& aMessage);
+
+        /**
+         * Cancels listning of one event type.
+         * @param aMessage: aMessage sent by clients CancelListenToEvent function.
+         */
+        void CancelListeningWithSpecL(const RMessage2& aMessage);
+
+        /**
+         * Cancels all listening.
+         * @param aMessage: aMessage sent by clients CancelAllListening function.
+         */
+        void CancelAll();
+
+        /**
+         * Copies event data from the server to the client.
+         * @param aMessage: aMessage sent by clients FetchData function.
+         * @return: error code, KErrNone if successfull.
+         */
+        TInt FetchDataL(const RMessage2& aMessage);
+
+        /**
+         * Looks up a message from iListenedEvents.
+         * @param aType: type of the event the message is listening to.
+         * @param aIndex: the position of the message in iListenedEvents.
+         * @return ETrue if message exists, EFalse if not.
+         */
+        TBool FindListenerMsg(const TEventType aType,TInt& index);
+
+        /**
+         * Looks up a message from iListenedEvents.
+         * @param aType: type of the event the message is listening to.
+         * @param aIndex: the position of the message in iListenedEvents.
+         * @return ETrue if message exists, EFalse if not.
+         */
+        TBool FindListenerMsg(const TEventType aType,const TDesC8* aSpec,TInt& index);
+
+        /**
+         * Searches for a task request type event listening request
+         */
+        TBool FindTaskRequestListenerMsg(TInt& index);
+        
+        /**
+         * Reads data that was reported with the event from client. Allocates a buffer
+         * for data and gives ownership of that buffer to caller.
+         * @param aMessage: aMessage sent by clients ReportEvent function.
+         * @return pointer to the newly created buffer containig data.
+         */
+        HBufC8* ReadEventDataFromClientL(const RMessage2& aMessage);
+
+        /**
+         * Reads specification describing the event from client. Allocates a buffer
+         * for secification and gives ownership of that buffer to caller.
+         * @param aMessage: aMessage sent with event specification.
+         * @return pointer to the newly created buffer containig data.
+         */
+        HBufC8* ReadSpecificationFromClientL(const RMessage2& aMessage);
+
+        /**
+         * Completes the specified listener and deletes it from the
+         * listener list
+         */
+        void CompleteListener(TInt aIndex, TInt aStatus);
+
+        /**
+         * Returns to the client a new event specification ID
+         */
+        void NewEventSpecIdL(const RMessage2& aMessage);
+
+        TInt DeletePrivateFiles();
+        void DeletePrivateFilesL();
+        
+        TInt GetEventLogSize(const RMessage2& aMessage);
+        TInt GetEventLogHeader(const RMessage2& aMessage);
+        TInt GetEventLogData(const RMessage2& aMessage);
+        TInt ClearEventLog();
+        
+    private: //Data
+        // List of messages listening to events
+        CArrayFixFlat<CListenerContainer*> iListenedEvents;
+        // Event mediator server
+        CEventMediatorServer& iServer;
+
+        RFs     iFs;
+        RFile   iEventLogFile;
+        TBool   iEventLogFileOpen;
+        // Is this session from a SIT or not
+
+    public:        
+        TBool iIsSitSession;
+    };
+
+#endif /* EVENTMEDIATORSESSION_H_ */
--- a/vpnengine/eventmediator/src/eventlogger.cpp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/eventmediator/src/eventlogger.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -37,14 +37,6 @@
     return server;
     }
 
-CEventLogger::CEventLogger(TInt aFileMaxLength, CEventMediatorServer* aServer)
-{
-    iServer = aServer;
-    if ( aFileMaxLength == 0 || aFileMaxLength > LOGFILE_MAX_LTH )
-         iFileMaxLength = KBYTES_TO_BYTES * LOGFILE_MAX_LTH;           
-    else iFileMaxLength = KBYTES_TO_BYTES * aFileMaxLength; 
-}
-
 CEventLogger::~CEventLogger()
 {
 }
--- a/vpnengine/eventmediator/src/eventmediator.cpp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/eventmediator/src/eventmediator.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -23,26 +23,28 @@
  * This module contains eventmediator and the services of it.
  *
  */
-#include <es_sock.h>
 #include "eventmediator.h"
+#include "eventmediatorsession.h"
+#include "eventmediatorclientservercommon.h"
 #include "eventlogger.h"
-#include "eventmediatordefs.h"
 #include "sit.h"
 #include "log_em.h"
 
+
 #define FIRST_ARGUMENT 0
 #define SECOND_ARGUMENT 1
 #define THIRD_ARGUMENT 2
 #define FOURTH_ARGUMENT 3
 
+
 // ============================= CEventMediatorServer =============================
 
 const TUint CEventMediatorServer::iRangeCount = 2;
     
 const TInt CEventMediatorServer::iRanges[iRangeCount] = 
     {
-    CEventMediatorSession::KEventMediatorListen,
-    CEventMediatorSession::KEventMediatorClearEventLog+1
+    KEventMediatorListen,
+    KEventMediatorClearEventLog+1
     };
 
 const TUint8 CEventMediatorServer::iElementIndex[iRangeCount] = 
@@ -74,23 +76,27 @@
 CEventMediatorServer* CEventMediatorServer::NewL()
     {
     LOG(Log::Printf(_L("CEventMediatorServer::NewL - begin\n")));
-    CEventMediatorServer* server = CEventMediatorServer::NewLC();
-    CleanupStack::Pop(); // server
+    
+    CEventMediatorServer* self = CEventMediatorServer::NewLC();
+    CleanupStack::Pop(self); // server
     LOG(Log::Printf(_L("CEventMediatorServer::NewL - end\n")));
-    return server;
+    
+    return self;
     }
 
 CEventMediatorServer* CEventMediatorServer::NewLC()
     {
     LOG(Log::Printf(_L("CEventMediatorServer::NewLC - begin\n")));
-    CEventMediatorServer* server = new (ELeave) CEventMediatorServer();
-    CleanupStack::PushL(server); 
-    server->ConstructL(server);
+    
+    CEventMediatorServer* self = new (ELeave) CEventMediatorServer();
+    CleanupStack::PushL(self); 
+    self->ConstructL();
+    
     LOG(Log::Printf(_L("CEventMediatorServer::NewLC - end\n")));
-    return server;
+    return self;
     }
 
-void CEventMediatorServer::ConstructL(CEventMediatorServer* aServer)
+void CEventMediatorServer::ConstructL()
     {
     RFs fs;
     User::LeaveIfError(fs.Connect());
@@ -105,7 +111,7 @@
     
     CleanupStack::PopAndDestroy(); // fs
     
-    aServer->iLogger = CEventLogger::NewL(this);
+    iLogger = CEventLogger::NewL(this);
     iSit = new (ELeave) CSit(this);
     StartL(KEventMediatorServer);
     }
@@ -128,19 +134,6 @@
     delete iSit;
     }
 
-// ----------------------------------------------------------------------------
-// CEventMediatorServer::StopEventMediator
-// Stops Event Mediator service if there are no sessions left.
-// ----------------------------------------------------------------------------
-//
-void CEventMediatorServer::StopEventMediator(void)
-    {
-    if (iSessionCount == 0) 
-        {
-        LOG(Log::Printf(_L("CEventMediatorServer::StopEventMediator - session count 0, stopping scheduler and thus the server\n")));
-        CActiveScheduler::Stop();   
-        }   
-    }
 
 TInt CEventMediatorServer::RunError(TInt aError)
     {
@@ -172,10 +165,51 @@
         User::Leave(KErrServerTerminated);
         }
     
-    CSession2* session = CEventMediatorSession::NewL(CONST_CAST(CEventMediatorServer*, this), aMessage);
+    
+    CSession2* session = CEventMediatorSession::NewL(const_cast<CEventMediatorServer&>(*this), 
+                                                     IsClientTheSitL(aMessage));
+    iSessionCount++;
     return session;
     }
 
+void CEventMediatorServer::SessionDeleted(TBool aIsSitSession)
+    {
+    TInt normalSessionCount = NormalSessionCount();
+
+    // If this too is a normal session and is dying,
+    // decrement the normal session count by one
+    if (!aIsSitSession)
+        {
+        normalSessionCount--;        
+        }
+
+    if (normalSessionCount == 0)
+        {
+        // If "normal" (non-sit) sessions are no longer present,
+        // we complete the task arrival observation request, thus
+        // causing the SIT to terminate and close its connection
+        // to this server. This should be the last connection whose
+        // closing will cause this server to terminate.
+        // NOTE. KErrCancel cannot be used here as the Event Mediator 
+        // does not report it to the caller
+        LOG(Log::Printf(_L("CEventMediatorServer::SessionDeleted - normal session count = 0\n")));
+        CompleteListener(ETaskArrivedEvent, NULL, KErrAbort);
+
+        // Set the server state to "shutting down". This will
+        // cause the server to discard any new connect requests
+        // with KErrServerTerminated.
+        iShuttingDown = ETrue;
+        }
+
+    __ASSERT_DEBUG(iSessionCount > 0, User::Invariant());
+    iSessionCount--;
+    if (iSessionCount == 0) 
+        {
+        LOG(Log::Printf(_L("CEventMediatorServer::SessionDeleted - session count 0, stopping scheduler and thus the server\n")));
+        CActiveScheduler::Stop();   
+        }       
+    }
+
 void CEventMediatorServer::ReportEventL(const TEventType aType, TDesC8* aSpec,
                                         TDesC8* aData, TInt aStatus)
     {
@@ -204,8 +238,11 @@
         iStoredEvents.AppendL(container);
         CleanupStack::Pop();
         }
+    
     // Write event to log
-    if (aType == ELogEvent && iLogger)
+    __ASSERT_DEBUG(iLogger != NULL, User::Invariant());
+    
+    if (aType == ELogEvent)
         {
         LOG(Log::Printf(_L("CEventMediatorServer::ReportEventL - calling iLogger->LogEvent\n")));
         iLogger->LogEvent(*aData);
@@ -257,7 +294,7 @@
         }
     }
 
-TBool CEventMediatorServer::IsClientTheSitL(const RMessage2& aMessage)
+TBool CEventMediatorServer::IsClientTheSitL(const RMessage2& aMessage) const
     {
     LOG(Log::Printf(_L("CEventMediatorServer::IsClientTheSitL\n")));
     TBool isClientTheSit = EFalse;
@@ -559,689 +596,11 @@
         session = (CEventMediatorSession*) iSessionIter++;
         }
     }
-
-void CEventMediatorServer::SetShuttingDown(TBool aShuttingDown)
-    {
-    iShuttingDown = aShuttingDown;
-    }
-
-// ============================= CEventMediatorSession =============================     
-
-CEventMediatorSession* CEventMediatorSession::NewL(CEventMediatorServer* aServer, const RMessage2& aMessage)
-    {
-    LOG(Log::Printf(_L("CEventMediatorSession::NewL - begin\n")));
-    CEventMediatorSession* self;
-    self = new (ELeave) CEventMediatorSession(aServer);
-    CleanupStack::PushL(self);
-
-    // Marks the session as a "SIT session"
-    // if the client is the SIT thread
-    self->iIsSitSession = aServer->IsClientTheSitL(aMessage);
-
-    aServer->iSessionCount++;
-
-    if ( !self->IsASitSession() )
-        {
-        User::LeaveIfError(self->iFs.Connect()); // For EventLog
-        self->iEventLogFileOpen = EFalse;
-        }
-
-    CleanupStack::Pop(); // self
-
-    LOG(Log::Printf(_L("CEventMediatorSession::NewL - end\n")));
-    return self;
-    }
-
-CEventMediatorSession::CEventMediatorSession(CEventMediatorServer* aServer)
-    : iListenedEvents(2), iServer(aServer)
-    {
-    }
-
-CEventMediatorSession::~CEventMediatorSession(void)
-    {
-    LOG(Log::Printf(_L("CEventMediatorSession::~CEventMediatorSession\n")));
-    CancelAll();
-    if (iServer)
-        {        
-        TInt normalSessionCount = iServer->NormalSessionCount();
-
-        // If this too is a normal session and is dying,
-        // decrement the normal session count by one
-        if (!IsASitSession())
-            {
-            normalSessionCount--;
-            
-            if (iEventLogFileOpen)
-                {
-                iEventLogFile.Close();
-                iEventLogFileOpen = EFalse;
-                }
-            iFs.Close(); // For EventLog
-            
-            }
-
-        if (normalSessionCount == 0)
-            {
-            // If "normal" (non-sit) sessions are no longer present,
-            // we complete the task arrival observation request, thus
-            // causing the SIT to terminate and close its connection
-            // to this server. This should be the last connection whose
-            // closing will cause this server to terminate.
-            // NOTE. KErrCancel cannot be used here as the Event Mediator 
-            // does not report it to the caller
-            LOG(Log::Printf(_L("CEventMediatorSession::~CEventMediatorSession - normal session count = 0\n")));
-            iServer->CompleteListener(ETaskArrivedEvent, NULL, KErrAbort);
-
-            // Set the server state to "shutting down". This will
-            // cause the server to discard any new connect requests
-            // with KErrServerTerminated.
-            iServer->SetShuttingDown(ETrue);
-            }
-
-        if (iServer->iSessionCount)
-            {
-            iServer->iSessionCount--;
-            }
-
-        iServer->StopEventMediator();
-        }
-    }
-
-void CEventMediatorSession::ServiceL(const RMessage2& aMessage)
-    {
-    TInt status = 0;
-
-    switch (aMessage.Function())
-        {
-        case KEventMediatorListen:
-            ListenToEventL(aMessage);
-            break;
-
-        case KEventMediatorListenWithSpec:
-            ListenToEventWithSpecL(aMessage);
-            break;
-
-        case KEventMediatorCancel:
-            CancelListening(aMessage);        
-            aMessage.Complete(KErrNone);
-            break;
-
-        case KEventMediatorCancelWithSpec:
-            CancelListeningWithSpecL(aMessage);        
-            aMessage.Complete(KErrNone);
-            break;
-
-        case KEventMediatorCancelAll:
-            CancelAll();        
-            aMessage.Complete(KErrNone);
-            break;
-
-        case KEventMediatorReportEvent:
-            ReportEventL(aMessage);
-            aMessage.Complete(KErrNone);
-            break;
-
-        case KEventMediatorReportEventWithSpec:
-            ReportEventWithSpecL(aMessage);
-            aMessage.Complete(KErrNone);
-            break;
-
-        case KEventMediatorFetchData:
-            status = FetchDataL(aMessage);
-            aMessage.Complete(status);
-            break;
-
-        case KEventMediatorReportLogEvent:
-            ReportLogEventL(aMessage);
-            aMessage.Complete(KErrNone);
-            break;
-
-        case KEventMediatorNewEventSpecId:
-            NewEventSpecIdL(aMessage);
-            aMessage.Complete(KErrNone);
-            break;
-        case KEventMediatorDeletePrivateFiles:
-            status = DeletePrivateFiles();
-            aMessage.Complete(status);
-            break;
-
-        case KEventMediatorGetEventLogSize:
-            status = GetEventLogSize(aMessage);
-            aMessage.Complete(status);
-            break;
-
-        case KEventMediatorGetEventLogHeader:
-            status = GetEventLogHeader(aMessage);
-            aMessage.Complete(status);
-            break;
-        case KEventMediatorGetEventLogData:
-            status = GetEventLogData(aMessage);
-            aMessage.Complete(status);
-            break;
-        case KEventMediatorClearEventLog:
-            status = ClearEventLog();
-            aMessage.Complete(status);
-            break;
-        default:
-            aMessage.Complete(KErrGeneral);
-            break;
-        }
-    }
-
-TInt CEventMediatorSession::ListenToEventL(const RMessage2& aMessage)
-    {
-    CListenerContainer* listener = new (ELeave) CListenerContainer(aMessage, NULL, iServer);
-    CleanupStack::PushL(listener);
-
-    iListenedEvents.AppendL(listener);
-    CleanupStack::Pop(); // listener
-
-    listener->AnalyzeRequestL();
-
-    return KErrNone;
-    }
-
-TInt CEventMediatorSession::ListenToEventWithSpecL(const RMessage2& aMessage)
-    {
-    HBufC8* specBuf = NULL;
-
-    // Read specification
-    specBuf = ReadSpecificationFromClientL(aMessage);
-    CleanupStack::PushL(specBuf);
-
-    // Ownership of specBuf is given to listener
-    CListenerContainer* listener = new (ELeave) CListenerContainer(aMessage, specBuf, iServer);
-    CleanupStack::Pop(); // specBuf
-    CleanupStack::PushL(listener);
-        
-    iListenedEvents.AppendL(listener);
-    CleanupStack::Pop(); // listener
-
-    listener->AnalyzeRequestL();
-
-    return KErrNone;
-    }
-
-void CEventMediatorSession::CancelListening(const RMessage2& aMessage)
-    {
-    TInt index;
-    
-    while (FindListenerMsg((TEventType)aMessage.Int0(), index))
-        {
-        CompleteListener(index, KErrCancel);
-        }
-    }
-
-void CEventMediatorSession::CancelListeningWithSpecL(const RMessage2& aMessage)
-    {
-    HBufC8* specBuf = NULL;
-    TInt index;
-    
-    // Read specification
-    specBuf = ReadSpecificationFromClientL(aMessage);
-    CleanupStack::PushL(specBuf);
-
-    // Cancel listeners
-    while (FindListenerMsg((TEventType)aMessage.Int0(), specBuf, index))
-        {
-        CompleteListener(index, KErrCancel);
-        }
-    CleanupStack::PopAndDestroy(); // specBuf
-    }
-
-void CEventMediatorSession::CancelAll()
-    {
-    TInt nEvents = iListenedEvents.Count();
-    for (TInt i = 0; i < nEvents; i++)  
-        {
-        iListenedEvents.At(i)->Complete(KErrCancel);
-        delete iListenedEvents.At(i);
-        iListenedEvents.At(i) = NULL;
-        }
-    iListenedEvents.Reset();
-    }
-
-void CEventMediatorSession::ReportEventL(const RMessage2& aMessage)
-    {
-    TEventType eventType = (TEventType)aMessage.Int0();
-    LOG(Log::Printf(_L("CEventMediatorSession::ReportEventL - event type = %d\n"), eventType));
-    // Read data
-    HBufC8* dataBuf = ReadEventDataFromClientL(aMessage);
-    CleanupStack::PushL(dataBuf);
-    // Report event to server
-    iServer->ReportEventL(eventType, NULL, dataBuf);
-    CleanupStack::Pop();
-    }
-
-void CEventMediatorSession::ReportEventWithSpecL(const RMessage2& aMessage)
-    {
-    TEventType eventType=(TEventType) aMessage.Int0();
-    LOG(Log::Printf(_L("CEventMediatorSession::ReportEventWithSpecL - event type = %d\n"), eventType));
-    // Read data
-    HBufC8* dataBuf = ReadEventDataFromClientL(aMessage);
-    CleanupStack::PushL(dataBuf);
-    // Read specification
-    HBufC8* specBuf = ReadSpecificationFromClientL(aMessage);
-    CleanupStack::PushL(specBuf);
-    // Report event to server
-    iServer->ReportEventL(eventType, specBuf, dataBuf);
-    CleanupStack::PopAndDestroy(); // specBuf
-    CleanupStack::Pop(); // dataBuf 
-    }
-
-void CEventMediatorSession::ReportLogEventL(const RMessage2& aMessage)
-    {
-    LOG(Log::Printf(_L("CEventMediatorSession::ReportLogEventL\n")));
-    // Read event
-    TLogEvent event;
-    TPckg<TLogEvent> eventPckg(event);
-    aMessage.ReadL(FIRST_ARGUMENT, eventPckg);
-
-    // Create one buffer to contain put everything in a normal buffer and
-    TInt lengthsDesLth = event.iDesCount * sizeof(TInt);
-    TInt position = eventPckg.Length();
-    TInt dataLength = position + lengthsDesLth + aMessage.Int2();
-    HBufC8* dataBuf = HBufC8::NewLC(dataLength);
-    TPtr8 dataPtr = dataBuf->Des();
-
-    // Copy event to buffer
-    dataPtr.Append(eventPckg);
-    // Read lengths to buffer
-    TPtr8 tmpPtr(&dataPtr[position], 0, dataLength - position);
-    aMessage.ReadL(SECOND_ARGUMENT, tmpPtr);
-    // Read descriptors to the buffer
-    position= dataPtr.Length();
-    tmpPtr.Set(&dataPtr[position], 0, dataLength - position);
-    aMessage.ReadL(THIRD_ARGUMENT, tmpPtr);
-
-    // Report event to server
-    iServer->ReportEventL(ELogEvent, NULL, dataBuf);
-    CleanupStack::Pop();
-    }
-
-TInt CEventMediatorSession::FetchDataL(const RMessage2& aMessage)
-    {
-    LOG(Log::Printf(_L("CEventMediatorSession::FetchDataL\n")));
-    return iServer->CopyEventDataL(aMessage);
-    }
-
-TInt CEventMediatorSession::CheckEventL(const TEventType aType, const TDesC8* aSpec,
-                                        const TDesC8* aData, TInt aStatus)
-    {
-    TInt index;
-    TInt listenerCount = 0;
-    TInt dataLth = 0;
-    // Some events don't not have data
-    if (aData)
-        {
-        dataLth = aData->Length();
-        }
-    TPckg<TInt> lengthpckg(dataLth);
-    TPckgC<const TAny*> ptrpckg(aData);
-
-    while (FindListenerMsg(aType, aSpec, index))
-        {
-        RMessage2& listener = iListenedEvents.At(index)->Message();
-
-        if (aStatus == KErrNone)
-            {
-            // Write info about data
-            listener.WriteL(SECOND_ARGUMENT, lengthpckg);
-            listener.WriteL(THIRD_ARGUMENT, ptrpckg);
-
-            // Complete listener
-            listener.Complete(KErrNone);
-            }
-        else
-            {
-            listener.Complete(aStatus);
-            }
-        
-        delete iListenedEvents.At(index);
-        iListenedEvents.Delete(index);
-        listenerCount++;    
-        }
-
-    return listenerCount;
-    }
-
-TBool CEventMediatorSession::FindListenerMsg(const TEventType aType, TInt& index)
-    {
-    for (TInt i = 0; i < iListenedEvents.Count(); i++)
-        {
-        if (iListenedEvents.At(i)->Type() == aType)
-            {
-            index=i;
-            return ETrue;
-            }
-        }
-    return EFalse;
-    }
-
-TBool CEventMediatorSession::FindListenerMsg(const TEventType aType, const TDesC8* aSpec, TInt& index)
-    {
-    for (TInt i = 0; i < iListenedEvents.Count(); i++)
-        {
-        if (iListenedEvents.At(i)->HandlesEvent(aType, aSpec))
-            {
-            index = i;
-            return ETrue;
-            }
-        }
-    return EFalse;
-    }
-
-TBool CEventMediatorSession::FindTaskRequestListenerMsg(TInt& index)
-    {
-    for (TInt i = 0; i < iListenedEvents.Count(); i++)
-        {
-        if (CSit::EventRequiresSit(iListenedEvents.At(i)->Type()))
-            {
-            index = i;
-            return ETrue;
-            }
-        }
-    return EFalse;
-    }
-    
-HBufC8* CEventMediatorSession::ReadSpecificationFromClientL(const RMessage2& aMessage)
-    {
-    HBufC8* specBuf;
-    // Read specification descriptor length from client, create specification buffer
-    const TAny* desPtr = aMessage.Ptr3();
-    if (desPtr == NULL)
-        {
-        return NULL;
-        }
-    TInt specLength = aMessage.GetDesLength(FOURTH_ARGUMENT);
-    // Create spcification buffer
-    specBuf = HBufC8::NewLC(specLength);
-    TPtr8 ptr = specBuf->Des();
-    // Read specification
-    aMessage.ReadL(FOURTH_ARGUMENT, ptr);
-    CleanupStack::Pop(); // specBuf
-    return specBuf;
-    }
-
-HBufC8* CEventMediatorSession::ReadEventDataFromClientL(const RMessage2& aMessage)
-    {
-    HBufC8* dataBuf = NULL;
-    TInt desLength = aMessage.Int1();
-    
-    if (desLength != 0) // Some events have no data 
-        {
-        dataBuf = HBufC8::NewLC(desLength);
-        TPtr8 ptr = dataBuf->Des();
-        aMessage.ReadL(THIRD_ARGUMENT, ptr);
-        CleanupStack::Pop(); // dataBuf
-        }
-    return dataBuf;
-    }
-
-CListenerContainer* CEventMediatorSession::FindWaitingTaskRequest()
-    {
-    CListenerContainer* listener = NULL;
-    
-    for (TInt i = 0; i < iListenedEvents.Count(); i++)
-        {
-        if (iListenedEvents.At(i)->WaitingForFulfilling())
-            {
-            listener = iListenedEvents.At(i);
-            break;
-            }
-        }
-
-    return listener;
-    }
-
-CListenerContainer* CEventMediatorSession::FindListener(TEventType aEventType,
-                                                        TInt aEventSpecId)
-    {
-    CListenerContainer* listener = NULL;
-    
-    for (TInt i = 0; i < iListenedEvents.Count(); i++)
-        {
-        if (iListenedEvents.At(i)->Type() == aEventType)
-            {
-            TEventSpec* eventSpec = (TEventSpec*)(iListenedEvents.At(i)->Specification()->Ptr());
-
-            if (eventSpec->iId == aEventSpecId)
-                {
-                listener = iListenedEvents.At(i);
-                break;
-                }
-            }
-        }
-
-    return listener;
-    }
-    
-CListenerContainer* CEventMediatorSession::FindListener(TEventType aEventType,
-                                                        const TDesC8* aEventSpec)
-    {
-    CListenerContainer* listener = NULL;
-    
-    for (TInt i = 0; i < iListenedEvents.Count(); i++)
-        {
-        if (iListenedEvents.At(i)->HandlesEvent(aEventType, aEventSpec))
-            {
-            listener = iListenedEvents.At(i);
-            break;
-            }
-        }
-
-    return listener;
-    }
-
-void CEventMediatorSession::CompleteListener(TEventType aEventType,
-                                             const TDesC8* aEventSpec,
-                                             TInt aStatus)
-    {
-    TInt index;
-    while (FindListenerMsg(aEventType, aEventSpec, index))
-        {
-        CompleteListener(index, aStatus);
-        }
-    }
-        
-void CEventMediatorSession::CompleteListener(TInt aIndex, TInt aStatus)
-    {
-    iListenedEvents.At(aIndex)->Complete(aStatus);
-    delete iListenedEvents.At(aIndex);
-    iListenedEvents.Delete(aIndex);
-    }
-
-void CEventMediatorSession::CompleteTaskRequests(TInt aStatus)
-    {
-    LOG(Log::Printf(_L("CEventMediatorSession::CompleteTaskRequests\n")));
-    TInt index;
-    while (FindTaskRequestListenerMsg(index))
-        {
-        CompleteListener(index, aStatus);
-        }
-    }
-
-TBool CEventMediatorSession::IsASitSession()
-    {
-    return iIsSitSession;
-    }
-
-void CEventMediatorSession::NewEventSpecIdL(const RMessage2& aMessage)
-    {
-    TInt newEventSpecId = iServer->NewEventSpecId();
-    TPckg<TInt> newEventSpecIdDes(newEventSpecId);
-    aMessage.WriteL(FIRST_ARGUMENT, newEventSpecIdDes);
-    }
-
-TInt CEventMediatorSession::DeletePrivateFiles()
-    {
-    TRAPD(err, DeletePrivateFilesL());
-    if ( err )
-        {
-        LOG(Log::Printf(_L("DeletePrivateFilesL() leave error %d\n"), err));
-        return err;
-        }
-
-    return KErrNone;
-    }
-
-void CEventMediatorSession::DeletePrivateFilesL()
-    {
-    LOG(Log::Printf(_L("DeletePrivateFilesL() called\n")));
-
-    CFileMan* fileMan = CFileMan::NewL(iFs);
-    CleanupStack::PushL(fileMan);
-
-    TPath privateDir;
-    User::LeaveIfError(iFs.PrivatePath(privateDir));
-
-    TInt err = fileMan->RmDir(privateDir);
-    if (err != KErrNone && err != KErrPathNotFound && err != KErrNotFound)
-        {
-        User::Leave(err);
-        }
-    CleanupStack::PopAndDestroy(); //fileMan
-    }
-
-TInt CEventMediatorSession::GetEventLogSize(
-    const RMessage2& aMessage)
-    {
-    if ( iEventLogFileOpen )
-        {
-        iEventLogFile.Close();
-        iEventLogFileOpen = EFalse;
-        }
-
-    TInt err = iEventLogFile.Open(iFs, iServer->EventLogFileName(), EFileRead | EFileShareAny);
-    if ( err )
-        return err;
-
-    TInt size(0);
-    err = iEventLogFile.Size(size);
-    if ( err )
-        {
-        iEventLogFile.Close();
-        return err;
-        }
-    
-    TPckg<TInt> sizePckg(size);
-    err = aMessage.Write(FIRST_ARGUMENT, sizePckg);
-    if ( err )
-        {
-        iEventLogFile.Close();
-        return err;
-        }
-
-    iEventLogFileOpen = ETrue;
-    
-    return KErrNone;
-    }
-
-TInt CEventMediatorSession::GetEventLogHeader(
-    const RMessage2& aMessage)
-    {
-    TInt err(0);
-    
-    if ( !iEventLogFileOpen )
-        {
-        err = iEventLogFile.Open(iFs, iServer->EventLogFileName(), EFileRead | EFileShareAny);
-        if ( err )
-            return err;
-        iEventLogFileOpen = ETrue;
-        }
-    
-    TInt position = 0;
-    err = iEventLogFile.Seek(ESeekStart, position);     
-    if (err != KErrNone)
-        return err;
-
-    TBuf8<EVENTLOG_FILE_HEADER_LTH> fileHeaderBuf;
-    err = iEventLogFile.Read(fileHeaderBuf, EVENTLOG_FILE_HEADER_LTH);
-    if (err != KErrNone)
-        return err;
-
-    TRAP(err, aMessage.WriteL(FIRST_ARGUMENT, fileHeaderBuf));
-    if ( err )
-        return err;
-
-    return KErrNone;
-    }
-    
-TInt CEventMediatorSession::GetEventLogData(
-    const RMessage2& aMessage)
-    {
-    TInt err(0);
-
-    if ( !iEventLogFileOpen )
-        {
-        err = iEventLogFile.Open(iFs, iServer->EventLogFileName(), EFileRead | EFileShareAny);
-        if ( err )
-            return err;
-        iEventLogFileOpen = ETrue;
-        }
-    
-    TInt size(0);
-    err = iEventLogFile.Size(size);
-    if ( err )
-        return err;
-
-    if ( size < EVENTLOG_FILE_HEADER_LTH )
-        return KErrNotFound;
-
-    HBufC8* eventLogFileBuf = NULL;
-    TRAP(err, eventLogFileBuf = HBufC8::NewL(size));
-    if ( err )
-        {
-        return err;
-        }
-    
-    TPtr8 eventLogDataPtr(eventLogFileBuf->Des());
-    TInt position(0);
-    err = iEventLogFile.Seek(ESeekStart, position);
-    if ( err )
-        {
-        delete eventLogFileBuf;
-        return err;
-        }
-    err = iEventLogFile.Read(eventLogDataPtr); // iLogFileSize);
-    if ( err )
-        {
-        delete eventLogFileBuf;
-        return err;
-        }
-    
-    TRAP( err, aMessage.WriteL(FIRST_ARGUMENT, eventLogDataPtr));
-    if ( err )
-        {
-        delete eventLogFileBuf;
-        return err;
-        }
-
-    delete eventLogFileBuf;
-    eventLogFileBuf = NULL;
-    
-    return KErrNone;
-    }
-    
-TInt CEventMediatorSession::ClearEventLog()
-    {
-    if ( iEventLogFileOpen )
-        {
-        iEventLogFile.Close();
-        iEventLogFileOpen = EFalse;
-        }
-
-    TInt err = iFs.Delete(iServer->EventLogFileName());
-
-    return err;
-    }
-
-
     
 // ============================= CEventMediatorServer =============================    
 
 CListenerContainer::CListenerContainer(const RMessage2& aMessage, TDesC8* aSpec,
-                                       CEventMediatorServer* aServer)
+                                       CEventMediatorServer& aServer)
     : iSpec(aSpec), iMessage(aMessage), iServer(aServer)
     {
     iEventType = Type();
@@ -1253,23 +612,23 @@
     if (CSit::EventRequiresSit(iEventType))
         {
         LOG(Log::Printf(_L("CListenerContainer::AnalyzeRequestL - event type = %d, requires SIT\n"), iEventType));
-        iServer->MakeSureSitIsRunningL();
-        iServer->TaskRequestArrivedL(this);
+        iServer.MakeSureSitIsRunningL();
+        iServer.TaskRequestArrivedL(this);
         }
 
     // If this event listening request is the one
     // made by the SIT task arrival observer...
     if (iEventType == ETaskArrivedEvent)
         {
-        iServer->SetTaskArrivalListenerL(this);
-        iServer->TaskArrivalObservationRequestArrivedL();
+        iServer.SetTaskArrivalListenerL(this);
+        iServer.TaskArrivalObservationRequestArrivedL();
         }
 
     // If this event listening request is one
     // made by a SIT TH to fetch a task...
     if (iEventType == EFetchTaskInfoEvent)
         {
-        iServer->TaskRequestEventSpecFetchingRequestArrivedL(this);
+        iServer.TaskRequestEventSpecFetchingRequestArrivedL(this);
         }
 
     // If the event listening request is one
@@ -1277,7 +636,7 @@
     // of the task request it is handling
     if (CSit::IsTaskCancellationObservationRequest(iEventType))
         {
-        iServer->TaskCancellationObservationRequestArrivedL(this);
+        iServer.TaskCancellationObservationRequestArrivedL(this);
         }
     }
     
@@ -1285,9 +644,9 @@
     {
     delete iSpec;
 
-    if (iServer->TaskArrivalListener() == this)
+    if (iServer.TaskArrivalListener() == this)
         {
-        iServer->ClearTaskArrivalListener();
+        iServer.ClearTaskArrivalListener();
         }
     }
 
@@ -1324,7 +683,7 @@
             {
             // Complete the task request cancellation
             // observation, if found
-            iServer->CompleteListener(cancelEventType, iSpec, KErrNone);
+            iServer.CompleteListener(cancelEventType, iSpec, KErrNone);
             }
         }
     
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vpnengine/eventmediator/src/eventmediatorsession.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -0,0 +1,666 @@
+/*
+* Copyright (c) 2003-2010 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   This module defines event mediator server side session.
+*
+*/
+
+#include "eventmediatorsession.h"
+#include "eventmediator.h"
+#include "eventmediatorclientservercommon.h"
+#include "eventlogger.h"
+#include "sit.h"
+#include "log_em.h"
+
+#define FIRST_ARGUMENT 0
+#define SECOND_ARGUMENT 1
+#define THIRD_ARGUMENT 2
+#define FOURTH_ARGUMENT 3
+
+
+// ============================= CEventMediatorSession =============================     
+
+CEventMediatorSession* CEventMediatorSession::NewL(CEventMediatorServer& aServer, 
+                                                   TBool aIsSitSession)
+    {
+    LOG(Log::Printf(_L("CEventMediatorSession::NewL - begin\n")));
+    
+    CEventMediatorSession* self = new (ELeave) CEventMediatorSession(aServer, aIsSitSession);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(); // self
+
+    LOG(Log::Printf(_L("CEventMediatorSession::NewL - end\n")));
+    return self;
+    }
+
+CEventMediatorSession::CEventMediatorSession(CEventMediatorServer& aServer, TBool aIsSitSession)
+    : iListenedEvents(2), iServer(aServer), iIsSitSession(aIsSitSession)
+    {
+    }
+
+void CEventMediatorSession::ConstructL()
+    {
+    if ( !IsASitSession() )
+        {
+        User::LeaveIfError(iFs.Connect()); // For EventLog
+        iEventLogFileOpen = EFalse;
+        }    
+    }
+
+
+CEventMediatorSession::~CEventMediatorSession(void)
+    {
+    LOG(Log::Printf(_L("CEventMediatorSession::~CEventMediatorSession\n")));
+    CancelAll();
+
+    // If this too is a normal session and is dying,
+    // decrement the normal session count by one
+    if (!IsASitSession())
+        {
+        iEventLogFile.Close();
+        iEventLogFileOpen = EFalse;
+        iFs.Close();         
+        }
+    iServer.SessionDeleted(IsASitSession());    
+    }
+
+void CEventMediatorSession::ServiceL(const RMessage2& aMessage)
+    {
+    TInt status = 0;
+
+    switch (aMessage.Function())
+        {
+        case KEventMediatorListen:
+            ListenToEventL(aMessage);
+            break;
+
+        case KEventMediatorListenWithSpec:
+            ListenToEventWithSpecL(aMessage);
+            break;
+
+        case KEventMediatorCancel:
+            CancelListening(aMessage);        
+            aMessage.Complete(KErrNone);
+            break;
+
+        case KEventMediatorCancelWithSpec:
+            CancelListeningWithSpecL(aMessage);        
+            aMessage.Complete(KErrNone);
+            break;
+
+        case KEventMediatorCancelAll:
+            CancelAll();        
+            aMessage.Complete(KErrNone);
+            break;
+
+        case KEventMediatorReportEvent:
+            ReportEventL(aMessage);
+            aMessage.Complete(KErrNone);
+            break;
+
+        case KEventMediatorReportEventWithSpec:
+            ReportEventWithSpecL(aMessage);
+            aMessage.Complete(KErrNone);
+            break;
+
+        case KEventMediatorFetchData:
+            status = FetchDataL(aMessage);
+            aMessage.Complete(status);
+            break;
+
+        case KEventMediatorReportLogEvent:
+            ReportLogEventL(aMessage);
+            aMessage.Complete(KErrNone);
+            break;
+
+        case KEventMediatorNewEventSpecId:
+            NewEventSpecIdL(aMessage);
+            aMessage.Complete(KErrNone);
+            break;
+        case KEventMediatorDeletePrivateFiles:
+            status = DeletePrivateFiles();
+            aMessage.Complete(status);
+            break;
+
+        case KEventMediatorGetEventLogSize:
+            status = GetEventLogSize(aMessage);
+            aMessage.Complete(status);
+            break;
+
+        case KEventMediatorGetEventLogHeader:
+            status = GetEventLogHeader(aMessage);
+            aMessage.Complete(status);
+            break;
+        case KEventMediatorGetEventLogData:
+            status = GetEventLogData(aMessage);
+            aMessage.Complete(status);
+            break;
+        case KEventMediatorClearEventLog:
+            status = ClearEventLog();
+            aMessage.Complete(status);
+            break;
+        default:
+            aMessage.Complete(KErrGeneral);
+            break;
+        }
+    }
+
+TInt CEventMediatorSession::ListenToEventL(const RMessage2& aMessage)
+    {
+    CListenerContainer* listener = new (ELeave) CListenerContainer(aMessage, NULL, iServer);
+    CleanupStack::PushL(listener);
+
+    iListenedEvents.AppendL(listener);
+    CleanupStack::Pop(); // listener
+
+    listener->AnalyzeRequestL();
+
+    return KErrNone;
+    }
+
+TInt CEventMediatorSession::ListenToEventWithSpecL(const RMessage2& aMessage)
+    {
+    HBufC8* specBuf = NULL;
+
+    // Read specification
+    specBuf = ReadSpecificationFromClientL(aMessage);
+    CleanupStack::PushL(specBuf);
+
+    // Ownership of specBuf is given to listener
+    CListenerContainer* listener = new (ELeave) CListenerContainer(aMessage, specBuf, iServer);
+    CleanupStack::Pop(); // specBuf
+    CleanupStack::PushL(listener);
+        
+    iListenedEvents.AppendL(listener);
+    CleanupStack::Pop(); // listener
+
+    listener->AnalyzeRequestL();
+
+    return KErrNone;
+    }
+
+void CEventMediatorSession::CancelListening(const RMessage2& aMessage)
+    {
+    TInt index;
+    
+    while (FindListenerMsg((TEventType)aMessage.Int0(), index))
+        {
+        CompleteListener(index, KErrCancel);
+        }
+    }
+
+void CEventMediatorSession::CancelListeningWithSpecL(const RMessage2& aMessage)
+    {
+    HBufC8* specBuf = NULL;
+    TInt index;
+    
+    // Read specification
+    specBuf = ReadSpecificationFromClientL(aMessage);
+    CleanupStack::PushL(specBuf);
+
+    // Cancel listeners
+    while (FindListenerMsg((TEventType)aMessage.Int0(), specBuf, index))
+        {
+        CompleteListener(index, KErrCancel);
+        }
+    CleanupStack::PopAndDestroy(); // specBuf
+    }
+
+void CEventMediatorSession::CancelAll()
+    {
+    TInt nEvents = iListenedEvents.Count();
+    for (TInt i = 0; i < nEvents; i++)  
+        {
+        iListenedEvents.At(i)->Complete(KErrCancel);
+        delete iListenedEvents.At(i);
+        iListenedEvents.At(i) = NULL;
+        }
+    iListenedEvents.Reset();
+    }
+
+void CEventMediatorSession::ReportEventL(const RMessage2& aMessage)
+    {
+    TEventType eventType = (TEventType)aMessage.Int0();
+    LOG(Log::Printf(_L("CEventMediatorSession::ReportEventL - event type = %d\n"), eventType));
+    // Read data
+    HBufC8* dataBuf = ReadEventDataFromClientL(aMessage);
+    CleanupStack::PushL(dataBuf);
+    // Report event to server
+    iServer.ReportEventL(eventType, NULL, dataBuf);
+    CleanupStack::Pop();
+    }
+
+void CEventMediatorSession::ReportEventWithSpecL(const RMessage2& aMessage)
+    {
+    TEventType eventType=(TEventType) aMessage.Int0();
+    LOG(Log::Printf(_L("CEventMediatorSession::ReportEventWithSpecL - event type = %d\n"), eventType));
+    // Read data
+    HBufC8* dataBuf = ReadEventDataFromClientL(aMessage);
+    CleanupStack::PushL(dataBuf);
+    // Read specification
+    HBufC8* specBuf = ReadSpecificationFromClientL(aMessage);
+    CleanupStack::PushL(specBuf);
+    // Report event to server
+    iServer.ReportEventL(eventType, specBuf, dataBuf);
+    CleanupStack::PopAndDestroy(); // specBuf
+    CleanupStack::Pop(); // dataBuf 
+    }
+
+void CEventMediatorSession::ReportLogEventL(const RMessage2& aMessage)
+    {
+    LOG(Log::Printf(_L("CEventMediatorSession::ReportLogEventL\n")));
+    // Read event
+    TLogEvent event;
+    TPckg<TLogEvent> eventPckg(event);
+    aMessage.ReadL(FIRST_ARGUMENT, eventPckg);
+
+    // Create one buffer to contain put everything in a normal buffer and
+    TInt lengthsDesLth = event.iDesCount * sizeof(TInt);
+    TInt position = eventPckg.Length();
+    TInt dataLength = position + lengthsDesLth + aMessage.Int2();
+    HBufC8* dataBuf = HBufC8::NewLC(dataLength);
+    TPtr8 dataPtr = dataBuf->Des();
+
+    // Copy event to buffer
+    dataPtr.Append(eventPckg);
+    // Read lengths to buffer
+    TPtr8 tmpPtr(&dataPtr[position], 0, dataLength - position);
+    aMessage.ReadL(SECOND_ARGUMENT, tmpPtr);
+    // Read descriptors to the buffer
+    position= dataPtr.Length();
+    tmpPtr.Set(&dataPtr[position], 0, dataLength - position);
+    aMessage.ReadL(THIRD_ARGUMENT, tmpPtr);
+
+    // Report event to server
+    iServer.ReportEventL(ELogEvent, NULL, dataBuf);
+    CleanupStack::Pop();
+    }
+
+TInt CEventMediatorSession::FetchDataL(const RMessage2& aMessage)
+    {
+    LOG(Log::Printf(_L("CEventMediatorSession::FetchDataL\n")));
+    return iServer.CopyEventDataL(aMessage);
+    }
+
+TInt CEventMediatorSession::CheckEventL(const TEventType aType, const TDesC8* aSpec,
+                                        const TDesC8* aData, TInt aStatus)
+    {
+    TInt index;
+    TInt listenerCount = 0;
+    TInt dataLth = 0;
+    // Some events don't not have data
+    if (aData)
+        {
+        dataLth = aData->Length();
+        }
+    TPckg<TInt> lengthpckg(dataLth);
+    TPckgC<const TAny*> ptrpckg(aData);
+
+    while (FindListenerMsg(aType, aSpec, index))
+        {
+        RMessage2& listener = iListenedEvents.At(index)->Message();
+
+        if (aStatus == KErrNone)
+            {
+            // Write info about data
+            listener.WriteL(SECOND_ARGUMENT, lengthpckg);
+            listener.WriteL(THIRD_ARGUMENT, ptrpckg);
+
+            // Complete listener
+            listener.Complete(KErrNone);
+            }
+        else
+            {
+            listener.Complete(aStatus);
+            }
+        
+        delete iListenedEvents.At(index);
+        iListenedEvents.Delete(index);
+        listenerCount++;    
+        }
+
+    return listenerCount;
+    }
+
+TBool CEventMediatorSession::FindListenerMsg(const TEventType aType, TInt& index)
+    {
+    for (TInt i = 0; i < iListenedEvents.Count(); i++)
+        {
+        if (iListenedEvents.At(i)->Type() == aType)
+            {
+            index=i;
+            return ETrue;
+            }
+        }
+    return EFalse;
+    }
+
+TBool CEventMediatorSession::FindListenerMsg(const TEventType aType, const TDesC8* aSpec, TInt& index)
+    {
+    for (TInt i = 0; i < iListenedEvents.Count(); i++)
+        {
+        if (iListenedEvents.At(i)->HandlesEvent(aType, aSpec))
+            {
+            index = i;
+            return ETrue;
+            }
+        }
+    return EFalse;
+    }
+
+TBool CEventMediatorSession::FindTaskRequestListenerMsg(TInt& index)
+    {
+    for (TInt i = 0; i < iListenedEvents.Count(); i++)
+        {
+        if (CSit::EventRequiresSit(iListenedEvents.At(i)->Type()))
+            {
+            index = i;
+            return ETrue;
+            }
+        }
+    return EFalse;
+    }
+    
+HBufC8* CEventMediatorSession::ReadSpecificationFromClientL(const RMessage2& aMessage)
+    {
+    HBufC8* specBuf;
+    // Read specification descriptor length from client, create specification buffer
+    const TAny* desPtr = aMessage.Ptr3();
+    if (desPtr == NULL)
+        {
+        return NULL;
+        }
+    TInt specLength = aMessage.GetDesLength(FOURTH_ARGUMENT);
+    // Create spcification buffer
+    specBuf = HBufC8::NewLC(specLength);
+    TPtr8 ptr = specBuf->Des();
+    // Read specification
+    aMessage.ReadL(FOURTH_ARGUMENT, ptr);
+    CleanupStack::Pop(); // specBuf
+    return specBuf;
+    }
+
+HBufC8* CEventMediatorSession::ReadEventDataFromClientL(const RMessage2& aMessage)
+    {
+    HBufC8* dataBuf = NULL;
+    TInt desLength = aMessage.Int1();
+    
+    if (desLength != 0) // Some events have no data 
+        {
+        dataBuf = HBufC8::NewLC(desLength);
+        TPtr8 ptr = dataBuf->Des();
+        aMessage.ReadL(THIRD_ARGUMENT, ptr);
+        CleanupStack::Pop(); // dataBuf
+        }
+    return dataBuf;
+    }
+
+CListenerContainer* CEventMediatorSession::FindWaitingTaskRequest()
+    {
+    CListenerContainer* listener = NULL;
+    
+    for (TInt i = 0; i < iListenedEvents.Count(); i++)
+        {
+        if (iListenedEvents.At(i)->WaitingForFulfilling())
+            {
+            listener = iListenedEvents.At(i);
+            break;
+            }
+        }
+
+    return listener;
+    }
+
+CListenerContainer* CEventMediatorSession::FindListener(TEventType aEventType,
+                                                        TInt aEventSpecId)
+    {
+    CListenerContainer* listener = NULL;
+    
+    for (TInt i = 0; i < iListenedEvents.Count(); i++)
+        {
+        if (iListenedEvents.At(i)->Type() == aEventType)
+            {
+            TEventSpec* eventSpec = (TEventSpec*)(iListenedEvents.At(i)->Specification()->Ptr());
+
+            if (eventSpec->iId == aEventSpecId)
+                {
+                listener = iListenedEvents.At(i);
+                break;
+                }
+            }
+        }
+
+    return listener;
+    }
+    
+CListenerContainer* CEventMediatorSession::FindListener(TEventType aEventType,
+                                                        const TDesC8* aEventSpec)
+    {
+    CListenerContainer* listener = NULL;
+    
+    for (TInt i = 0; i < iListenedEvents.Count(); i++)
+        {
+        if (iListenedEvents.At(i)->HandlesEvent(aEventType, aEventSpec))
+            {
+            listener = iListenedEvents.At(i);
+            break;
+            }
+        }
+
+    return listener;
+    }
+
+void CEventMediatorSession::CompleteListener(TEventType aEventType,
+                                             const TDesC8* aEventSpec,
+                                             TInt aStatus)
+    {
+    TInt index;
+    while (FindListenerMsg(aEventType, aEventSpec, index))
+        {
+        CompleteListener(index, aStatus);
+        }
+    }
+        
+void CEventMediatorSession::CompleteListener(TInt aIndex, TInt aStatus)
+    {
+    iListenedEvents.At(aIndex)->Complete(aStatus);
+    delete iListenedEvents.At(aIndex);
+    iListenedEvents.Delete(aIndex);
+    }
+
+void CEventMediatorSession::CompleteTaskRequests(TInt aStatus)
+    {
+    LOG(Log::Printf(_L("CEventMediatorSession::CompleteTaskRequests\n")));
+    TInt index;
+    while (FindTaskRequestListenerMsg(index))
+        {
+        CompleteListener(index, aStatus);
+        }
+    }
+
+TBool CEventMediatorSession::IsASitSession()
+    {
+    return iIsSitSession;
+    }
+
+void CEventMediatorSession::NewEventSpecIdL(const RMessage2& aMessage)
+    {
+    TInt newEventSpecId = iServer.NewEventSpecId();
+    TPckg<TInt> newEventSpecIdDes(newEventSpecId);
+    aMessage.WriteL(FIRST_ARGUMENT, newEventSpecIdDes);
+    }
+
+TInt CEventMediatorSession::DeletePrivateFiles()
+    {
+    TRAPD(err, DeletePrivateFilesL());
+    if ( err )
+        {
+        LOG(Log::Printf(_L("DeletePrivateFilesL() leave error %d\n"), err));
+        return err;
+        }
+
+    return KErrNone;
+    }
+
+void CEventMediatorSession::DeletePrivateFilesL()
+    {
+    LOG(Log::Printf(_L("DeletePrivateFilesL() called\n")));
+
+    CFileMan* fileMan = CFileMan::NewL(iFs);
+    CleanupStack::PushL(fileMan);
+
+    TPath privateDir;
+    User::LeaveIfError(iFs.PrivatePath(privateDir));
+
+    TInt err = fileMan->RmDir(privateDir);
+    if (err != KErrNone && err != KErrPathNotFound && err != KErrNotFound)
+        {
+        User::Leave(err);
+        }
+    CleanupStack::PopAndDestroy(); //fileMan
+    }
+
+TInt CEventMediatorSession::GetEventLogSize(
+    const RMessage2& aMessage)
+    {
+    if ( iEventLogFileOpen )
+        {
+        iEventLogFile.Close();
+        iEventLogFileOpen = EFalse;
+        }
+
+    TInt err = iEventLogFile.Open(iFs, iServer.EventLogFileName(), EFileRead | EFileShareAny);
+    if ( err )
+        return err;
+
+    TInt size(0);
+    err = iEventLogFile.Size(size);
+    if ( err )
+        {
+        iEventLogFile.Close();
+        return err;
+        }
+    
+    TPckg<TInt> sizePckg(size);
+    err = aMessage.Write(FIRST_ARGUMENT, sizePckg);
+    if ( err )
+        {
+        iEventLogFile.Close();
+        return err;
+        }
+
+    iEventLogFileOpen = ETrue;
+    
+    return KErrNone;
+    }
+
+TInt CEventMediatorSession::GetEventLogHeader(
+    const RMessage2& aMessage)
+    {
+    TInt err(0);
+    
+    if ( !iEventLogFileOpen )
+        {
+        err = iEventLogFile.Open(iFs, iServer.EventLogFileName(), EFileRead | EFileShareAny);
+        if ( err )
+            return err;
+        iEventLogFileOpen = ETrue;
+        }
+    
+    TInt position = 0;
+    err = iEventLogFile.Seek(ESeekStart, position);     
+    if (err != KErrNone)
+        return err;
+
+    TBuf8<EVENTLOG_FILE_HEADER_LTH> fileHeaderBuf;
+    err = iEventLogFile.Read(fileHeaderBuf, EVENTLOG_FILE_HEADER_LTH);
+    if (err != KErrNone)
+        return err;
+
+    TRAP(err, aMessage.WriteL(FIRST_ARGUMENT, fileHeaderBuf));
+    if ( err )
+        return err;
+
+    return KErrNone;
+    }
+    
+TInt CEventMediatorSession::GetEventLogData(
+    const RMessage2& aMessage)
+    {
+    TInt err(0);
+
+    if ( !iEventLogFileOpen )
+        {
+        err = iEventLogFile.Open(iFs, iServer.EventLogFileName(), EFileRead | EFileShareAny);
+        if ( err )
+            return err;
+        iEventLogFileOpen = ETrue;
+        }
+    
+    TInt size(0);
+    err = iEventLogFile.Size(size);
+    if ( err )
+        return err;
+
+    if ( size < EVENTLOG_FILE_HEADER_LTH )
+        return KErrNotFound;
+
+    HBufC8* eventLogFileBuf = NULL;
+    TRAP(err, eventLogFileBuf = HBufC8::NewL(size));
+    if ( err )
+        {
+        return err;
+        }
+    
+    TPtr8 eventLogDataPtr(eventLogFileBuf->Des());
+    TInt position(0);
+    err = iEventLogFile.Seek(ESeekStart, position);
+    if ( err )
+        {
+        delete eventLogFileBuf;
+        return err;
+        }
+    err = iEventLogFile.Read(eventLogDataPtr); // iLogFileSize);
+    if ( err )
+        {
+        delete eventLogFileBuf;
+        return err;
+        }
+    
+    TRAP( err, aMessage.WriteL(FIRST_ARGUMENT, eventLogDataPtr));
+    if ( err )
+        {
+        delete eventLogFileBuf;
+        return err;
+        }
+
+    delete eventLogFileBuf;
+    eventLogFileBuf = NULL;
+    
+    return KErrNone;
+    }
+    
+TInt CEventMediatorSession::ClearEventLog()
+    {
+    if ( iEventLogFileOpen )
+        {
+        iEventLogFile.Close();
+        iEventLogFileOpen = EFalse;
+        }
+
+    TInt err = iFs.Delete(iServer.EventLogFileName());
+
+    return err;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vpnengine/eventmediatorapi/inc/eventmediatorclientservercommon.h	Tue Sep 14 23:16:15 2010 +0300
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2003-2010 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:   Commond definitions with the even
+*
+*/
+
+#ifndef EVENTMEDIATORCLIENTSERVERCOMMON_H_
+#define EVENTMEDIATORCLIENTSERVERCOMMON_H_
+
+enum
+    {
+    KEventMediatorListen,
+    KEventMediatorListenWithSpec,
+    KEventMediatorCancel,
+    KEventMediatorCancelWithSpec,
+    KEventMediatorCancelAll,
+    KEventMediatorReportEvent,
+    KEventMediatorReportEventWithSpec,
+    KEventMediatorFetchData,
+    KEventMediatorReportLogEvent,
+    KEventMediatorNewEventSpecId,
+    KEventMediatorDeletePrivateFiles,
+    KEventMediatorGetEventLogSize,
+    KEventMediatorGetEventLogHeader,
+    KEventMediatorGetEventLogData,
+    KEventMediatorClearEventLog
+    };
+
+
+#endif /* EVENTMEDIATORCLIENTSERVERCOMMON_H_ */
--- a/vpnengine/eventmediatorapi/src/EventMediatorAPI.cpp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/eventmediatorapi/src/EventMediatorAPI.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -17,7 +17,7 @@
 
 
 #include <e32std.h>
-#include "eventmediator.h"
+#include "eventmediatorclientservercommon.h"
 #include "eventmediatorapi.h"
 #include "eventlogger.h"
 #include "clistatic.h"
@@ -45,32 +45,44 @@
  *----------------------------------------------------------*/
 EXPORT_C TInt REventMediator::Connect(void)
     {
+    static const TUint KMaxRetryCount = 2;
     TInt ret = KErrNone;
     TRAP(ret, CreateListenedEventsListL());
-    if (ret != KErrNone)
-        {
-        return ret;
-        }
-    
-    TInt retry=2;
-    for (;;)
+    if (ret == KErrNone)
         {
-        TInt r=CreateSession(KEventMediatorServer,
-                             TVersion(KEventMediatorMajorVersionNumber,
-                                      KEventMediatorMinorVersionNumber,
-                                      KEventMediatorBuildVersionNumber),
-                             2 * KDefaultMessageSlots);
-        
-        if (r!=KErrNotFound && r!=KErrServerTerminated)
-            return r;
-        if (--retry==0)
-            return r;
-        r = Launcher::LaunchServer(KEventMediatorServer, KEventMediatorFile,
-                                   KEventMediatorUid3);
+        for (TUint i = 0; i < KMaxRetryCount; i++)
+            {
+            ret = CreateSession(KEventMediatorServer,
+                                TVersion(KEventMediatorMajorVersionNumber,
+                                         KEventMediatorMinorVersionNumber,
+                                         KEventMediatorBuildVersionNumber),
+                                 2 * KDefaultMessageSlots);
+            
+            if ( ret == KErrNotFound )
+                {
+                //do nothing
+                }
+            else if ( ret == KErrServerTerminated )
+                {
+                //Wait for one second so that the Eventmed
+                //and sit has sufficient time to go down.
+                User::After(500000);
+                }
+            else
+                {
+                break;
+                }
 
-        if (r!=KErrNone && r!=KErrAlreadyExists)
-            return r;
+            ret = Launcher::LaunchServer(KEventMediatorServer, KEventMediatorFile,
+                                       KEventMediatorUid3);
+    
+            if ( ret != KErrNone && ret !=KErrAlreadyExists)
+                {
+                break;
+                }
+            }
         }
+    return ret;
     }
 
 void REventMediator::CreateListenedEventsListL()
@@ -108,7 +120,7 @@
         {
         LOG(Log::Printf(_L("REventMediator::ListenToEvent(TEventType aType, MEventObserver& aObserver) - calling SendReceive\n")));
             
-        SendReceive(CEventMediatorSession::KEventMediatorListen,
+        SendReceive(KEventMediatorListen,
                     TIpcArgs(aType,
                              &(listener->iDataLengthPckg),
                              &(listener->iSrvDataPtrPckg)),
@@ -141,7 +153,7 @@
         {
         LOG(Log::Printf(_L("REventMediator::ListenToEvent(TEventType aType, TDesC8& aEventSpec, MEventObserver& aObserver) - calling SendReceive\n")));
         
-        SendReceive(CEventMediatorSession::KEventMediatorListenWithSpec,
+        SendReceive(KEventMediatorListenWithSpec,
                     TIpcArgs(aType,
                              &(listener->iDataLengthPckg),
                              &(listener->iSrvDataPtrPckg),
@@ -198,17 +210,17 @@
 
 EXPORT_C TInt REventMediator::ReportEvent(TEventType aType)
     {
-    return SendReceive(CEventMediatorSession::KEventMediatorReportEvent, TIpcArgs(aType, 0, NULL));
+    return SendReceive(KEventMediatorReportEvent, TIpcArgs(aType, 0, NULL));
     }
 
 EXPORT_C TInt REventMediator::ReportEvent(TEventType aType, TDesC8& aData)
     {
-    return SendReceive(CEventMediatorSession::KEventMediatorReportEvent, TIpcArgs(aType, aData.Length(), &aData));
+    return SendReceive(KEventMediatorReportEvent, TIpcArgs(aType, aData.Length(), &aData));
     }
 
 EXPORT_C TInt REventMediator::ReportEvent(TEventType aType, TDesC8& aEventSpec, TDesC8& aData)
     {
-    return SendReceive(CEventMediatorSession::KEventMediatorReportEventWithSpec, TIpcArgs(aType, aData.Length(), &aData, &aEventSpec));
+    return SendReceive(KEventMediatorReportEventWithSpec, TIpcArgs(aType, aData.Length(), &aData, &aEventSpec));
     }
 
 EXPORT_C TInt REventMediator::ReportLogEvent(TUid& aSrc, TLogCategory aCategory, TUint aMsgId, TInt aDesCount,...)
@@ -264,7 +276,7 @@
     TInt specId = 0;
     TPckg<TInt> specIdDes(specId);
 
-    SendReceive(CEventMediatorSession::KEventMediatorNewEventSpecId, TIpcArgs(&specIdDes));
+    SendReceive(KEventMediatorNewEventSpecId, TIpcArgs(&specIdDes));
 
     return specId;
     }
@@ -273,14 +285,14 @@
     {
     LOG(Log::Printf(_L("REventMediator::CancelListenToEvent(TEventType aType)\n")));
     
-    SendReceive(CEventMediatorSession::KEventMediatorCancel, TIpcArgs(aType));
+    SendReceive(KEventMediatorCancel, TIpcArgs(aType));
     }
 
 TInt REventMediator::CancelListenToEvent(TEventType aType, TDesC8& aEventSpec)
     {
     LOG(Log::Printf(_L("REventMediator::CancelListenToEvent(TEventType aType, TDesC8& aEventSpec)\n")));
     
-    return SendReceive(CEventMediatorSession::KEventMediatorCancelWithSpec, TIpcArgs(aType, NULL, NULL, &aEventSpec));
+    return SendReceive(KEventMediatorCancelWithSpec, TIpcArgs(aType, NULL, NULL, &aEventSpec));
     }
 
 TInt REventMediator::FetchData(TAny* aSrvPtr, TDes8& aDataPtr)
@@ -288,7 +300,7 @@
     LOG(Log::Printf(_L("REventMediator::FetchData()\n")));
     
     TRequestStatus status;
-    SendReceive(CEventMediatorSession::KEventMediatorFetchData,
+    SendReceive(KEventMediatorFetchData,
                 TIpcArgs(aSrvPtr, &aDataPtr), status);
     User::WaitForRequest(status);
 
@@ -375,7 +387,7 @@
 
 EXPORT_C TInt REventMediator::DeletePrivateFiles()
     {
-    return SendReceive (CEventMediatorSession::KEventMediatorDeletePrivateFiles, TIpcArgs());
+    return SendReceive (KEventMediatorDeletePrivateFiles, TIpcArgs());
     }
 
     
@@ -383,25 +395,25 @@
     {
     TPckg<TInt> eventLogSizePckg(aEventLogSize);
 
-    return SendReceive (CEventMediatorSession::KEventMediatorGetEventLogSize,
+    return SendReceive (KEventMediatorGetEventLogSize,
                         TIpcArgs(&eventLogSizePckg));
     }
 
 EXPORT_C TInt REventMediator::GetEventLogHeader(TDes8& aEventLogHeader)
     {
-    return SendReceive (CEventMediatorSession::KEventMediatorGetEventLogHeader,
+    return SendReceive (KEventMediatorGetEventLogHeader,
                         TIpcArgs(&aEventLogHeader));
     }
 
 EXPORT_C TInt REventMediator::GetEventLogData(TDes8& aEventLogData)
     {
-    return SendReceive (CEventMediatorSession::KEventMediatorGetEventLogData,
+    return SendReceive (KEventMediatorGetEventLogData,
                         TIpcArgs(&aEventLogData));
     }
 
 EXPORT_C TInt REventMediator::ClearEventLog()
     {
-    return SendReceive (CEventMediatorSession::KEventMediatorClearEventLog, TIpcArgs());
+    return SendReceive (KEventMediatorClearEventLog, TIpcArgs());
     }
 
 
--- a/vpnengine/ikecert/src/ikev1pkiservice.cpp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/ikecert/src/ikev1pkiservice.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+* Copyright (c) 2005-2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * This component and the accompanying materials are made available
 * under the terms of "Eclipse Public License v1.0"
@@ -150,7 +150,7 @@
         delete iCaName;
 
         iCaName     = NULL;
-        iCaName     = HBufC8::NewL(256);
+        iCaName     = HBufC8::NewL( KMaxX500DN );
         iCaNameList = aCAList;
         iCurrIndex  = 0;
         iOperation  = KBuildingCaList;
@@ -1008,36 +1008,34 @@
 
 void CIkeV1PkiService::CertReadCompleted(TBool aCaCert, TInt aStatus, TInt aLine )
 {
-  TBuf<320>DebugMsg;
-  if ( aCaCert )
-  {
+    if ( aCaCert )
+    {
+        DEBUG_LOG2(_L("Trusted CA certificate read completed with status = %d (line = %d)\n"),
+                       aStatus, aLine);
+    
         ASSERT( iCurrIndex < iCaNameList->Count() );
-     DebugMsg.Format(_L("Trusted CA certificate read completed with status = %d (line = %d)"),
-                     aStatus, aLine);
-     DebugMsg.AppendFormat(_L(" ; Search criteria: "));
-     TCertInfo* CertInfo = iCaNameList->At(iCurrIndex);
-     switch ( CertInfo->iFormat )
-     {
-       case CA_NAME:
-         DebugMsg.AppendFormat(_L("CA_NAME = %S\n"), &CertInfo->iData);
-         break;
-       case KEY_ID:
-         DebugMsg.AppendFormat(_L("KEY_ID = %S\n"), &CertInfo->iData);
-         break;
-       default:
-         TBuf<48> KeyIdString;
+    
+        TCertInfo* CertInfo = iCaNameList->At(iCurrIndex);
+    
+        switch ( CertInfo->iFormat )
+        {
+            case CA_NAME:
+            case KEY_ID:
+                DEBUG_LOG1(_L("Search data = %S\n"), &CertInfo->iData);
+                break;
+            default:
+                TBuf<48> KeyIdString;
                 ASSERT( iListIndex < iCaCertList->Count() );
-         HexToString(iCaCertList->At(iListIndex).iSubjectKeyId, KeyIdString);
-         DebugMsg.AppendFormat(_L("APPL_UID/<KEY_ID> = %S\n"), &KeyIdString);
-         break;
-     }
-  }
-  else
-  {
-     DEBUG_LOG2(_L("End user certificate read completed with status = %d (line = %d)\n"),
-                     aStatus, aLine);
-  }
-    DEBUG_LOG(DebugMsg);
+                HexToString(iCaCertList->At(iListIndex).iSubjectKeyId, KeyIdString);
+                DEBUG_LOG1(_L("APPL_UID/<KEY_ID> = %S\n"), &KeyIdString);
+                break;
+        }
+    }
+    else
+    {
+        DEBUG_LOG2(_L("End user certificate read completed with status = %d (line = %d)\n"),
+                       aStatus, aLine);
+    }
 }
 
 void CIkeV1PkiService::HexToString(const TDesC8& aKeyId, TDes16& aKeyIdString)
--- a/vpnengine/ikepolparser/group/ikepolparser.mmp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/ikepolparser/group/ikepolparser.mmp	Tue Sep 14 23:16:15 2010 +0300
@@ -30,6 +30,7 @@
 SOURCE      ikepolparser.cpp
 
 USERINCLUDE ../inc
+USERINCLUDE ../../pkiserviceapi/inc
 
 MW_LAYER_SYSTEMINCLUDE
 
--- a/vpnengine/ikepolparser/inc/ikepolparser.h	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/ikepolparser/inc/ikepolparser.h	Tue Sep 14 23:16:15 2010 +0300
@@ -11,7 +11,7 @@
 *
 * Contributors:
 *
-* Description:   IKE policy parser main module
+* Description:  IKE policy parser main module
 *
 */
 
@@ -22,6 +22,9 @@
 #include <badesca.h>
 #include <in_sock.h>
 
+#include "pkidefs.h"
+
+
 #define FIRST_SEC_PARSER_VERSION    1
 #define SEC_PARSER_VERSION          3
 
@@ -79,7 +82,6 @@
 const TInt KSecParserErrUnknown             = -5297;
 
 
-
 //Values for the choice lists used in the .RSS
 enum {IKE_PARSER_MAIN,
       IKE_PARSER_AGGRESSIVE};       //Modes
@@ -154,11 +156,11 @@
 };
 
 
-//RSA Encryption peer public keys
+// RSA Encryption peer public keys
 struct TCertInfo
 {
-    TCertFormat iFormat;
-    TFileName   iData;    
+    TCertFormat       iFormat;
+    TBuf<KMaxX500DN>  iData;    
 };
 
 
@@ -172,13 +174,13 @@
 //Own certificates
 struct TOwnCertInfo
 {
-    TCertFormat iFormat;
-    TFileName iData;    //File containing the peer RSA public key
-    TBuf<128> iRfc822NameFqdn;
-    TIdentityAsRfc822Name iIdentityAsRfc822Name;
-    TBuf<256> iSubjectDnSuffix;
-    TInt iPrivateKeyLength;
-    TInt iOwnCertExists;                     // 0 = no own cert   1 = own cert exists
+    TCertFormat            iFormat;
+    TFileName              iData;  // File containing the peer cert
+    TBuf<KMaxRfc822>       iRfc822NameFqdn;
+    TIdentityAsRfc822Name  iIdentityAsRfc822Name;
+    TBuf<KMaxX500DN>       iSubjectDnSuffix;
+    TInt                   iPrivateKeyLength;
+    TInt                   iOwnCertExists;  // 0=no own cert, 1=own cert exists
 };
 
 class TStringData
--- a/vpnengine/ikepolparser/src/ikepolparser.cpp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/ikepolparser/src/ikepolparser.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -19,6 +19,7 @@
 
 #include <e32std.h>
 #include <coeutils.h>
+
 #include "ikepolparser.h"
 
 //
@@ -1690,7 +1691,14 @@
             case CA_NAME: //falls through
             case APPL_UID:
                 {
-                aCA->iData = GetRestOfLine();   //ASCII format CA name or Appl uid list
+                TPtrC data = GetRestOfLine();
+
+                if( KMaxX500DN < data.Length() )
+                    {
+                    return KSecParserErrCA;
+                    }
+
+                aCA->iData = data;   //ASCII format CA name or Appl uid list
                 // Check if data contains empty attributes
                 if( KErrNotFound != aCA->iData.FindF(_L("=,")) || KErrNotFound != aCA->iData.FindF(_L("=\"\"")))
                     {
@@ -1698,11 +1706,19 @@
                     }
                 }
                 break;
-            case BIN_CERT:                
-                return ParseFileName(aCA->iData);                               
-                //No break needed
+            case BIN_CERT:
+                {           
+                return ParseFileName(aCA->iData);
+                }                               
             default:
-                aCA->iData = NextToken();       //PEM cert or  Key identifier      
+                TPtrC next = NextToken();
+
+                if( KMaxX500DN < next.Length() )
+                    {
+                    return KSecParserErrCA;
+                    }
+
+                aCA->iData = next;  // PEM cert or  Key identifier      
                 break;
             }
 
@@ -1833,7 +1849,16 @@
         else if (token.CompareF(_L("SUBJECT_DN_SUFFIX:"))==0) //CompareF ignores case
         {
             nMandatoryFields++;
-            own_cert->iSubjectDnSuffix = GetRestOfLine();                          
+            
+            TPtrC data = GetRestOfLine();
+
+            if( KMaxX500DN < data.Length() )
+                {
+                return KSecParserErrOwnCerts;
+                }
+
+            own_cert->iSubjectDnSuffix = data;
+            
             // Check if data contains empty attributes
         	if( KErrNotFound != own_cert->iSubjectDnSuffix.FindF(_L("=,")) || 
         	    KErrNotFound != own_cert->iSubjectDnSuffix.FindF(_L("=\"\"")))
@@ -1856,10 +1881,19 @@
         else if (token.CompareF(_L("RFC822NAME_FQDN:"))==0) //CompareF ignores case
         {
             nMandatoryFields++;
-            own_cert->iRfc822NameFqdn = NextToken();  
+            
+            TPtrC next = NextToken();
+            
+            if( KMaxRfc822 < next.Length() )
+                {
+                return KSecParserErrOwnCerts;
+                }
+            
+            own_cert->iRfc822NameFqdn = next;  
         }
 
-        else if (token.CompareF(_L("PRIVATE_KEY_LENGTH:"))==0) //CompareF ignores case
+        // CompareF ignores case
+        else if (token.CompareF(_L("PRIVATE_KEY_LENGTH:"))==0) 
         {
             nMandatoryFields++;
             TLex sub_num = NextToken();
@@ -1868,18 +1902,19 @@
         }
         else
         {
-            UnGetToMark(); // current token didn't belong to this section
+            UnGetToMark();  // current token didn't belong to this section
             endOfSection=ETrue;
         }
     }
-    if (nMandatoryFields<1) // Some mandatory fields are missing
+    if (nMandatoryFields<1)  // Some mandatory fields are missing
         {
         err= KSecParserErrOwnCerts;
         }
     else
         {
-        own_cert->iOwnCertExists = 1;                             // Write Own Certs 
+        own_cert->iOwnCertExists = 1;  // Write Own Certs 
         }
+
     return err;
 }
 
--- a/vpnengine/ikev1lib/src/ikev1negotiation.cpp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/ikev1lib/src/ikev1negotiation.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -551,7 +551,7 @@
     if ( iPkiService && iHostData->iCAList )
 		{
        TCertInfo* CertInfo;
-	   HBufC8* CAName = HBufC8::NewLC(256);  	   
+	   HBufC8* CAName = HBufC8::NewLC( KMaxX500DN );  	   
        TInt i = 0;
        if ( iHostData->iCAList->At(0)->iData!=KVpnApplUid )
           {
--- a/vpnengine/kmdserver/group/kmdserver.mmp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/kmdserver/group/kmdserver.mmp	Tue Sep 14 23:16:15 2010 +0300
@@ -56,6 +56,7 @@
 USERINCLUDE ../../eventviewer/inc 
 USERINCLUDE ../../ikesocket/inc
 USERINCLUDE ../../ikeutils/inc
+USERINCLUDE ../../pkiserviceapi/inc
 
 MW_LAYER_SYSTEMINCLUDE
 SYSTEMINCLUDE /epoc32/include/networking
--- a/vpnengine/kmdserver/group/kmdservertest.mmp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/kmdserver/group/kmdservertest.mmp	Tue Sep 14 23:16:15 2010 +0300
@@ -56,6 +56,7 @@
 USERINCLUDE ../../eventviewer/inc 
 USERINCLUDE ../../ikesocket/inc
 USERINCLUDE ../../ikeutils/inc
+USERINCLUDE ../../pkiserviceapi/inc
 
 MW_LAYER_SYSTEMINCLUDE
 SYSTEMINCLUDE /epoc32/include/networking
--- a/vpnengine/pkiservice/inc/PKIMapper.h	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/pkiservice/inc/PKIMapper.h	Tue Sep 14 23:16:15 2010 +0300
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2006-2008 Nokia Corporation and/or its subsidiary(-ies).
+* Copyright (c) 2006-2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * This component and the accompanying materials are made available
 * under the terms of "Eclipse Public License v1.0"
@@ -17,7 +17,6 @@
 */
 
 
-
 #if !defined (__PKIMAPPER_H__)
 #define __PKIMAPPER_H__
 
@@ -80,7 +79,14 @@
         TBool LabelIsUnique(const TDesC& aLabel) const;
         void LogMap(CMapDescriptor& aDescriptor) const;
         void LogSearchArguments(TSecurityObjectDescriptor& aDescriptor) const;        
-                
+        
+        /**
+         * Copies applicable data from aMapping to aCertInfo
+         */
+        void CopyCertDataL(
+            const CMapDescriptor& aMapping, TCertificateListEntry& aCertInfo
+        ) const;
+
     private: // C'tor    
 
         CPKIMapper();
@@ -89,7 +95,6 @@
     private: // data    
         TBool   iCacheCreated;       
         TInt    iCount;
-        /// Used when generating uniqname
 
         RPointerArray<CMapDescriptor>*      iMapping;
         TPckgBuf<TSecurityObjectDescriptor> iCurrentDescriptor;
--- a/vpnengine/pkiservice/inc/pkiserviceclientservercommon.h	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/pkiservice/inc/pkiserviceclientservercommon.h	Tue Sep 14 23:16:15 2010 +0300
@@ -168,7 +168,8 @@
             };              // Optional if only certificate is needed
         void SetObjectName(const TDesC &aObjectName)
             {
-            if(aObjectName.Length() > 0)
+            TInt len = aObjectName.Length();
+            if(0 < len && SHORT_FILENAME_LENGTH >= len)
                 {
                 iObjectName.Copy(aObjectName);
                 iObjectNameUsed = ETrue;
@@ -180,44 +181,48 @@
             };
         // Issuer and serial are not defined in the filter, these will be checked separately
         void SetTrustedAuthority(const TDesC8 &aTrustedAuthority)
+            {
+            TInt len = aTrustedAuthority.Length();
+            if(0 < len && KMaxX500DN >= len)
                 {
-                if(aTrustedAuthority.Length() > 0)
-                    {
-                    iTrustedAuthority.Copy(aTrustedAuthority);
-                    iTrustedAuthorityUsed = ETrue;
-                    }
-                else
-                    {
-                    iTrustedAuthorityUsed = EFalse;
-                    }
-                };
+                iTrustedAuthority.Copy(aTrustedAuthority);
+                iTrustedAuthorityUsed = ETrue;
+                }
+            else
+                {
+                iTrustedAuthorityUsed = EFalse;
+                }
+            };
         void SetIdentitySubjectName(const TDesC8 &aIdentitySubjectName)
+            {
+            TInt len = aIdentitySubjectName.Length();
+            if(0 < len && KMaxX500DN >= len)
                 {
-                    if(aIdentitySubjectName.Length() > 0)
-                        {
-                        iIdentitySubjectName.Copy(aIdentitySubjectName);
-                        iIdentitySubjectNameUsed = ETrue;
-                        }
-                    else
-                        {
-                        iIdentitySubjectNameUsed = EFalse;
-                        }
-                };
+                iIdentitySubjectName.Copy(aIdentitySubjectName);
+                iIdentitySubjectNameUsed = ETrue;
+                }
+            else
+                {
+                iIdentitySubjectNameUsed = EFalse;
+                }
+            };
         void SetIdentityRfc822Name(const TDesC8 &aIdentityRfc822Name)
+            {
+            TInt len = aIdentityRfc822Name.Length();
+            if(0 < len && KMaxRfc822 >= len)
                 {
-                    if(aIdentityRfc822Name.Length() > 0)
-                        {
-                        iIdentityRfc822Name.Copy(aIdentityRfc822Name);
-                        iIdentityRfc822NameUsed = ETrue;
-                        }
-                    else
-                        {
-                        iIdentityRfc822NameUsed = EFalse;
-                        }
-                };
+                iIdentityRfc822Name.Copy(aIdentityRfc822Name);
+                iIdentityRfc822NameUsed = ETrue;
+                }
+                else
+                {
+                iIdentityRfc822NameUsed = EFalse;
+                }
+            };
         void SetSerialNumber(const TDesC8 &aSerialNumber)
             {
-            if(aSerialNumber.Length() > 0)
+            TInt len = aSerialNumber.Length();
+            if(0 < len && KMaxSerial >= len)
                 {
                 iSerialNumber.Copy(aSerialNumber);
                 iSerialNumberUsed = ETrue;
--- a/vpnengine/pkiservice/src/pkimapper.cpp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/pkiservice/src/pkimapper.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
+* Copyright (c) 2006-2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * This component and the accompanying materials are made available
 * under the terms of "Eclipse Public License v1.0"
@@ -146,6 +146,8 @@
                                  TBool aInfoOnly,
                                  TCertificateListEntry& aResultCertInfo)
     {
+    LOG(Log::Printf(_L("CPKIMapper::GetCertDetailsL\n")));
+    
     TInt index;
     TInt err = KErrNone;
     
@@ -159,23 +161,18 @@
     
     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();           
+        const CMapDescriptor* mapping = (*iMapping)[index];
+        CopyCertDataL( *mapping, aResultCertInfo );  
         }
+
     return err;    
     }
 
 
 TInt CPKIMapper::GetCertListL(const RMessage2 &aMessage, TBool aInfoOnly)
 {
+    LOG(Log::Printf(_L("CPKIMapper::GetCertListL\n")));
+
     TInt pos = 0;
     TInt iLast = 0;
     TInt iFirst = 0;
@@ -184,25 +181,19 @@
     CBufFlat* list = CBufFlat::NewL(sizeof(TCertificateListEntry));
     CleanupStack::PushL(list);
     list->ResizeL(iCount * sizeof(TCertificateListEntry));
-    TCertificateListEntry certInfo;
+    
+    TCertificateListEntry* certInfo = new (ELeave) TCertificateListEntry();
+    CleanupStack::PushL( certInfo );
     
     for(TInt i = iFirst; i < iLast; i++)
         {
         CMapDescriptor* mapping = (*iMapping)[i];
         if(aInfoOnly || mapping->CertValidity() != CMapDescriptor::EExpired)
             {
-            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
+            CopyCertDataL( *mapping, *certInfo );
 
             list->Write(pos * sizeof(TCertificateListEntry),
-                        (TAny*)&certInfo,
+                        (TAny*)certInfo,
                         sizeof(TCertificateListEntry));
             pos++;
             if(pos >= iCount)
@@ -214,19 +205,23 @@
     TPtr8 ptrList = list->Ptr(0);
     aMessage.WriteL(0, ptrList);
 
-    CleanupStack::PopAndDestroy(1); // list
+    CleanupStack::PopAndDestroy(  2 );  // list, certInfo
     return KErrNone;
 }
 
 
 void CPKIMapper::GetApplicableCertListL(const RMessage2& aMessage, const RArray<TUid>& aUidArray)
 {
+    LOG(Log::Printf(_L("CPKIMapper::GetApplicableCertListL\n")));
+    
     TInt pos = 0;
     
     CBufFlat* list = CBufFlat::NewL(sizeof(TCertificateListEntry));
     CleanupStack::PushL(list);
     list->ResizeL(iCount * sizeof(TCertificateListEntry));
-    TCertificateListEntry certInfo;
+
+    TCertificateListEntry* certInfo = new (ELeave) TCertificateListEntry();
+    CleanupStack::PushL( certInfo );
 
     for(TInt i = 0; (i < iMapping->Count()) && (pos < iCount); i++)
         {
@@ -239,18 +234,10 @@
                     {
                     if(mapping->IsApplicable(aUidArray[j]))
                         {
-                        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
+                        CopyCertDataL( *mapping, *certInfo );
 
                         list->Write(pos * sizeof(TCertificateListEntry),
-                                    (TAny*)&certInfo,
+                                    (TAny*)certInfo,
                                     sizeof(TCertificateListEntry));
                         pos++;
                         break;
@@ -262,7 +249,7 @@
     TPtr8 ptrList = list->Ptr(0);
     aMessage.WriteL(0, ptrList);
 
-    CleanupStack::PopAndDestroy(1); // list
+    CleanupStack::PopAndDestroy( 2 );  // list, certInfo
 }
 
 
@@ -490,44 +477,20 @@
 
 void CPKIMapper::LogSearchArguments(TSecurityObjectDescriptor &aDescriptor) const
     {
-    TBuf<256> temp;
     LOG(Log::Printf(_L("====Object Search arguments====\n")));
     if(aDescriptor.iTrustedAuthorityUsed)
         {
-        temp.Copy(aDescriptor.iTrustedAuthority);
-        if((aDescriptor.iTrustedAuthority[0] != 0x30)
-           || ((aDescriptor.iTrustedAuthority[1] != 0x81)
-               && (aDescriptor.iTrustedAuthority[1] != 0x82)
-               && ((aDescriptor.iTrustedAuthority[1] + 2) != aDescriptor.iTrustedAuthority.Length())))
-            {
-            LOG(Log::Printf(_L("Trusted authority: %S\n"), &temp));
-            }
-        else
-            {
-            LOG(Log::Printf(_L("Trusted authority:")));
-            LOG(Log::HexDump(NULL, NULL, aDescriptor.iTrustedAuthority.Ptr(), aDescriptor.iTrustedAuthority.Length()));
-            }
+        LOG(Log::Printf(_L("Trusted authority:")));
+        LOG(Log::HexDump(NULL, NULL, aDescriptor.iTrustedAuthority.Ptr(), aDescriptor.iTrustedAuthority.Length()));
         }
     if(aDescriptor.iIdentitySubjectNameUsed)
         {
-        temp.Copy(aDescriptor.iIdentitySubjectName);
-        if((aDescriptor.iIdentitySubjectName[0] != 0x30)
-           || ((aDescriptor.iIdentitySubjectName[1] != 0x81)
-               && (aDescriptor.iIdentitySubjectName[1] != 0x82)
-               && ((aDescriptor.iIdentitySubjectName[1] + 2) != aDescriptor.iIdentitySubjectName.Length())))
-            {
-            LOG(Log::Printf(_L("SubjectName: %S\n"), &temp));
-            }
-        else
-            {
-            LOG(Log::Printf(_L("SubjectName:")));
-            LOG(Log::HexDump(NULL, NULL, aDescriptor.iIdentitySubjectName.Ptr(), aDescriptor.iIdentitySubjectName.Length()));
-            }
+        LOG(Log::Printf(_L("SubjectName:")));
+        LOG(Log::HexDump(NULL, NULL, aDescriptor.iIdentitySubjectName.Ptr(), aDescriptor.iIdentitySubjectName.Length()));
         }
     if(aDescriptor.iIdentityRfc822NameUsed)
         {
-        temp.Copy(aDescriptor.iIdentityRfc822Name);
-        LOG(Log::Printf(_L("Rfc822Name: %S\n"), &temp));
+        LOG(Log::Printf(_L("Rfc822Name: %S\n"), &aDescriptor.iIdentityRfc822Name));
         }
     if(aDescriptor.iSerialNumberUsed)
         {
@@ -558,3 +521,58 @@
         }
     }   
 
+
+void CPKIMapper::CopyCertDataL(
+    const CMapDescriptor& aMapping, TCertificateListEntry& aCertInfo ) const
+    {
+    LOG(Log::Printf(_L("CPKIMapper::CopyCertDataL\n")));
+
+    TInt len = 0;
+
+    aCertInfo.iObjectName = aMapping.Label();
+    aCertInfo.iOwnerType  = aMapping.OwnerType();
+
+    TPtrC8 ta = aMapping.TrustedAuthority();
+    len = ta.Length();
+
+    if( KMaxX500DN >= len )
+        {
+        aCertInfo.iTrustedAuthority = ta;
+        }
+    else
+        {
+        LOG(Log::Printf(_L("Trusted authority length: %d\n"), len ));
+        User::Leave( KErrArgument );
+        }
+
+    TPtrC8 isn = aMapping.IdentitySubjectName();       
+    len = isn.Length();
+    
+    if( KMaxX500DN >= len )
+        {
+        aCertInfo.iIdentitySubjectName = isn;
+        }
+    else{
+        LOG(Log::Printf(_L("Subject name length: %d\n"), len ));
+        User::Leave( KErrArgument );
+        }    
+    
+    TPtrC8 sn = aMapping.SerialNumber();
+    len = sn.Length();
+            
+    if( KMaxSerial >= len )
+        {
+        aCertInfo.iSerialNumber = sn;
+        }
+    else
+        {
+        LOG(Log::Printf(_L("Serial number length: %d\n"), len ));
+        User::Leave( KErrArgument );
+        }
+
+    aCertInfo.iSubjectKeyId = aMapping.CertificateKeyId();
+    aCertInfo.iKeySize      = aMapping.KeySize();
+    aCertInfo.iKeyAlgorithm = aMapping.KeyAlgorithm();  // RSA, DSA
+    aCertInfo.iIsDeletable  = aMapping.Deletable();
+    }
+
--- a/vpnengine/pkiservice/src/pkisession.cpp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/pkiservice/src/pkisession.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -146,11 +146,13 @@
     		break;
        case PkiService::EGetCertDetails:
             {
-            TPckgBuf<TSecurityObjectDescriptor> secDescPtr;
-            aMessage.ReadL(1, secDescPtr);
+            TPckgBuf<TSecurityObjectDescriptor>* secDescPtr =
+                new (ELeave) TPckgBuf<TSecurityObjectDescriptor>();
+            CleanupStack::PushL(secDescPtr);
+            aMessage.ReadL(1, *secDescPtr);
             TCertificateListEntry* resultCertInfo = new (ELeave) TCertificateListEntry;
             CleanupStack::PushL(resultCertInfo);            
-            Status = iMapper.GetCertDetailsL(secDescPtr(), 
+            Status = iMapper.GetCertDetailsL((*secDescPtr)(), 
                                              iWrapper->CertStoreType(), 
                                              iWrapper->Informational(),
                                              *resultCertInfo);
@@ -160,7 +162,8 @@
 	            aMessage.WriteL(0, certDetailsPtr);
 		        }
 		    aMessage.Complete(Status);
-		    CleanupStack::PopAndDestroy(resultCertInfo);            
+		    CleanupStack::PopAndDestroy(resultCertInfo);
+		    CleanupStack::PopAndDestroy(secDescPtr);       
             }
 		    break;
         case PkiService::EGetCertList:
--- a/vpnengine/pkiserviceapi/inc/pkidefs.h	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/pkiserviceapi/inc/pkidefs.h	Tue Sep 14 23:16:15 2010 +0300
@@ -25,7 +25,7 @@
 const TInt MAX_FILENAME_LENGTH = 64;
 const TInt SHORT_FILENAME_LENGTH = 64;
 
-const TUint32 KMaxX500DN = 256;
+const TUint32 KMaxX500DN = 1024;
 const TUint32 KMaxRfc822 = 64;
 const TUint32 KMaxUsageDer = 16;
 const TUint32 KMaxSerial = 128;
@@ -92,7 +92,6 @@
 typedef TX509KeyUsage TPKIKeyUsage;
    
 
-
 class TCertificateRequestListEntry
 {
     public:
@@ -124,4 +123,5 @@
         TPKIKeyAlgorithm            iKeyAlgorithm;              // RSA, DSA
 };
 
-#endif
\ No newline at end of file
+
+#endif
--- a/vpnengine/pkiserviceapi/src/pkiserviceapi.cpp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/pkiserviceapi/src/pkiserviceapi.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -415,14 +415,16 @@
 
 	User::LeaveIfError(SendReceive (PkiService::EGetCertList, TIpcArgs(&ptrList)));
 
-	TCertificateListEntry certInfo;
+	TCertificateListEntry* certInfo = new (ELeave) TCertificateListEntry();
+	CleanupStack::PushL( certInfo );
+	
 	for (TInt i = 0; i < certCount; i++)
 		{
-		list->Read(i * sizeof(TCertificateListEntry), (TAny*)&certInfo, sizeof(TCertificateListEntry));
-		certList->AppendL(certInfo);
+		list->Read(i * sizeof(TCertificateListEntry), (TAny*)certInfo, sizeof(TCertificateListEntry));
+		certList->AppendL(*certInfo);
 		}
 
-	CleanupStack::PopAndDestroy(1);     // list
+	CleanupStack::PopAndDestroy(2);     // list, certInfo
 	CleanupStack::Pop();                // certList
 
 	aCertList = certList;
@@ -481,14 +483,16 @@
 
 	User::LeaveIfError(SendReceive (PkiService::EGetApplicableCertList, TIpcArgs(&ptrList2)));
 
-	TCertificateListEntry certInfo;
+	TCertificateListEntry* certInfo = new (ELeave) TCertificateListEntry();
+	CleanupStack::PushL(certInfo);
+	
 	for (i = 0; i < certCount; i++)
 		{
-		list->Read(i * sizeof(TCertificateListEntry), (TAny*)&certInfo, sizeof(TCertificateListEntry));
-		certList->AppendL(certInfo);
+		list->Read(i * sizeof(TCertificateListEntry), (TAny*)certInfo, sizeof(TCertificateListEntry));
+		certList->AppendL(*certInfo);
 		}
 
-	CleanupStack::PopAndDestroy(1);     // list
+	CleanupStack::PopAndDestroy(2);     // list, certInfo
 	CleanupStack::Pop();                // certList
 
 	aCertList = certList;
@@ -974,8 +978,16 @@
 {
     TSecurityObjectDescriptor *certDesc = new (ELeave) TSecurityObjectDescriptor;
     CleanupStack::PushL(certDesc);
+    
     certDesc->SetTrustedAuthority(aTrustedAuthority);
     certDesc->SetSerialNumber(aSerialNumber);
+    
+    if( EFalse == certDesc->iTrustedAuthorityUsed ||
+        EFalse == certDesc->iSerialNumberUsed )
+        {
+        User::Leave( KErrArgument );
+        }
+
     TPckg<TSecurityObjectDescriptor> pckgTSecurityObjectDescriptor(*certDesc);
 
 
--- a/vpnengine/sit/inc/taskarrivalobserver.h	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/sit/inc/taskarrivalobserver.h	Tue Sep 14 23:16:15 2010 +0300
@@ -32,14 +32,13 @@
 /**
  * Combined task handler arrival observer and task handler manager.
  */
-NONSHARABLE_CLASS(CTaskArrivalObserver) : public CAsyncOneShot, public MEventObserver, public MTaskHandlerManager
+NONSHARABLE_CLASS(CTaskArrivalObserver) : public CBase,
+                                          public MEventObserver, 
+                                          public MTaskHandlerManager
     {
 public:
     static CTaskArrivalObserver* NewL();
     ~CTaskArrivalObserver();
-
-private: // From CAsyncOneShot
-    void RunL();
     
 public:
     void Start();
@@ -59,17 +58,12 @@
     void ConstructL();
 
 private: // Implementation
-    void LaunchTaskHandlerL(const TTaskArrivedEventData& aEventSpec);
-    CTaskHandler* CreateTaskHandlerL(const TTaskArrivedEventData& aEventSpec);
-    TInt FindTaskHandler(CTaskHandler* aTaskHandler);
-    TInt FindAsyncCleaner(CAsyncCleaner* aAsyncCleaner);
-    void AsyncDeleteTaskHandler(CTaskHandler* aTaskHandler);
+    void LaunchTaskHandlerL(const TTaskArrivedEventData& aEventSpec);    
 
 private:
     REventMediator iEventMediator;
     CArrayPtrFlat<CTaskHandler>* iTaskHandlerList;
     CArrayPtrFlat<CAsyncCleaner>* iAsyncCleanerList;
-    CTaskHandler* iTaskHandlerToDelete;
     };
 
 NONSHARABLE_CLASS(CAsyncCleaner) : public CAsyncOneShot
@@ -77,8 +71,8 @@
 public:
     CAsyncCleaner(CTaskArrivalObserver* aTaskArrivalObserver,
                   CTaskHandler* aTaskHandlerToDelete);
-    void Start();
-        
+    void Start();        
+    TBool IsMatchingCleaner(const CTaskHandler& aTaskHandler) const;
 private: // From CAsyncOneShot
     void RunL();
 
--- a/vpnengine/sit/src/sit.cpp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/sit/src/sit.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -157,7 +157,8 @@
     CActiveScheduler::Start();
 
     // Cleanup the task handler and scheduler
-    CleanupStack::PopAndDestroy(2); // taskArrivalObserver, scheduler
+    CleanupStack::PopAndDestroy(taskArrivalObserver);
+    CleanupStack::PopAndDestroy(scheduler);
 
     LOG(Log::Printf(_L("CSit::StartWorkingL - end\n")));
     }
--- a/vpnengine/sit/src/taskarrivalobserver.cpp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/sit/src/taskarrivalobserver.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -33,7 +33,6 @@
     }
     
 CTaskArrivalObserver::CTaskArrivalObserver()
-    : CAsyncOneShot(EPriorityNormal)
     {
     }
 
@@ -49,8 +48,9 @@
     LOG(Log::Printf(_L("CTaskArrivalObserver::~CTaskArrivalObserver\n")));
     Cancel();
     iEventMediator.Close();
+    
     if (iTaskHandlerList)
-        {
+        {    
         iTaskHandlerList->ResetAndDestroy();
         delete iTaskHandlerList;
         }
@@ -116,62 +116,25 @@
     {
     LOG(Log::Printf(_L("CTaskArrivalObserver::LaunchTaskHandlerL\n")));
     // A new task has arrived so create a task handler for it
-    CTaskHandler* taskHandler = CreateTaskHandlerL(aEventSpec);
 
-    // Add the handler to the list of active handlers
-    iTaskHandlerList->AppendL(taskHandler);
-
-    // And start performing the task
-    taskHandler->Start();
-    }
-
-CTaskHandler* CTaskArrivalObserver::CreateTaskHandlerL(const TTaskArrivedEventData& aEventSpec)
-    {
-    LOG(Log::Printf(_L("CTaskArrivalObserver::CreateTaskHandlerL\n")));
-    CTaskHandler* taskHandler = NULL;
-
-    taskHandler = TaskHandlerCreator::CreateTaskHandlerL(this, aEventSpec);
-
+    CTaskHandler* taskHandler = TaskHandlerCreator::CreateTaskHandlerL(this, aEventSpec);
     if (!taskHandler)
         {
         User::Panic(KSitName, EPanicUnknownEventType);
         }
-
-    return taskHandler;
-    }
+        
+    // Add the handler to the list of active handlers
+    iTaskHandlerList->AppendL(taskHandler);
 
-TInt CTaskArrivalObserver::FindTaskHandler(CTaskHandler* aTaskHandler)
-    {
-    TInt foundIndex = KUnfoundIndex;
-    
-    for (TInt i = 0; i < iTaskHandlerList->Count(); i++)
-        {
-        if (iTaskHandlerList->At(i) == aTaskHandler)
-            {
-            foundIndex = i;
-            break;
-            };
-        }
-
-    return foundIndex;
+    //Create the asyncleaner for cleaning the task handler, when the
+    //task is done.
+    CAsyncCleaner* asyncCleaner = new (ELeave) CAsyncCleaner(this, taskHandler);    
+    iAsyncCleanerList->AppendL(asyncCleaner);
+       
+    // And start performing the task
+    taskHandler->Start();
     }
     
-TInt CTaskArrivalObserver::FindAsyncCleaner(CAsyncCleaner* aAsyncCleaner)
-    {
-    TInt foundIndex = KUnfoundIndex;
-    
-    for (TInt i = 0; i < iAsyncCleanerList->Count(); i++)
-        {
-        if (iAsyncCleanerList->At(i) == aAsyncCleaner)
-            {
-            foundIndex = i;
-            break;
-            };
-        }
-
-    return foundIndex;
-    }
-
 void CTaskArrivalObserver::TaskHandlerComplete(CTaskHandler* aTaskHandler)
     {
     LOG(Log::Printf(_L("CTaskArrivalObserver::TaskHandlerComplete\n")));
@@ -181,98 +144,73 @@
     // Otherwise we'll get panic E32USER-CBase 42 (SetActive called
     // while active object is already active).
     
-    // NOTE. Each asyncCleaner instance will cause itself to be deleted
-    CAsyncCleaner* asyncCleaner = new CAsyncCleaner(this, aTaskHandler);
-    if (asyncCleaner)
-        {
-        // Add the handler to a list of cleaners. This list
-        // is needed to handle some rare cases where the SIT
-        // thread dies before one or more async cleaners get
-        // the chance to delete themselves. Such cleaner
-        // instances get destroyed by the CTaskArrivalObserver
-        // destructor.
-        TRAP_IGNORE(iAsyncCleanerList->AppendL(asyncCleaner));
-        // Initiate the task handler delete operation
-        asyncCleaner->Start();
-        }
-    else
+    //Find the async cleaner for the task handler:
+    TInt i = 0;
+    for (i = 0; i < iAsyncCleanerList->Count(); ++i)
         {
-        // Backup - just in case asyncCleaner could not be created
-        AsyncDeleteTaskHandler(aTaskHandler);
+        if (iAsyncCleanerList->At(i)->IsMatchingCleaner(*aTaskHandler))
+            {
+            iAsyncCleanerList->At(i)->Start();
+            }
         }
-    }
-
-void CTaskArrivalObserver::AsyncDeleteTaskHandler(CTaskHandler* aTaskHandler)
-    {
-    LOG(Log::Printf(_L("CTaskArrivalObserver::AsyncDeleteTaskHandler\n")));
-    iTaskHandlerToDelete = aTaskHandler;
-    Call();
-    }
-
-void CTaskArrivalObserver::RunL() // Called as a result of AsyncDeleteTaskHandler
-    {
-    LOG(Log::Printf(_L("CTaskArrivalObserver::RunL\n")));
-
-    DeleteTaskHandler(iTaskHandlerToDelete);
-
-    iTaskHandlerToDelete = NULL;    
+    __ASSERT_DEBUG(i <= iAsyncCleanerList->Count(), User::Invariant());
+    
     }
 
 void CTaskArrivalObserver::DeleteTaskHandler(CTaskHandler* aTaskHandler)
     {
     LOG(Log::Printf(_L("CTaskArrivalObserver::DeleteTaskHandler\n")));
     
+    __ASSERT_DEBUG(aTaskHandler != NULL, User::Invariant());
+     
     // The specified task handler has done its
     // job succesfully so it can be deleted
-    TInt taskHandlerIndex = FindTaskHandler(aTaskHandler);
-    
-    if (taskHandlerIndex != KUnfoundIndex)
+    TInt taskHandlerIndex = KErrNotFound;
+        
+    for (TInt i = 0; i < iTaskHandlerList->Count(); i++)
         {
-        LOG(Log::Printf(_L("CTaskArrivalObserver::DeleteTaskHandler - deleting task handler\n")));
-        // Delete the task handler
-        delete iTaskHandlerList->At(taskHandlerIndex);
-        // Delete the list item
-        iTaskHandlerList->Delete(taskHandlerIndex);
-        // Deleting elements from the array does not cause
-        // the array buffer to be automatically compressed.
-        // Compress it to return excess space to the heap
-        // as task handlers come and go.
-        iTaskHandlerList->Compress();
+        if (iTaskHandlerList->At(i) == aTaskHandler)
+            {
+            taskHandlerIndex = i;
+            break;
+            };
         }
-    else
-        {
-        // 
-        delete aTaskHandler;
-        }
+    
+    __ASSERT_DEBUG(taskHandlerIndex >= 0, User::Invariant());
+       
+    LOG(Log::Printf(_L("CTaskArrivalObserver::DeleteTaskHandler - deleting task handler\n")));
+    // Delete the task handler
+    delete aTaskHandler;
+    iTaskHandlerList->Delete(taskHandlerIndex);
+    iTaskHandlerList->Compress();
     }
     
 void CTaskArrivalObserver::DeleteAsyncCleaner(CAsyncCleaner* aAsyncCleaner)
     {
     LOG(Log::Printf(_L("CTaskArrivalObserver::DeleteAsyncCleaner\n")));
     
+    __ASSERT_DEBUG(aAsyncCleaner != NULL, User::Invariant());
+    
     // The specified asynchronous cleaner
     // has done its job and be deleted
-    TInt asyncCleanerIndex = FindAsyncCleaner(aAsyncCleaner);
     
-    if (asyncCleanerIndex != KUnfoundIndex)
+    TInt asyncCleanerIndex = KErrNotFound;
+    for (TInt i = 0; i < iAsyncCleanerList->Count(); i++)
         {
-        LOG(Log::Printf(_L("CTaskArrivalObserver::DeleteAsyncCleaner - deleting async cleaner\n")));
-        // Delete the cleaner object
-        delete iAsyncCleanerList->At(asyncCleanerIndex);
-        // Delete the list item
-        iAsyncCleanerList->Delete(asyncCleanerIndex);
-        // Deleting elements from the array does not cause
-        // the array buffer to be automatically compressed.
-        // Compress it to return excess space to the heap
-        // as cleaner objects come and go.
-        iAsyncCleanerList->Compress();
+        if (iAsyncCleanerList->At(i) == aAsyncCleaner)
+            {
+            asyncCleanerIndex = i;
+            break;
+            };
         }
-    else
-        {
-        // Always delete the cleaner instance even
-        // though it have not been added to the list
-        delete aAsyncCleaner;
-        }
+   
+    __ASSERT_DEBUG(asyncCleanerIndex >= 0, User::Invariant());
+    
+    // Delete the cleaner object
+    delete aAsyncCleaner;
+    iAsyncCleanerList->Delete(asyncCleanerIndex);
+    iAsyncCleanerList->Compress();
+    
     }
 
 void CTaskArrivalObserver::TaskHandlerFatalError(CTaskHandler* /*aTaskHandler*/, TInt /*aError*/)
@@ -310,3 +248,8 @@
     // Delete this cleaner object instance as well
     iTaskArrivalObserver->DeleteAsyncCleaner(this);
     }
+
+TBool CAsyncCleaner::IsMatchingCleaner(const CTaskHandler& aTaskHandler) const
+    {
+    return iTaskHandlerToDelete == &aTaskHandler;
+    }
--- a/vpnengine/vpnmanager/src/pkiutil.cpp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/vpnmanager/src/pkiutil.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+* Copyright (c) 2003-2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * This component and the accompanying materials are made available
 * under the terms of "Eclipse Public License v1.0"
@@ -251,7 +251,9 @@
 
     HBufC8* certData = HBufC8::NewL(KExpectedMaxCertSize);
     HBufC8* subjectNameString;
+    
     _LIT8(KEmptyString, "");
+    
     CleanupStack::PushL(certData);
 
     TPtr8 certDataPtr = certData->Des();
@@ -283,7 +285,6 @@
         aPkiService.Finalize(opContext);
         }
 
-
     // Make sure that the cert, if found, is valid
     if (status.Int() == KErrNone)
         {
@@ -292,6 +293,7 @@
     else //if not found, check wether certificate chain exists
         {
         certStatus = ECertNotFound;
+        
         //checking if certificate chain is found
         CleanupStack::PopAndDestroy(); //  certData
         
@@ -711,7 +713,7 @@
 
             for (TInt i = 0; i < certListArray->Count(); ++i)
                 {
-                TCertificateListEntry entry = (*certListArray)[i];
+                TCertificateListEntry& entry = (*certListArray)[i];
                 if (entry.iOwnerType == EPKICACertificate)
                     {
                     CX509Certificate* cert = ReadCertificateLC(aPkiService,
@@ -847,6 +849,7 @@
                     break;
                     }
                 }
+            
 
             CleanupStack::PopAndDestroy(rfc822Name);
             CleanupStack::PopAndDestroy(subjectName);
--- a/vpnengine/vpnmanager/src/policypatcher.cpp	Wed Sep 01 12:23:21 2010 +0100
+++ b/vpnengine/vpnmanager/src/policypatcher.cpp	Tue Sep 14 23:16:15 2010 +0300
@@ -1,5 +1,5 @@
 /*
-* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+* Copyright (c) 2003-2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * This component and the accompanying materials are made available
 * under the terms of "Eclipse Public License v1.0"
@@ -11,14 +11,13 @@
 *
 * Contributors:
 *
-* Description:   Policy importer
+* Description:  Policy importer
 *
 */
 
-
-
 #include "policypatcher.h"
 #include "vpnapidefs.h"
+#include "pkidefs.h"
 
 
 TAny* TPatchKeyArrayPtr::At(TInt aIndex) const
@@ -314,7 +313,7 @@
     {
     return iUserCertKeyLen;
     }
-    
+
 HBufC8* CPolicyPatchInfo::CheckSubjectNameSyntaxL(const TDesC8& aSubj)
     {
     const TInt KMaxSubjectItems = 20;
@@ -408,41 +407,41 @@
             updateArrCount++;
             updateArrCount++;
             }
-       
-       TBuf8<256> resultBuf;
-       resultBuf.Copy(aSubj);
-       
-       i=0;       
-       
+
+       HBufC8* buf  = HBufC8::NewLC( KMaxX500DN );
+       TPtr8 bufPtr = buf->Des();
+
+       if ( KMaxX500DN >= aSubj.Length() )
+           {
+           bufPtr.Copy( aSubj );
+           }
+       else
+           {
+           User::Leave( KErrArgument );
+           }
+
+       i=0;
+
        //update subjectname acoording to updateArr array.
        if ( updateArr->Count()>0 )
            {
            while (i<updateArrCount)
                {
-               if ( resultBuf.Length()<256 )
-                   resultBuf.Insert(updateArr->At(i) + i, KReplacementChar);
+               if ( bufPtr.Length()<KMaxX500DN )
+                   bufPtr.Insert(updateArr->At(i) + i, KReplacementChar);
                else
                    User::Leave(KErrNotSupported);
                i++;
                }
            }
        
-       CleanupStack::Pop(updateArr);
-       CleanupStack::Pop(commaSignArr);
-       CleanupStack::Pop(equalSignArr);
-       
-       delete equalSignArr;
-       equalSignArr=NULL;
+       CleanupStack::Pop( buf );
+
+       CleanupStack::PopAndDestroy(updateArr);
+       CleanupStack::PopAndDestroy(commaSignArr);
+       CleanupStack::PopAndDestroy(equalSignArr);
        
-       delete commaSignArr;
-       commaSignArr=NULL;
-       
-       delete updateArr;
-       updateArr=NULL;
-       
-       HBufC8* resultHeap = resultBuf.AllocL();
-       
-       return resultHeap;
+       return buf;
     }