/*<<<***************************************************************************
The MIT License (MIT)

Copyright(C) 2013 - 2015 Marc Mirti Mancinelli, Christophe Lardau and Philippe Pamart (xdcube.org)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
#Title: xbCookie
#Project: xdcBase
////////////////////////////////////////////////////////////////////////////////
#Author: Marc MIRTI MANCINELLI
#History:
<15/09/2013: creation.
12/02/2014: this notice inserted.
***************************************************************************>>>*/
#include "stdafx.h"

#include "xbCookie.h"
#include "xbFileTools.h"
#include "xbDnItf.h"
#include "xbTypesAdv.h"
#include "xbSync.h"

#include <wininet.h>

//rfc sur les cookies:
//http://ftp.redfoxcenter.org/pub/Documentation/RFCs/2100/rfc2109.txt

xbCookieEngine	g_xbCookieEngine("xdcBase Cookies Engine",xbEngines(&g_xbCfgEngine));

xbString xbCookieEngine::getValueList(const xbString &url,const xbDateTime *pDtNow)
{
	if (!pDtNow)
	{
		xbDateTime dtNow(xbDateTime::UtcNow());
		return getValueList(url,&dtNow);
	}

	xbString _url(url);
	xbString proto(::xbGetProtocol(_url,&_url));
	if (proto == "file" || proto.IsEmpty())
		return xbString();

	xbString host(::xbSubPath(_url,&_url));
	if (host.IsEmpty())
		return xbString();

	xbString port;
	host.GetToken(0,":",&host,&port);
//	host.GetToken(1,".",NULL,&domain);

	xbString ret;
	if (m_bMScookieSupport)
		getMScookieValueList(url,&ret);

	_url.Trim("/\\");
	if (port.IsValid())
		getValueListForPathRec(host+':'+port,_url,*pDtNow,&ret);
	else
		getValueListForPathRec(host,_url,*pDtNow,&ret);

	host.GetToken(0,".",NULL,&host);
	if(host.IndexOf('.')>=0)
	{
		getValueListForPathRec("."+host,_url,*pDtNow,&ret);
//		host.GetToken(1,".",NULL,&host);
	}

	return ret;
}

void xbCookieEngine::getValueListForPathRec(const xbString &domain,const xbString &path,const xbDateTime &dtNow,xbString *pRet)
{
	xbString _path(path);
	for(;;)
	{
		getValueListForPath(domain,_path,dtNow,pRet);

		if (_path.IsEmpty())
			break;
		::xbSubPathEnd(_path,&_path);
		_path.Trim("/\\");
	}
}

void xbCookieEngine::getValueListForPath(const xbString &domain,const xbString &path,const xbDateTime &dtNow,xbString *pRet)
{
	xbSectLock lck;
	CookieSet *pCookie = cookieSetFind(domain,path,&lck);
	if (!pCookie)
		return;
	bool bToSave = false;
	for(int i = 0; i < pCookie->m_arrItem.Length;i++)
	{
		CookieItem &item = pCookie->m_arrItem.GetAt(i);
		if (item.m_expire.IsValid() && item.m_expire <= dtNow)
		{
			pCookie->ItemDel(i,true);
			bToSave=true;
			i--;
			continue;
		}
		if (cookieAlreadyInStr(item.m_name,*pRet))
			continue;
		if (pRet->IsEmpty())
			(*pRet) = item.m_name+"=";
		else
			(*pRet) += "; "+item.m_name+"=";
/*		if (item.m_value.Find(';')>=0)
			(*pRet) += "\""+item.m_value+"\"";
		else*/
		(*pRet) += item.m_value;
	}
	if (!bToSave)
		return;
	int cRetry=0;
	while(!cookieSetSave(pCookie,lck))
	{
		if (cRetry++ > 10)
			xbThrow xbEdn("Too many tries to save internet cookies (domain="+domain+", path="+path+")","xbCookieEngine");
		pCookie = cookieSetFind(domain,path,&lck);
		if (!pCookie)
			break;
	}
}

