/*****************************************************************************************
*  Copyright (c) 2004, Beijing Senselock Data Security Centre
*  All rights reserved.
*
*  Filename£ºsample_34_win32.c
*          
*  Briefs£º  The purpose of this snippet is to demonstrate how to use SenseLock EL time-counter
*            to implement software trial version.
*            
*  History:        
*  --------------------------------------------------------        
*            10/28/2004 v1.0.0.0 Lihua created
*            
*            
*******************************************************************************************/

#include <stdio.h>
#include <conio.h>
#include <assert.h>

#include "..\..\inc\win32\sense4.h"
#include "..\..\inc\win32\crypt2.h"
#include "..\..\inc\win32\ses_err_msg.h"/* for debug purpose only */
#include "..\..\common\common.h"

#include "..\inc\sample_34.h"


/* global variables definition */
SENSE4_CONTEXT stS4Ctx = {0};
unsigned long dwResult = 0;
unsigned long dwBytesReturned = 0;

IO_PACKAGE stDataPkgIn = {0};
IO_PACKAGE stDataPkgOut = {0};

#define S4_EXE_FILE_ID "ef34"
#define TIME_COUNT_FID_STR "0034"
#define ONE_MINUTE (16000000*60/64)

/* for debug purpose only : handle results returned by stDataPkgOut.tag */
#ifdef _DEBUG
void HandleError(unsigned char bErrCode, unsigned char *pbErrInfo)
{
	switch(bErrCode)
	{
	case ERR_SUCCESS:
		printf("Success!\n");
		break;
	case ERR_SES:
		printf("Error during SES Execution :\n%s\n", SesErrMsgs[*pbErrInfo]);
		break;
	case ERR_INVALID_PARAMETER:
		printf("Invalid input,pls check your input data\n");
		break;
	case ERR_SW_EXPIRED:
		printf("Trial software expired!\n");
		break;
	default:
		printf("Undefined error code!\n");
		break;
	}
	return;
}
#else
void HandleError(unsigned char bErrCode, unsigned char *pbErrInfo)
{
	return;
}	
#endif

