-
Notifications
You must be signed in to change notification settings - Fork 0
/
KissUnescaper.cpp
102 lines (78 loc) · 2.02 KB
/
KissUnescaper.cpp
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
102
#include "KissUnescaper.h"
#include <tuple>
using namespace std;
KissUnescaper::~KissUnescaper()
{
for (int i = 0; i < _buf_vec.size(); i++)
{
delete[] _buf_vec[i];
}
}
unsigned KissUnescaper::unescape(unsigned char **buf, FILE *fp)
{
const unsigned size = getFileSize(fp);
unsigned char *raw_buf = allocate(size);
fread(raw_buf, sizeof(unsigned char), size, fp);
unsigned buf_size;
tie(*buf, buf_size) = _unescape(raw_buf, size);
delete[] raw_buf;
return buf_size;
}
unsigned KissUnescaper::unescape(unsigned char **buf, unsigned char *packets, unsigned size)
{
unsigned buf_size;
tie(*buf, buf_size) = _unescape(packets, size);
return buf_size;
}
unsigned KissUnescaper::getFileSize(FILE *fp)
{
fseek(fp, 0, SEEK_END);
const unsigned size = ftell(fp);
fseek(fp, 0, SEEK_SET);
return size;
}
unsigned char *KissUnescaper::allocate(unsigned size)
{
unsigned char *buf = NULL;
try
{
buf = new unsigned char[sizeof(unsigned char) * size];
}
catch (bad_alloc &e)
{
cerr << "Error: Failed to allocate memory" << endl;
cerr << e.what() << endl;
exit(EXIT_FAILURE);
}
return buf;
}
pair<unsigned char *, unsigned> KissUnescaper::_unescape(unsigned char *raw_buf, unsigned size)
{
//! pointer to unescaped data
unsigned char *buf = allocate(size);
//! size of unescaped data [byte]
unsigned buf_size = 0;
_buf_vec.push_back(buf);
for (unsigned i = 0; i < size; i++)
{
if (raw_buf[i] == 0xC0) // delete "C0"
{
continue;
}
else if (raw_buf[i] == 0xDB && raw_buf[i + 1] == 0xDC) // "DB DC" -> "C0"
{
buf[buf_size++] = 0xC0;
i++;
}
else if (raw_buf[i] == 0xDB && raw_buf[i + 1] == 0xDD) // "DB DD" -> "DB"
{
buf[buf_size++] = 0xDB;
i++;
}
else
{
buf[buf_size++] = raw_buf[i];
}
}
return {buf, buf_size};
}