bool xbCookieEngine::cookieAlreadyInStr(const xbString &itemName,const xbString &ret)
{
	int pos = ret.IndexOf(itemName+"=");
	if (pos < 0)
		return false;

	return true;
}

void xbCookieEngine::getMScookieValueList(const xbString &url,xbString *pRet)
{
	xbString ret;
	ulong sz = 128;
	int cnt = 0;
	for(;;)
	{
		xbStrExp strExp(&ret,sz,false);
		if (::InternetGetCookie(url,NULL,strExp,&sz))
		{
			strExp.Unlock(sz);
			if (pRet) 
				*pRet = ret;
			return;
		}
		ulong err = GetLastError();
		if (err == ERROR_NO_MORE_ITEMS)
			return;
		if (err != ERROR_INSUFFICIENT_BUFFER || cnt > 4)
			xbThrow xbEdnUser(xbHR_LAST,"Internet cookies are not available (url="+url+")","xbCookieEngine/MSCookies");
		cnt++;
	}
}

void xbCookieEngine::setMScookieValue(const xbString &url,const xbString &val)
{
	ulong ret;
	if ((ret = ::InternetSetCookieEx(url,NULL,val,0,NULL)) != TRUE)
	{
		if (ret == COOKIE_STATE_REJECT)
			xbThrow xbEdnUser(xbHR_LAST,"Internet cookies rejected for security reason (url="+url+")","xbCookieEngine/MSCookies");

		xbThrow xbEdnUser(xbHR_LAST,"Internet cookies are not available (url="+url+")",
			"xbCookieEngine/MSCookies, code="+xbString(ret,xbStringNum_hexa));
	}
}

