/*
 * <insert one-line description of what the program does>
 * Copyright (c) <2008-2009>, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU Lesser General Public License,
 * version 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */
#include <stdio.h>
#include <string.h>
#include "GUI/error.h"
#include "InfoMgmt/InfoMgmt.h"
#include "GUI/macro.h"
#include <time.h>
#include "GUI/resmgmt.h"
extern RESOURCE_MANAGER g_resManager;
char* errtable[10][50] = {
{//ConnMgmt
"The remote service point could not be contacted at the transport level.", 
"The connection was prematurely closed.",
"The connection for a request that specifies the Keep-alive header was closed unexpectedly.",
"A message was received that exceeded the specified limit when sending a request or receiving a response from the server.", 
"The name resolver service could not resolve the host name.", 
"An internal asynchronous request is pending.",
"The response received from the server was complete but indicated a protocol-level error.", 
"The name resolver service could not resolve the proxy host name.", 
"A complete response was not received from the remote server.",
"The request was canceled.",
"An error occurred while establishing a connection using SSL.", 
"A complete request could not be sent to the remote server.", 
"The server response was not a valid HTTP response.", 
"No error was encountered.",
"No response was received during the time-out period for a request.",		
"A server certificate could not be validated.",
"return data from web service fromat Invalidation.",
"parameter of Send to web service error.",
"Web service inner Error.",
"An exception of unknown type has occurred.", 
"HWIDInvalid.",
"BootTickInvalid.",
"DeviceStolen.",
"BooCertPointIsNull.", 
"CurrentStatePointIsNull.",
"ConnMgmt invoke DeviceInfo_Construct error.",
"ConnMgmt invoke DeviceInfo_StudentID error.",
"ConnMgmt invoke DeviceInfo_Construct error.",
"ConnMgmt invoke DeviceInfo_Construct error.",

// Start add by Roc Zhang 2007-9-19
"Open Root CA file failed",
"Wrtie data to Root CA file failed"
// End add

},
{//ConnMgmt_SOAP
"No error.",                                                                                                    
"The service returned a client fault (SOAP 1.2 Sender fault).",                                                 
"The service returned a server fault (SOAP 1.2 Receiver fault).",                                               
"An XML element didn't correspond to anything expected.",                                                       
"An XML schema type mismatch.",                                                                                 
"An XML syntax error occurred on the input.",                                                                   
"Begin of an element expected, but not found.",                                                                 
"Array index out of bounds.",                                                                                   
"An element needs to be ignored that need to be understood.",                                                   
"Namespace name mismatch (validation error).",                                                                  
"Mismatch in the size and/or shape of an object.",                                                              
"Internal error.",                                                                                             
"An exception raised by the service.",                                                                          
"Skeleton error: the skeleton cannot serve the method.",                                                        
"Unsupported HTTP GET.",                                                                                        
"Out of memory.",                                                                                               
"An element was null, while it is not supposed to be null.",                                                    
"Multiple occurrences of the same element ID on the input.",                                                    
"Element ID missing for an HREF on the input.",                                                                 
"Reference to object is incompatible with the object refered to.",                                              
"A UDP connection error occured.", 
"A TCP connection error occured.",                                                                              
"An HTTP error occured.",                                                                                       
"An SSL error occured.",                                                                                        
"A Zlib error occured.",                                                                                        
"Failed to register plugin.",                                                                                   
"MIME parsing error.",                                                                                          
"DIME parsing error.",                                                                                          
"End of DIME error.",                                                                                           
"DIME attachment has no href from SOAP body (and no DIME_callbacks were dened to save the attachment).",        
"DIME version/transmission error.",                                                                             
"SOAP version mismatch or no SOAP message.",                                                                    
"SOAP 1.2 DataEncodingUnknown fault.",                                                                          
"Attributed required validation error.",                                                                        
"Attributed prohibited validation error.",                                                                      
"Element minOccurs/maxOccurs validation error.",                                                                
"Element length validation error.",                                                                             
"Unexpected end of le, no input, or timeout while receiving data."
},
{//ConnMgmt_HTTP2
"HTTP_Created.",
"HTTP_Accepted.",
"HTTP_Non_Authoritative_Information.",
"HTTP_No_Content.",
"HTTP_Reset_Content.",
"HTTP_Partial_Content."
},
{//ConnMgmt_HTTP3
"HTTP_Multiple_Choices.",
"HTTP_Moved_Permanently.",
"HTTP_Found.",
"HTTP_See_Other.",
"HTTP_Not_Modified.",
"HTTP_Use_Proxy.",
"HTTP_Temporary_Redirect."
},
{//ConnMgmt_HTTP4
"HTTP_Bad_Request.",
"HTTP_Unauthorized.",
"HTTP_Payment_Required.",
"HTTP_Forbidden.",
"HTTP_Not_Found.",
"HTTP_Method_Not_Allowed.",
"HTTP_Not_Acceptable.",
"HTTP_Proxy_Authentication_Required.",
"HTTP_Request_Time_out.",
"HTTP_Conflict.",
"HTTP_Gone.",
"HTTP_Length_Required.",
"HTTP_Precondition_Failed.",
"HTTP_Request_Entity_Too_Large.",
"HTTP_Request_URI_Too_Large.",
"HTTP_Unsupported_Media_Type.",
"HTTP_Requested_range_not_satisable.",
"HTTP_Expectation_Failed."
},
{//ConnMgmt_HTTP5
"HTTP_Internal_Server_Error.",
"HTTP_Not_Implemented.",
"HTTP_Bad_Gateway.",
"HTTP_Service_Unavailable.",
"HTTP_Gateway_Time_out.",
"HTTP_Version_not_supported."
},
{//Engine
"There's no Boot Certificate got back from connection module.",
"Try to fetch the Boot Counter but failed.",
"Try to create memory for Expiry Date but failed.",
"Try to fetch the Expiry Date but failed.",
"Try to fetch the Student ID but failed.",
"Try to create memory for TPM object but failed.",
"Try to fetch data from TPM but failed.",
"Try to write data to TPM but failed.",
"The parameter passed down by caller has error format.",
"The TCEngine module encounter an unknown error.",
},
{//TPM
"Try to fetch the User Data from TPM but failed.",
"Try to fetch the Boot Tick from TPM but failed.",		
"Try to fetch the Boot Counter from TPM but failed.",
"Try to fetch the Expiry Date from TPM but failed.",
"Try to fetch the Hardware ID from TPM but failed.",
"Try to initialize the TPM NV storage but failed.",		
"Try to read data from TPM but failed." ,
"Try to write data to TPM but failed.",
"Try to create TPM object but failed.",
"Try to assign the priority to TPM but failed.",
"Try to fetch the valid data length from TPM but failed.",
"The parameter passed down by caller has error format.",
"The TPMCtrl module encounter an unknown error.",
"Try to initialize the TPM NV storage but failed.",		
"Try to fetch the valid data length from TPM but failed.",
"The Provision parameter passed down by caller has error format.",
"The Provision module encounter an unknown error.",
},
{//INFOMGMT
"/etc/resolv.conf doesn't exist",
"Function Parameter Error",
"/proc/net/route doesn't exist",
"inconsistent format in /proc/net/route",
"Function Call 'ioctl' error",
"Function Call 'socket' error",
"No Gateway in Current Platform",
"No Network Interface",
"Wrong Command Parameter (only SET and GET available)",
"~/.mozilla/firefox/profiles.ini doesn't exist",
"~/.mozilla/firefox/$(PATH)/prefs.js doesn't exist",
"No proxy is used",
"INI File cannot be written",
"Target INI File doesn't exist",
"Getting Device Information ... Error",
"Getting Other Information ... Error",
"Getting Proxy Information ... Error",
"Getting Prompt Information ... Error",
"Getting Server Information ... Error",
"Wrong Character in GateWay Info"
},

{//GUI
	"Couldn't open the file.",
	"The format of the file is not correct.",
	"TheftControl may be already running! If not, please remove /tmp/theftcontrol/.tclock file.",
	"Unknown Error."
}
};


