2 * Copyright (C) 2004-2005 Kay Sievers <kay.sievers@vrfy.org>
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the
6 * Free Software Foundation version 2 of the License.
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 static void remove_trailing_chars(char *path, char c)
25 while (len > 0 && path[len-1] == c)
29 /* count of characters used to encode one unicode char */
30 static int utf8_encoded_expected_len(const char *str)
32 unsigned char c = (unsigned char)str[0];
36 if ((c & 0xe0) == 0xc0)
38 if ((c & 0xf0) == 0xe0)
40 if ((c & 0xf8) == 0xf0)
42 if ((c & 0xfc) == 0xf8)
44 if ((c & 0xfe) == 0xfc)
49 /* decode one unicode char */
50 static int utf8_encoded_to_unichar(const char *str)
56 len = utf8_encoded_expected_len(str);
61 unichar = str[0] & 0x1f;
64 unichar = (int)str[0] & 0x0f;
67 unichar = (int)str[0] & 0x07;
70 unichar = (int)str[0] & 0x03;
73 unichar = (int)str[0] & 0x01;
79 for (i = 1; i < len; i++) {
80 if (((int)str[i] & 0xc0) != 0x80)
83 unichar |= (int)str[i] & 0x3f;
89 /* expected size used to encode one unicode char */
90 static int utf8_unichar_to_encoded_len(int unichar)
96 if (unichar < 0x10000)
98 if (unichar < 0x200000)
100 if (unichar < 0x4000000)
105 /* check if unicode char has a valid numeric range */
106 static int utf8_unichar_valid_range(int unichar)
108 if (unichar > 0x10ffff)
110 if ((unichar & 0xfffff800) == 0xd800)
112 if ((unichar > 0xfdcf) && (unichar < 0xfdf0))
114 if ((unichar & 0xffff) == 0xffff)
119 /* validate one encoded unicode char and return its length */
120 static int utf8_encoded_valid_unichar(const char *str)
126 len = utf8_encoded_expected_len(str);
134 /* check if expected encoded chars are available */
135 for (i = 0; i < len; i++)
136 if ((str[i] & 0x80) != 0x80)
139 unichar = utf8_encoded_to_unichar(str);
141 /* check if encoded length matches encoded value */
142 if (utf8_unichar_to_encoded_len(unichar) != len)
145 /* check if value has valid range */
146 if (!utf8_unichar_valid_range(unichar))
152 /* replace everything but whitelisted plain ascii and valid utf8 */
153 static int replace_untrusted_chars(char *str)
158 while (str[i] != '\0') {
161 /* valid printable ascii char */
162 if ((str[i] >= '0' && str[i] <= '9') ||
163 (str[i] >= 'A' && str[i] <= 'Z') ||
164 (str[i] >= 'a' && str[i] <= 'z') ||
165 strchr(" #$%+-./:=?@_,", str[i])) {
169 /* valid utf8 is accepted */
170 len = utf8_encoded_valid_unichar(&str[i]);
176 /* everything else is garbage */