void xbCookieEngine::setValue(const xbString &url,const xbString &val,const xbDateTime *pDtNow)
{
	if (!pDtNow)
	{
		xbDateTime dtNow(xbDateTime::UtcNow());
		setValue(url,val,&dtNow);
		return;
	}

	xbString _url(url);
	xbString proto(::xbGetProtocol(_url,&_url));
	if (proto == "file" || proto.IsEmpty())
		xbThrow xbEdn("Invalid url to get internet cookies (url="+url+")","xbCookieEngine");

	xbString host(::xbSubPath(_url,&_url));
	if (host.IsEmpty())
		xbThrow xbEdn("Invalid url to get internet cookies (url="+url+")","xbCookieEngine");

	_url.Trim("/\\");
	bool bHttpOnly = false,bSecure=false;
	CookieSet cookieSet(host,_url);

	/*val syntax:
	<name>=<value>[; <name>=<value>]
	[; expires=<date>][; domain=<domain_name>]
	[; path=<some_path>][; secure][; HttpOnly]
	*/
	bool bProps=false;
	xbString str,sname,sval;
	int pos=0;
	while((pos=val.GetToken(pos,";",&str,NULL,NULL,"\""))>0)
	{
		str.GetToken(0,"=",&sname,&sval);
		if (sname.CompareNoCase("expires")==0)
		{
			bProps=true;
			xbDateTime dtExpire;
			{
				xbString tz;
				comcfgTime ti;
				ti.Set(sval,&tz);
				ti.ToDateTime(&dtExpire);
				int decal=0 /*,stopPos=0*/;
				while(tz.IsValid() && tz.CompareNoCase("GMT")!=0 && tz.CompareNoCase("UTC")!=0)
				{
					if (tz.Length == 4)
					{						
						decal = xbStrToInt(tz);
						break;
					}
					if (tz.Length == 5 && tz.First() == '-')
					{
						decal = -xbStrToInt((LPCSTR)tz+1);
						break;
					}
					if (tz.Length == 5 && tz.First() == '+')
					{
						decal = xbStrToInt((LPCSTR)tz+1);
						break;
					}
					if (tz.Length == 6 && tz.First() == '-'&& tz.GetAt(3) == ':')
					{
						tz.Delete(3);
						decal = -xbStrToInt((LPCSTR)tz+1);
						break;
					}
					if (tz.Length == 6 && tz.First() == '+'&& tz.GetAt(3) == ':')
					{
						tz.Delete(3);
						decal = xbStrToInt((LPCSTR)tz+1);
						break;
					}
					xbRelOutput("[PB]cookies: invalid date timezone "+tz+" for date '"+sval+"' in ("+val+")");
					break;
				}
				
				if (decal)
				{
					double utcOffs = -double((decal/100)*60+(decal%100))/double(24*60);
					utcOffs += double(dtExpire);

					dtExpire = utcOffs;
				}
			}
			cookieSet.m_cItemPersist = cookieSet.m_arrItem.Length;
			for(int i = 0; i < cookieSet.m_cItemPersist;i++)
			{
				cookieSet.m_arrItem.GetAt(i).m_expire = dtExpire;
			}
			continue;
		}
		if (sname.CompareNoCase("max-age")==0)
		{
			bProps=true;
			xbDateTime dtExpire(*pDtNow);
			//int stopPos=0;
			dtExpire += double(xbStrToInt(sval))/(24*60*60);
/*			if (stopPos>0)
			{
				xbRelOutput("[PB]cookies: invalid max-age "+sval+" in ("+val+")");
				continue;
			}*/
			cookieSet.m_cItemPersist = cookieSet.m_arrItem.Length;
			for(int i = 0; i < cookieSet.m_cItemPersist;i++)
			{
				cookieSet.m_arrItem.GetAt(i).m_expire = dtExpire;
			}
			continue;
		}
		if (sname.CompareNoCase("domain")==0)
		{
			bProps=true;
			if (sval.IsEmpty() || sval.First() != '.')
			{
				xbRelOutput("[PB]cookies: invalid domain "+sval+" in ("+val+")");
				continue;
			}
			sval.Delete(0);
			if (sval.IndexOf('.')< 0)
			{
				xbRelOutput("[PB]cookies: invalid domain ."+sval+" in ("+val+")(2)");
				continue;
			}

			cookieSet.m_domain = "."+sval;
			continue;
		}
		if (sname.CompareNoCase("path")==0)
		{
			bProps=true;
			sval.Trim("/\\");
			cookieSet.m_path = sval;
			continue;
		}
		if (sname.CompareNoCase("secure")==0)
		{
			bProps=true;
			bSecure=true;
			if (sval.IsValid())
				xbRelOutput("[PB]cookies: invalid prop "+sname+" in ("+val+")");
			continue;
		}
		if (sname.CompareNoCase("httpOnly")==0)
		{
			bProps=true;
			bHttpOnly=true;
			if (sval.IsValid())
				xbRelOutput("[PB]cookies: invalid prop "+sname+" in ("+val+")");
			continue;
		}
		if (sname.CompareNoCase("version")==0 || sname.CompareNoCase("comment")==0)
		{
			bProps=true;
			continue;
		}
		if (sname.First() == '$')
		{
			xbRelOutput("[PB]cookies: ignored prop "+sname+" in ("+val+")");
			continue;
		}
		if (bProps)
		{
			xbRelOutput("[PB]cookies: unsupported prop "+sname+" in ("+val+")");
			continue;
		}

		cookieSet.ItemAdd(sname,sval);
	}

	cookieSetAdd(cookieSet,*pDtNow);

	if (!bHttpOnly && m_bMScookieSupport)
		setMScookieValue(url,val);
}

int xbCookieEngine::cookieItemFindCb(const CookieItem &item, const void *pName)
{
	return item.m_name.CompareNoCase((LPCSTR)pName);
}

int xbCookieEngine::cookieSetFindCb(CookieSet * const &pSet1, const void *pSet2)
{
	int ret = pSet1->m_domain.CompareNoCase(((CookieSet*)pSet2)->m_domain);
	if (ret != 0)
		return ret;
	return pSet1->m_path.CompareNoCase(((CookieSet*)pSet2)->m_path);
}

