27e2cda5dcb1ae8f560b2f2c7b1338444da2f550
[pspp] / src / libpspp / encoding-guesser.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2011, 2012 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "libpspp/encoding-guesser.h"
20
21 #include <errno.h>
22 #include <iconv.h>
23 #include <stdbool.h>
24 #include <stdio.h>
25 #include <stdint.h>
26 #include <string.h>
27 #include <unistr.h>
28
29 #include "libpspp/cast.h"
30 #include "libpspp/i18n.h"
31
32 #include "gl/localcharset.h"
33 #include "gl/c-strcase.h"
34
35 /* http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info is a useful source
36    of information about encoding detection.
37 */
38
39 /* Parses and returns the fallback encoding from ENCODING, which must be in one
40    of the forms described at the top of encoding-guesser.h.  The returned
41    string might be ENCODING itself or a suffix of it, or it might be a
42    statically allocated string. */
43 const char *
44 encoding_guess_parse_encoding (const char *encoding)
45 {
46   if (encoding == NULL
47       || !c_strcasecmp (encoding, "auto")
48       || !c_strcasecmp (encoding, "auto,locale")
49       || !c_strcasecmp (encoding, "locale"))
50     return locale_charset ();
51   else if (!c_strncasecmp (encoding, "auto,", 5))
52     return encoding + 5;
53   else
54     return encoding;
55 }
56
57 /* Returns true if ENCODING, which must be in one of the forms described at the
58    top of encoding-guesser.h, is one that performs encoding autodetection,
59    false otherwise. */
60 bool
61 encoding_guess_encoding_is_auto (const char *encoding)
62 {
63   return (encoding == NULL
64           || (!c_strncasecmp (encoding, "auto", 4)
65               && (encoding[4] == ',' || encoding[4] == '\0')));
66 }
67
68 static uint16_t
69 get_be16 (const uint8_t *data)
70 {
71   return (data[0] << 8) | data[1];
72 }
73
74 static uint16_t
75 get_le16 (const uint8_t *data)
76 {
77   return (data[1] << 8) | data[0];
78 }
79
80 static uint32_t
81 get_be32 (const uint8_t *data)
82 {
83   return (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3];
84
85 }
86
87 static uint32_t
88 get_le32 (const uint8_t *data)
89 {
90   return (data[3] << 24) | (data[2] << 16) | (data[1] << 8) | data[0];
91 }
92
93 static const char *
94 guess_utf16 (const uint8_t *data, size_t n)
95 {
96   size_t even_nulls, odd_nulls;
97
98   if (n < ENCODING_GUESS_MIN && n % 2 != 0)
99     return NULL;
100
101   even_nulls = odd_nulls = 0;
102   while (n >= 2)
103     {
104       even_nulls += data[0] == 0;
105       odd_nulls += data[1] == 0;
106       if (data[0] == 0 && data[1] == 0)
107         return NULL;
108
109       data += 2;
110       n -= 2;
111     }
112
113   if (odd_nulls > even_nulls)
114     return "UTF-16LE";
115   else if (even_nulls > 0)
116     return "UTF-16BE";
117   else
118     return NULL;
119 }
120
121 static bool
122 is_utf32 (const uint8_t *data, size_t n, uint32_t (*get_u32) (const uint8_t *))
123 {
124   if (n < ENCODING_GUESS_MIN && n % 4 != 0)
125     return false;
126
127   while (n >= 4)
128     {
129       uint32_t uc = get_u32 (data);
130
131       if (uc < 0x09 || uc > 0x10ffff)
132         return false;
133
134       data += 4;
135       n -= 4;
136     }
137
138   return true;
139 }
140
141 /* Counts and returns the number of bytes, but no more than N, starting at S
142    that are ASCII text characters. */
143 size_t
144 encoding_guess_count_ascii (const void *s_, size_t n)
145 {
146   const uint8_t *s = s_;
147   size_t ofs;
148
149   for (ofs = 0; ofs < n; ofs++)
150     if (!encoding_guess_is_ascii_text (s[ofs]))
151       break;
152   return ofs;
153 }
154
155 static bool
156 is_all_utf8_text (const void *s_, size_t n)
157 {
158   const uint8_t *s = s_;
159   size_t ofs;
160
161   ofs = 0;
162   while (ofs < n)
163     {
164       uint8_t c = s[ofs];
165       if (c < 0x80)
166         {
167           if (!encoding_guess_is_ascii_text (c))
168             return false;
169           ofs++;
170         }
171       else
172         {
173           ucs4_t uc;
174           int mblen;
175
176           mblen = u8_mbtoucr (&uc, s + ofs, n - ofs);
177           if (mblen < 0)
178             return mblen == -2;
179
180           ofs += mblen;
181         }
182     }
183   return true;
184 }
185
186 /* Attempts to guess the encoding of a text file based on ENCODING, an encoding
187    name in one of the forms described at the top of encoding-guesser.h, and
188    DATA, which contains the first N bytes of the file.  Returns the guessed
189    encoding, which might be ENCODING itself or a suffix of it or a statically
190    allocated string.
191
192    Encoding autodetection only takes place if ENCODING actually specifies
193    autodetection.  See encoding-guesser.h for details.
194
195    UTF-8 cannot be distinguished from other ASCII-based encodings until a
196    non-ASCII text character is encountered.  If ENCODING specifies
197    autodetection and this function returns "ASCII", then the client should
198    process the input until it encounters an non-ASCII character (as returned by
199    encoding_guess_is_ascii_text()) and then use encoding_guess_tail_encoding()
200    to make a final encoding guess.  See encoding-guesser.h for details.
201
202    N must be at least ENCODING_GUESS_MIN, unless the file is shorter than
203    that. */
204 const char *
205 encoding_guess_head_encoding (const char *encoding,
206                               const void *data_, size_t n)
207 {
208   const uint8_t *data = data_;
209   const char *fallback_encoding;
210   const char *guess;
211
212   fallback_encoding = encoding_guess_parse_encoding (encoding);
213   if (!encoding_guess_encoding_is_auto (encoding))
214     return fallback_encoding;
215
216   if (n == 0)
217     return fallback_encoding;
218
219   if ((n >= ENCODING_GUESS_MIN || n % 4 == 0)
220       && (get_be32 (data) == 0xfeff || get_le32 (data) == 0xfeff))
221     return "UTF-32";
222
223   if (n >= 4)
224     {
225       uint32_t x = get_be32 (data);
226       if (x == 0x84319533)
227         return "GB-18030";
228       else if (x == 0xdd736673)
229         return "UTF-EBCDIC";
230     }
231
232   if ((n >= ENCODING_GUESS_MIN || n % 2 == 0)
233       && (get_be16 (data) == 0xfeff || get_le16 (data) == 0xfeff))
234     return "UTF-16";
235
236   if (n >= 3 && data[0] == 0xef && data[1] == 0xbb && data[2] == 0xbf)
237     return "UTF-8";
238
239   guess = guess_utf16 (data, n);
240   if (guess != NULL)
241     return guess;
242
243   if (is_utf32 (data, n, get_be32))
244     return "UTF-32BE";
245   if (is_utf32 (data, n, get_le32))
246     return "UTF-32LE";
247
248   if (!is_encoding_ascii_compatible (fallback_encoding)
249       || !encoding_guess_tail_is_utf8 (data, n))
250     return fallback_encoding;
251
252   return "ASCII";
253 }
254
255 /* Returns an encoding guess based on ENCODING and the N bytes of text starting
256    at DATA.  DATA should start with the first non-ASCII text character (as
257    determined by encoding_guess_is_ascii_text()) found in the input.
258
259    The return value will either be "UTF-8" or the fallback encoding for
260    ENCODING.
261
262    See encoding-guesser.h for intended use of this function.
263
264    N must be at least ENCODING_GUESS_MIN, unless the file has fewer bytes than
265    that starting with the first non-ASCII text character. */
266 const char *
267 encoding_guess_tail_encoding (const char *encoding,
268                               const void *data, size_t n)
269 {
270   return (encoding_guess_tail_is_utf8 (data, n)
271           ? "UTF-8"
272           : encoding_guess_parse_encoding (encoding));
273 }
274
275 /* Same as encoding_guess_tail_encoding() but returns true for UTF-8 or false
276    for the fallback encoding. */
277 bool
278 encoding_guess_tail_is_utf8 (const void *data, size_t n)
279 {
280   return (n < ENCODING_GUESS_MIN
281           ? u8_check (data, n) == NULL
282           : is_all_utf8_text (data, n));
283 }
284
285 /* Attempts to guess the encoding of a text file based on ENCODING, an encoding
286    name in one of the forms described at the top of encoding-guesser.h, and the
287    SIZE byts in DATA, which contains the entire contents of the file.  Returns
288    the guessed encoding, which might be ENCODING itself or a suffix of it or a
289    statically allocated string.
290
291    Encoding autodetection only takes place if ENCODING actually specifies
292    autodetection.  See encoding-guesser.h for details. */
293 const char *
294 encoding_guess_whole_file (const char *encoding, const void *text, size_t size)
295 {
296   const char *guess;
297
298   guess = encoding_guess_head_encoding (encoding, text, size);
299   if (!strcmp (guess, "ASCII") && encoding_guess_encoding_is_auto (encoding))
300     {
301       size_t ofs = encoding_guess_count_ascii (text, size);
302       if (ofs < size)
303         return encoding_guess_tail_encoding (encoding,
304                                              (const char *) text + ofs,
305                                              size - ofs);
306       else
307         return encoding_guess_parse_encoding (encoding);
308     }
309   else
310     return guess;
311 }