// Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
// mdnsserver.cpp
// 
//
/**
@file
@internalTechnology
*/

#include "mdnsserver.h"
#include <commdbConnpref.h>
#include "mdnsserversession.h"
#include "shutdowntimer.h"
#include "cmessagehandler.h"
#include "cmdnscacheconsistencymgr.h"
#include <mdns/cmdnsserverconstants.h>
#include "cmdnsprobemanager.h"
#include <nifman.h>
#include <comms-infras/es_config.h> 
#include <EscapeUtils.h>
#include <ecom/ECom.h> 
#include <btengsettings.h>// Console
#include "cengsettingsobserver.h"
__FLOG_STMT(_LIT8(KComponent,"MDNSServer");)
CMdnsServer* CMdnsServer::NewL()
	{

	CMdnsServer* self = CMdnsServer::NewLC();
	CleanupStack::Pop(self);

	return self;
	}
	
/*
 * Two phase constructor
 */
CMdnsServer* CMdnsServer::NewLC()
	{
	CMdnsServer* self = new (ELeave) CMdnsServer;
	CleanupStack::PushL(self);
	self->ConstructL();
	return self;
	}

/*
 * Derived from CPolicy server
 * Creates a new session object.
 */
CSession2* CMdnsServer::NewSessionL(const TVersion& /*aVersion*/, const RMessage2& /*aMessage*/) const
	{
	__FLOG(_L8("CMdnsServer::NewSessionL - Entry"));
	// if we're in the process of shutting the server down cleanly,
	// don't accept any more connections.
	if (iShutdownInProgress)
		{
		User::Leave(KErrCouldNotConnect);
		}
	
	CMdnsServerSession* session = CMdnsServerSession::NewL(*this);
	__FLOG(_L8("CMdnsServer::NewSessionL - Exit"));
	return session;
	}
	
TInt CMdnsServer::NewSession()
	{
	__FLOG(_L8("CMdnsServer::NewSession - Entry"));
	iShutdownTimer->Cancel();
	++iConnectionCount;
	++iSessionIdCounter;
	__FLOG(_L8("CMdnsServer::NewSession - Exit"));
	return iSessionIdCounter;
	}
	
void CMdnsServer::DropSession()
	{
	__FLOG(_L8("CMdnsServer::DropSession - Entry"));
	if (0 == --iConnectionCount)
		{
		//CActiveScheduler::Stop();
		iShutdownTimer->Start();
		}
	__FLOG(_L8("CMdnsServer::DropSession - Exit"));
	}
	
void CMdnsServer::BeginShutdownL()
	{
	__FLOG(_L8("CMdnsServer::BeginShutdownL - Entry"));
	iShutdownInProgress = ETrue;
	CActiveScheduler::Stop();
	__FLOG(_L8("CMdnsServer::BeginShutdownL - Exit"));
	}
	
/*
 * Destructor
 */
CMdnsServer::~CMdnsServer()
	{
	__FLOG(_L8("CMdnsServer::~CMdnsServer - Entry"));
	iCacheConsistencyMgr->Stop();
	delete iShutdownTimer;
	delete iMessageHandler;
	delete iProbeManager;
	delete iInternalMessageQueue;
	delete iCacheConsistencyMgr;
	iConnection.Close();
	iSockServ.Close();
	iHostName.Close();
	REComSession::FinalClose();
	__FLOG(_L8("CMdnsServer::~CMdnsServer - Exit"));
	__FLOG_CLOSE;
	}

CMdnsServer::CMdnsServer()
	: CPolicyServer(EPriorityStandard, zeroconfPolicy),iConnectionCount(0),iSessionIdCounter(0)
	{
	}

/*
 * Get the system ipaddress by amaking a query to the dns.
 * @param aAddr on return contains the address.
 */
TInt CMdnsServer::GetLocalHost ( TSockAddr& aAddr )
    {
    __FLOG(_L8("CMdnsServer::GetLocalHost - Entry"));
    RSocket socket;
    TInt err = socket.Open ( iSockServ, KAfInet, KSockStream, KProtocolInetTcp );

    if ( err == KErrNone )
        {
        TInetAddr localHost;
        localHost.SetAddress ( KInetAddrAny );
        TPckgBuf<TSoInetIfQuery> query;
        query ().iDstAddr = localHost;

        err = socket.GetOpt ( KSoInetIfQueryByDstAddr, KSolInetIfQuery, query );

        if ( err == KErrNone )
            {
            // its local IP address
            localHost = query ().iSrcAddr;
            aAddr = localHost;
            TBuf<255>name ;
            name.Append(query ().iName);
            }
        }

    socket.Close ();
    __FLOG(_L8("CMdnsServer::GetLocalHost - Exit"));
    return err;
    }

/*
 * Two phase constructor
 */