void xbCookieEngine::CookieSet::ItemAdd(const xbString &name, const xbString &val, const xbDateTime *pDtExpire,const xbDateTime *pDtNow,bool bLoad)
{
	int pos;
	CookieItem *pItem = m_arrItem.SortedFind((LPCSTR)name,cookieItemFindCb,&pos);
	if (pItem)
	{
		if (pDtExpire)
		{
			if (pDtNow && pDtExpire->IsValid() && *pDtNow >= *pDtExpire)
			{
				ItemDel(pos,pItem->m_expire.IsValid());
				return;
			}
			if (pItem->m_expire.IsValid() != pDtExpire->IsValid())
			{
				if (pItem->m_expire.IsValid())
				{
					xbRdbgAssert(m_cItemPersist>0);
					m_cItemPersist--;
				}
				else
				{
					m_cItemPersist++;
				}
			}
			else
			{
				if (bLoad && pItem->m_expire > *pDtExpire)
					return;
			}
			pItem->m_expire = *pDtExpire;
		}
		pItem->m_value = val;
		return;
	}

	m_arrItem.Insert(pos,CookieItem());

	pItem = &m_arrItem.GetAt(pos);
	pItem->m_name = name;
	pItem->m_value = val;
	if (pDtExpire && pDtExpire->IsValid())
	{
		m_cItemPersist++;
		pItem->m_expire = *pDtExpire;
	}
}

xbCookieEngine::CookieSet	*xbCookieEngine::cookieSetFind(const xbString &domain,const xbString &path,xbSectLock *pLck,bool bCreate)
{
	int cRetry=0;
retryFind:
	if (cRetry++ > 10)
		xbThrow xbEdn("Too many tries to get internet cookies (domain="+domain+", path="+path+")","xbCookieEngine");
	pLck->Lock(&m_sect);

	CookieSet cookieSet(domain,path);

	int pos;
	CookieSet **ppFnd = m_arrCookie.SortedFind(&cookieSet,cookieSetFindCb,&pos);
	if (ppFnd)
	{
		if (!cookieSetUpdate(*ppFnd,*pLck))
			goto retryFind;
		return *ppFnd;
	}
	CookieSet *pFnd=NULL;
	if (!cookieSetLoad(&cookieSet,pos,*pLck,&pFnd))
		goto retryFind;

	if (pFnd)
		return pFnd;

	if (!bCreate)
		return NULL;

	pFnd = xbDnew CookieSet(domain,path);

	m_arrCookie.Insert(pos,pFnd);

	return pFnd;
}

bool xbCookieEngine::cookieSetUpdate(CookieSet *pCookie,xbSectLock &lck)
{
	xbString ckPath(cookieGetPath(pCookie));
	if (!::xbFileExists(ckPath))
		return cookieSetDelPersist(pCookie,lck);

	try
	{
		xbFileStream stm(ckPath,xbOpen,xbAccessR,xbWorkSharedR);
		xbDateTime wti;
		{
			FILETIME _wti;
			stm.GetFileTime(NULL,NULL,&_wti);
			wti = _wti;
		}
		if (pCookie->m_fileDtModif.IsValid())
		{
			if (pCookie->m_fileDtModif == wti)
				return true;
		}

		cookieSetStreamLoad(pCookie,&stm);

		pCookie->m_fileDtModif = wti;
	}
	catch(xbEstream *pE)
	{
		pE->Delete();
		if (!::xbFileExists(ckPath))
			return cookieSetDelPersist(pCookie,lck);
		lck.Unlock();

		::xbSleep(200);
		return false;
	}
	return true;
}