/*
int initErrTable()
{
	char pculture[TEMP_MAX_LEN];
	char errfilename[TEMP_MAX_LEN];
	char tmp[RESOURCE_MAX_LEN];

	OtherInfo_Culture(pculture, "GET");
	sprintf(errfilename, "err.%s.txt", pculture);

	FILE* file;
	
	if ((file = fopen(errfilename, "r"))== NULL)	
	{		
		return GUI_ERR_FILE_NOT_OPEN;
	}
	while(!feof(file))
	{	
		fgets(tmp, RESOURCE_MAX_LEN-1, file);
		tmp[strlen(tmp)-1] = '\0'; //remove the end-of-line character
		
	}
	fclose(file);

}

*/


int maperrcode(int errcode)
{
	int moduleno = errcode>>24;
	int index = errcode-(moduleno <<24);
	switch (index / 100)
	{//Alice Http Error Msg
	case 2:
		return (ConnMgmt_Http2_Base + index % 100);
	case 3:
		return (ConnMgmt_Http3_Base + index % 100);
	case 4:
		return (ConnMgmt_Http4_Base + index % 100);
	case 5:
		return (ConnMgmt_Http5_Base + index % 100);
	default:
		return errcode;	
	}
	
}

char* geterrmsg( int* errcode)
{
	if (!( (*errcode>=ConnMgmt_Base&&*errcode<=ConnMgmt_END ) || (*errcode>=ConnMgmt_Soap_Base&&*errcode<=ConnMgmt_SOAP_END )
		|| (*errcode>=ConnMgmt_Http2_START&&*errcode<=ConnMgmt_Http2_END) || (*errcode>=ConnMgmt_Http3_START&&*errcode<=ConnMgmt_Http3_END)
		|| (*errcode>=ConnMgmt_Http4_START&&*errcode<=ConnMgmt_Http4_END) || (*errcode>=ConnMgmt_Http5_START&&*errcode<=ConnMgmt_Http5_END)
		|| (*errcode>=TCEngine_Base&&*errcode<=TCEngine_END) || (*errcode>=TPMCtrl_Base&&*errcode<=TPMCtrl_END)
		|| (*errcode>=INFOMGMT_Base&&*errcode<=INFOMGMT_END)  || (*errcode>=GUI_Base&&*errcode<=GUI_END) ))
		*errcode = GUI_ERR_UNKNOWN;
	int newerrcode = maperrcode(*errcode);
	*errcode = newerrcode;
	int moduleno = newerrcode>>24;
	int err = newerrcode-(moduleno <<24);
	if (moduleno > MAX_MODULENO ||  errtable[moduleno][err] == "")
		return "Unknown Error.";
	return errtable[moduleno][err];
}