void CMdnsServer::ConstructL()
	{
	__FLOG_OPEN(KMDNSSubsystem, KComponent);
	__FLOG(_L8("CMdnsServer::ConstructL - Entry"));
	User::LeaveIfError(iSockServ.Connect());
	User::LeaveIfError(iConnection.Open(iSockServ));
	
	// fetch the IAP from the command line
	HBufC* iapBuf = HBufC::NewLC(User::CommandLineLength());
	TPtr iapPtr = iapBuf->Des();
	User::CommandLine(iapPtr);
	
	TUint32 iap(0);
	TLex lex(*iapBuf);
	User::LeaveIfError(lex.Val(iap, EDecimal));
	
	CleanupStack::PopAndDestroy(iapBuf);
	
	// start a connection with the appropriate IAP
	TCommDbConnPref prefs;
	prefs.SetIapId(iap);
	prefs.SetDialogPreference(ECommDbDialogPrefDoNotPrompt);
	User::LeaveIfError(iConnection.Start(prefs));
		
	User::LeaveIfError(iSocket.Open(iSockServ, KAfInet, KSockDatagram, KProtocolInetUdp));
	User::LeaveIfError(iSocket.SetLocalPort(KMdnsPort));
	TInetAddr broadcast;
	//To be added in constant header
	const TUint32 KMDnsAddr = INET_ADDR(224, 0, 0, 251);
	broadcast.SetAddress(KMDnsAddr);
	JoinMulticastGroupL(broadcast);
	iMessageHandler = CMessageHandler::NewL(*this);
	iShutdownTimer = CShutdownTimer::NewL(*this);
	/***************************************PROBE**************************************************/
	 //From here : Probe only for Host Name
    iProbeManager = CMDNSProbeManager::NewL(iMessageHandler->DnsCache(),*iMessageHandler,ETrue);
    TInetAddr addr;
    GetLocalHost(addr);
    //iHostName.Create(_L8("vadan.Local")); 
    CEngSettingsObserver* observer = CEngSettingsObserver::NewLC();
            
    CBTEngSettings* btsettings= CBTEngSettings::NewL(observer);
    
    RBuf name;
    name.CreateL(64);
    btsettings->GetLocalName(name);
    if(name.Length()==0)
        {
        iHostName.CreateL(_L8("MyNokiaPhone.Local"));
        }
    else
        {
        name.Append(_L(".local"));    
        iHostName.CreateL(name.Collapse());
        }    
    
    iProbeManager->StartNameProbeL(iHostName,addr);
    /*****************************************END**************************************************/
    iInternalMessageQueue = CInternalMessageQueue::NewL(*this);
    /*****************************************ConsistencyMgr***************************************/
    iCacheConsistencyMgr = CMDNSCacheConsistencyMgr::NewL(ETrue,*iMessageHandler);
    iCacheConsistencyMgr->Start();
	// start up the server
	StartL(KMdnsServerName);
	__FLOG(_L8("CMdnsServer::ConstructL - Exit"));
	}
/*
 * Interface to join the multicast group.
 * @param aMulticastAddr specifies the multicast address to which it will join
 * this is generally the mdns multicast address.
 */
void CMdnsServer::JoinMulticastGroupL(TInetAddr& aMulticastAddr)
	{
	__FLOG(_L8("CMdnsServer::JoinMulticastGroupL - Entry"));
	TPckgBuf<TIp6Mreq> mReq;
	
	if (aMulticastAddr.Family() != KAfInet6)
		{
		aMulticastAddr.ConvertToV4Mapped();
		}
		
	mReq().iAddr =  aMulticastAddr.Ip6Address();
	mReq().iInterface = 0;
	User::LeaveIfError(iSocket.SetOpt(KSoIp6MulticastHops, KSolInetIp, 255));
	User::LeaveIfError(iSocket.SetOpt(KSoIp6JoinGroup, KSolInetIp, mReq));
	User::LeaveIfError(iSocket.SetOpt(KSoIp6MulticastLoop, KSolInetIp, 0));
	__FLOG(_L8("CMdnsServer::JoinMulticastGroupL - Exit"));
	}

/*
 * @return returns the reference to the socket.
 */
RSocket& CMdnsServer::Socket()
	{
	__FLOG(_L8("CMdnsServer::Socket -Entry  Exit"));
	return iSocket;	
	}
/*
 * returns the reference to messagehandler.
 */
CMessageHandler& CMdnsServer::MessageHandler()const
	{
	__FLOG(_L8("CMdnsServer::MessageHandler -Entry Exit"));
	return *iMessageHandler;
	}		

/*
 * Query from the client should be served after a delay .If sent to the 
 * network. usually 120ms. 
 * Server will be notified with the same after the time elapses.
 * @param aClientHandle session id which actually requested for the query .
 * 
 * */
void CMdnsServer::NotifyClientQuery(TInt aClientHandle)
	{
	__FLOG(_L8("CMdnsServer::NotifyClientQuery - Entry"));
	iSessionIter.SetToFirst();
	CSession2* session = NULL;
	while (NULL != (session = iSessionIter++))
		{
		CMdnsServerSession* serverSession = static_cast<CMdnsServerSession*>(session);
		if(serverSession->OutStandQueryClientHandle() == aClientHandle)
			{
			serverSession->SendResponseL();	
			}
		}	
	__FLOG(_L8("CMdnsServer::NotifyClientQuery - Exit"));
	}

/*
 * Returns the hostname with which it has been probed.
 */
