summaryrefslogtreecommitdiff
path: root/plugins/CryptoPP/src/cpp_cntx.cpp
blob: feab8a48e92b020fdff677af2db7b5f56b3abd8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include "commonheaders.h"

// get context data on context id
pCNTX get_context_on_id(HANDLE context)
{
	if (context) {
		pCNTX cntx = (pCNTX)context;
		if (cntx->header == HEADER && cntx->footer == FOOTER)
			return cntx;

#if defined(_DEBUG) || defined(NETLIB_LOG)
		Sent_NetLog("get_context_on_id: corrupted context %08X", cntx);
#endif
	}
	return nullptr;
}

// create context, return context id
HANDLE __cdecl cpp_create_context(int mode)
{
	pCNTX cntx = (pCNTX)malloc(sizeof(CNTX));
	memset(cntx, 0, sizeof(CNTX)); // очищаем выделенный блок
	cntx->header = HEADER;
	cntx->footer = FOOTER;
	cntx->mode = mode;
	return (HANDLE)cntx;
}

// delete context
void __cdecl cpp_delete_context(HANDLE context)
{
	pCNTX tmp = get_context_on_id(context);
	if (tmp) { // помечаем на удаление
		cpp_free_keys(tmp);
		free(tmp);
	}
}

// reset context
void __cdecl cpp_reset_context(HANDLE context)
{
	pCNTX tmp = get_context_on_id(context);
	if (tmp)
		cpp_free_keys(tmp);
}

// allocate pdata
uint8_t* cpp_alloc_pdata(pCNTX ptr)
{
	if (!ptr->pdata) {
		if (ptr->mode & MODE_PGP) {
			ptr->pdata = (uint8_t*)malloc(sizeof(PGPDATA));
			memset(ptr->pdata, 0, sizeof(PGPDATA));
		}
		else if (ptr->mode & MODE_GPG) {
			ptr->pdata = (uint8_t*)malloc(sizeof(GPGDATA));
			memset(ptr->pdata, 0, sizeof(GPGDATA));
		}
		else if (ptr->mode & MODE_RSA) {
			rsa_alloc(ptr);
		}
		else {
			ptr->pdata = (uint8_t*)malloc(sizeof(SIMDATA));
			memset(ptr->pdata, 0, sizeof(SIMDATA));
		}
	}
	return ptr->pdata;
}

// free memory from keys
void cpp_free_keys(pCNTX ptr)
{
	mir_free(ptr->tmp);
	ptr->tmp = nullptr;
	cpp_alloc_pdata(ptr);
	if (ptr->mode & MODE_PGP) {
		pPGPDATA p = (pPGPDATA)ptr->pdata;
		SAFE_FREE(p->pgpKeyID);
		SAFE_FREE(p->pgpKey);
		SAFE_FREE(ptr->pdata);
	}
	else if (ptr->mode & MODE_GPG) {
		pGPGDATA p = (pGPGDATA)ptr->pdata;
		SAFE_FREE(p->gpgKeyID);
		SAFE_FREE(ptr->pdata);
	}
	else if (ptr->mode & MODE_RSA) {
		if (rsa_free(ptr))
			SAFE_DELETE(ptr->pdata);
	}
	else {
		pSIMDATA p = (pSIMDATA)ptr->pdata;
		SAFE_FREE(p->PubA);
		SAFE_FREE(p->KeyA);
		mir_free(p->KeyB);
		SAFE_FREE(p->KeyX);
		SAFE_FREE(p->KeyP);
		SAFE_DELETE(p->dh);
		SAFE_FREE(ptr->pdata);
	}
}