char* geterrmsg2( int* errcode)
{
	int olderrcode = *errcode;

	if (!( (*errcode>=ConnMgmt_Base&&*errcode<=ConnMgmt_END ) || (*errcode>=ConnMgmt_Soap_Base&&*errcode<=ConnMgmt_SOAP_END )
		|| (*errcode>=ConnMgmt_Http2_START&&*errcode<=ConnMgmt_Http2_END) || (*errcode>=ConnMgmt_Http3_START&&*errcode<=ConnMgmt_Http3_END)
		|| (*errcode>=ConnMgmt_Http4_START&&*errcode<=ConnMgmt_Http4_END) || (*errcode>=ConnMgmt_Http5_START&&*errcode<=ConnMgmt_Http5_END)
		|| (*errcode>=TCEngine_Base&&*errcode<=TCEngine_END) || (*errcode>=TPMCtrl_Base&&*errcode<=TPMCtrl_END)
		|| (*errcode>=INFOMGMT_Base&&*errcode<=INFOMGMT_END)  || (*errcode>=GUI_Base&&*errcode<=GUI_END) ))
		*errcode = GUI_ERR_UNKNOWN;
	int newerrcode = maperrcode(*errcode);
	*errcode = newerrcode;
	int moduleno = newerrcode>>24;
	int err = newerrcode-(moduleno <<24);
	if (moduleno > MAX_MODULENO ||  errtable[moduleno][err] == "")
		return "Unknown Error.";

	switch(moduleno)
	{
	case 0:
	case 1:
	case 2:
	case 3:
	case 4:
	case 5:
		moduleno = MODULE_CONNMGMT;
		break;
	case 6:
		moduleno = MODULE_ENGINE;
		break;
	case 7:
		moduleno = MODULE_TPMCTRL;
		break;
	case 8:
		moduleno = MODULE_INFOMGMT;
		break;
	case 9:
		moduleno = MODULE_GUI;
		break;
	default:
		moduleno = MODULE_GUI;
	//	errcode = GUI_ERR_UNKNOWN;
		break;

	}

	switch (moduleno)
	{
	case MODULE_CONNMGMT:
		if (olderrcode == ConnMgmt_ExceptionStatus_TrustFailure)
			return g_resManager.M_strUnable;

		if (olderrcode == ConnMgmt_ExceptionStatus_ReturnDataInvalidation)
			return g_resManager.M_strData;

		if (olderrcode == ConnMgmt_ExceptionStatus_ParameterError )
			return g_resManager.M_strException;
		
		if (olderrcode == ConnMgmt_ExceptionStatus_Timeout )
			return g_resManager.M_strTimeout ;
		

		if (olderrcode == ConnMgmt_RefuseServiceExceptionReason_HWIDInvalid )
			return g_resManager.M_strHWIDInvalid;
		if (olderrcode == ConnMgmt_RefuseServiceExceptionReason_BootTickInvalid )
			return g_resManager.M_strBootTickInvalid;
	//	if (olderrcode == ConnMgmt_RefuseServiceExceptionReason_DeviceStolen )
	//		return g_resManager.M_strDeviceStolen;


		if (olderrcode < ConnMgmt_ExceptionStatus_Success && olderrcode >= ConnMgmt_ExceptionStatus_ConnectFailure)
			return g_resManager.M_strErrorConnect;
		
		if (olderrcode <= ConnMgmt_SOAP_END && olderrcode >= ConnMgmt_SOAP_OK)
			return g_resManager.M_strErrorConnect;
		
		if (olderrcode <= ConnMgmt_Http5_END && olderrcode >= ConnMgmt_Http2_START)
			return g_resManager.M_strErrorConnect;


		if (olderrcode < ConnMgmt_invoke_ServerInfo_Construct_Error && olderrcode >= ConnMgmt_BooCertPointIsNull)
			return g_resManager.M_strUnknow;



		return g_resManager.M_strUnknow ;
		break;
	case MODULE_ENGINE:
		if (olderrcode == TCEngine_ExceptionStatus_NoBootCert)
			return NULL;
		return g_resManager.M_strSystem;
		break;
	case MODULE_TPMCTRL:
		return g_resManager.M_strTPM;
		break;
	case MODULE_INFOMGMT:
		return NULL;
		break;
	case MODULE_GUI:
		if (olderrcode == GUI_ERR_TWO_INSTANCE)
			return g_resManager.M_strTwoInstance;
		return NULL;
		break;

	default:
		return g_resManager.M_strUnknow ;
	}
	return NULL;
//	return errtable[moduleno][err];
}