bool xbCookieEngine::cookieSetLoad(const CookieSet *pCookieRef,int insertPos,xbSectLock &lck,CookieSet **ppRetCookie)
{
	xbString ckPath(cookieGetPath(pCookieRef));
	if (!::xbFileExists(ckPath))
		return true;
	try
	{
		xbFileStream stm(ckPath,xbOpen,xbAccessR,xbWorkSharedR);
		xbDateTime wti;
		{
			FILETIME _wti;
			stm.GetFileTime(NULL,NULL,&_wti);
			wti = _wti;
		}

		CookieSet *pCookie = xbDnew CookieSet(pCookieRef->m_domain,pCookieRef->m_path);
		try
		{
			cookieSetStreamLoad(pCookie,&stm);

			pCookie->m_fileDtModif = wti;

			m_arrCookie.Insert(insertPos,pCookie);
		}
		catch(...)
		{
			delete pCookie;
			throw;
		}

		*ppRetCookie = pCookie;

	}
	catch(xbEstream *pE)
	{
		pE->Delete();
		if (!::xbFileExists(ckPath))
			return true;
		lck.Unlock();

		::xbSleep(200);
		return false;
	}
	return true;
}

bool xbCookieEngine::cookieSetDelPersist(CookieSet *pCookie,xbSectLock &lck)
{
	if (pCookie->m_cItemPersist != 0)
	{
		for(int i = 0; i < pCookie->m_arrItem.Length;i++)
		{
			CookieItem &item = pCookie->m_arrItem.GetAt(i);
			if (item.m_expire.IsEmpty())
				continue;
			
			pCookie->m_arrItem.Delete(i);
			i--;
		}

		pCookie->m_cItemPersist=0;
	}
/*
	if (!bFileToo)
		return true;

	xbString ckPath(cookieGetPath(pCookie));
	if (!::xbFileExists(ckPath))
		return true;

	if (::xbDeleteFile(ckPath))
		return true;

	lck.Unlock();

	::xbSleep(200);

	return false;*/
	return true;
}

bool xbCookieEngine::cookieSetSave(CookieSet *pCookie,xbSectLock &lck)
{
	xbString ckPath(cookieGetPath(pCookie,pCookie->m_cItemPersist!=0));
	if (!pCookie->m_cItemPersist && !::xbFileExists(ckPath))
		return true;
	try
	{
		xbFileStream stm(ckPath,xbOpenAlways,xbAccessRW,xbWorkExclusive);
		xbDateTime wti;
		{
			FILETIME _wti;
			stm.GetFileTime(NULL,NULL,&_wti);
			wti = _wti;
		}

		if (stm.GetLength()>0 && pCookie->m_fileDtModif != wti)
		{
			cookieSetStreamLoad(pCookie,&stm);
			pCookie->m_fileDtModif = wti;

			stm.Seek(0);
		}
		if (!pCookie->m_cItemPersist)
		{
			stm.Close();
			if (!::xbFileExists(ckPath))
				return true;

			if (::xbDeleteFile(ckPath))
				return true;

			lck.Unlock();

			::xbSleep(200);

			return false;
		}

		cookieSetStreamSave(pCookie,&stm);

		{
			FILETIME _wti;
			stm.GetFileTime(NULL,NULL,&_wti);
			wti = _wti;
		}
		pCookie->m_fileDtModif = wti;
	}
	catch(xbEstream *pE)
	{
		if (!xbIsHRsharedViolation(pE->GetHR()))
			throw;

		pE->Delete();
		lck.Unlock();

		::xbSleep(200);
		return false;
	}
	return true;
}

void xbCookieEngine::cookieSetAdd(const CookieSet &cookieSet,const xbDateTime &dtNow)
{
	xbSectLock lck;
	CookieSet *pCookie = cookieSetFind(cookieSet.m_domain,cookieSet.m_path,&lck,true);

	for(int i = 0; i < cookieSet.m_arrItem.Length;i++)
	{
		const CookieItem &item = cookieSet.m_arrItem.GetAt(i);
		pCookie->ItemAdd(item.m_name,item.m_value,&item.m_expire,&dtNow);
	}

	int cRetry=0;
	while(!cookieSetSave(pCookie,lck))
	{
		if (cRetry++ > 10)
			xbThrow xbEdn("Too many tries to add internet cookies (domain="+cookieSet.m_domain+", path="+cookieSet.m_path+")","xbCookieEngine");
		pCookie = cookieSetFind(cookieSet.m_domain,cookieSet.m_path,&lck);
		if (!pCookie)
			break;
	}
}