/* check result for S4Execute(...) */
unsigned long CheckS4ExecutionResult(unsigned long dwResult,unsigned long dwBytesReturned,unsigned char tag)
{
	
	if (dwResult != S4_SUCCESS) 
	{
		printf("S4 Execution failed! <error code: 0x%08x>\n", dwResult);
		return 0;
	}
	
	if (dwBytesReturned < 2)
	{
		printf("Invalid data package returned!\n");
		return 0;
	}
	
	if (tag != ERR_SUCCESS)
	{
		HandleError(stDataPkgOut.tag, stDataPkgOut.buff);
		return 0;
	}
	return 1;
}
int main(int argc, char* argv[])
{
	unsigned char lpUserPin[8] = "12345678";
    DATA_BLOCK stDataBlk = {0};
	unsigned char c = 0;
	unsigned char lpDevPin[24] = "123456781234567812345678";
	unsigned char lpBuff[9];
	unsigned char btBuffLen = sizeof(lpBuff);
	unsigned long dwBytesWritten = 0;
	/* set time limit to be 1 minute, in our case ,can run 0xef34 EXF for about 18 times*/
	unsigned long dwTimeLimit =  ONE_MINUTE;
	int i = 0;
	dwTimeLimit = dwTimeLimit>>1; // 0.5 minute, run 0xef34 for about 9 times
    if (!(dwResult = OpenS4ByIndex(FIRST_S4_INDEX,&stS4Ctx)))
	{
		return 1;
	}   
	
	dwResult = S4ChangeDir(&stS4Ctx, "\\");
	if (dwResult != S4_SUCCESS) 
	{
		printf("Change directory failed! <error code: 0x%08x>\n",dwResult);
		S4Close(&stS4Ctx);
		return dwResult;
	}
	printf("[If it's the first time you run this program, do remember to press '1' or '2' to \
    set the program run on \"trial mode\" or \"activated mode\"!]\n");
	while (c != '4')
	{
		printf("1.Reset trial count [dev mode];\
				\n2.Activate trial software[dev mode];\
				\n3.Run trial software[user mode];\
				\n4.Exit;\
				\nYour choice:");
		c = getch();
		switch(c) 
		{
		case '1':
		case '2':	
			dwResult = S4VerifyPin(&stS4Ctx, lpDevPin, sizeof(lpDevPin), S4_DEV_PIN);
			if (dwResult != S4_SUCCESS) 
			{
				printf("Verify DEV-Pin failed! <error code: 0x%08x>\n",dwResult);
				S4Close(&stS4Ctx);
				return dwResult;
			}
			lpBuff[0] = (c == '1')?1:0; // trialFlag
			memset(lpBuff+1, 0, sizeof(DWORD)); // time count reset to be 0
			memcpy(lpBuff+5, &dwTimeLimit, 4); // time limit
			dwResult = S4WriteFile(&stS4Ctx, TIME_COUNT_FID_STR, 0, lpBuff, btBuffLen, btBuffLen, &dwBytesWritten, 
				S4_CREATE_NEW, S4_DATA_FILE);
			if (dwResult == S4_FILE_EXIST)
			{
				dwResult = S4WriteFile(&stS4Ctx, TIME_COUNT_FID_STR, 0, lpBuff, btBuffLen, 0, &dwBytesWritten, 
					S4_UPDATE_FILE, S4_DATA_FILE);
				if (dwResult != S4_SUCCESS)
				{
					printf("Update time-count file failed! <error code: 0x%08x>\n", dwResult);
					ResetAndCloseS4(&stS4Ctx);
					return 1;
				}
			}
			else if (dwResult != S4_SUCCESS)
			{
				printf("Create time-count file failed! <error code: 0x%08x>\n", dwResult);
				ResetAndCloseS4(&stS4Ctx);
				return 1;
			}
			if (c == '1')
			{
				printf("Time count file reset successfully!\n");
			}
			else
			{
				printf("Trial software activated!\n");
			}
			break;
		case '3':

			// Call S4VerifyPin(...) to verify User PIN so as to get the privilege to execute the program in SenseLock EL.
			dwResult = S4VerifyPin(&stS4Ctx, lpUserPin, sizeof(lpUserPin), S4_USER_PIN);
			if (dwResult != S4_SUCCESS) 
			{
				printf("Verify Pin failed! <error code: 0x%08x>\n",dwResult);
				S4Close(&stS4Ctx);
				return dwResult;
			}	
			
			stDataBlk.op1 = 1.234e3;//(float)3.14159;
			stDataBlk.op2 = 1.234e3;//(float)1.57158;
			stDataBlk.times = 5000;
			stDataPkgIn.tag = 0; /* no meaning */
			stDataPkgIn.len = sizeof(DATA_BLOCK);
			memcpy(stDataPkgIn.buff, &stDataBlk, stDataPkgIn.len);
			
			printf("Call SenseLock EL to execute a trial version software [times:%d]...\n", i++);
			dwResult = S4Execute(&stS4Ctx, S4_EXE_FILE_ID, &stDataPkgIn, 
				IO_PACKAGE_HEADER_SIZE+stDataPkgIn.len,
				&stDataPkgOut, sizeof(IO_PACKAGE), &dwBytesReturned);
			if (!CheckS4ExecutionResult(dwResult, dwBytesReturned, stDataPkgOut.tag))
			{
 				ResetAndCloseS4(&stS4Ctx);
				getch();
				return 1;
			}
			printf("Success!\n");
			printf("The result: %e\n", (*(float *)stDataPkgOut.buff));
			break;
		case '4':
			break;
		default:
			printf("Incorrect input!\n");
		}
	}
	
	
	/* for better security,use the following instead of using S4close() directly */
	ResetAndCloseS4(&stS4Ctx);

	return dwResult;
}
