#include "test_common.h"
#ifdef WIN32
#include "getopt.h"
#else 
extern char *optarg;
#endif

void usage(void);
CK_RV test_crypto();
int test_gost3410(CK_SESSION_HANDLE sess);

CK_SLOT_ID SlotId;

CK_SLOT_ID_PTR SlotList = NULL;
CK_ULONG SlotCount = 0;

int main(int argc, char *argv[]) {
   CK_RV rc = 1;
   CK_FLAGS flags = 0;
   unsigned long slot_num = 0;  
   int i;

   // parse the command line parameters
	for (i=1; i<argc; i++) {
		if (strcmp("-api", argv[i]) == 0) {
			i++;
			api_path = argv[i];
		} else if (strcmp("-user_pin", argv[i]) == 0) {
			i++;
			user_pin = argv[i];
		}
	}

	// load the PKCS11 library 
	rc = init(api_path, &funcs, NULL);
	if (rc != CKR_OK) {
		fprintf(stderr, "ERROR calling init, rc = %p.\n", (void *)rc);
		return rc;
	}

/*
	// Пример направления диагностических сообщений в stderr
	// управляющей командой C_Ctrl.
	rc = pctrl(PKCS11_CTRL_LOG_PATH, 0, "stderr", NULL);
	if (rc != CKR_OK) {
		printf("C_Ctrl failed, rc = 0x%x\n", rc );
		return rc;
	}
*/
/*
	// Пример направления диагностических сообщений в файл
	// управляющей командой C_Ctrl.
	// Имя файла "stderr" просто так использовать нельзя, 
	// но если очень хочется, то используйте "./stderr".
	rc = pctrl(PKCS11_CTRL_LOG_PATH, 0, "./errors.log", NULL);
	if (rc != CKR_OK) {
		printf("C_Ctrl failed, rc = 0x%x\n", rc );
		return rc;
	}
*/
/*
	// Пример отключения диагностических сообщений
	// управляющей командой C_Ctrl.
	rc = pctrl(PKCS11_CTRL_LOG_PATH, 0, NULL, NULL);
	if (rc != CKR_OK) {
		printf("C_Ctrl failed, rc = 0x%x\n", rc );
		return rc;
	}
*/

	rc = get_slot_list(funcs, 
                    &SlotList, 
                    &SlotCount);
	if (rc != CKR_OK) {
		printf("get_slot_list failed, rc = 0x%x\n", rc );
		return rc;
	}
	rc = find_slot_with_token(funcs, 
                           SlotList, 
                           SlotCount, 
                           &SlotId);
	if (rc != CKR_OK) {
		printf("find_slot_with_token failed, rc = 0x%x\n", rc );
		return rc;
	}
//	for (i=0; i<5; i++) {
		// test the crypto functions 
		rc = test_crypto();
		if (rc != CKR_OK) {
			fprintf(stderr, "ERROR call to lissi failed.\n");
			return rc;
		}
//	}
	return CKR_OK;
}


void usage(void)
{
   fprintf(stderr, "Usage: lissi [-c <slotId>]\n"
      "Default slotID is 0\n"
      "To get a list of slotIDs, call pkcs11_cfg -s\n");
   exit(-1);
}

CK_RV test_crypto() 
{
   CK_RV rc, ret;
   CK_SESSION_HANDLE hSession;
	CK_MECHANISM_INFO minfo;

   // open a R/W cryptoki session, CKR_SERIAL_SESSION is a legacy bit we have to set
   rc = funcs->C_OpenSession(SlotId, CKF_RW_SESSION | CKF_SERIAL_SESSION, NULL_PTR,
         NULL_PTR, &hSession);
   if (rc != CKR_OK) {
      fprintf(stderr, "ERROR call to C_OpenSession failed, rc = %p\n", (void *)rc);
      goto out;
   }
  fprintf(stderr, "C_OpenSession success\n");

   // log in as normal user 
   rc = funcs->C_Login(hSession, CKU_USER, user_pin, strlen(user_pin));
   if (rc != CKR_OK) {
      fprintf(stderr, "ERROR call to C_Login failed, rc = %p\n", (void *)rc);
      goto out_close;
   }
  fprintf(stderr, "C_Login success\n");
	rc = funcs->C_GetMechanismInfo(SlotId, CKM_GOSTR3410, &minfo);
	if (rc != CKR_OK) {
		fprintf(stderr, "\n======== Mechanism CKM_GOSTR3410 not supported ===========\n");
	} else {
		fprintf(stderr, "\n==================== CKM_GOSTR3410 test ==================\n");
		rc = test_gost3410(hSession);
		if (rc != CKR_OK) {
			fprintf(stderr, "ERROR CKM_GOSTR3410 failed, rc = %p\n", (void *)rc);
		} else {
			fprintf(stderr, "CKM_GOSTR3410 test passed.\n");
		}
	}


out_close:
   if( (ret = funcs->C_CloseSession(hSession)) != CKR_OK ) {
      fprintf(stderr, "Error: C_CloseSession failed with %p\n", (void *)ret);
	  rc = ret;
   }
   else {
      fprintf(stderr, "C_CloseSession success\n");
   }

out:
   return rc;
}