TDesC8& CMdnsServer::HostName()const
    {
    __FLOG(_L8("CMdnsServer::HostName -Entry Exit"));
    return (TDesC8&)iHostName; 
    }


void CMdnsServer::SetHostNameL(const TDesC8& aName)
    {
    iHostName.Close();
    iHostName.CreateL(aName);
    }

/*
 * When a new service appears in the network. 
 * will be notified to the server using this.
 * Server in turn looks for the session interested in the service and completes the asynchronous reuest.
 */
void CMdnsServer::NotifyNewServiceL(const RArray<RBuf8>& aName)
	{
	__FLOG(_L8("CMdnsServer::NotifyNewServiceL - Entry"));
	iSessionIter.SetToFirst();
	CSession2* session = NULL;
	while (NULL != (session = iSessionIter++))
		{
		CMdnsServerSession* serverSession = static_cast<CMdnsServerSession*>(session);
		serverSession->NewServiceL(aName);
		}
	__FLOG(_L8("CMdnsServer::NotifyNewServiceL - Exit"));
	}

/*
 * After the service has been published succesfully.
 * Server will be notified with this interface.
 * @param aName name with which the service is published.
 * @param aError result of submission.
 * @param aSessionId session id of the client.
 */
void CMdnsServer::NotifyServicePublishL(const RBuf8& aName,TInt aError, TInt aSessionId)
	{
	__FLOG(_L8("CMdnsServer::NotifyServicePublishL - Entry"));
	iSessionIter.SetToFirst();
	CSession2* session = NULL;
	while ((NULL != (session = iSessionIter++)) )
		{
		CMdnsServerSession* serverSession = static_cast<CMdnsServerSession*>(session);
		if(serverSession->SessionId() == aSessionId)
		    {
		    serverSession->HandleServiceNameConflictL(aName,aError);
		    }
		}
	SetPublishingService(EFalse);
	if(MessageQueue()->Count()>0)
	    {
	    MessageQueue()->StartProcessing();
	    }
	__FLOG(_L8("CMdnsServer::NotifyServicePublishL - Exit"));
	}

/*
 * This performs two tast.
 * 1. Set the iIsHostprobing to ETrue if host probing is going on.
 * 2. If Hostprobing is over it sees whether there are any pending queries or 
 * publish request . IF there are any it will start processing the same .
 * @param aProbing true if host probing.
 */
void CMdnsServer::SetStateHostProbing(TBool aProbing)
    {
    __FLOG(_L8("CMdnsServer::SetStateHostProbing - Entry"));
    iIsHostProbing = aProbing;
    if(!aProbing && MessageQueue()->Count()>0)
        {
        MessageQueue()->StartProcessing();
        }
    __FLOG(_L8("CMdnsServer::SetStateHostProbing - Exit"));        
    }

/*
 * @return returns wheteher host probing is going on or not.
 */
TBool CMdnsServer::IsHostProbing()const
    {
    __FLOG(_L8("CMdnsServer::IsHostProbing - Exit"));
    return iIsHostProbing;
    }

/*
 * Starts any pending publish or query request in the queue.
 * @param aMessage query or publish request.
 * @param aType can be either publish or query.
 * @param aSessionId session which requested .
 */
void CMdnsServer::ProcessQueuedMessage(const RMessage2& aMessage, const TMessageType aType,TInt aSessionId)
    {
    __FLOG(_L8("CMdnsServer::ProcessQueuedMessage - Entry"));
    iSessionIter.SetToFirst();
        CSession2* session = NULL;
        while (NULL != (session = iSessionIter++))
            {
            CMdnsServerSession* serverSession = static_cast<CMdnsServerSession*>(session);
            if(aSessionId == serverSession->SessionId())
                {
                switch(aType)
                    {
                    case EQueryMessage:
                        {
                        serverSession->ServiceQueryL(aMessage);
                        break;
                        }
                    case EPublishMessage:
                        {
                        serverSession->PublishL(aMessage);
                        break;
                        }
                    }
                }
            }  
    __FLOG(_L8("CMdnsServer::ProcessQueuedMessage - Exit"));
    }

/*
 * Pointer to the internall message queue.
 */
CInternalMessageQueue* CMdnsServer::MessageQueue()
    {
    __FLOG(_L8("CMdnsServer::MessageQueue -Entry Exit"));
    return iInternalMessageQueue;
    }


void CMdnsServer::OnPacketSendL(TInt /*aError*/)
    {
    // this is the call back after the bye-bye packet is sent.
    // do nothing
    __FLOG(_L8("CMdnsServer::OnPacketSendL -Entry Exit"));
    }
/*
 * if publishing will be set to true.
 * this is to halt any further publish , till the one undergoing gets over.
 */
void CMdnsServer::SetPublishingService(TBool aFlag)
    {
    __FLOG(_L8("CMdnsServer::SetPublishingService - Entry"));
    iIsPublishing = aFlag;
    __FLOG(_L8("CMdnsServer::SetPublishingService - Exit"));

    }
TBool CMdnsServer::IsPublishingService() const
    {
    __FLOG(_L8("CMdnsServer::IsPublishingService -Entry Exit"));
    return iIsPublishing ;
    }
