summaryrefslogtreecommitdiffstats
path: root/src/common/mime.c
blob: fe45123ccc94c0f3f8e030a2d127d3662fedf1ca (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
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2011 New Dream Network
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */
#include "common/utf8.h"

#include <errno.h>
#include <stdio.h>

int mime_encode_as_qp(const char *input, char *output, int outlen)
{
	int ret = 1;
	char *o = output;
	const unsigned char *i = (const unsigned char*)input;
	while (1) {
		int c = *i;
		if (c == '\0') {
			break;
		}
		else if ((c & 0x80) || (c == '=') || (is_control_character(c))) {
			if (outlen >= 3) {
				snprintf(o, outlen, "=%02X", c);
				outlen -= 3;
				o += 3;
			}
			else
				outlen = 0;
			ret += 3;
		}
		else {
			if (outlen >= 1) {
				snprintf(o, outlen, "%c", c);
				outlen -= 1;
				o += 1;
			}
			ret += 1;
		}
		++i;
	}
	return ret;
}

static inline signed int hexchar_to_int(unsigned int c)
{
	switch(c) {
	case '0':
		return 0;
	case '1':
		return 1;
	case '2':
		return 2;
	case '3':
		return 3;
	case '4':
		return 4;
	case '5':
		return 5;
	case '6':
		return 6;
	case '7':
		return 7;
	case '8':
		return 8;
	case '9':
		return 9;
	case 'A':
	case 'a':
		return 10;
	case 'B':
	case 'b':
		return 11;
	case 'C':
	case 'c':
		return 12;
	case 'D':
	case 'd':
		return 13;
	case 'E':
	case 'e':
		return 14;
	case 'F':
	case 'f':
		return 15;
	case '\0':
	default:
	    return -EDOM;
	}
}

int mime_decode_from_qp(const char *input, char *output, int outlen)
{
	int ret = 1;
	char *o = output;
	const unsigned char *i = (const unsigned char*)input;
	while (1) {
		unsigned int c = *i;
		if (c == '\0') {
			break;
		}
		else if (c & 0x80) {
			/* The high bit is never set in quoted-printable encoding! */
			return -EDOM;
		}
		else if (c == '=') {
			int high = hexchar_to_int(*++i);
			if (high < 0)
				return -EINVAL;
			int low = hexchar_to_int(*++i);
			if (low < 0)
				return -EINVAL;
			c = (high << 4) + low;
		}
		++i;

		if (outlen >= 1) {
			snprintf(o, outlen, "%c", c);
			outlen -= 1;
			o += 1;
		}
		ret += 1;
	}
	return ret;
}