#include "StdAfx.h"
#include "KeepAliveFilter.h"
#include "ServerException.h"
#include "TextTools.h"

//!	モジュール名
static TCHAR _MODULE_NAME[] = _T("KeepAliveFilter");

CKeepAliveFilter::CKeepAliveFilter(void)
{
}

CKeepAliveFilter::~CKeepAliveFilter(void)
{
}



/*!
	フィルタ名取得
*/
LPCTSTR CKeepAliveFilter::GetFilterName()
{
	return _MODULE_NAME;
};

/*!
	初期化
*/
void CKeepAliveFilter::StartFactory(IServerToolPtr serverTool)
{
	//	初期化済み？
	if(m_init)
		return;
	m_init = TRUE;

	//	コピー、初期化
	m_serverTool = serverTool;

	//	設定取得
	m_setting = m_serverTool->GetFilterSetting(m_setting.GetSettingName());
	m_enableKeepAlive = m_setting.GetEnableKeepAlive();
	m_keepAliveTime = m_setting.GetMaxKeepConnectionTime();
	m_keepAliveCount = m_setting.GetMaxKeepConnectionCount();
}


/*!
	停止
*/
void CKeepAliveFilter::StopFactory()
{
	//	初期化チェック
	if(!m_init)
		return;
	m_init = FALSE;
}



//////////////////////////////////////////////////////////////////////////////////////////////
//	リクエスト受信
//////////////////////////////////////////////////////////////////////////////////////////////
/*!
	リクエストヘッダ
*/
void CKeepAliveFilter::FilterRequestHeader(IFilterContextPtr filterContext, CContextRequestInfo &requestInfo)
{
	//	リクエストオプション取得
	CContextRequestOption	requestOption = requestInfo.GetRequestOption();

	//	KeepAlive指定？
	if(m_enableKeepAlive && requestOption.GetConnection().CompareNoCase("keep-alive") == 0)
		filterContext->GetIConnectionControl()->SetReuseConnection(TRUE);
	else
		filterContext->GetIConnectionControl()->SetReuseConnection(FALSE);
}



//////////////////////////////////////////////////////////////////////////////////////////////
//	レスポンス送信
//////////////////////////////////////////////////////////////////////////////////////////////
/*!
	レスポンスヘッダ
*/
void CKeepAliveFilter::FilterResponseHeader(IFilterContextPtr filterContext, CContextResponseInfo &responseInfo)
{
	//	レスポンスオプション取得
	CContextResponseOption	responseOption = responseInfo.GetResponseOption();

	//	KeepAlive可能？
	if(filterContext->GetIConnectionControl()->CanReuseConnection())
	{
		responseOption.SetConnection("Keep-Alive");
		responseOption.SetKeepAlive(CTextTools::GetFormat("timeout=%d, max=%d", m_keepAliveTime / 1000, m_keepAliveCount));
	}
	else
	{
		responseOption.SetConnection("Close");
		responseOption.ClearKeepAlive();
	}
}