int test_gost3410(CK_SESSION_HANDLE sess)
{
	int rc = 0;
	CK_BYTE value[256];
	CK_ULONG i, len;
	CK_OBJECT_HANDLE pub_key = CK_INVALID_HANDLE;
	CK_OBJECT_HANDLE priv_key = CK_INVALID_HANDLE;
	CK_OBJECT_HANDLE new_key = CK_INVALID_HANDLE;
//	CK_ATTRIBUTE attr;
   	CK_MECHANISM mechanism_desc = {CKM_GOSTR3410, NULL, 0};
   	CK_MECHANISM_PTR mechanism = &mechanism_desc;
   	CK_MECHANISM mechanism_gen_desc = {CKM_GOSTR3410_KEY_PAIR_GEN, NULL, 0};
   	CK_MECHANISM_PTR mechanism_gen = &mechanism_gen_desc;

	static CK_BBOOL ltrue = CK_TRUE;
	static CK_BBOOL lfalse = CK_FALSE;
	static CK_OBJECT_CLASS oclass = CKO_SECRET_KEY;
	static CK_OBJECT_CLASS oclass_pub = CKO_PUBLIC_KEY;
	static CK_OBJECT_CLASS oclass_priv = CKO_PRIVATE_KEY;
	static CK_KEY_TYPE key_type = CKK_GOSTR3410;

	static CK_BYTE gostR3410params[] = { 0x06, 0x07, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x23, 0x01 };
	static CK_BYTE gostR3411params[] = { 0x06, 0x07, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x1e, 0x01 };
	static CK_BYTE data[] = {
		0xee,0x8c,0xd9,0x40,0x23,0xdd,0x9a,0xf8,
		0x17,0xdd,0xe8,0x1f,0x02,0x25,0x5b,0xb3,
		0xaa,0x6b,0xd3,0x21,0x09,0x41,0x95,0x7e,
		0xea,0x7e,0x0e,0x3c,0x35,0x9f,0x04,0x5a
	};
	static CK_BYTE pub_key_value[64];
	static CK_UTF8CHAR *label = "Yet Another Keypair";
	CK_ATTRIBUTE pub_template[] = { 
		{ CKA_TOKEN, &ltrue, sizeof(ltrue)},
		{ CKA_GOSTR3410PARAMS, gostR3410params, sizeof(gostR3410params) },
//		{ CKA_GOSTR3411PARAMS, gostR3411params, sizeof(gostR3411params) },
		{ CKA_VERIFY, &ltrue, sizeof(CK_BBOOL) },
//		{ CKA_LABEL, label, strlen(label)},
	};
	CK_ATTRIBUTE priv_template[] = {
		{ CKA_TOKEN, &ltrue, sizeof(ltrue)},
		{ CKA_PRIVATE, &ltrue, sizeof(ltrue)},
//		{ CKA_EXTRACTABLE, &lfalse, sizeof(lfalse) },
//		{ CKA_SENSITIVE, &ltrue, sizeof(ltrue) },
		{ CKA_SIGN, &ltrue, sizeof(CK_BBOOL) },
//		{ CKA_LABEL, label, strlen(label)},
	};
	CK_ATTRIBUTE tmpl_value[] = {
		{ CKA_VALUE, pub_key_value, sizeof(pub_key_value)},
	};
	CK_ATTRIBUTE new_pub_template[] = {
		{ CKA_CLASS, &oclass_pub, sizeof(oclass_pub) },
		{ CKA_KEY_TYPE, &key_type, sizeof(key_type) }, 
		{ CKA_GOSTR3410PARAMS, gostR3410params, sizeof(gostR3410params) },
//		{ CKA_GOSTR3411PARAMS, gostR3411params, sizeof(gostR3411params) },
		{ CKA_VERIFY, &ltrue, sizeof(CK_BBOOL) },
		{ CKA_VALUE, pub_key_value, sizeof(pub_key_value)},
	};
/*
	// S-Terra verify test
	static CK_ATTRIBUTE pub_template[] = {
		{ CKA_GOSTR3410PARAMS, gostR3410params, sizeof(gostR3410params) },
		{ CKA_GOSTR3411PARAMS, gostR3411params, sizeof(gostR3411params) },
		{ CKA_CLASS, &oclass_pub, sizeof(CK_OBJECT_CLASS) },
		{ CKA_KEY_TYPE, &key_type, sizeof(key_type) },
		{ CKA_VALUE, pub_key_value, 64} 
	};
	FILE *f = NULL;
	CK_BYTE buf[64];
	CK_BYTE sig[64];
	CK_BYTE hash[32];
*/

	rc = funcs->C_GenerateKeyPair(sess, mechanism_gen,
			pub_template, sizeof(pub_template)/sizeof(CK_ATTRIBUTE),
			priv_template, sizeof(priv_template)/sizeof(CK_ATTRIBUTE),
			&pub_key, &priv_key);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_GenerateKeyPair failed: 0x%x\n", rc);
		return rc;
	}

	rc = funcs->C_SignInit(sess, mechanism, priv_key);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_SignInit failed: 0x%x\n", rc);
		return rc;
	}

	len = sizeof(value);
	rc = funcs->C_Sign(sess, data, sizeof(data), value, &len);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_Sign failed: 0x%x\n", rc);
		return rc;
	}

	printf("\n %%%%%% SIGNATURE: ");
	for (i = 0; i < len; i++) printf(" %02x", value[i]);
	printf(" %%%%%%\n\n");

	rc = funcs->C_GetAttributeValue(sess, pub_key, tmpl_value, 1);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_GetAttributeValue failed: 0x%x\n", rc);
		return rc;
	}

	rc = funcs->C_DestroyObject(sess, pub_key);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DestroyObject failed: 0x%x\n", rc);
		return rc;
	}

	rc = funcs->C_CreateObject(sess, new_pub_template, sizeof(new_pub_template)/sizeof(CK_ATTRIBUTE), &pub_key); 
	if (rc != CKR_OK) {
		fprintf(stderr, "C_CreateObject failed: 0x%x\n", rc);
		return rc;
	}

	rc = funcs->C_VerifyInit(sess, mechanism, pub_key);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_VerifyInit failed: 0x%x\n", rc);
		return rc;
	}

	rc = funcs->C_Verify(sess, data, sizeof(data), value, len);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_Verify failed: 0x%x\n", rc);
		return rc;
	}

	value[5] ^= 0x08;
	// Signature changed and not valid
	rc = funcs->C_VerifyInit(sess, mechanism, pub_key);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_VerifyInit failed: 0x%x\n", rc);
		return rc;
	}
	rc = funcs->C_Verify(sess, data, sizeof(data), value, len);
	if (rc == CKR_OK) {
		fprintf(stderr, "C_Verify not failed for bad data: 0x%x\n", rc);
		return -1;
	}

    // Restore valid signature
	value[5] ^= 0x08;
	rc = funcs->C_VerifyInit(sess, mechanism, pub_key);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_VerifyInit failed: 0x%x\n", rc);
		return rc;
	}
	rc = funcs->C_Verify(sess, data, sizeof(data), value, len);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_Verify failed: 0x%x\n", rc);
		return rc;
	}

	rc = funcs->C_DestroyObject(sess, priv_key);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DestroyObject failed: 0x%x\n", rc);
		return rc;
	}
	rc = funcs->C_DestroyObject(sess, pub_key);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DestroyObject failed: 0x%x\n", rc);
		return rc;
	}

	return rc;

}