int ErrMsgBox(int errcode)
{
	char cmd[ERR_MSG_LEN]="";
	char tmp[LOG_MAX_LEN];
	char * aa = geterrmsg2(&errcode);
	if (aa == NULL)
		return 0;

	memset(tmp,0,LOG_MAX_LEN);
	
	sprintf(tmp,"%s(0x%x):",g_resManager.M_strError ,errcode);

	//kdialog --title "lalala" --error "hiskdfajkdsf"
	strcpy(cmd, "kdialog --caption \"");
//	strcat(cmd,g_resManager.M_strError);
	strcat(cmd, "\" --error \"");
	strcat(cmd,tmp);
	
	strcat(cmd,aa);
	//strcat(cmd,geterrmsg2(&errcode));
	strcat(cmd, "\"");
	system(cmd);
}


static char modulename[6][20] = { "CONNMGMT","ENGINE","TPMCTRL","INFOMGMT","GUI","OTHER"};

/// <summary>
/// function: write log file
/// </summary>

int WritestrLog(int moduleno, char* loginfo)
{
extern int g_enable_debug;
    if(!g_enable_debug)
	{
	return 0;
	}
	if (loginfo == NULL || strcmp(loginfo,"")==0 ) return 0;
	if (moduleno <0 || moduleno > 5) moduleno = 5;

	char path[FILEPATH_MAX_LEN];
	getrespath(THEFTCONTROL_LOG,path);
	strncat(path, "/",1);
       	strncat(path, LOG_FILE,strlen(LOG_FILE));

	FILE* file;
	char tmp[LOG_MAX_LEN];
	
	memset(tmp,0,LOG_MAX_LEN);
	
	time_t timeNow;
	struct tm * pTmNow;
	time(&timeNow);
	pTmNow = localtime(&timeNow);

	sprintf(tmp, "%s: %s", modulename[moduleno],asctime(pTmNow));
//	sprintf(tmp, "%s: %d-%d-%d %d:%d:%d", modulename[moduleno], pTmNow->tm_year+1900, pTmNow->tm_mon+1, pTmNow->tm_mday,					pTmNow->tm_hour,pTmNow->tm_min, pTmNow->tm_sec);
	
	if ((file = fopen(path, "a"))!= NULL)	
	{
		
		fprintf(file,"%s %s \n",tmp,loginfo);
	}
	else
		return GUI_ERR_FILE_NOT_OPEN;
	fclose(file);
	return 0;
}


int WriteLog(int errcode)
{
	char msg[ERR_MSG_LEN]="";

	sprintf(msg,"%d:",errcode);
	strcpy(msg,geterrmsg(&errcode));
	
	int moduleno = errcode>>24;
	switch(moduleno)
	{
	case 0:
	case 1:
	case 2:
	case 3:
	case 4:
	case 5:
		moduleno = MODULE_CONNMGMT;
		break;
	case 6:
		moduleno = MODULE_ENGINE;
		break;
	case 7:
		moduleno = MODULE_TPMCTRL;
		break;
	case 8:
		moduleno = MODULE_INFOMGMT;
		break;
	case 9:
		moduleno = MODULE_GUI;
		break;
	default:
		moduleno = MODULE_GUI;
	//	errcode = GUI_ERR_UNKNOWN;
		break;

	}
	
	
	WritestrLog(moduleno, msg);
	return 0;
}

