#include "StdAfx.h"
#include "KeepAliveFilter.h"

#include "TextTools.h"

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

CKeepAliveFilter::CKeepAliveFilter(void)
{
}

CKeepAliveFilter::~CKeepAliveFilter(void)
{
}



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

/*!
	初期化
*/
void CKeepAliveFilter::_FilterFactoryStart(CIServerToolWrap 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::FilterFactoryStop()
{
	//	初期化チェック
	if(!m_init)
		return;
	m_init = FALSE;
}



//////////////////////////////////////////////////////////////////////////////////////////////
//	リクエスト受信
//////////////////////////////////////////////////////////////////////////////////////////////
/*!
	リクエストヘッダ
*/
void CKeepAliveFilter::_FilterRequestHeader(CIConnectionToolWrap filterContext)
{
	//	リクエストオプション取得
	CContextRequestInfo		requestInfo = filterContext.GetContxet().GetRequestInfo();
	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(CIConnectionToolWrap filterContext)
{
	//	レスポンスオプション取得
	CContextResponseInfo	responseInfo = filterContext.GetContxet().GetResponseInfo();
	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();
	}
}


