summaryrefslogtreecommitdiffstats
path: root/libmail/qp.C
blob: 0d30a45c2dbec69bb189cb1245ba9c5d36a9729a (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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
/*
** Copyright 2002-2009, Double Precision Inc.
**
** See COPYING for distribution information.
*/
#include "libmail_config.h"

#include "qp.H"

#include <string.h>

using namespace std;

static inline int xdigit(char c)
{
	static const char xdigits[]="0123456789ABCDEFabcdef";

	const char *p=strchr(xdigits, c);

	if (p == NULL)
		return -1;

	int n= p - xdigits;

	if (n >= 16)
		n -= 6;
	return n;
}

mail::decodeqp::decodeqp()
	: decodeBuffer("")
{
}

mail::decodeqp::~decodeqp()
{
}

void mail::decodeqp::decode(string text)
{
	string decodedString="";

	text=decodeBuffer + text;

	// Just decode as much as possible, and leave the rest for next time.

	string::iterator b=text.begin(), e=text.end(), c=b;

	while (b != e)
	{
		// Look for the next =

		for (c=b; c != e; c++)
			if (*c == '=')
				break;

		decodedString += string(b, c);

		if (c == e) // Got everything.
		{
			b=c;
			break;
		}

		b=c++;

		if (c == e)
			break;

		if (*c == '\r')
			c++;

		if (c == e)
			break;

		if (*c == '\n')
		{
			c++;
			b=c;
			continue;
		}

		int a1=xdigit(*c++);

		if (a1 < 0)
		{
			b=c;
			continue;
		}

		if (c == e)
			break;

		int a2=xdigit(*c++);

		if (a2 < 0)
		{
			b=c;
			continue;
		}

		decodedString += (char)(a1 * 16 + a2);

		b=c;
	}

	decodeBuffer=string(b, e); // Leftovers

	decoded(decodedString);
}

#if 0

class testqp : public mail::decodeqp {

	void decoded(string buffer)
	{
		cout << buffer;
	}
};

int main(int argc, char **argv)
{
	testqp qp;

	int argn;

	for (argn=1; argn < argc; argn++)
	{
		string s=argv[argn];

		size_t p;

		while ((p=s.find('~')) != std::string::npos)
			s[p]='\n';

		qp.decode(s);
	}

	cout << endl;

	return (0);
}
#endif