void xbCookieEngine::cookieSetStreamLoad(CookieSet *pCookie,IxbInputStream *pStm)
{
	xbDateTime dtNow(xbDateTime::UtcNow());

	ulong maj = pStm->ReadUlong();
	ulong ver = pStm->ReadUlong();
	if (maj != xbCOOKIE_MAJ && ver != xbCOOKIE_VER)
		xbThrow xbEdn("Invalid cookie file (domain="+pCookie->m_domain+", path="+pCookie->m_path+")","xbCookieEngine");
	xbString cname,cval;
	xbDateTime dtExpire;
	long op;
	for(;;)
	{
		op = pStm->ReadLong();
		if (!op)
			break;
		if (op != 1)
			xbThrow xbEdn("Invalid cookie file (domain="+pCookie->m_domain+", path="+pCookie->m_path+")","xbCookieEngine/op invalid");
		(*pStm)>>&cname;
		(*pStm)>>&cval;
		dtExpire = pStm->ReadDouble();

		pCookie->ItemAdd(cname,cval,&dtExpire,&dtNow,true);
	}
}

void xbCookieEngine::cookieSetStreamSave(const CookieSet *pCookie,IxbOutputStream *pStm)
{
	pStm->WriteUlong(xbCOOKIE_MAJ);
	pStm->WriteUlong(xbCOOKIE_VER);
	for(int i = 0; i < pCookie->m_arrItem.Length;i++)
	{
		const CookieItem &item = pCookie->m_arrItem.GetAt(i);
		if (item.m_expire.IsEmpty())
			continue;
		pStm->WriteLong(1);
		(*pStm) << item.m_name;
		(*pStm) << item.m_value;
		pStm->WriteDouble(item.m_expire);
	}
	pStm->WriteLong(0);
	(*pStm) << pCookie->m_domain;
	(*pStm) << pCookie->m_path;
}

xbString xbCookieEngine::cookieGetPath(const CookieSet *pCookie,bool bCreatePath)
{
	xbString urlEncoded(::xbBase64encode(pCookie->m_domain+"§"+pCookie->m_path));
	for(int i = 6; i < urlEncoded.Length-1; i+= 6)
	{
		urlEncoded.Insert(i,xbPath_SLASHch);
		i++;
	}
	urlEncoded = GetCookiePath()+urlEncoded;

	if (bCreatePath)
	{
		xbString path;
		::xbSubPathEnd(urlEncoded,&path);
		::xbMakeDir(path,true);
	}

	return urlEncoded;
}

xbString xbCookieEngine::GetCookiePath()
{
	xbLock lckStart(this);
	xbSectLock lck(&m_sect);
	if (m_cookiePath.IsEmpty())
	{
		xbString ckPath;
		lck.Unlock();

		for(;;)
		{
			{
				xbCfgKey key(xbCfgCommonUser,"Cookies");
				xbVariant val(key.Value["Path"]);
				if (val.IsValid())
				{
					ckPath = g_xbCfgEngine.GetExpandedString(val.AsString);
					break;
				}
			}
			{
				xbCfgKey key(xbCfgCommon,"Cookies");
				xbVariant val(key.Value["Path"]);
				if (val.IsValid())
				{
					ckPath = g_xbCfgEngine.GetExpandedString(val.AsString);
					break;
				}
			}

			ckPath = g_xbCfgEngine.GetExpandedString(xbCOOKIE_PATH);
			break;
		}

		lck.Lock(&m_sect);
		if (m_cookiePath.IsEmpty())
		{
			m_cookiePath = ::xbPathSlash(ckPath);
			m_cookiePath.TrimRight("/\\");
		}
	}
	return m_cookiePath+xbPath_SLASH;
}

void xbCookieEngine::SetCookiePath(const xbString &ckPath)
{
	xbLock lckStart(this);
	xbSectLock lck(&m_sect);
	m_cookiePath = xbPathSlash(ckPath);
	m_cookiePath.TrimRight("/\\");
}
